/* Inline Validation pattern.
 *
 * Options:
 *    type(string): The type of form generating library. Either z3c.form, formlib or archetypes
 *
 * Documentation:
 *
 *    # z3c.form
 *
 *    {{ example-1 }}
 *
 * Example: example-1
 *    <div class="pat-inlinevalidation" data-pat-upload='{"type": "z3c.form"}'>
 *      <input id="form-widgets-IDublinCore-title"
 *             name="form.widgets.IDublinCore.title"
 *             class="text-widget required textline-field"
 *             value="Welcome to Plone" type="text">
 *    </div>
 */

define('mockup-patterns-inlinevalidation',[
  'jquery',
  'pat-base'
], function ($, Base) {
  'use strict';

  var InlineValidation = Base.extend({
    name: 'inlinevalidation',
    trigger: '.pat-inlinevalidation',
    parser: 'mockup',

    render_error: function ($field, errmsg) {
       var $errbox = $('div.fieldErrorBox', $field);
       if (errmsg !== '') {
           $field.addClass('error');
           $errbox.html(errmsg);
       } else {
           $field.removeClass('error');
           $errbox.html('');
       }
    },

    append_url_path: function (url, extra) {
        // Add '/extra' on to the end of the URL, respecting querystring
        var i, ret, urlParts = url.split(/\?/);
        ret = urlParts[0];
        if (ret[ret.length - 1] !== '/') { ret += '/'; }
        ret += extra;
        for (i = 1; i < urlParts.length; i+=1) {
            ret += '?' + urlParts[i];
        }
        return ret;
    },

    validate_archetypes_field: function (input) {
        var $input = $(input),
            $field = $input.closest('.field'),
            uid = $field.attr('data-uid'),
            fname = $field.attr('data-fieldname'),
            value = $input.val();

        // value is null for empty multiSelection select, turn it into a [] instead
        // so it does not break at_validate_field
        if ($input.prop('multiple') && value === null) {
            value = $([]).serialize();
        }

        // if value is an Array, it will be send as value[]=value1&value[]=value2 by $.post
        // turn it into something that will be useable or value will be omitted from the request
        var traditional;
        var params = $.param({uid: uid, fname: fname, value: value}, traditional = true);
        if ($field && uid && fname) {
            $.post($('base').attr('href') + '/at_validate_field', params, function (data) {
                this.render_error($field, data.errmsg);
            });
        }
    },

    validate_formlib_field: function (input) {
        var $input = $(input),
            $field = $input.closest('.field'),
            $form = $field.closest('form'),
            fname = $field.attr('data-fieldname');

        $form.ajaxSubmit({
            url: this.append_url_path($form.attr('action'), '@@formlib_validate_field'),
            data: {fname: fname},
            iframe: false,
            success: $.proxy(function (data) {
                this.render_error($field, data.errmsg);
            }, this),
            dataType: 'json'
        });
    },

    validate_z3cform_field: function (input) {
        var $input = $(input),
            $field = $input.closest('.field'),
            $form = $field.closest('form'),
            fset = $input.closest('fieldset').attr('data-fieldset'),
            fname = $field.attr('data-fieldname');

        if (fname) {
            $form.ajaxSubmit({
                url: this.append_url_path($form.attr('action'), '@@z3cform_validate_field'),
                data: {fname: fname, fset: fset},
                iframe: false,
                success: $.proxy(function (data) {
                    this.render_error($field, data.errmsg);
                }, this),
                dataType: 'json'
            });
        }
    },

    init: function () {

      this.$el.find(
          'input[type="text"], ' +
          'input[type="password"], ' +
          'input[type="checkbox"], ' +
          'select, ' +
          'textarea').on('blur', 

          $.proxy(function (ev) {
            if (this.options.type === 'archetypes') {
              this.validate_archetypes_field(ev.target);
            } else if (this.options.type === 'z3c.form') {
              this.validate_z3cform_field(ev.target);
            } else if (this.options.type === 'formlib') {
              this.validate_formlib_field(ev.target);
            }
          }, this));
      },
  });
  return InlineValidation;
});

/**
 * React v0.13.3
 *
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define('castle-url/libs/react/react.min',[],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.React=e()}}(function(){return function e(t,n,r){function o(a,u){if(!n[a]){if(!t[a]){var s="function"==typeof require&&require;if(!u&&s)return s(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t,n){"use strict";var r=e(19),o=e(32),i=e(34),a=e(33),u=e(38),s=e(39),l=e(55),c=(e(56),e(40)),p=e(51),d=e(54),f=e(64),h=e(68),m=e(73),v=e(76),g=e(79),y=e(82),C=e(27),E=e(115),b=e(142);d.inject();var _=l.createElement,x=l.createFactory,D=l.cloneElement,M=m.measure("React","render",h.render),N={Children:{map:o.map,forEach:o.forEach,count:o.count,only:b},Component:i,DOM:c,PropTypes:v,initializeTouchEvents:function(e){r.useTouchEvents=e},createClass:a.createClass,createElement:_,cloneElement:D,createFactory:x,createMixin:function(e){return e},constructAndRenderComponent:h.constructAndRenderComponent,constructAndRenderComponentByID:h.constructAndRenderComponentByID,findDOMNode:E,render:M,renderToString:y.renderToString,renderToStaticMarkup:y.renderToStaticMarkup,unmountComponentAtNode:h.unmountComponentAtNode,isValidElement:l.isValidElement,withContext:u.withContext,__spread:C};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:s,InstanceHandles:f,Mount:h,Reconciler:g,TextComponent:p});N.version="0.13.3",t.exports=N},{115:115,142:142,19:19,27:27,32:32,33:33,34:34,38:38,39:39,40:40,51:51,54:54,55:55,56:56,64:64,68:68,73:73,76:76,79:79,82:82}],2:[function(e,t,n){"use strict";var r=e(117),o={componentDidMount:function(){this.props.autoFocus&&r(this.getDOMNode())}};t.exports=o},{117:117}],3:[function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case T.topCompositionStart:return P.compositionStart;case T.topCompositionEnd:return P.compositionEnd;case T.topCompositionUpdate:return P.compositionUpdate}}function a(e,t){return e===T.topKeyDown&&t.keyCode===b}function u(e,t){switch(e){case T.topKeyUp:return-1!==E.indexOf(t.keyCode);case T.topKeyDown:return t.keyCode!==b;case T.topKeyPress:case T.topMouseDown:case T.topBlur:return!0;default:return!1}}function s(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function l(e,t,n,r){var o,l;if(_?o=i(e):w?u(e,r)&&(o=P.compositionEnd):a(e,r)&&(o=P.compositionStart),!o)return null;M&&(w||o!==P.compositionStart?o===P.compositionEnd&&w&&(l=w.getData()):w=v.getPooled(t));var c=g.getPooled(o,n,r);if(l)c.data=l;else{var p=s(r);null!==p&&(c.data=p)}return h.accumulateTwoPhaseDispatches(c),c}function c(e,t){switch(e){case T.topCompositionEnd:return s(t);case T.topKeyPress:var n=t.which;return n!==N?null:(R=!0,I);case T.topTextInput:var r=t.data;return r===I&&R?null:r;default:return null}}function p(e,t){if(w){if(e===T.topCompositionEnd||u(e,t)){var n=w.getData();return v.release(w),w=null,n}return null}switch(e){case T.topPaste:return null;case T.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case T.topCompositionEnd:return M?null:t.data;default:return null}}function d(e,t,n,r){var o;if(o=D?c(e,r):p(e,r),!o)return null;var i=y.getPooled(P.beforeInput,n,r);return i.data=o,h.accumulateTwoPhaseDispatches(i),i}var f=e(15),h=e(20),m=e(21),v=e(22),g=e(91),y=e(95),C=e(139),E=[9,13,27,32],b=229,_=m.canUseDOM&&"CompositionEvent"in window,x=null;m.canUseDOM&&"documentMode"in document&&(x=document.documentMode);var D=m.canUseDOM&&"TextEvent"in window&&!x&&!r(),M=m.canUseDOM&&(!_||x&&x>8&&11>=x),N=32,I=String.fromCharCode(N),T=f.topLevelTypes,P={beforeInput:{phasedRegistrationNames:{bubbled:C({onBeforeInput:null}),captured:C({onBeforeInputCapture:null})},dependencies:[T.topCompositionEnd,T.topKeyPress,T.topTextInput,T.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:C({onCompositionEnd:null}),captured:C({onCompositionEndCapture:null})},dependencies:[T.topBlur,T.topCompositionEnd,T.topKeyDown,T.topKeyPress,T.topKeyUp,T.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:C({onCompositionStart:null}),captured:C({onCompositionStartCapture:null})},dependencies:[T.topBlur,T.topCompositionStart,T.topKeyDown,T.topKeyPress,T.topKeyUp,T.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:C({onCompositionUpdate:null}),captured:C({onCompositionUpdateCapture:null})},dependencies:[T.topBlur,T.topCompositionUpdate,T.topKeyDown,T.topKeyPress,T.topKeyUp,T.topMouseDown]}},R=!1,w=null,O={eventTypes:P,extractEvents:function(e,t,n,r){return[l(e,t,n,r),d(e,t,n,r)]}};t.exports=O},{139:139,15:15,20:20,21:21,22:22,91:91,95:95}],4:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},i=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){i.forEach(function(t){o[r(t,e)]=o[e]})});var a={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},u={isUnitlessNumber:o,shorthandPropertyExpansions:a};t.exports=u},{}],5:[function(e,t,n){"use strict";var r=e(4),o=e(21),i=(e(106),e(111)),a=e(131),u=e(141),s=(e(150),u(function(e){return a(e)})),l="cssFloat";o.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(l="styleFloat");var c={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=s(n)+":",t+=i(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var o in t)if(t.hasOwnProperty(o)){var a=i(o,t[o]);if("float"===o&&(o=l),a)n[o]=a;else{var u=r.shorthandPropertyExpansions[o];if(u)for(var s in u)n[s]="";else n[o]=""}}}};t.exports=c},{106:106,111:111,131:131,141:141,150:150,21:21,4:4}],6:[function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=e(28),i=e(27),a=e(133);i(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){a(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),t.exports=r},{133:133,27:27,28:28}],7:[function(e,t,n){"use strict";function r(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function o(e){var t=x.getPooled(T.change,R,e);E.accumulateTwoPhaseDispatches(t),_.batchedUpdates(i,t)}function i(e){C.enqueueEvents(e),C.processEventQueue()}function a(e,t){P=e,R=t,P.attachEvent("onchange",o)}function u(){P&&(P.detachEvent("onchange",o),P=null,R=null)}function s(e,t,n){return e===I.topChange?n:void 0}function l(e,t,n){e===I.topFocus?(u(),a(t,n)):e===I.topBlur&&u()}function c(e,t){P=e,R=t,w=e.value,O=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(P,"value",k),P.attachEvent("onpropertychange",d)}function p(){P&&(delete P.value,P.detachEvent("onpropertychange",d),P=null,R=null,w=null,O=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==w&&(w=t,o(e))}}function f(e,t,n){return e===I.topInput?n:void 0}function h(e,t,n){e===I.topFocus?(p(),c(t,n)):e===I.topBlur&&p()}function m(e,t,n){return e!==I.topSelectionChange&&e!==I.topKeyUp&&e!==I.topKeyDown||!P||P.value===w?void 0:(w=P.value,R)}function v(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===I.topClick?n:void 0}var y=e(15),C=e(17),E=e(20),b=e(21),_=e(85),x=e(93),D=e(134),M=e(136),N=e(139),I=y.topLevelTypes,T={change:{phasedRegistrationNames:{bubbled:N({onChange:null}),captured:N({onChangeCapture:null})},dependencies:[I.topBlur,I.topChange,I.topClick,I.topFocus,I.topInput,I.topKeyDown,I.topKeyUp,I.topSelectionChange]}},P=null,R=null,w=null,O=null,S=!1;b.canUseDOM&&(S=D("change")&&(!("documentMode"in document)||document.documentMode>8));var A=!1;b.canUseDOM&&(A=D("input")&&(!("documentMode"in document)||document.documentMode>9));var k={get:function(){return O.get.call(this)},set:function(e){w=""+e,O.set.call(this,e)}},L={eventTypes:T,extractEvents:function(e,t,n,o){var i,a;if(r(t)?S?i=s:a=l:M(t)?A?i=f:(i=m,a=h):v(t)&&(i=g),i){var u=i(e,t,n);if(u){var c=x.getPooled(T.change,u,o);return E.accumulateTwoPhaseDispatches(c),c}}a&&a(e,t,n)}};t.exports=L},{134:134,136:136,139:139,15:15,17:17,20:20,21:21,85:85,93:93}],8:[function(e,t,n){"use strict";var r=0,o={createReactRootIndex:function(){return r++}};t.exports=o},{}],9:[function(e,t,n){"use strict";function r(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var o=e(12),i=e(70),a=e(145),u=e(133),s={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:a,processUpdates:function(e,t){for(var n,s=null,l=null,c=0;c<e.length;c++)if(n=e[c],n.type===i.MOVE_EXISTING||n.type===i.REMOVE_NODE){var p=n.fromIndex,d=n.parentNode.childNodes[p],f=n.parentID;u(d),s=s||{},s[f]=s[f]||[],s[f][p]=d,l=l||[],l.push(d)}var h=o.dangerouslyRenderMarkup(t);if(l)for(var m=0;m<l.length;m++)l[m].parentNode.removeChild(l[m]);for(var v=0;v<e.length;v++)switch(n=e[v],n.type){case i.INSERT_MARKUP:r(n.parentNode,h[n.markupIndex],n.toIndex);break;case i.MOVE_EXISTING:r(n.parentNode,s[n.parentID][n.fromIndex],n.toIndex);break;case i.TEXT_CONTENT:a(n.parentNode,n.textContent);break;case i.REMOVE_NODE:}}};t.exports=s},{12:12,133:133,145:145,70:70}],10:[function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=e(133),i={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},n=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},s=e.DOMMutationMethods||{};e.isCustomAttribute&&u._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var l in t){o(!u.isStandardName.hasOwnProperty(l)),u.isStandardName[l]=!0;var c=l.toLowerCase();if(u.getPossibleStandardName[c]=l,n.hasOwnProperty(l)){var p=n[l];u.getPossibleStandardName[p]=l,u.getAttributeName[l]=p}else u.getAttributeName[l]=c;u.getPropertyName[l]=a.hasOwnProperty(l)?a[l]:l,s.hasOwnProperty(l)?u.getMutationMethod[l]=s[l]:u.getMutationMethod[l]=null;var d=t[l];u.mustUseAttribute[l]=r(d,i.MUST_USE_ATTRIBUTE),u.mustUseProperty[l]=r(d,i.MUST_USE_PROPERTY),u.hasSideEffects[l]=r(d,i.HAS_SIDE_EFFECTS),u.hasBooleanValue[l]=r(d,i.HAS_BOOLEAN_VALUE),u.hasNumericValue[l]=r(d,i.HAS_NUMERIC_VALUE),u.hasPositiveNumericValue[l]=r(d,i.HAS_POSITIVE_NUMERIC_VALUE),u.hasOverloadedBooleanValue[l]=r(d,i.HAS_OVERLOADED_BOOLEAN_VALUE),o(!u.mustUseAttribute[l]||!u.mustUseProperty[l]),o(u.mustUseProperty[l]||!u.hasSideEffects[l]),o(!!u.hasBooleanValue[l]+!!u.hasNumericValue[l]+!!u.hasOverloadedBooleanValue[l]<=1)}}},a={},u={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<u._isCustomAttributeFunctions.length;t++){var n=u._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=a[e];return r||(a[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:i};t.exports=u},{133:133}],11:[function(e,t,n){"use strict";function r(e,t){return null==t||o.hasBooleanValue[e]&&!t||o.hasNumericValue[e]&&isNaN(t)||o.hasPositiveNumericValue[e]&&1>t||o.hasOverloadedBooleanValue[e]&&t===!1}var o=e(10),i=e(143),a=(e(150),{createMarkupForID:function(e){return o.ID_ATTRIBUTE_NAME+"="+i(e)},createMarkupForProperty:function(e,t){if(o.isStandardName.hasOwnProperty(e)&&o.isStandardName[e]){if(r(e,t))return"";var n=o.getAttributeName[e];return o.hasBooleanValue[e]||o.hasOverloadedBooleanValue[e]&&t===!0?n:n+"="+i(t)}return o.isCustomAttribute(e)?null==t?"":e+"="+i(t):null},setValueForProperty:function(e,t,n){if(o.isStandardName.hasOwnProperty(t)&&o.isStandardName[t]){var i=o.getMutationMethod[t];if(i)i(e,n);else if(r(t,n))this.deleteValueForProperty(e,t);else if(o.mustUseAttribute[t])e.setAttribute(o.getAttributeName[t],""+n);else{var a=o.getPropertyName[t];o.hasSideEffects[t]&&""+e[a]==""+n||(e[a]=n)}}else o.isCustomAttribute(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){if(o.isStandardName.hasOwnProperty(t)&&o.isStandardName[t]){var n=o.getMutationMethod[t];if(n)n(e,void 0);else if(o.mustUseAttribute[t])e.removeAttribute(o.getAttributeName[t]);else{var r=o.getPropertyName[t],i=o.getDefaultValueForProperty(e.nodeName,r);o.hasSideEffects[t]&&""+e[r]===i||(e[r]=i)}}else o.isCustomAttribute(t)&&e.removeAttribute(t)}});t.exports=a},{10:10,143:143,150:150}],12:[function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=e(21),i=e(110),a=e(112),u=e(125),s=e(133),l=/^(<[^ \/>]+)/,c="data-danger-index",p={dangerouslyRenderMarkup:function(e){s(o.canUseDOM);for(var t,n={},p=0;p<e.length;p++)s(e[p]),t=r(e[p]),t=u(t)?t:"*",n[t]=n[t]||[],n[t][p]=e[p];var d=[],f=0;for(t in n)if(n.hasOwnProperty(t)){var h,m=n[t];for(h in m)if(m.hasOwnProperty(h)){var v=m[h];m[h]=v.replace(l,"$1 "+c+'="'+h+'" ')}for(var g=i(m.join(""),a),y=0;y<g.length;++y){var C=g[y];C.hasAttribute&&C.hasAttribute(c)&&(h=+C.getAttribute(c),C.removeAttribute(c),s(!d.hasOwnProperty(h)),d[h]=C,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(o.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=i(t,a)[0];e.parentNode.replaceChild(n,e)}};t.exports=p},{110:110,112:112,125:125,133:133,21:21}],13:[function(e,t,n){"use strict";var r=e(139),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null}),r({AnalyticsEventPlugin:null}),r({MobileSafariClickEventPlugin:null})];t.exports=o},{139:139}],14:[function(e,t,n){"use strict";var r=e(15),o=e(20),i=e(97),a=e(68),u=e(139),s=r.topLevelTypes,l=a.getFirstReactDOM,c={mouseEnter:{registrationName:u({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:u({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},p=[null,null],d={eventTypes:c,extractEvents:function(e,t,n,r){if(e===s.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var u;if(t.window===t)u=t;else{var d=t.ownerDocument;u=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=l(r.relatedTarget||r.toElement)||u):(f=u,h=t),f===h)return null;var m=f?a.getID(f):"",v=h?a.getID(h):"",g=i.getPooled(c.mouseLeave,m,r);g.type="mouseleave",g.target=f,g.relatedTarget=h;var y=i.getPooled(c.mouseEnter,v,r);return y.type="mouseenter",y.target=h,y.relatedTarget=f,o.accumulateEnterLeaveDispatches(g,y,m,v),p[0]=g,p[1]=y,p}};t.exports=d},{139:139,15:15,20:20,68:68,97:97}],15:[function(e,t,n){"use strict";var r=e(138),o=r({bubbled:null,captured:null}),i=r({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:o};t.exports=a},{138:138}],16:[function(e,t,n){var r=e(112),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};t.exports=o},{112:112}],17:[function(e,t,n){"use strict";var r=e(18),o=e(19),i=e(103),a=e(118),u=e(133),s={},l=null,c=function(e){if(e){var t=o.executeDispatch,n=r.getPluginModuleForEvent(e);n&&n.executeDispatch&&(t=n.executeDispatch),o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},p=null,d={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){p=e},getInstanceHandle:function(){return p},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){u(!n||"function"==typeof n);var r=s[t]||(s[t]={});r[e]=n},getListener:function(e,t){var n=s[t];return n&&n[e]},deleteListener:function(e,t){var n=s[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in s)delete s[t][e]},extractEvents:function(e,t,n,o){for(var a,u=r.plugins,s=0,l=u.length;l>s;s++){var c=u[s];if(c){var p=c.extractEvents(e,t,n,o);p&&(a=i(a,p))}}return a},enqueueEvents:function(e){e&&(l=i(l,e))},processEventQueue:function(){var e=l;l=null,a(e,c),u(!l)},__purge:function(){s={}},__getListenerBank:function(){return s}};t.exports=d},{103:103,118:118,133:133,18:18,19:19}],18:[function(e,t,n){"use strict";function r(){if(u)for(var e in s){var t=s[e],n=u.indexOf(e);if(a(n>-1),!l.plugins[n]){a(t.extractEvents),l.plugins[n]=t;var r=t.eventTypes;for(var i in r)a(o(r[i],t,i))}}}function o(e,t,n){a(!l.eventNameDispatchConfigs.hasOwnProperty(n)),l.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var u=r[o];i(u,t,n)}return!0}return e.registrationName?(i(e.registrationName,t,n),!0):!1}function i(e,t,n){a(!l.registrationNameModules[e]),l.registrationNameModules[e]=t,l.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=e(133),u=null,s={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){a(!u),u=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];s.hasOwnProperty(n)&&s[n]===o||(a(!s[n]),s[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return l.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=l.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){u=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];l.plugins.length=0;var t=l.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=l.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=l},{133:133}],19:[function(e,t,n){"use strict";function r(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel}function o(e){return e===v.topMouseMove||e===v.topTouchMove}function i(e){return e===v.topMouseDown||e===v.topTouchStart}function a(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function u(e,t,n){e.currentTarget=m.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function s(e,t){a(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=l(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function p(e){var t=e._dispatchListeners,n=e._dispatchIDs;h(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function d(e){return!!e._dispatchListeners}var f=e(15),h=e(133),m={Mount:null,injectMount:function(e){m.Mount=e}},v=f.topLevelTypes,g={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:p,executeDispatch:u,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:d,injection:m,useTouchEvents:!1};t.exports=g},{133:133,15:15}],20:[function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return v(e,r)}function o(e,t,n){var o=t?m.bubbled:m.captured,i=r(e,n,o);i&&(n._dispatchListeners=f(n._dispatchListeners,i),n._dispatchIDs=f(n._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function a(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=v(e,r);o&&(n._dispatchListeners=f(n._dispatchListeners,o),n._dispatchIDs=f(n._dispatchIDs,e))}}function u(e){e&&e.dispatchConfig.registrationName&&a(e.dispatchMarker,null,e)}function s(e){h(e,i)}function l(e,t,n,r){d.injection.getInstanceHandle().traverseEnterLeave(n,r,a,e,t)}function c(e){h(e,u)}var p=e(15),d=e(17),f=e(103),h=e(118),m=p.PropagationPhases,v=d.getListener,g={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:l};t.exports=g},{103:103,118:118,15:15,17:17}],21:[function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};t.exports=o},{}],22:[function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=e(28),i=e(27),a=e(128);i(r.prototype,{getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var u=t>1?1-t:void 0;return this._fallbackText=o.slice(e,u),this._fallbackText}}),o.addPoolingTo(r),t.exports=r},{128:128,27:27,28:28}],23:[function(e,t,n){"use strict";var r,o=e(10),i=e(21),a=o.injection.MUST_USE_ATTRIBUTE,u=o.injection.MUST_USE_PROPERTY,s=o.injection.HAS_BOOLEAN_VALUE,l=o.injection.HAS_SIDE_EFFECTS,c=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,d=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var f=document.implementation;r=f&&f.hasFeature&&f.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var h={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:a|s,allowTransparency:a,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:a,checked:u|s,classID:a,className:r?a:u,cols:a|p,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:u|s,coords:null,crossOrigin:null,data:null,dateTime:a,defer:s,dir:null,disabled:a|s,download:d,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:s,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|s,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:u,label:null,lang:null,list:a,loop:u|s,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,multiple:u|s,muted:u|s,name:null,noValidate:s,open:s,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:u|s,rel:null,required:s,role:a,rows:a|p,rowSpan:null,sandbox:null,scope:null,scoped:s,scrolling:null,seamless:a|s,selected:u|s,shape:null,size:a|p,sizes:a,span:p,spellCheck:null,src:null,srcDoc:u,srcSet:a,start:c,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:u|l,width:a,wmode:a,autoCapitalize:null,autoCorrect:null,itemProp:a,itemScope:a|s,itemType:a,itemID:a,itemRef:a,property:null,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=h},{10:10,21:21}],24:[function(e,t,n){"use strict";function r(e){l(null==e.props.checkedLink||null==e.props.valueLink)}function o(e){r(e),l(null==e.props.value&&null==e.props.onChange)}function i(e){r(e),l(null==e.props.checked&&null==e.props.onChange)}function a(e){this.props.valueLink.requestChange(e.target.value)}function u(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e(76),l=e(133),c={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},p={Mixin:{propTypes:{value:function(e,t,n){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func}},getValue:function(e){return e.props.valueLink?(o(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(i(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(o(e),a):e.props.checkedLink?(i(e),u):e.props.onChange}};t.exports=p},{133:133,76:76}],25:[function(e,t,n){"use strict";function r(e){e.remove()}var o=e(30),i=e(103),a=e(118),u=e(133),s={trapBubbledEvent:function(e,t){u(this.isMounted());var n=this.getDOMNode();u(n);var r=o.trapBubbledEvent(e,t,n);this._localEventListeners=i(this._localEventListeners,r)},componentWillUnmount:function(){this._localEventListeners&&a(this._localEventListeners,r)}};t.exports=s},{103:103,118:118,133:133,30:30}],26:[function(e,t,n){"use strict";var r=e(15),o=e(112),i=r.topLevelTypes,a={eventTypes:null,extractEvents:function(e,t,n,r){if(e===i.topTouchStart){var a=r.target;a&&!a.onclick&&(a.onclick=o)}}};t.exports=a},{112:112,15:15}],27:[function(e,t,n){"use strict";function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),r=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i){var a=Object(i);for(var u in a)r.call(a,u)&&(n[u]=a[u])}}return n}t.exports=r},{}],28:[function(e,t,n){"use strict";var r=e(133),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},u=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},s=function(e){var t=this;r(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=10,c=o,p=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=l),n.release=s,n},d={addPoolingTo:p,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fiveArgumentPooler:u};t.exports=d},{133:133}],29:[function(e,t,n){"use strict";var r=e(115),o={getDOMNode:function(){return r(this)}};t.exports=o},{115:115}],30:[function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=f++,p[e[m]]={}),p[e[m]]}var o=e(15),i=e(17),a=e(18),u=e(59),s=e(102),l=e(27),c=e(134),p={},d=!1,f=0,h={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),v=l({},u,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(v.handleTopLevel),v.ReactEventListener=e}},setEnabled:function(e){v.ReactEventListener&&v.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!v.ReactEventListener||!v.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=r(n),u=a.registrationNameDependencies[e],s=o.topLevelTypes,l=0,p=u.length;p>l;l++){var d=u[l];i.hasOwnProperty(d)&&i[d]||(d===s.topWheel?c("wheel")?v.ReactEventListener.trapBubbledEvent(s.topWheel,"wheel",n):c("mousewheel")?v.ReactEventListener.trapBubbledEvent(s.topWheel,"mousewheel",n):v.ReactEventListener.trapBubbledEvent(s.topWheel,"DOMMouseScroll",n):d===s.topScroll?c("scroll",!0)?v.ReactEventListener.trapCapturedEvent(s.topScroll,"scroll",n):v.ReactEventListener.trapBubbledEvent(s.topScroll,"scroll",v.ReactEventListener.WINDOW_HANDLE):d===s.topFocus||d===s.topBlur?(c("focus",!0)?(v.ReactEventListener.trapCapturedEvent(s.topFocus,"focus",n),v.ReactEventListener.trapCapturedEvent(s.topBlur,"blur",n)):c("focusin")&&(v.ReactEventListener.trapBubbledEvent(s.topFocus,"focusin",n),v.ReactEventListener.trapBubbledEvent(s.topBlur,"focusout",n)),i[s.topBlur]=!0,i[s.topFocus]=!0):h.hasOwnProperty(d)&&v.ReactEventListener.trapBubbledEvent(d,h[d],n),i[d]=!0)}},trapBubbledEvent:function(e,t,n){
return v.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return v.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!d){var e=s.refreshScrollValues;v.ReactEventListener.monitorScrollValue(e),d=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});t.exports=v},{102:102,134:134,15:15,17:17,18:18,27:27,59:59}],31:[function(e,t,n){"use strict";var r=e(79),o=e(116),i=e(132),a=e(147),u={instantiateChildren:function(e,t,n){var r=o(e);for(var a in r)if(r.hasOwnProperty(a)){var u=r[a],s=i(u,null);r[a]=s}return r},updateChildren:function(e,t,n,u){var s=o(t);if(!s&&!e)return null;var l;for(l in s)if(s.hasOwnProperty(l)){var c=e&&e[l],p=c&&c._currentElement,d=s[l];if(a(p,d))r.receiveComponent(c,d,n,u),s[l]=c;else{c&&r.unmountComponent(c,l);var f=i(d,null);s[l]=f}}for(l in e)!e.hasOwnProperty(l)||s&&s.hasOwnProperty(l)||r.unmountComponent(e[l]);return s},unmountChildren:function(e){for(var t in e){var n=e[t];r.unmountComponent(n)}}};t.exports=u},{116:116,132:132,147:147,79:79}],32:[function(e,t,n){"use strict";function r(e,t){this.forEachFunction=e,this.forEachContext=t}function o(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function i(e,t,n){if(null==e)return e;var i=r.getPooled(t,n);f(e,o,i),r.release(i)}function a(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function u(e,t,n,r){var o=e,i=o.mapResult,a=!i.hasOwnProperty(n);if(a){var u=o.mapFunction.call(o.mapContext,t,r);i[n]=u}}function s(e,t,n){if(null==e)return e;var r={},o=a.getPooled(r,t,n);return f(e,u,o),a.release(o),d.create(r)}function l(e,t,n,r){return null}function c(e,t){return f(e,l,null)}var p=e(28),d=e(61),f=e(149),h=(e(150),p.twoArgumentPooler),m=p.threeArgumentPooler;p.addPoolingTo(r,h),p.addPoolingTo(a,m);var v={forEach:i,map:s,count:c};t.exports=v},{149:149,150:150,28:28,61:61}],33:[function(e,t,n){"use strict";function r(e,t){var n=D.hasOwnProperty(t)?D[t]:null;N.hasOwnProperty(t)&&y(n===_.OVERRIDE_BASE),e.hasOwnProperty(t)&&y(n===_.DEFINE_MANY||n===_.DEFINE_MANY_MERGED)}function o(e,t){if(t){y("function"!=typeof t),y(!d.isValidElement(t));var n=e.prototype;t.hasOwnProperty(b)&&M.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==b){var i=t[o];if(r(n,o),M.hasOwnProperty(o))M[o](e,i);else{var a=D.hasOwnProperty(o),l=n.hasOwnProperty(o),c=i&&i.__reactDontBind,p="function"==typeof i,f=p&&!a&&!l&&!c;if(f)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[o]=i,n[o]=i;else if(l){var h=D[o];y(a&&(h===_.DEFINE_MANY_MERGED||h===_.DEFINE_MANY)),h===_.DEFINE_MANY_MERGED?n[o]=u(n[o],i):h===_.DEFINE_MANY&&(n[o]=s(n[o],i))}else n[o]=i}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in M;y(!o);var i=n in e;y(!i),e[n]=r}}}function a(e,t){y(e&&t&&"object"==typeof e&&"object"==typeof t);for(var n in t)t.hasOwnProperty(n)&&(y(void 0===e[n]),e[n]=t[n]);return e}function u(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return a(o,n),a(o,r),o}}function s(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var n=t.bind(e);return n}function c(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=l(e,f.guard(n,e.constructor.displayName+"."+t))}}var p=e(34),d=(e(39),e(55)),f=e(58),h=e(65),m=e(66),v=(e(75),e(74),e(84)),g=e(27),y=e(133),C=e(138),E=e(139),b=(e(150),E({mixins:null})),_=C({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),x=[],D={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},M={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=g({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=g({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=g({},e.propTypes,t)},statics:function(e,t){i(e,t)}},N={replaceState:function(e,t){v.enqueueReplaceState(this,e),t&&v.enqueueCallback(this,t)},isMounted:function(){var e=h.get(this);return e&&e!==m.currentlyMountingInstance},setProps:function(e,t){v.enqueueSetProps(this,e),t&&v.enqueueCallback(this,t)},replaceProps:function(e,t){v.enqueueReplaceProps(this,e),t&&v.enqueueCallback(this,t)}},I=function(){};g(I.prototype,p.prototype,N);var T={createClass:function(e){var t=function(e,t){this.__reactAutoBindMap&&c(this),this.props=e,this.context=t,this.state=null;var n=this.getInitialState?this.getInitialState():null;y("object"==typeof n&&!Array.isArray(n)),this.state=n};t.prototype=new I,t.prototype.constructor=t,x.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),y(t.prototype.render);for(var n in D)t.prototype[n]||(t.prototype[n]=null);return t.type=t,t},injection:{injectMixin:function(e){x.push(e)}}};t.exports=T},{133:133,138:138,139:139,150:150,27:27,34:34,39:39,55:55,58:58,65:65,66:66,74:74,75:75,84:84}],34:[function(e,t,n){"use strict";function r(e,t){this.props=e,this.context=t}{var o=e(84),i=e(133);e(150)}r.prototype.setState=function(e,t){i("object"==typeof e||"function"==typeof e||null==e),o.enqueueSetState(this,e),t&&o.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){o.enqueueForceUpdate(this),e&&o.enqueueCallback(this,e)};t.exports=r},{133:133,150:150,84:84}],35:[function(e,t,n){"use strict";var r=e(44),o=e(68),i={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};t.exports=i},{44:44,68:68}],36:[function(e,t,n){"use strict";var r=e(133),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){r(!o),i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};t.exports=i},{133:133}],37:[function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}var o=e(36),i=e(38),a=e(39),u=e(55),s=(e(56),e(65)),l=e(66),c=e(71),p=e(73),d=e(75),f=(e(74),e(79)),h=e(85),m=e(27),v=e(113),g=e(133),y=e(147),C=(e(150),1),E={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._isTopLevel=!1,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=C++,this._rootNodeID=e;var r=this._processProps(this._currentElement.props),o=this._processContext(this._currentElement._context),i=c.getComponentClassForElement(this._currentElement),a=new i(r,o);a.props=r,a.context=o,a.refs=v,this._instance=a,s.set(a,this);var u=a.state;void 0===u&&(a.state=u=null),g("object"==typeof u&&!Array.isArray(u)),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var p,d,h=l.currentlyMountingInstance;l.currentlyMountingInstance=this;try{a.componentWillMount&&(a.componentWillMount(),this._pendingStateQueue&&(a.state=this._processPendingState(a.props,a.context))),p=this._getValidatedChildContext(n),d=this._renderValidatedComponent(p)}finally{l.currentlyMountingInstance=h}this._renderedComponent=this._instantiateReactComponent(d,this._currentElement.type);var m=f.mountComponent(this._renderedComponent,e,t,this._mergeChildContext(n,p));return a.componentDidMount&&t.getReactMountReady().enqueue(a.componentDidMount,a),m},unmountComponent:function(){var e=this._instance;if(e.componentWillUnmount){var t=l.currentlyUnmountingInstance;l.currentlyUnmountingInstance=this;try{e.componentWillUnmount()}finally{l.currentlyUnmountingInstance=t}}f.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,s.remove(e)},_setPropsInternal:function(e,t){var n=this._pendingElement||this._currentElement;this._pendingElement=u.cloneAndReplaceProps(n,m({},n.props,e)),h.enqueueUpdate(this,t)},_maskContext:function(e){var t=null;if("string"==typeof this._currentElement.type)return v;var n=this._currentElement.type.contextTypes;if(!n)return v;t={};for(var r in n)t[r]=e[r];return t},_processContext:function(e){var t=this._maskContext(e);return t},_getValidatedChildContext:function(e){var t=this._instance,n=t.getChildContext&&t.getChildContext();if(n){g("object"==typeof t.constructor.childContextTypes);for(var r in n)g(r in t.constructor.childContextTypes);return n}return null},_mergeChildContext:function(e,t){return t?m({},e,t):e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{g("function"==typeof e[i]),a=e[i](t,i,o,n)}catch(u){a=u}a instanceof Error&&(r(this),n===d.prop)}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&f.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},_warnIfContextsDiffer:function(e,t){e=this._maskContext(e),t=this._maskContext(t);for(var n=Object.keys(t).sort(),r=(this.getName()||"ReactCompositeComponent",0);r<n.length;r++)n[r]},updateComponent:function(e,t,n,r,o){var i=this._instance,a=i.context,u=i.props;t!==n&&(a=this._processContext(n._context),u=this._processProps(n.props),i.componentWillReceiveProps&&i.componentWillReceiveProps(u,a));var s=this._processPendingState(u,a),l=this._pendingForceUpdate||!i.shouldComponentUpdate||i.shouldComponentUpdate(u,s,a);l?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,u,s,a,e,o)):(this._currentElement=n,this._context=o,i.props=u,i.state=s,i.context=a)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=m({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var u=r[a];m(i,"function"==typeof u?u.call(n,i,e,t):u)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a=this._instance,u=a.props,s=a.state,l=a.context;a.componentWillUpdate&&a.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,a.props=t,a.state=n,a.context=r,this._updateRenderedComponent(o,i),a.componentDidUpdate&&o.getReactMountReady().enqueue(a.componentDidUpdate.bind(a,u,s,l),a)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._getValidatedChildContext(),i=this._renderValidatedComponent(o);if(y(r,i))f.receiveComponent(n,i,e,this._mergeChildContext(t,o));else{var a=this._rootNodeID,u=n._rootNodeID;f.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(i,this._currentElement.type);var s=f.mountComponent(this._renderedComponent,a,e,this._mergeChildContext(t,o));this._replaceNodeWithMarkupByID(u,s)}},_replaceNodeWithMarkupByID:function(e,t){o.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(e){var t,n=i.current;i.current=this._mergeChildContext(this._currentElement._context,e),a.current=this;try{t=this._renderValidatedComponentWithoutOwnerOrContext()}finally{i.current=n,a.current=null}return g(null===t||t===!1||u.isValidElement(t)),t},attachRef:function(e,t){var n=this.getPublicInstance(),r=n.refs===v?n.refs={}:n.refs;r[e]=t.getPublicInstance()},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){return this._instance},_instantiateReactComponent:null};p.measureMethods(E,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var b={Mixin:E};t.exports=b},{113:113,133:133,147:147,150:150,27:27,36:36,38:38,39:39,55:55,56:56,65:65,66:66,71:71,73:73,74:74,75:75,79:79,85:85}],38:[function(e,t,n){"use strict";var r=e(27),o=e(113),i=(e(150),{current:o,withContext:function(e,t){var n,o=i.current;i.current=r({},o,e);try{n=t()}finally{i.current=o}return n}});t.exports=i},{113:113,150:150,27:27}],39:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],40:[function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=e(55),i=(e(56),e(140)),a=i({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);t.exports=a},{140:140,55:55,56:56}],41:[function(e,t,n){"use strict";var r=e(2),o=e(29),i=e(33),a=e(55),u=e(138),s=a.createFactory("button"),l=u({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=i.createClass({displayName:"ReactDOMButton",tagName:"BUTTON",mixins:[r,o],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&l[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});t.exports=c},{138:138,2:2,29:29,33:33,55:55}],42:[function(e,t,n){"use strict";function r(e){e&&(null!=e.dangerouslySetInnerHTML&&(g(null==e.children),g("object"==typeof e.dangerouslySetInnerHTML&&"__html"in e.dangerouslySetInnerHTML)),g(null==e.style||"object"==typeof e.style))}function o(e,t,n,r){var o=d.findReactContainerForID(e);if(o){var i=o.nodeType===D?o.ownerDocument:o;E(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function i(e){P.call(T,e)||(g(I.test(e)),T[e]=!0)}function a(e){i(e),this._tag=e,this._renderedChildren=null,this._previousStyleCopy=null,this._rootNodeID=null}var u=e(5),s=e(10),l=e(11),c=e(30),p=e(35),d=e(68),f=e(69),h=e(73),m=e(27),v=e(114),g=e(133),y=(e(134),e(139)),C=(e(150),c.deleteListener),E=c.listenTo,b=c.registrationNameModules,_={string:!0,number:!0},x=y({style:null}),D=1,M=null,N={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},I=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,T={},P={}.hasOwnProperty;a.displayName="ReactDOMComponent",a.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e,r(this._currentElement.props);var o=N[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t,n)+o},_createOpenTagMarkupAndPutListeners:function(e){var t=this._currentElement.props,n="<"+this._tag;for(var r in t)if(t.hasOwnProperty(r)){var i=t[r];if(null!=i)if(b.hasOwnProperty(r))o(this._rootNodeID,r,i,e);else{r===x&&(i&&(i=this._previousStyleCopy=m({},t.style)),i=u.createMarkupForStyles(i));var a=l.createMarkupForProperty(r,i);a&&(n+=" "+a)}}if(e.renderToStaticMarkup)return n+">";var s=l.createMarkupForID(this._rootNodeID);return n+" "+s+">"},_createContentMarkup:function(e,t){var n="";("listing"===this._tag||"pre"===this._tag||"textarea"===this._tag)&&(n="\n");var r=this._currentElement.props,o=r.dangerouslySetInnerHTML;if(null!=o){if(null!=o.__html)return n+o.__html}else{var i=_[typeof r.children]?r.children:null,a=null!=i?null:r.children;if(null!=i)return n+v(i);if(null!=a){var u=this.mountChildren(a,e,t);return n+u.join("")}}return n},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,o){r(this._currentElement.props),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e,o)},_updateDOMProperties:function(e,t){var n,r,i,a=this._currentElement.props;for(n in e)if(!a.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===x){var u=this._previousStyleCopy;for(r in u)u.hasOwnProperty(r)&&(i=i||{},i[r]="");this._previousStyleCopy=null}else b.hasOwnProperty(n)?C(this._rootNodeID,n):(s.isStandardName[n]||s.isCustomAttribute(n))&&M.deletePropertyByID(this._rootNodeID,n);for(n in a){var l=a[n],c=n===x?this._previousStyleCopy:e[n];if(a.hasOwnProperty(n)&&l!==c)if(n===x)if(l?l=this._previousStyleCopy=m({},l):this._previousStyleCopy=null,c){for(r in c)!c.hasOwnProperty(r)||l&&l.hasOwnProperty(r)||(i=i||{},i[r]="");for(r in l)l.hasOwnProperty(r)&&c[r]!==l[r]&&(i=i||{},i[r]=l[r])}else i=l;else b.hasOwnProperty(n)?o(this._rootNodeID,n,l,t):(s.isStandardName[n]||s.isCustomAttribute(n))&&M.updatePropertyByID(this._rootNodeID,n,l)}i&&M.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t,n){var r=this._currentElement.props,o=_[typeof e.children]?e.children:null,i=_[typeof r.children]?r.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,u=r.dangerouslySetInnerHTML&&r.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,l=null!=i?null:r.children,c=null!=o||null!=a,p=null!=i||null!=u;null!=s&&null==l?this.updateChildren(null,t,n):c&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=u?a!==u&&M.updateInnerHTMLByID(this._rootNodeID,u):null!=l&&this.updateChildren(l,t,n)},unmountComponent:function(){this.unmountChildren(),c.deleteAllListeners(this._rootNodeID),p.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null}},h.measureMethods(a,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),m(a.prototype,a.Mixin,f.Mixin),a.injection={injectIDOperations:function(e){a.BackendIDOperations=M=e}},t.exports=a},{10:10,11:11,114:114,133:133,134:134,139:139,150:150,27:27,30:30,35:35,5:5,68:68,69:69,73:73}],43:[function(e,t,n){"use strict";var r=e(15),o=e(25),i=e(29),a=e(33),u=e(55),s=u.createFactory("form"),l=a.createClass({displayName:"ReactDOMForm",tagName:"FORM",mixins:[i,o],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(r.topLevelTypes.topSubmit,"submit")}});t.exports=l},{15:15,25:25,29:29,33:33,55:55}],44:[function(e,t,n){"use strict";var r=e(5),o=e(9),i=e(11),a=e(68),u=e(73),s=e(133),l=e(144),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},p={updatePropertyByID:function(e,t,n){var r=a.getNode(e);s(!c.hasOwnProperty(t)),null!=n?i.setValueForProperty(r,t,n):i.deleteValueForProperty(r,t)},deletePropertyByID:function(e,t,n){var r=a.getNode(e);s(!c.hasOwnProperty(t)),i.deleteValueForProperty(r,t,n)},updateStylesByID:function(e,t){var n=a.getNode(e);r.setValueForStyles(n,t)},updateInnerHTMLByID:function(e,t){var n=a.getNode(e);l(n,t)},updateTextContentByID:function(e,t){var n=a.getNode(e);o.updateTextContent(n,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=a.getNode(e);o.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=a.getNode(e[n].parentID);o.processUpdates(e,t)}};u.measureMethods(p,"ReactDOMIDOperations",{updatePropertyByID:"updatePropertyByID",deletePropertyByID:"deletePropertyByID",updateStylesByID:"updateStylesByID",updateInnerHTMLByID:"updateInnerHTMLByID",updateTextContentByID:"updateTextContentByID",dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),t.exports=p},{11:11,133:133,144:144,5:5,68:68,73:73,9:9}],45:[function(e,t,n){"use strict";var r=e(15),o=e(25),i=e(29),a=e(33),u=e(55),s=u.createFactory("iframe"),l=a.createClass({displayName:"ReactDOMIframe",tagName:"IFRAME",mixins:[i,o],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load")}});t.exports=l},{15:15,25:25,29:29,33:33,55:55}],46:[function(e,t,n){"use strict";var r=e(15),o=e(25),i=e(29),a=e(33),u=e(55),s=u.createFactory("img"),l=a.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[i,o],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(r.topLevelTypes.topError,"error")}});t.exports=l},{15:15,25:25,29:29,33:33,55:55}],47:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var o=e(2),i=e(11),a=e(24),u=e(29),s=e(33),l=e(55),c=e(68),p=e(85),d=e(27),f=e(133),h=l.createFactory("input"),m={},v=s.createClass({displayName:"ReactDOMInput",tagName:"INPUT",mixins:[o,a.Mixin,u],getInitialState:function(){var e=this.props.defaultValue;return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=d({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=a.getValue(this);e.value=null!=t?t:this.state.initialValue;var n=a.getChecked(this);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,h(e,this.props.children)},componentDidMount:function(){var e=c.getID(this.getDOMNode());m[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=c.getID(e);delete m[t]},componentDidUpdate:function(e,t,n){var r=this.getDOMNode();null!=this.props.checked&&i.setValueForProperty(r,"checked",this.props.checked||!1);var o=a.getValue(this);null!=o&&i.setValueForProperty(r,"value",""+o)},_handleChange:function(e){var t,n=a.getOnChange(this);n&&(t=n.call(this,e)),p.asap(r,this);var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var i=this.getDOMNode(),u=i;u.parentNode;)u=u.parentNode;for(var s=u.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),l=0,d=s.length;d>l;l++){var h=s[l];if(h!==i&&h.form===i.form){var v=c.getID(h);f(v);var g=m[v];f(g),p.asap(r,g)}}}return t}});t.exports=v},{11:11,133:133,2:2,24:24,27:27,29:29,33:33,55:55,68:68,85:85}],48:[function(e,t,n){"use strict";var r=e(29),o=e(33),i=e(55),a=(e(150),i.createFactory("option")),u=o.createClass({displayName:"ReactDOMOption",tagName:"OPTION",mixins:[r],componentWillMount:function(){},render:function(){return a(this.props,this.props.children)}});t.exports=u},{150:150,29:29,33:33,55:55}],49:[function(e,t,n){"use strict";function r(){if(this._pendingUpdate){this._pendingUpdate=!1;var e=u.getValue(this);null!=e&&this.isMounted()&&i(this,e)}}function o(e,t,n){if(null==e[t])return null;if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function i(e,t){var n,r,o,i=e.getDOMNode().options;if(e.props.multiple){for(n={},r=0,o=t.length;o>r;r++)n[""+t[r]]=!0;for(r=0,o=i.length;o>r;r++){var a=n.hasOwnProperty(i[r].value);i[r].selected!==a&&(i[r].selected=a)}}else{for(n=""+t,r=0,o=i.length;o>r;r++)if(i[r].value===n)return void(i[r].selected=!0);i.length&&(i[0].selected=!0)}}var a=e(2),u=e(24),s=e(29),l=e(33),c=e(55),p=e(85),d=e(27),f=c.createFactory("select"),h=l.createClass({displayName:"ReactDOMSelect",tagName:"SELECT",mixins:[a,u.Mixin,s],propTypes:{defaultValue:o,value:o},render:function(){var e=d({},this.props);return e.onChange=this._handleChange,e.value=null,f(e,this.props.children)},componentWillMount:function(){this._pendingUpdate=!1},componentDidMount:function(){var e=u.getValue(this);null!=e?i(this,e):null!=this.props.defaultValue&&i(this,this.props.defaultValue)},componentDidUpdate:function(e){var t=u.getValue(this);null!=t?(this._pendingUpdate=!1,i(this,t)):!e.multiple!=!this.props.multiple&&(null!=this.props.defaultValue?i(this,this.props.defaultValue):i(this,this.props.multiple?[]:""))},_handleChange:function(e){var t,n=u.getOnChange(this);return n&&(t=n.call(this,e)),this._pendingUpdate=!0,p.asap(r,this),t}});t.exports=h},{2:2,24:24,27:27,29:29,33:33,55:55,85:85}],50:[function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,u=t.getRangeAt(0),s=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=s?0:u.toString().length,c=u.cloneRange();c.selectNodeContents(e),c.setEnd(u.startContainer,u.startOffset);var p=r(c.startContainer,c.startOffset,c.endContainer,c.endOffset),d=p?0:c.toString().length,f=d+l,h=document.createRange();h.setStart(n,o),h.setEnd(i,a);var m=h.collapsed;return{start:m?f:d,end:m?d:f}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function u(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var u=l(e,o),s=l(e,i);if(u&&s){var p=document.createRange();p.setStart(u.node,u.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(s.node,s.offset)):(p.setEnd(s.node,s.offset),n.addRange(p))}}}var s=e(21),l=e(126),c=e(128),p=s.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:i,setOffsets:p?a:u};t.exports=d},{126:126,128:128,21:21}],51:[function(e,t,n){"use strict";var r=e(11),o=e(35),i=e(42),a=e(27),u=e(114),s=function(e){};a(s.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){this._rootNodeID=e;var o=u(this._stringText);return t.renderToStaticMarkup?o:"<span "+r.createMarkupForID(e)+">"+o+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;n!==this._stringText&&(this._stringText=n,i.BackendIDOperations.updateTextContentByID(this._rootNodeID,n))}},unmountComponent:function(){o.unmountIDFromEnvironment(this._rootNodeID)}}),t.exports=s},{11:11,114:114,27:27,35:35,42:42}],52:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var o=e(2),i=e(11),a=e(24),u=e(29),s=e(33),l=e(55),c=e(85),p=e(27),d=e(133),f=(e(150),l.createFactory("textarea")),h=s.createClass({displayName:"ReactDOMTextarea",tagName:"TEXTAREA",mixins:[o,a.Mixin,u],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(d(null==e),Array.isArray(t)&&(d(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=a.getValue(this);return{initialValue:""+(null!=n?n:e)}},render:function(){var e=p({},this.props);return d(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,f(e,this.state.initialValue)},componentDidUpdate:function(e,t,n){var r=a.getValue(this);if(null!=r){var o=this.getDOMNode();i.setValueForProperty(o,"value",""+r)}},_handleChange:function(e){var t,n=a.getOnChange(this);return n&&(t=n.call(this,e)),c.asap(r,this),t}});t.exports=h},{11:11,133:133,150:150,2:2,24:24,27:27,29:29,33:33,55:55,85:85}],53:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=e(85),i=e(101),a=e(27),u=e(112),s={initialize:u,close:function(){d.isBatchingUpdates=!1}},l={initialize:u,close:o.flushBatchedUpdates.bind(o)},c=[l,s];a(r.prototype,i.Mixin,{getTransactionWrappers:function(){return c}});var p=new r,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o){var i=d.isBatchingUpdates;d.isBatchingUpdates=!0,i?e(t,n,r,o):p.perform(e,null,t,n,r,o)}};t.exports=d},{101:101,112:112,27:27,85:85}],54:[function(e,t,n){"use strict";function r(e){return h.createClass({tagName:e.toUpperCase(),render:function(){return new T(e,null,null,null,null,this.props)}})}function o(){R.EventEmitter.injectReactEventListener(P),R.EventPluginHub.injectEventPluginOrder(s),R.EventPluginHub.injectInstanceHandle(w),R.EventPluginHub.injectMount(O),R.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:L,EnterLeaveEventPlugin:l,ChangeEventPlugin:a,MobileSafariClickEventPlugin:d,SelectEventPlugin:A,BeforeInputEventPlugin:i}),R.NativeComponent.injectGenericComponentClass(g),R.NativeComponent.injectTextComponentClass(I),R.NativeComponent.injectAutoWrapper(r),R.Class.injectMixin(f),R.NativeComponent.injectComponentClasses({button:y,form:C,iframe:_,img:E,input:x,option:D,select:M,textarea:N,html:F("html"),head:F("head"),body:F("body")}),R.DOMProperty.injectDOMPropertyConfig(p),R.DOMProperty.injectDOMPropertyConfig(U),R.EmptyComponent.injectEmptyComponent("noscript"),R.Updates.injectReconcileTransaction(S),R.Updates.injectBatchingStrategy(v),R.RootIndex.injectCreateReactRootIndex(c.canUseDOM?u.createReactRootIndex:k.createReactRootIndex),R.Component.injectEnvironment(m),R.DOMComponent.injectIDOperations(b)}var i=e(3),a=e(7),u=e(8),s=e(13),l=e(14),c=e(21),p=e(23),d=e(26),f=e(29),h=e(33),m=e(35),v=e(53),g=e(42),y=e(41),C=e(43),E=e(46),b=e(44),_=e(45),x=e(47),D=e(48),M=e(49),N=e(52),I=e(51),T=e(55),P=e(60),R=e(62),w=e(64),O=e(68),S=e(78),A=e(87),k=e(88),L=e(89),U=e(86),F=e(109);

t.exports={inject:o}},{109:109,13:13,14:14,21:21,23:23,26:26,29:29,3:3,33:33,35:35,41:41,42:42,43:43,44:44,45:45,46:46,47:47,48:48,49:49,51:51,52:52,53:53,55:55,60:60,62:62,64:64,68:68,7:7,78:78,8:8,86:86,87:87,88:88,89:89}],55:[function(e,t,n){"use strict";var r=e(38),o=e(39),i=e(27),a=(e(150),{key:!0,ref:!0}),u=function(e,t,n,r,o,i){this.type=e,this.key=t,this.ref=n,this._owner=r,this._context=o,this.props=i};u.prototype={_isReactElement:!0},u.createElement=function(e,t,n){var i,s={},l=null,c=null;if(null!=t){c=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(s[i]=t[i])}var p=arguments.length-2;if(1===p)s.children=n;else if(p>1){for(var d=Array(p),f=0;p>f;f++)d[f]=arguments[f+2];s.children=d}if(e&&e.defaultProps){var h=e.defaultProps;for(i in h)"undefined"==typeof s[i]&&(s[i]=h[i])}return new u(e,l,c,o.current,r.current,s)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceProps=function(e,t){var n=new u(e.type,e.key,e.ref,e._owner,e._context,t);return n},u.cloneElement=function(e,t,n){var r,s=i({},e.props),l=e.key,c=e.ref,p=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,p=o.current),void 0!==t.key&&(l=""+t.key);for(r in t)t.hasOwnProperty(r)&&!a.hasOwnProperty(r)&&(s[r]=t[r])}var d=arguments.length-2;if(1===d)s.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];s.children=f}return new u(e.type,l,c,p,e._context,s)},u.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},t.exports=u},{150:150,27:27,38:38,39:39}],56:[function(e,t,n){"use strict";function r(){if(y.current){var e=y.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e){var t=e&&e.getPublicInstance();if(!t)return void 0;var n=t.constructor;return n?n.displayName||n.name||void 0:void 0}function i(){var e=y.current;return e&&o(e)||void 0}function a(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,s('Each child in an array or iterator should have a unique "key" prop.',e,t))}function u(e,t,n){D.test(e)&&s("Child objects should have non-numeric keys so ordering is preserved.",t,n)}function s(e,t,n){var r=i(),a="string"==typeof n?n:n.displayName||n.name,u=r||a,s=_[e]||(_[e]={});if(!s.hasOwnProperty(u)){s[u]=!0;var l="";if(t&&t._owner&&t._owner!==y.current){var c=o(t._owner);l=" It was passed a child from "+c+"."}}}function l(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];m.isValidElement(r)&&a(r,t)}else if(m.isValidElement(e))e._store.validated=!0;else if(e){var o=E(e);if(o){if(o!==e.entries)for(var i,s=o.call(e);!(i=s.next()).done;)m.isValidElement(i.value)&&a(i.value,t)}else if("object"==typeof e){var l=v.extractIfFragment(e);for(var c in l)l.hasOwnProperty(c)&&u(c,l[c],t)}}}function c(e,t,n,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{b("function"==typeof t[i]),a=t[i](n,i,e,o)}catch(u){a=u}a instanceof Error&&!(a.message in x)&&(x[a.message]=!0,r(this))}}function p(e,t){var n=t.type,r="string"==typeof n?n:n.displayName,o=t._owner?t._owner.getPublicInstance().constructor.displayName:null,i=e+"|"+r+"|"+o;if(!M.hasOwnProperty(i)){M[i]=!0;var a="";r&&(a=" <"+r+" />");var u="";o&&(u=" The element was created by "+o+".")}}function d(e,t){return e!==e?t!==t:0===e&&0===t?1/e===1/t:e===t}function f(e){if(e._store){var t=e._store.originalProps,n=e.props;for(var r in n)n.hasOwnProperty(r)&&(t.hasOwnProperty(r)&&d(t[r],n[r])||(p(r,e),t[r]=n[r]))}}function h(e){if(null!=e.type){var t=C.getComponentClassForElement(e),n=t.displayName||t.name;t.propTypes&&c(n,t.propTypes,e.props,g.prop),"function"==typeof t.getDefaultProps}}var m=e(55),v=e(61),g=e(75),y=(e(74),e(39)),C=e(71),E=e(124),b=e(133),_=(e(150),{}),x={},D=/^\d+$/,M={},N={checkAndWarnForMutatedProps:f,createElement:function(e,t,n){var r=m.createElement.apply(this,arguments);if(null==r)return r;for(var o=2;o<arguments.length;o++)l(arguments[o],e);return h(r),r},createFactory:function(e){var t=N.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=m.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)l(arguments[o],r.type);return h(r),r}};t.exports=N},{124:124,133:133,150:150,39:39,55:55,61:61,71:71,74:74,75:75}],57:[function(e,t,n){"use strict";function r(e){c[e]=!0}function o(e){delete c[e]}function i(e){return!!c[e]}var a,u=e(55),s=e(65),l=e(133),c={},p={injectEmptyComponent:function(e){a=u.createFactory(e)}},d=function(){};d.prototype.componentDidMount=function(){var e=s.get(this);e&&r(e._rootNodeID)},d.prototype.componentWillUnmount=function(){var e=s.get(this);e&&o(e._rootNodeID)},d.prototype.render=function(){return l(a),a()};var f=u.createElement(d),h={emptyElement:f,injection:p,isNullComponentID:i};t.exports=h},{133:133,55:55,65:65}],58:[function(e,t,n){"use strict";var r={guard:function(e,t){return e}};t.exports=r},{}],59:[function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue()}var o=e(17),i={handleTopLevel:function(e,t,n,i){var a=o.extractEvents(e,t,n,i);r(a)}};t.exports=i},{17:17}],60:[function(e,t,n){"use strict";function r(e){var t=p.getID(e),n=c.getReactRootIDFromNodeID(t),r=p.findReactContainerForID(n),o=p.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){for(var t=p.getFirstReactDOM(h(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0,i=e.ancestors.length;i>o;o++){t=e.ancestors[o];var a=p.getID(t)||"";v._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function a(e){var t=m(window);e(t)}var u=e(16),s=e(21),l=e(28),c=e(64),p=e(68),d=e(85),f=e(27),h=e(123),m=e(129);f(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?u.listen(r,t,v.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?u.capture(r,t,v.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(v._enabled){var n=o.getPooled(e,t);try{d.batchedUpdates(i,n)}finally{o.release(n)}}}};t.exports=v},{123:123,129:129,16:16,21:21,27:27,28:28,64:64,68:68,85:85}],61:[function(e,t,n){"use strict";var r=(e(55),e(150),{create:function(e){return e},extract:function(e){return e},extractIfFragment:function(e){return e}});t.exports=r},{150:150,55:55}],62:[function(e,t,n){"use strict";var r=e(10),o=e(17),i=e(36),a=e(33),u=e(57),s=e(30),l=e(71),c=e(42),p=e(73),d=e(81),f=e(85),h={Component:i.injection,Class:a.injection,DOMComponent:c.injection,DOMProperty:r.injection,EmptyComponent:u.injection,EventPluginHub:o.injection,EventEmitter:s.injection,NativeComponent:l.injection,Perf:p.injection,RootIndex:d.injection,Updates:f.injection};t.exports=h},{10:10,17:17,30:30,33:33,36:36,42:42,57:57,71:71,73:73,81:81,85:85}],63:[function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=e(50),i=e(107),a=e(117),u=e(119),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=u();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=u(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};t.exports=s},{107:107,117:117,119:119,50:50}],64:[function(e,t,n){"use strict";function r(e){return f+e.toString(36)}function o(e,t){return e.charAt(t)===f||t===e.length}function i(e){return""===e||e.charAt(0)===f&&e.charAt(e.length-1)!==f}function a(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function u(e){return e?e.substr(0,e.lastIndexOf(f)):""}function s(e,t){if(d(i(e)&&i(t)),d(a(e,t)),e===t)return e;var n,r=e.length+h;for(n=r;n<t.length&&!o(t,n);n++);return t.substr(0,n)}function l(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,a=0;n>=a;a++)if(o(e,a)&&o(t,a))r=a;else if(e.charAt(a)!==t.charAt(a))break;var u=e.substr(0,r);return d(i(u)),u}function c(e,t,n,r,o,i){e=e||"",t=t||"",d(e!==t);var l=a(t,e);d(l||a(e,t));for(var c=0,p=l?u:s,f=e;;f=p(f,t)){var h;if(o&&f===e||i&&f===t||(h=n(f,l,r)),h===!1||f===t)break;d(c++<m)}}var p=e(81),d=e(133),f=".",h=f.length,m=100,v={createReactRootID:function(){return r(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===f&&e.length>1){var t=e.indexOf(f,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=l(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},_getFirstCommonAncestorID:l,_getNextDescendantID:s,isAncestorIDOf:a,SEPARATOR:f};t.exports=v},{133:133,81:81}],65:[function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=r},{}],66:[function(e,t,n){"use strict";var r={currentlyMountingInstance:null,currentlyUnmountingInstance:null};t.exports=r},{}],67:[function(e,t,n){"use strict";var r=e(104),o={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(">"," "+o.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var n=t.getAttribute(o.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var i=r(e);return i===n}};t.exports=o},{104:104}],68:[function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){var t=P(e);return t&&K.getID(t)}function i(e){var t=a(e);if(t)if(L.hasOwnProperty(t)){var n=L[t];n!==e&&(w(!c(n,t)),L[t]=e)}else L[t]=e;return t}function a(e){return e&&e.getAttribute&&e.getAttribute(k)||""}function u(e,t){var n=a(e);n!==t&&delete L[n],e.setAttribute(k,t),L[t]=e}function s(e){return L.hasOwnProperty(e)&&c(L[e],e)||(L[e]=K.findReactNodeByID(e)),L[e]}function l(e){var t=b.get(e)._rootNodeID;return C.isNullComponentID(t)?null:(L.hasOwnProperty(t)&&c(L[t],t)||(L[t]=K.findReactNodeByID(t)),L[t])}function c(e,t){if(e){w(a(e)===t);var n=K.findReactContainerForID(t);if(n&&T(n,e))return!0}return!1}function p(e){delete L[e]}function d(e){var t=L[e];return t&&c(t,e)?void(W=t):!1}function f(e){W=null,E.traverseAncestors(e,d);var t=W;return W=null,t}function h(e,t,n,r,o){var i=D.mountComponent(e,t,r,I);e._isTopLevel=!0,K._mountImageIntoNode(i,n,o)}function m(e,t,n,r){var o=N.ReactReconcileTransaction.getPooled();o.perform(h,null,e,t,n,o,r),N.ReactReconcileTransaction.release(o)}var v=e(10),g=e(30),y=(e(39),e(55)),C=(e(56),e(57)),E=e(64),b=e(65),_=e(67),x=e(73),D=e(79),M=e(84),N=e(85),I=e(113),T=e(107),P=e(127),R=e(132),w=e(133),O=e(144),S=e(147),A=(e(150),E.SEPARATOR),k=v.ID_ATTRIBUTE_NAME,L={},U=1,F=9,B={},V={},j=[],W=null,K={_instancesByReactRootID:B,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return K.scrollMonitor(n,function(){M.enqueueElementInternal(e,t),r&&M.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){w(t&&(t.nodeType===U||t.nodeType===F)),g.ensureScrollValueMonitoring();var n=K.registerContainer(t);return B[n]=e,n},_renderNewRootComponent:function(e,t,n){var r=R(e,null),o=K._registerComponent(r,t);return N.batchedUpdates(m,r,o,t,n),r},render:function(e,t,n){w(y.isValidElement(e));var r=B[o(t)];if(r){var i=r._currentElement;if(S(i,e))return K._updateRootComponent(r,e,t,n).getPublicInstance();K.unmountComponentAtNode(t)}var a=P(t),u=a&&K.isRenderedByReact(a),s=u&&!r,l=K._renderNewRootComponent(e,t,s).getPublicInstance();return n&&n.call(l),l},constructAndRenderComponent:function(e,t,n){var r=y.createElement(e,t);return K.render(r,n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return w(r),K.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=o(e);return t&&(t=E.getReactRootIDFromNodeID(t)),t||(t=E.createReactRootID()),V[t]=e,t},unmountComponentAtNode:function(e){w(e&&(e.nodeType===U||e.nodeType===F));var t=o(e),n=B[t];return n?(K.unmountComponentFromNode(n,e),delete B[t],delete V[t],!0):!1},unmountComponentFromNode:function(e,t){for(D.unmountComponent(e),t.nodeType===F&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=E.getReactRootIDFromNodeID(e),n=V[t];return n},findReactNodeByID:function(e){var t=K.findReactContainerForID(e);return K.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=K.getID(e);return t?t.charAt(0)===A:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(K.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=j,r=0,o=f(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var u=K.getID(a);u?t===u?i=a:E.isAncestorIDOf(u,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,w(!1)},_mountImageIntoNode:function(e,t,n){if(w(t&&(t.nodeType===U||t.nodeType===F)),n){var o=P(t);if(_.canReuseMarkup(e,o))return;var i=o.getAttribute(_.CHECKSUM_ATTR_NAME);o.removeAttribute(_.CHECKSUM_ATTR_NAME);var a=o.outerHTML;o.setAttribute(_.CHECKSUM_ATTR_NAME,i);var u=r(e,a);" (client) "+e.substring(u-20,u+20)+"\n (server) "+a.substring(u-20,u+20),w(t.nodeType!==F)}w(t.nodeType!==F),O(t,e)},getReactRootID:o,getID:i,setID:u,getNode:s,getNodeFromInstance:l,purgeID:p};x.measureMethods(K,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),t.exports=K},{10:10,107:107,113:113,127:127,132:132,133:133,144:144,147:147,150:150,30:30,39:39,55:55,56:56,57:57,64:64,65:65,67:67,73:73,79:79,84:84,85:85}],69:[function(e,t,n){"use strict";function r(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:m.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function o(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function a(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function u(){h.length&&(l.processChildrenUpdates(h,m),s())}function s(){h.length=0,m.length=0}var l=e(36),c=e(70),p=e(79),d=e(31),f=0,h=[],m=[],v={Mixin:{mountChildren:function(e,t,n){var r=d.instantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var u=r[a],s=this._rootNodeID+a,l=p.mountComponent(u,s,t,n);u._mountIndex=i,o.push(l),i++}return o},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;d.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{f--,f||(t?s():u())}},updateChildren:function(e,t,n){f++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{f--,f||(r?s():u())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=d.updateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var i,a=0,u=0;for(i in o)if(o.hasOwnProperty(i)){var s=r&&r[i],l=o[i];s===l?(this.moveChild(s,u,a),a=Math.max(s._mountIndex,a),s._mountIndex=u):(s&&(a=Math.max(s._mountIndex,a),this._unmountChildByName(s,i)),this._mountChildByNameAtIndex(l,i,u,t,n)),u++}for(i in r)!r.hasOwnProperty(i)||o&&o.hasOwnProperty(i)||this._unmountChildByName(r[i],i)}},unmountChildren:function(){var e=this._renderedChildren;d.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var i=this._rootNodeID+t,a=p.mountComponent(e,i,r,o);e._mountIndex=n,this.createChild(e,a)},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null}}};t.exports=v},{31:31,36:36,70:70,79:79}],70:[function(e,t,n){"use strict";var r=e(138),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=o},{138:138}],71:[function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=l(t)),n}function o(e){return s(c),new c(e.type,e.props)}function i(e){return new d(e)}function a(e){return e instanceof d}var u=e(27),s=e(133),l=null,c=null,p={},d=null,f={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){u(p,e)},injectAutoWrapper:function(e){l=e}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:f};t.exports=h},{133:133,27:27}],72:[function(e,t,n){"use strict";var r=e(133),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){r(o.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(o.isValidOwner(n)),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};t.exports=o},{133:133}],73:[function(e,t,n){"use strict";function r(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:r,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){o.storedMeasure=e}}};t.exports=o},{}],74:[function(e,t,n){"use strict";var r={};t.exports=r},{}],75:[function(e,t,n){"use strict";var r=e(138),o=r({prop:null,context:null,childContext:null});t.exports=o},{138:138}],76:[function(e,t,n){"use strict";function r(e){function t(t,n,r,o,i){if(o=o||b,null==n[r]){var a=C[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o){var i=t[n],a=m(i);if(a!==e){var u=C[o],s=v(i);return new Error("Invalid "+u+" `"+n+"` of type `"+s+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}return null}return r(t)}function i(){return r(E.thatReturns(null))}function a(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=C[o],u=m(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var s=0;s<i.length;s++){var l=e(i,s,r,o);if(l instanceof Error)return l}return null}return r(t)}function u(){function e(e,t,n,r){if(!g.isValidElement(e[t])){var o=C[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}return null}return r(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=C[o],a=e.name||b;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}return null}return r(t)}function l(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return null;var u=C[o],s=JSON.stringify(e);return new Error("Invalid "+u+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+s+"."))}return r(t)}function c(e){function t(t,n,r,o){var i=t[n],a=m(i);if("object"!==a){var u=C[o];return new Error("Invalid "+u+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))}for(var s in i)if(i.hasOwnProperty(s)){var l=e(i,s,r,o);if(l instanceof Error)return l}return null}return r(t)}function p(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return null}var u=C[o];return new Error("Invalid "+u+" `"+n+"` supplied to "+("`"+r+"`."))}return r(t)}function d(){function e(e,t,n,r){if(!h(e[t])){var o=C[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function f(e){function t(t,n,r,o){var i=t[n],a=m(i);if("object"!==a){var u=C[o];return new Error("Invalid "+u+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var s in e){var l=e[s];if(l){var c=l(i,s,r,o);if(c)return c}}return null}return r(t)}function h(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(h);if(null===e||g.isValidElement(e))return!0;e=y.extractIfFragment(e);for(var t in e)if(!h(e[t]))return!1;return!0;default:return!1}}function m(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function v(e){var t=m(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var g=e(55),y=e(61),C=e(74),E=e(112),b="<<anonymous>>",_=u(),x=d(),D={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:i(),arrayOf:a,element:_,instanceOf:s,node:x,objectOf:c,oneOf:l,oneOfType:p,shape:f};t.exports=D},{112:112,55:55,61:61,74:74}],77:[function(e,t,n){"use strict";function r(){this.listenersToPut=[]}var o=e(28),i=e(30),a=e(27);a(r.prototype,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];i.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),o.addPoolingTo(r),t.exports=r},{27:27,28:28,30:30}],78:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.putListenerQueue=s.getPooled()}var o=e(6),i=e(28),a=e(30),u=e(63),s=e(77),l=e(101),c=e(27),p={initialize:u.getSelectionInformation,close:u.restoreSelection},d={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},m=[h,p,d,f],v={getTransactionWrappers:function(){return m},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};c(r.prototype,l.Mixin,v),i.addPoolingTo(r),t.exports=r},{101:101,27:27,28:28,30:30,6:6,63:63,77:77}],79:[function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=e(80),i=(e(56),{mountComponent:function(e,t,n,o){var i=e.mountComponent(t,n,o);return n.getReactMountReady().enqueue(r,e),i},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||null==t._owner){var u=o.shouldUpdateRefs(a,t);u&&o.detachRefs(e,a),e.receiveComponent(t,n,i),u&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}});t.exports=i},{56:56,80:80}],80:[function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=e(72),a={};a.attachRefs=function(e,t){var n=t.ref;null!=n&&r(n,e,t._owner)},a.shouldUpdateRefs=function(e,t){return t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){var n=t.ref;null!=n&&o(n,e,t._owner)},t.exports=a},{72:72}],81:[function(e,t,n){"use strict";var r={injectCreateReactRootIndex:function(e){o.createReactRootIndex=e}},o={createReactRootIndex:null,injection:r};t.exports=o},{}],82:[function(e,t,n){"use strict";function r(e){p(i.isValidElement(e));var t;try{var n=a.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=c(e,null),o=r.mountComponent(n,t,l);return u.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function o(e){p(i.isValidElement(e));var t;try{var n=a.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=c(e,null);return r.mountComponent(n,t,l)},null)}finally{s.release(t)}}var i=e(55),a=e(64),u=e(67),s=e(83),l=e(113),c=e(132),p=e(133);t.exports={renderToString:r,renderToStaticMarkup:o}},{113:113,132:132,133:133,55:55,64:64,67:67,83:83}],83:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null),this.putListenerQueue=a.getPooled()}var o=e(28),i=e(6),a=e(77),u=e(101),s=e(27),l=e(112),c={initialize:function(){this.reactMountReady.reset()},close:l},p={initialize:function(){this.putListenerQueue.reset()},close:l},d=[p,c],f={getTransactionWrappers:function(){return d},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null,a.release(this.putListenerQueue),this.putListenerQueue=null}};s(r.prototype,u.Mixin,f),o.addPoolingTo(r),t.exports=r},{101:101,112:112,27:27,28:28,6:6,77:77}],84:[function(e,t,n){"use strict";function r(e){e!==i.currentlyMountingInstance&&l.enqueueUpdate(e)}function o(e,t){p(null==a.current);var n=s.get(e);return n?n===i.currentlyUnmountingInstance?null:n:null}var i=e(66),a=e(39),u=e(55),s=e(65),l=e(85),c=e(27),p=e(133),d=(e(150),{enqueueCallback:function(e,t){p("function"==typeof t);var n=o(e);return n&&n!==i.currentlyMountingInstance?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){p("function"==typeof t),e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");if(n){p(n._isTopLevel);var i=n._pendingElement||n._currentElement,a=c({},i.props,t);n._pendingElement=u.cloneAndReplaceProps(i,a),r(n)}},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");if(n){p(n._isTopLevel);var i=n._pendingElement||n._currentElement;n._pendingElement=u.cloneAndReplaceProps(i,t),r(n)}},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});t.exports=d},{133:133,150:150,27:27,39:39,55:55,65:65,66:66,85:85}],85:[function(e,t,n){"use strict";function r(){v(N.ReactReconcileTransaction&&E)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=N.ReactReconcileTransaction.getPooled()}function i(e,t,n,o,i){r(),E.batchedUpdates(e,t,n,o,i)}function a(e,t){return e._mountOrder-t._mountOrder}function u(e){var t=e.dirtyComponentsLength;v(t===g.length),g.sort(a);for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,f.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var i=0;i<o.length;i++)e.callbackQueue.enqueue(o[i],r.getPublicInstance())}}function s(e){return r(),E.isBatchingUpdates?void g.push(e):void E.batchedUpdates(s,e)}function l(e,t){v(E.isBatchingUpdates),y.enqueue(e,t),C=!0}var c=e(6),p=e(28),d=(e(39),e(73)),f=e(79),h=e(101),m=e(27),v=e(133),g=(e(150),[]),y=c.getPooled(),C=!1,E=null,b={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),D()):g.length=0}},_={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},x=[b,_];m(o.prototype,h.Mixin,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,N.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return h.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var D=function(){for(;g.length||C;){if(g.length){var e=o.getPooled();e.perform(u,null,e),o.release(e)}if(C){C=!1;var t=y;y=c.getPooled(),t.notifyAll(),c.release(t)}}};D=d.measure("ReactUpdates","flushBatchedUpdates",D);var M={injectReconcileTransaction:function(e){v(e),N.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){v(e),v("function"==typeof e.batchedUpdates),v("boolean"==typeof e.isBatchingUpdates),E=e}},N={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:s,flushBatchedUpdates:D,injection:M,asap:l};t.exports=N},{101:101,133:133,150:150,27:27,28:28,39:39,6:6,73:73,79:79}],86:[function(e,t,n){"use strict";var r=e(10),o=r.injection.MUST_USE_ATTRIBUTE,i={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,y1:o,y2:o,y:o},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}};t.exports=i},{10:10}],87:[function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e){if(y||null==m||m!==l())return null;var t=r(m);if(!g||!d(g,t)){g=t;var n=s.getPooled(h.select,v,e);return n.type="select",n.target=m,a.accumulateTwoPhaseDispatches(n),n}}var i=e(15),a=e(20),u=e(63),s=e(93),l=e(119),c=e(136),p=e(139),d=e(146),f=i.topLevelTypes,h={select:{phasedRegistrationNames:{bubbled:p({onSelect:null}),captured:p({onSelectCapture:null})},dependencies:[f.topBlur,f.topContextMenu,f.topFocus,f.topKeyDown,f.topMouseDown,f.topMouseUp,f.topSelectionChange]
}},m=null,v=null,g=null,y=!1,C={eventTypes:h,extractEvents:function(e,t,n,r){switch(e){case f.topFocus:(c(t)||"true"===t.contentEditable)&&(m=t,v=n,g=null);break;case f.topBlur:m=null,v=null,g=null;break;case f.topMouseDown:y=!0;break;case f.topContextMenu:case f.topMouseUp:return y=!1,o(r);case f.topSelectionChange:case f.topKeyDown:case f.topKeyUp:return o(r)}}};t.exports=C},{119:119,136:136,139:139,146:146,15:15,20:20,63:63,93:93}],88:[function(e,t,n){"use strict";var r=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*r)}};t.exports=o},{}],89:[function(e,t,n){"use strict";var r=e(15),o=e(19),i=e(20),a=e(90),u=e(93),s=e(94),l=e(96),c=e(97),p=e(92),d=e(98),f=e(99),h=e(100),m=e(120),v=e(133),g=e(139),y=(e(150),r.topLevelTypes),C={blur:{phasedRegistrationNames:{bubbled:g({onBlur:!0}),captured:g({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:g({onClick:!0}),captured:g({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:g({onContextMenu:!0}),captured:g({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:g({onCopy:!0}),captured:g({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:g({onCut:!0}),captured:g({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:g({onDoubleClick:!0}),captured:g({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:g({onDrag:!0}),captured:g({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:g({onDragEnd:!0}),captured:g({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:g({onDragEnter:!0}),captured:g({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:g({onDragExit:!0}),captured:g({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:g({onDragLeave:!0}),captured:g({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:g({onDragOver:!0}),captured:g({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:g({onDragStart:!0}),captured:g({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:g({onDrop:!0}),captured:g({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:g({onFocus:!0}),captured:g({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:g({onInput:!0}),captured:g({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:g({onKeyDown:!0}),captured:g({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:g({onKeyPress:!0}),captured:g({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:g({onKeyUp:!0}),captured:g({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:g({onLoad:!0}),captured:g({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:g({onError:!0}),captured:g({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:g({onMouseDown:!0}),captured:g({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:g({onMouseMove:!0}),captured:g({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:g({onMouseOut:!0}),captured:g({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:g({onMouseOver:!0}),captured:g({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:g({onMouseUp:!0}),captured:g({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:g({onPaste:!0}),captured:g({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:g({onReset:!0}),captured:g({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:g({onScroll:!0}),captured:g({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:g({onSubmit:!0}),captured:g({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:g({onTouchCancel:!0}),captured:g({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:g({onTouchEnd:!0}),captured:g({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:g({onTouchMove:!0}),captured:g({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:g({onTouchStart:!0}),captured:g({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:g({onWheel:!0}),captured:g({onWheelCapture:!0})}}},E={topBlur:C.blur,topClick:C.click,topContextMenu:C.contextMenu,topCopy:C.copy,topCut:C.cut,topDoubleClick:C.doubleClick,topDrag:C.drag,topDragEnd:C.dragEnd,topDragEnter:C.dragEnter,topDragExit:C.dragExit,topDragLeave:C.dragLeave,topDragOver:C.dragOver,topDragStart:C.dragStart,topDrop:C.drop,topError:C.error,topFocus:C.focus,topInput:C.input,topKeyDown:C.keyDown,topKeyPress:C.keyPress,topKeyUp:C.keyUp,topLoad:C.load,topMouseDown:C.mouseDown,topMouseMove:C.mouseMove,topMouseOut:C.mouseOut,topMouseOver:C.mouseOver,topMouseUp:C.mouseUp,topPaste:C.paste,topReset:C.reset,topScroll:C.scroll,topSubmit:C.submit,topTouchCancel:C.touchCancel,topTouchEnd:C.touchEnd,topTouchMove:C.touchMove,topTouchStart:C.touchStart,topWheel:C.wheel};for(var b in E)E[b].dependencies=[b];var _={eventTypes:C,executeDispatch:function(e,t,n){var r=o.executeDispatch(e,t,n);r===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var o=E[e];if(!o)return null;var g;switch(e){case y.topInput:case y.topLoad:case y.topError:case y.topReset:case y.topSubmit:g=u;break;case y.topKeyPress:if(0===m(r))return null;case y.topKeyDown:case y.topKeyUp:g=l;break;case y.topBlur:case y.topFocus:g=s;break;case y.topClick:if(2===r.button)return null;case y.topContextMenu:case y.topDoubleClick:case y.topMouseDown:case y.topMouseMove:case y.topMouseOut:case y.topMouseOver:case y.topMouseUp:g=c;break;case y.topDrag:case y.topDragEnd:case y.topDragEnter:case y.topDragExit:case y.topDragLeave:case y.topDragOver:case y.topDragStart:case y.topDrop:g=p;break;case y.topTouchCancel:case y.topTouchEnd:case y.topTouchMove:case y.topTouchStart:g=d;break;case y.topScroll:g=f;break;case y.topWheel:g=h;break;case y.topCopy:case y.topCut:case y.topPaste:g=a}v(g);var C=g.getPooled(o,n,r);return i.accumulateTwoPhaseDispatches(C),C}};t.exports=_},{100:100,120:120,133:133,139:139,15:15,150:150,19:19,20:20,90:90,92:92,93:93,94:94,96:96,97:97,98:98,99:99}],90:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(93),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),t.exports=r},{93:93}],91:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(93),i={data:null};o.augmentClass(r,i),t.exports=r},{93:93}],92:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(97),i={dataTransfer:null};o.augmentClass(r,i),t.exports=r},{97:97}],93:[function(e,t,n){"use strict";function r(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var o in r)if(r.hasOwnProperty(o)){var i=r[o];i?this[o]=i(n):this[o]=n[o]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;u?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse}var o=e(28),i=e(27),a=e(112),u=e(123),s={type:null,target:u,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};i(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);i(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.threeArgumentPooler)},o.addPoolingTo(r,o.threeArgumentPooler),t.exports=r},{112:112,123:123,27:27,28:28}],94:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(99),i={relatedTarget:null};o.augmentClass(r,i),t.exports=r},{99:99}],95:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(93),i={data:null};o.augmentClass(r,i),t.exports=r},{93:93}],96:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(99),i=e(120),a=e(121),u=e(122),s={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:u,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,s),t.exports=r},{120:120,121:121,122:122,99:99}],97:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(99),i=e(102),a=e(122),u={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,u),t.exports=r},{102:102,122:122,99:99}],98:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(99),i=e(122),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),t.exports=r},{122:122,99:99}],99:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(93),i=e(123),a={view:function(e){if(e.view)return e.view;var t=i(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),t.exports=r},{123:123,93:93}],100:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(97),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),t.exports=r},{97:97}],101:[function(e,t,n){"use strict";var r=e(133),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,u,s){r(!this.isInTransaction());var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=e.call(t,n,o,i,a,u,s),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){r(this.isInTransaction());for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],u=this.wrapperInitData[n];try{o=!0,u!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,u),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(s){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};t.exports=i},{133:133}],102:[function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{}],103:[function(e,t,n){"use strict";function r(e,t){if(o(null!=t),null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=e(133);t.exports=r},{133:133}],104:[function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0;r<e.length;r++)t=(t+e.charCodeAt(r))%o,n=(n+t)%o;return t|n<<16}var o=65521;t.exports=r},{}],105:[function(e,t,n){function r(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;t.exports=r},{}],106:[function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=e(105),i=/^-ms-/;t.exports=r},{105:105}],107:[function(e,t,n){function r(e,t){return e&&t?e===t?!0:o(e)?!1:o(t)?r(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var o=e(137);t.exports=r},{137:137}],108:[function(e,t,n){function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return r(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=e(148);t.exports=o},{148:148}],109:[function(e,t,n){"use strict";function r(e){var t=i.createFactory(e),n=o.createClass({tagName:e.toUpperCase(),displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){a(!1)},render:function(){return t(this.props)}});return n}var o=e(33),i=e(55),a=e(133);t.exports=r},{133:133,33:33,55:55}],110:[function(e,t,n){function r(e){var t=e.match(c);return t&&t[1].toLowerCase()}function o(e,t){var n=l;s(!!l);var o=r(e),i=o&&u(o);if(i){n.innerHTML=i[1]+e+i[2];for(var c=i[0];c--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(s(t),a(p).forEach(t));for(var d=a(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return d}var i=e(21),a=e(108),u=e(125),s=e(133),l=i.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=o},{108:108,125:125,133:133,21:21}],111:[function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=e(4),i=o.isUnitlessNumber;t.exports=r},{4:4}],112:[function(e,t,n){function r(e){return function(){return e}}function o(){}o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},t.exports=o},{}],113:[function(e,t,n){"use strict";var r={};t.exports=r},{}],114:[function(e,t,n){"use strict";function r(e){return i[e]}function o(e){return(""+e).replace(a,r)}var i={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},a=/[&><"']/g;t.exports=o},{}],115:[function(e,t,n){"use strict";function r(e){return null==e?null:u(e)?e:o.has(e)?i.getNodeFromInstance(e):(a(null==e.render||"function"!=typeof e.render),void a(!1))}{var o=(e(39),e(65)),i=e(68),a=e(133),u=e(135);e(150)}t.exports=r},{133:133,135:135,150:150,39:39,65:65,68:68}],116:[function(e,t,n){"use strict";function r(e,t,n){var r=e,o=!r.hasOwnProperty(n);o&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,r,t),t}{var i=e(149);e(150)}t.exports=o},{149:149,150:150}],117:[function(e,t,n){"use strict";function r(e){try{e.focus()}catch(t){}}t.exports=r},{}],118:[function(e,t,n){"use strict";var r=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=r},{}],119:[function(e,t,n){function r(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=r},{}],120:[function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=r},{}],121:[function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=e(120),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=r},{120:120}],122:[function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=i[e];return r?!!n[r]:!1}function o(e){return r}var i={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=o},{}],123:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=r},{}],124:[function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);return"function"==typeof t?t:void 0}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";t.exports=r},{}],125:[function(e,t,n){function r(e){return i(!!a),d.hasOwnProperty(e)||(e="*"),u.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",u[e]=!a.firstChild),u[e]?d[e]:null}var o=e(21),i=e(133),a=o.canUseDOM?document.createElement("div"):null,u={circle:!0,clipPath:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],l=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,"<svg>","</svg>"],d={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c,circle:p,clipPath:p,defs:p,ellipse:p,g:p,line:p,linearGradient:p,path:p,polygon:p,polyline:p,radialGradient:p,rect:p,stop:p,text:p};t.exports=r},{133:133,21:21}],126:[function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function i(e,t){for(var n=r(e),i=0,a=0;n;){if(3===n.nodeType){if(a=i+n.textContent.length,t>=i&&a>=t)return{node:n,offset:t-i};i=a}n=r(o(n))}}t.exports=i},{}],127:[function(e,t,n){"use strict";function r(e){return e?e.nodeType===o?e.documentElement:e.firstChild:null}var o=9;t.exports=r},{}],128:[function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=e(21),i=null;t.exports=r},{21:21}],129:[function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=r},{}],130:[function(e,t,n){function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;t.exports=r},{}],131:[function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=e(130),i=/^ms-/;t.exports=r},{130:130}],132:[function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e,t){var n;if((null===e||e===!1)&&(e=a.emptyElement),"object"==typeof e){var o=e;n=t===o.type&&"string"==typeof o.type?u.createInternalComponent(o):r(o.type)?new o.type(o):new c}else"string"==typeof e||"number"==typeof e?n=u.createInstanceForText(e):l(!1);return n.construct(e),n._mountIndex=0,n._mountImage=null,n}var i=e(37),a=e(57),u=e(71),s=e(27),l=e(133),c=(e(150),function(){});s(c.prototype,i.Mixin,{_instantiateReactComponent:o}),t.exports=o},{133:133,150:150,27:27,37:37,57:57,71:71}],133:[function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,a,u){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,u],c=0;s=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return l[c++]}))}throw s.framesToPop=1,s}};t.exports=r},{}],134:[function(e,t,n){"use strict";function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=e(21);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{21:21}],135:[function(e,t,n){function r(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=r},{}],136:[function(e,t,n){"use strict";function r(e){return e&&("INPUT"===e.nodeName&&o[e.type]||"TEXTAREA"===e.nodeName)}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=r},{}],137:[function(e,t,n){function r(e){return o(e)&&3==e.nodeType}var o=e(135);t.exports=r},{135:135}],138:[function(e,t,n){"use strict";var r=e(133),o=function(e){var t,n={};r(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};t.exports=o},{133:133}],139:[function(e,t,n){var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=r},{}],140:[function(e,t,n){"use strict";function r(e,t,n){if(!e)return null;var r={};for(var i in e)o.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}var o=Object.prototype.hasOwnProperty;t.exports=r},{}],141:[function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=r},{}],142:[function(e,t,n){"use strict";function r(e){return i(o.isValidElement(e)),e}var o=e(55),i=e(133);t.exports=r},{133:133,55:55}],143:[function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=e(114);t.exports=r},{114:114}],144:[function(e,t,n){"use strict";var r=e(21),o=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(a=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var u=document.createElement("div");u.innerHTML=" ",""===u.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML="\ufeff"+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=a},{21:21}],145:[function(e,t,n){"use strict";var r=e(21),o=e(114),i=e(144),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),t.exports=a},{114:114,144:144,21:21}],146:[function(e,t,n){"use strict";function r(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=r},{}],147:[function(e,t,n){"use strict";function r(e,t){if(null!=e&&null!=t){var n=typeof e,r=typeof t;if("string"===n||"number"===n)return"string"===r||"number"===r;if("object"===r&&e.type===t.type&&e.key===t.key){var o=e._owner===t._owner;return o}}return!1}e(150);t.exports=r},{150:150}],148:[function(e,t,n){function r(e){var t=e.length;if(o(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),o("number"==typeof t),o(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;t>i;i++)r[i]=e[i];return r}var o=e(133);t.exports=r},{133:133}],149:[function(e,t,n){"use strict";function r(e){return v[e]}function o(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(g,r)}function a(e){return"$"+i(e)}function u(e,t,n,r,i){var s=typeof e;if(("undefined"===s||"boolean"===s)&&(e=null),null===e||"string"===s||"number"===s||l.isValidElement(e))return r(i,e,""===t?h+o(e,0):t,n),1;var p,v,g,y=0;if(Array.isArray(e))for(var C=0;C<e.length;C++)p=e[C],v=(""!==t?t+m:h)+o(p,C),g=n+y,y+=u(p,v,g,r,i);else{var E=d(e);if(E){var b,_=E.call(e);if(E!==e.entries)for(var x=0;!(b=_.next()).done;)p=b.value,v=(""!==t?t+m:h)+o(p,x++),g=n+y,y+=u(p,v,g,r,i);else for(;!(b=_.next()).done;){var D=b.value;D&&(p=D[1],v=(""!==t?t+m:h)+a(D[0])+m+o(p,0),g=n+y,y+=u(p,v,g,r,i))}}else if("object"===s){f(1!==e.nodeType);var M=c.extract(e);for(var N in M)M.hasOwnProperty(N)&&(p=M[N],v=(""!==t?t+m:h)+a(N)+m+o(p,0),g=n+y,y+=u(p,v,g,r,i))}}return y}function s(e,t,n){return null==e?0:u(e,"",0,t,n)}var l=e(55),c=e(61),p=e(64),d=e(124),f=e(133),h=(e(150),p.SEPARATOR),m=":",v={"=":"=0",".":"=1",":":"=2"},g=/[=.:]/g;t.exports=s},{124:124,133:133,150:150,55:55,61:61,64:64}],150:[function(e,t,n){"use strict";var r=e(112),o=r;t.exports=o},{112:112}]},{},[1])(1)});
define('castle-url/patterns/querystring/widgets/string',[
  'castle-url/libs/react/react.min'
], function(R){
  'use strict';

  var D = R.DOM;

  return R.createClass({

    render: function(){
      return D.input({ type: 'text', onChange: this.props.onChange,
                       value: this.props.value,
                       className: 'querystring-criteria-value-StringWidget form-control' });
    }
  });

});

define('castle-url/patterns/querystring/widgets/select2',[
  'jquery',
  'castle-url/libs/react/react.min'
], function($, R){
  'use strict';

  var D = R.DOM;

  return R.createClass({

    getInitialState: function(){
      return {
        renderedValue: this.props.value,
        renderedOptions: this.props.options
      };
    },

    getDefaultProps: function(){
      return {
        value: '',
        width: '10em',
        multiple: false
      };
    },

    componentDidMount: function(){
      this.load();
    },

    load: function(){
      var that = this;
      var $input = $(this.refs.select.getDOMNode());
      $input.select2();
      $input.on('change', function(){
        if(that.props.onChange){
          that.props.onChange.call(that, {
            target: {
              value: $input.select2('val')
            }
          });
        }
      });
      if(this.props.value){
        $input.select2('val', this.props.value);
      }else{
        $input.select2('val', '');
      }
      that.state.renderedValue = this.props.value;
      that.state.renderedOptions = this.props.options;
    },

    componentDidUpdate: function(){
      // need to select or clear value
      var that = this;

      var $input = $(this.refs.select.getDOMNode());

      // first change if options changed, we need complete reload...
      if(JSON.stringify(that.state.renderedOptions) !== JSON.stringify(this.props.options)){
        // data changed, reload
        $input.select2("destroy");
        this.load();
      } else if(that.state.renderedValue !== this.props.value){
        // only data changed, manually change select2 now...
        $input.select2('val', that.props.value);
        that.state.renderedValue = this.props.value;
      }
    },

    render: function(){
      var options = [];
      var groups = {};
      this.props.options.forEach(function(option){
        var optionEl = D.option({ value: option.value }, option.label);
        if(option.group){
          if(!groups[option.group]){
            groups[option.group] = [];
          }
          groups[option.group].push(optionEl);
        }else{
          options.push(optionEl);
        }
      });
      for(var groupName in groups){
        options.push(D.optgroup({ label: groupName}, groups[groupName]));
      }
      return D.select({ ref: 'select', value: this.props.value,
                        style: { width: this.props.width },
                        multiple: this.props.multiple }, options);
    }
  });

});

define('castle-url/patterns/querystring/widgets/multipleselection',[
  'castle-url/libs/react/react.min',
  'castle-url/patterns/querystring/widgets/select2'
], function(R, Select2Component){
  'use strict';

  return R.createClass({
    render: function(){
      var options = [];
      for(var value in this.props.index.values){
        var label = this.props.index.values[value].title;
        options.push({ value: value, label: label});
      }
      return R.createElement(Select2Component, {
        onChange: this.props.onChange,
        value: this.props.value,
        options: options,
        multiple: true
      });
    }
  });

});

define('castle-url/patterns/querystring/widgets/relativedate',[
  'jquery',
  'castle-url/libs/react/react.min'
], function($, R){
  'use strict';

  var D = R.DOM;

  return R.createClass({
    onKeyDown: function(e){
      if([8, 9, 13, 27].indexOf(e.charCode || e.keyCode) !== -1){
        // valid characters
        return;
      }
      var val = String.fromCharCode (e.charCode || e.keyCode);
      if(isNaN(val)){
        e.preventDefault();
      }
    },

    render: function(){
      return D.input({ type: 'number', value: this.props.value,
                       onChange: this.props.onChange, onKeyDown: this.onKeyDown,
                       className: 'querystring-criteria-value-RelativeDateWidget' });
    }
  });

});

define('castle-url/patterns/querystring/widgets/daterange',[
  'jquery',
  'castle-url/libs/react/react.min',
  'mockup-patterns-pickadate'
], function($, R, PickADate){
  'use strict';

  var D = R.DOM;

  return R.createClass({
    getInitialState: function(){
      return {
        value: ['', '']
      };
    },

    componentDidMount: function(){
      var that = this;
      var $input1 = $(this.refs.input1.getDOMNode());
      this.props.pickadate1 = new PickADate($input1, {
        time: false
      });
      var $input2 = $(this.refs.input2.getDOMNode());
      this.props.pickadate2 = new PickADate($input2, {
        time: false
      });
      this.props.pickadate1.on('updated.pickadate.patterns', function() {
        if(!that.props.value){
          that.props.value = ['', ''];
        }
        that.props.value[0] = $input1.val();
        that.pushChange();
      });
      this.props.pickadate2.on('updated.pickadate.patterns', function() {
        if(!that.props.value){
          that.props.value = ['', ''];
        }
        that.props.value[1] = $input2.val();
        that.pushChange();
      });
    },

    componentDidUpdate: function(){
      var that = this;
      var $input1 = $(this.refs.input1.getDOMNode()).parent().find('.pattern-pickadate-date');
      var $input2 = $(this.refs.input2.getDOMNode()).parent().find('.pattern-pickadate-date');

      if(!that.props.value){
        that.props.value = ['', ''];
      }

      if(!this.props.value[0]){
        $input1.pickadate('clear');
      }else{
        $input1.pickadate('select', this.props.value[0]);
      }
      if(!this.props.value[1]){
        $input2.pickadate('clear');
      }else{
        $input2.pickadate('select', this.props.value[1]);
      }
    },

    pushChange: function(){
      this.props.onChange.call(this, {
        target: {
          value: this.props.value,
          force: true
        }
      }, true);
    },

    render: function(){
      var value = this.props.value;
      if(!value || !value[0] || !value[1]){
        value = ['', ''];
      }
      return D.div({ className: 'querystring-date-range' }, [
        D.span({ className: 'querystring-date-wrapper'},
          D.input({ className: 'pat-pickadate', ref: 'input1', value: value[0]})),
        D.span({ className: 'querystring-criteria-betweendt' }, 'to'),
        D.span({ className: 'querystring-date-wrapper'},
          D.input({ className: 'pat-pickadate', ref: 'input2', value: value[1]}))
      ]);
    }
  });

});

define('castle-url/patterns/querystring/widgets/date',[
  'jquery',
  'castle-url/libs/react/react.min',
  'mockup-patterns-pickadate'
], function($, R, PickADate){
  'use strict';

  var D = R.DOM;

  return R.createClass({
    componentDidMount: function(){
      var that = this;
      var $input = $(that.refs.input.getDOMNode());
      var pickadate = new PickADate($input, {
        time: false
      });
      pickadate.on('updated.pickadate.patterns', function() {
        that.props.onChange.call(that, {
          target: {
            value: $input.val()
          }
        });
      });
    },

    componentDidUpdate: function(){
      var $input = $(this.refs.input.getDOMNode()).parent().find('.pattern-pickadate-date');
      if(!this.props.value){
        $input.pickadate('clear');
      }else{
        $input.pickadate('select', this.props.value);
      }
    },

    render: function(){
      return D.input({ className: 'pat-pickadate', ref: 'input',
                       value: this.props.value});
    }
  });

});


define('castle-url/components/utils',[
  'jquery',
  'castle-url/libs/react/react.min'
], function($, R) {
  'use strict';

  var Class = function(bases, klass){
    /* poor mans class based system here.
       provide list of bases and they'll be merged.
       No super/etc provided, just overrided. */
    var _bases = [];
    bases.forEach(function(base){
      if(base.original_class){
        _bases.push(base.original_class);
      }else{
        _bases.push(base);
      }
    });
    var args = [true, {}].concat(_bases);
    args.push(klass);
    var merged_base = extend.apply(null, args);
    var _class = R.createClass(merged_base);
    _class.original_class = merged_base;
    return _class;
  };

  var extend = function(){
    var result = {};
    for(var i=0; i<arguments.length; i++){
      var other = arguments[i];
      for(var key in other){
        result[key] = other[key];
      }
    }
    return result;
  };

  var createModalComponent = function(Component, id, settings){
    if(settings === undefined){
      settings = {};
    }
    var el = document.getElementById(id);
    if(el){
      el.parentNode.removeChild(el);
    }
    var div = document.createElement('div');
    div.id = id;
    div.className = 'component-wrapper';
    document.body.appendChild(div);
    if(!settings.parent){
      settings.parent = this;
    }
    return R.render(R.createElement(Component, settings), div);
  };

  var BindComponentFactory = function(Component, SettingsFactory, settings){
    return function(el){
      if(settings === undefined){
        settings = {};
      }
      if(SettingsFactory){
        var newSettings = SettingsFactory(el);
        if(typeof(newSettings) === 'function'){
          // use callback to finish this...
          return newSettings(function(_settings){
            settings = $.extend({}, true, _settings, settings);
            return R.render(R.createElement(Component, settings), el);
          });
        }
        settings = $.extend({}, true, newSettings, settings);
      }
      return R.render(R.createElement(Component, settings), el);
    };
  };

  var BindComponentFactoryRoot = function(Component, SettingsFactory, id){
    /* binds to new element in body tag automatically */
    return function(settings){
      $('#' + id).remove();
      var $div = $('<div id="' + id + '" class="component-wrapper" />');
      $('body').append($div);
      return BindComponentFactory(Component, SettingsFactory, settings)($div[0]);
    };
  };

  return {
    Class: Class,
    createModalComponent: createModalComponent,
    extend: extend,
    BindComponentFactory: BindComponentFactory,
    BindComponentFactoryRoot: BindComponentFactoryRoot,
    getToolbarSettings: function(){
      var $el = $('.pat-castletoolbar,.castletoolbar-settings');
      if($el.length > 0){
        return JSON.parse($el.attr('data-pat-castletoolbar'));
      }
      return {};
    }
  };
});

define('castle-url/patterns/querystring/widgets/reference',[
  'jquery',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/utils'
], function($, R, utils, cutils){
  'use strict';

  var D = R.DOM;

  return R.createClass({

    getDefaultProps: function(){
      return {
        value: ''
      };
    },

    getDepth: function(){
      var value = this.props.value;
      if(!value){
        return -1;
      }
      if(value.indexOf('::') === -1){
        return -1;
      }
      return value.split('::')[1];
    },

    getPath: function(){
      var value = this.props.value;
      if(!value){
        return '';
      }
      if(value.indexOf('::') === -1){
        return value;
      }
      return value.split('::')[0];
    },

    browseClicked: function(e){
      var that = this;
      e.preventDefault();

      var tinyConfig = JSON.parse($('body').attr('data-pat-tinymce'));
      var query = new utils.QueryHelper({
        vocabularyUrl: tinyConfig.relatedItems.vocabularyUrl,
        batchSize: 30,
        sort_on: 'getObjPositionInParent',
        sort_order: 'ascending',
        attributes: ['UID', 'Title', 'portal_type', 'path', 'review_state', 'is_folderish']
      });
      // get current path instead?
      query.pattern.browsing = true;
      query.currentPath = '/';

      var ContentBrowserComponent = require('castle-url/components/content-browser');
      var ContentBrowserBinder = cutils.BindComponentFactoryRoot(
        ContentBrowserComponent, function(){
          return {
            onSelectItem: function(item){
              that.props.onChange({
                target: {
                  value: item.path + '::' + that.getDepth()
                }
              });
              that.props.value = item.path + '::' + that.getDepth();
            },
            query: query,
            multiple: false
          };
        }, 'content-browser-react-container');

      ContentBrowserBinder({});
      $('#content-browser-react-container').off('click').on('click', function(){
        // reopen query widget if opened...
        var $query = $('#popover-structure-query.active');
        if($query.length > 0){
          setTimeout(function(){
            $query.parent().find('.input-group-btn a').trigger('click');
          }, 10);
        }
      });
    },

    depthChange: function(e){
      var that = this;
      var depth = e.target.value;
      that.props.onChange({
        target: {
          value: that.getPath() + '::' + depth
        }
      });
      that.props.value = that.getPath() + '::' + depth;

    },

    render: function(){
      var that = this;

      var selected = '';
      if(that.getPath()){
        selected = D.span({}, [
          D.b({}, 'Selected: '),
          that.getPath()
        ]);
      }

      var depthOptions = [D.option({ value: '-1'}, 'Unlimited')];
      [0, 1, 2, 3, 4, 5].forEach(function(number){
        depthOptions.push(D.option({ value: number}, number));
      });

      return D.div({ className: 'querystring-reference-widget'}, [
        selected,
        D.button({ className: 'plone-btn plone-btn-default plone-btn-xs',
                   onClick: this.browseClicked }, 'Browse'),
        D.div({ className: "depth-select-box form-group" }, [
          D.label({ htmlFor: "depth-select" }, 'Depth'),
          D.select({ name: "depth-select", onChange: this.depthChange,
                     value: this.getDepth(),
                     className: "querystring-criteria-depth form-control" }, depthOptions)
        ])
      ]);
    }
  });

});

define('castle-url/patterns/querystring/widgets/relativepath',[
  'jquery',
  'castle-url/libs/react/react.min'
], function($, R){
  'use strict';

  var D = R.DOM;

  return R.createClass({
    render: function(){
      return D.div({ className: 'querystring-relative-path'}, [
        D.select({ onChange: this.props.onChange,
                   value: this.props.value,
                   className: "form-control" }, [
          D.option({ value: ''}, 'Select'),
          D.option({ value: '../::1'}, 'Parent'),
          D.option({ value: './::1'}, 'Current')
        ])
      ]);
    }
  });

});

define('castle-url/patterns/querystring/criteria',[
  'jquery',
  'castle-url/libs/react/react.min',
  'castle-url/patterns/querystring/widgets/string',
  'castle-url/patterns/querystring/widgets/multipleselection',
  'castle-url/patterns/querystring/widgets/relativedate',
  'castle-url/patterns/querystring/widgets/daterange',
  'castle-url/patterns/querystring/widgets/date',
  'castle-url/patterns/querystring/widgets/reference',
  'castle-url/patterns/querystring/widgets/relativepath',
  'castle-url/patterns/querystring/widgets/select2'
], function($, R, StringWidget, MultipleSelectionWidget, RelativeDateWidget, DateRangeWidget,
            DateWidget, ReferenceWidget, RelativePathWidget, Select2Component){
  'use strict';

  var D = R.DOM;

  return R.createClass({

    widgets: {
      StringWidget: StringWidget,
      MultipleSelectionWidget: MultipleSelectionWidget,
      RelativeDateWidget: RelativeDateWidget,
      DateRangeWidget: DateRangeWidget,
      DateWidget: DateWidget,
      ReferenceWidget: ReferenceWidget,
      RelativePathWidget: RelativePathWidget
    },

    getDefaultProps: function(){
      return {
        indexWidth: '20em',
        classWrapperName: 'querystring-criteria-wrapper',
        classIndexName: 'querystring-criteria-index',
        classOperatorName: 'querystring-criteria-operator',
        classValueName: 'querystring-criteria-value',
        classRemoveName: 'querystring-criteria-remove',
        classResultsName: 'querystring-criteria-results',
        classClearName: 'querystring-criteria-clear',
        i: null,
        o: null,
        v: '',
        idx: -1
      };
    },

    indexSelected: function(e){
      var indexes = this.props.parent.props.indexes;
      var index = indexes[e.target.value];

      this.props.storage.dispatcher.handleViewAction({
        actionType: 'updateCriteria',
        idx: this.props.idx,
        data: {
          i: e.target.value,
          o: index.operations[0],
          v: ''
        }
      });
    },

    operatorSelected: function(e){
      this.props.storage.dispatcher.handleViewAction({
        actionType: 'updateCriteria',
        idx: this.props.idx,
        data: {
          o: e.target.value,
          v: ''
        }
      });
    },

    valueChanged: function(e, force){
      this.props.storage.dispatcher.handleViewAction({
        actionType: 'updateCriteria',
        idx: this.props.idx,
        data: {
          v: e.target.value
        },
        force: force
      });
    },

    removeClicked: function(){
      this.props.storage.dispatcher.handleViewAction({
        actionType: 'removeCriteria',
        idx: this.props.idx,
      });
    },

    render: function(){
      return D.div({ className: this.props.classWrapperName }, [
        D.div({ className: this.props.classRemoveName,
                onClick: this.removeClicked }),
        this.renderIndexSelector(),
        this.renderOperatorSelector(),
        this.renderValueSelector(),
        D.div({ className: 'querystring-criteria-clear'})
      ]);
    },

    renderValueSelector: function(){
      var that = this;
      var indexes = that.props.parent.props.indexes;

      if(!that.props.i || !that.props.o){
        return '';
      }

      var index = indexes[that.props.i];
      var operator = index.operators[that.props.o];
      if(operator.widget === null){
        return '';
      }

      var widget = R.createElement(this.widgets[operator.widget], {
        index: index,
        operator: operator,
        value: this.props.v,
        onChange: this.valueChanged
      });
      return D.div({ className: this.props.classValueName,
                     key: this.props.idx + operator.widget}, widget);
    },

    renderOperatorSelector: function(){
      var that = this;
      var indexes = that.props.parent.props.indexes;

      if(!that.props.i){
        return '';
      }
      var index = indexes[that.props.i];

      var options = [];
      index.operations.forEach(function(operation){
        var operator = index.operators[operation];
        options.push({ value: operation, label: operator.title });
      });

      return D.div({ className: this.props.classOperatorName },
        R.createElement(Select2Component, {
          onChange: this.operatorSelected, options: options, parent: this,
          value: this.props.o })
      );
    },

    renderIndexSelector: function(){
      var options = [{ value: '', label: 'Select criteria'}];
      for (var indexName in this.props.parent.props.indexes) {
        var index = this.props.parent.props.indexes[indexName];
        if(index.enabled){
          options.push({ value: indexName, label: index.title, group: index.group });
        }
      }
      return D.div({ className: this.props.classIndexName },
        R.createElement(Select2Component, {
          onChange: this.indexSelected, options: options, parent: this,
          value: this.props.i, width: this.props.indexWidth, })
      );
    }
  });

});

define('castle-url/patterns/querystring/querystring',[
  'jquery',
  'castle-url/libs/react/react.min',
  'castle-url/patterns/querystring/criteria',
  'castle-url/patterns/querystring/widgets/select2',
  'castle-url/components/utils'
], function($, R, CriteriaComponent, Select2Component, cutils){
  'use strict';

  var D = R.DOM;

  return R.createClass({
    getInitialState: function(){
      return {
        sortOn: '',
        reversed: false,
        criterias: []
      };
    },

    getDefaultProps: function(){
      return {
        afterChange: function(){}
      };
    },

    componentDidMount: function() {
      this.props.storage.store.addChangeListener('change', this._onChange);
    },

    componentWillUnmount: function() {
      this.props.storage.store.removeChangeListener('change', this._onChange);
    },

    _onChange: function(){
      var that = this;
      this.setState(this.props.storage.store.getData(), function(){
        that.props.afterChange();
      });
    },

    reverseClicked: function(e){
      this.props.storage.dispatcher.handleViewAction({
        actionType: 'update',
        data: {
          reversed: e.target.checked
        }
      });
    },

    sortOnChanged: function(e){
      this.props.storage.dispatcher.handleViewAction({
        actionType: 'update',
        data: {
          sortOn: e.target.value
        }
      });
    },

    addCriteriaClicked: function(e){
      e.preventDefault();
      this.props.storage.dispatcher.handleViewAction({
        actionType: 'addCriteria',
        data: {
          i: '',
          o: '',
          v: ''
        }
      });
    },

    render: function(){
      return D.div({ className: this.props.classWrapperName }, [
        this.renderCriterias(),
        D.div({ className: this.props.classAddCriteriaName,
                style: { clear: 'both'}}, [
          D.button({ className: 'plone-btn plone-btn-default plone-btn-xs',
                     onClick: this.addCriteriaClicked }, 'Add criteria')
        ]),
        this.renderSorting()
      ]);
    },

    renderCriterias: function(){
      var that = this;

      if(this.state.criterias.length === 0){
        return D.p({ className: 'querystring-empty-criterias'}, 'No criteria defined.');
      }

      var criterias = [];

      this.state.criterias.forEach(function(criteria, idx){
        criterias.push(R.createElement(CriteriaComponent, cutils.extend(criteria, {
          parent: that,
          idx: idx,
          storage: that.props.storage
        })));
      });

      return criterias;
    },

    getQueryString: function(){
      var results = [];
      this.state.criterias.forEach(function(criteria){
        if(!criteria.i || !criteria.o){
          return;
        }
        results.push(criteria);
      });
      return results;
    },

    renderSorting: function(){
      var options = [{ value: '', label: 'No sorting'}];
      for (var key in this.props.sortable_indexes) {
        var index = this.props.sortable_indexes[key];
        options.push({ value: key, label: index.title});
      }

      return D.div({ className: this.props.classSortWrapperName }, [
        D.span({ className: this.props.classSortLabelName }, 'Sort on'),
        R.createElement(Select2Component, {
          parent: this, onChange: this.sortOnChanged,
          options: options, value: this.state.sortOn,
          ref: 'sortOn' }),
        D.label({ className: this.props.classSortReverseName }, [
          D.input({ type: 'checkbox', onClick: this.reverseClicked,
                    checked: this.state.reversed,
                    ref: 'sortOrder' }),
          'Reversed Order'
        ]),
        // D.div({}, JSON.stringify(this.getQueryString())),
        // D.div({}, 'Sort on: ' + this.state.sortOn),
        // D.div({}, 'Reversed: ' + this.state.reversed),
      ]);
    }
  });

  //
  // [{"i": "portal_type", "o": "plone.app.querystring.operation.selection.any", "v": ["Event"]},
  //  {"i": "review_state", "o": "plone.app.querystring.operation.selection.any", "v": ["published"]}]
});

/*!
 * @overview es6-promise - a tiny implementation of Promises/A+.
 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
 * @license   Licensed under MIT license
 *            See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
 * @version   3.0.2
 */

(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;var lib$es6$promise$asap$$customSchedulerFn;var lib$es6$promise$asap$$asap=function asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){if(lib$es6$promise$asap$$customSchedulerFn){lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush)}else{lib$es6$promise$asap$$scheduleFlush()}}};function lib$es6$promise$asap$$setScheduler(scheduleFn){lib$es6$promise$asap$$customSchedulerFn=scheduleFn}function lib$es6$promise$asap$$setAsap(asapFn){lib$es6$promise$asap$$asap=asapFn}var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){return function(){process.nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i<lib$es6$promise$asap$$len;i+=2){var callback=lib$es6$promise$asap$$queue[i];var arg=lib$es6$promise$asap$$queue[i+1];callback(arg);lib$es6$promise$asap$$queue[i]=undefined;lib$es6$promise$asap$$queue[i+1]=undefined}lib$es6$promise$asap$$len=0}function lib$es6$promise$asap$$attemptVertx(){try{var r=require;var vertx=r("vertx");lib$es6$promise$asap$$vertxNext=vertx.runOnLoop||vertx.runOnContext;return lib$es6$promise$asap$$useVertxTimer()}catch(e){return lib$es6$promise$asap$$useSetTimeout()}}var lib$es6$promise$asap$$scheduleFlush;if(lib$es6$promise$asap$$isNode){lib$es6$promise$asap$$scheduleFlush=lib$es6$promise$asap$$useNextTick()}else if(lib$es6$promise$asap$$BrowserMutationObserver){lib$es6$promise$asap$$scheduleFlush=lib$es6$promise$asap$$useMutationObserver()}else if(lib$es6$promise$asap$$isWorker){lib$es6$promise$asap$$scheduleFlush=lib$es6$promise$asap$$useMessageChannel()}else if(lib$es6$promise$asap$$browserWindow===undefined&&typeof require==="function"){lib$es6$promise$asap$$scheduleFlush=lib$es6$promise$asap$$attemptVertx()}else{lib$es6$promise$asap$$scheduleFlush=lib$es6$promise$asap$$useSetTimeout()}function lib$es6$promise$$internal$$noop(){}var lib$es6$promise$$internal$$PENDING=void 0;var lib$es6$promise$$internal$$FULFILLED=1;var lib$es6$promise$$internal$$REJECTED=2;var lib$es6$promise$$internal$$GET_THEN_ERROR=new lib$es6$promise$$internal$$ErrorObject;function lib$es6$promise$$internal$$selfFulfillment(){return new TypeError("You cannot resolve a promise with itself")}function lib$es6$promise$$internal$$cannotReturnOwn(){return new TypeError("A promises callback cannot return that same promise.")}function lib$es6$promise$$internal$$getThen(promise){try{return promise.then}catch(error){lib$es6$promise$$internal$$GET_THEN_ERROR.error=error;return lib$es6$promise$$internal$$GET_THEN_ERROR}}function lib$es6$promise$$internal$$tryThen(then,value,fulfillmentHandler,rejectionHandler){try{then.call(value,fulfillmentHandler,rejectionHandler)}catch(e){return e}}function lib$es6$promise$$internal$$handleForeignThenable(promise,thenable,then){lib$es6$promise$asap$$asap(function(promise){var sealed=false;var error=lib$es6$promise$$internal$$tryThen(then,thenable,function(value){if(sealed){return}sealed=true;if(thenable!==value){lib$es6$promise$$internal$$resolve(promise,value)}else{lib$es6$promise$$internal$$fulfill(promise,value)}},function(reason){if(sealed){return}sealed=true;lib$es6$promise$$internal$$reject(promise,reason)},"Settle: "+(promise._label||" unknown promise"));if(!sealed&&error){sealed=true;lib$es6$promise$$internal$$reject(promise,error)}},promise)}function lib$es6$promise$$internal$$handleOwnThenable(promise,thenable){if(thenable._state===lib$es6$promise$$internal$$FULFILLED){lib$es6$promise$$internal$$fulfill(promise,thenable._result)}else if(thenable._state===lib$es6$promise$$internal$$REJECTED){lib$es6$promise$$internal$$reject(promise,thenable._result)}else{lib$es6$promise$$internal$$subscribe(thenable,undefined,function(value){lib$es6$promise$$internal$$resolve(promise,value)},function(reason){lib$es6$promise$$internal$$reject(promise,reason)})}}function lib$es6$promise$$internal$$handleMaybeThenable(promise,maybeThenable){if(maybeThenable.constructor===promise.constructor){lib$es6$promise$$internal$$handleOwnThenable(promise,maybeThenable)}else{var then=lib$es6$promise$$internal$$getThen(maybeThenable);if(then===lib$es6$promise$$internal$$GET_THEN_ERROR){lib$es6$promise$$internal$$reject(promise,lib$es6$promise$$internal$$GET_THEN_ERROR.error)}else if(then===undefined){lib$es6$promise$$internal$$fulfill(promise,maybeThenable)}else if(lib$es6$promise$utils$$isFunction(then)){lib$es6$promise$$internal$$handleForeignThenable(promise,maybeThenable,then)}else{lib$es6$promise$$internal$$fulfill(promise,maybeThenable)}}}function lib$es6$promise$$internal$$resolve(promise,value){if(promise===value){lib$es6$promise$$internal$$reject(promise,lib$es6$promise$$internal$$selfFulfillment())}else if(lib$es6$promise$utils$$objectOrFunction(value)){lib$es6$promise$$internal$$handleMaybeThenable(promise,value)}else{lib$es6$promise$$internal$$fulfill(promise,value)}}function lib$es6$promise$$internal$$publishRejection(promise){if(promise._onerror){promise._onerror(promise._result)}lib$es6$promise$$internal$$publish(promise)}function lib$es6$promise$$internal$$fulfill(promise,value){if(promise._state!==lib$es6$promise$$internal$$PENDING){return}promise._result=value;promise._state=lib$es6$promise$$internal$$FULFILLED;if(promise._subscribers.length!==0){lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish,promise)}}function lib$es6$promise$$internal$$reject(promise,reason){if(promise._state!==lib$es6$promise$$internal$$PENDING){return}promise._state=lib$es6$promise$$internal$$REJECTED;promise._result=reason;lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection,promise)}function lib$es6$promise$$internal$$subscribe(parent,child,onFulfillment,onRejection){var subscribers=parent._subscribers;var length=subscribers.length;parent._onerror=null;subscribers[length]=child;subscribers[length+lib$es6$promise$$internal$$FULFILLED]=onFulfillment;subscribers[length+lib$es6$promise$$internal$$REJECTED]=onRejection;if(length===0&&parent._state){lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish,parent)}}function lib$es6$promise$$internal$$publish(promise){var subscribers=promise._subscribers;var settled=promise._state;if(subscribers.length===0){return}var child,callback,detail=promise._result;for(var i=0;i<subscribers.length;i+=3){child=subscribers[i];callback=subscribers[i+settled];if(child){lib$es6$promise$$internal$$invokeCallback(settled,child,callback,detail)}else{callback(detail)}}promise._subscribers.length=0}function lib$es6$promise$$internal$$ErrorObject(){this.error=null}var lib$es6$promise$$internal$$TRY_CATCH_ERROR=new lib$es6$promise$$internal$$ErrorObject;function lib$es6$promise$$internal$$tryCatch(callback,detail){try{return callback(detail)}catch(e){lib$es6$promise$$internal$$TRY_CATCH_ERROR.error=e;return lib$es6$promise$$internal$$TRY_CATCH_ERROR}}function lib$es6$promise$$internal$$invokeCallback(settled,promise,callback,detail){var hasCallback=lib$es6$promise$utils$$isFunction(callback),value,error,succeeded,failed;if(hasCallback){value=lib$es6$promise$$internal$$tryCatch(callback,detail);if(value===lib$es6$promise$$internal$$TRY_CATCH_ERROR){failed=true;error=value.error;value=null}else{succeeded=true}if(promise===value){lib$es6$promise$$internal$$reject(promise,lib$es6$promise$$internal$$cannotReturnOwn());return}}else{value=detail;succeeded=true}if(promise._state!==lib$es6$promise$$internal$$PENDING){}else if(hasCallback&&succeeded){lib$es6$promise$$internal$$resolve(promise,value)}else if(failed){lib$es6$promise$$internal$$reject(promise,error)}else if(settled===lib$es6$promise$$internal$$FULFILLED){lib$es6$promise$$internal$$fulfill(promise,value)}else if(settled===lib$es6$promise$$internal$$REJECTED){lib$es6$promise$$internal$$reject(promise,value)}}function lib$es6$promise$$internal$$initializePromise(promise,resolver){try{resolver(function resolvePromise(value){lib$es6$promise$$internal$$resolve(promise,value)},function rejectPromise(reason){lib$es6$promise$$internal$$reject(promise,reason)})}catch(e){lib$es6$promise$$internal$$reject(promise,e)}}function lib$es6$promise$enumerator$$Enumerator(Constructor,input){var enumerator=this;enumerator._instanceConstructor=Constructor;enumerator.promise=new Constructor(lib$es6$promise$$internal$$noop);if(enumerator._validateInput(input)){enumerator._input=input;enumerator.length=input.length;enumerator._remaining=input.length;enumerator._init();if(enumerator.length===0){lib$es6$promise$$internal$$fulfill(enumerator.promise,enumerator._result)}else{enumerator.length=enumerator.length||0;enumerator._enumerate();if(enumerator._remaining===0){lib$es6$promise$$internal$$fulfill(enumerator.promise,enumerator._result)}}}else{lib$es6$promise$$internal$$reject(enumerator.promise,enumerator._validationError())}}lib$es6$promise$enumerator$$Enumerator.prototype._validateInput=function(input){return lib$es6$promise$utils$$isArray(input)};lib$es6$promise$enumerator$$Enumerator.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")};lib$es6$promise$enumerator$$Enumerator.prototype._init=function(){this._result=new Array(this.length)};var lib$es6$promise$enumerator$$default=lib$es6$promise$enumerator$$Enumerator;lib$es6$promise$enumerator$$Enumerator.prototype._enumerate=function(){var enumerator=this;var length=enumerator.length;var promise=enumerator.promise;var input=enumerator._input;for(var i=0;promise._state===lib$es6$promise$$internal$$PENDING&&i<length;i++){enumerator._eachEntry(input[i],i)}};lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry=function(entry,i){var enumerator=this;var c=enumerator._instanceConstructor;if(lib$es6$promise$utils$$isMaybeThenable(entry)){if(entry.constructor===c&&entry._state!==lib$es6$promise$$internal$$PENDING){entry._onerror=null;enumerator._settledAt(entry._state,i,entry._result)}else{enumerator._willSettleAt(c.resolve(entry),i)}}else{enumerator._remaining--;enumerator._result[i]=entry}};lib$es6$promise$enumerator$$Enumerator.prototype._settledAt=function(state,i,value){var enumerator=this;var promise=enumerator.promise;if(promise._state===lib$es6$promise$$internal$$PENDING){enumerator._remaining--;if(state===lib$es6$promise$$internal$$REJECTED){lib$es6$promise$$internal$$reject(promise,value)}else{enumerator._result[i]=value}}if(enumerator._remaining===0){lib$es6$promise$$internal$$fulfill(promise,enumerator._result)}};lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt=function(promise,i){var enumerator=this;lib$es6$promise$$internal$$subscribe(promise,undefined,function(value){enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED,i,value)},function(reason){enumerator._settledAt(lib$es6$promise$$internal$$REJECTED,i,reason)})};function lib$es6$promise$promise$all$$all(entries){return new lib$es6$promise$enumerator$$default(this,entries).promise}var lib$es6$promise$promise$all$$default=lib$es6$promise$promise$all$$all;function lib$es6$promise$promise$race$$race(entries){var Constructor=this;var promise=new Constructor(lib$es6$promise$$internal$$noop);if(!lib$es6$promise$utils$$isArray(entries)){lib$es6$promise$$internal$$reject(promise,new TypeError("You must pass an array to race."));return promise}var length=entries.length;function onFulfillment(value){lib$es6$promise$$internal$$resolve(promise,value)}function onRejection(reason){lib$es6$promise$$internal$$reject(promise,reason)}for(var i=0;promise._state===lib$es6$promise$$internal$$PENDING&&i<length;i++){lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]),undefined,onFulfillment,onRejection)}return promise}var lib$es6$promise$promise$race$$default=lib$es6$promise$promise$race$$race;function lib$es6$promise$promise$resolve$$resolve(object){var Constructor=this;if(object&&typeof object==="object"&&object.constructor===Constructor){return object}var promise=new Constructor(lib$es6$promise$$internal$$noop);lib$es6$promise$$internal$$resolve(promise,object);return promise}var lib$es6$promise$promise$resolve$$default=lib$es6$promise$promise$resolve$$resolve;function lib$es6$promise$promise$reject$$reject(reason){var Constructor=this;var promise=new Constructor(lib$es6$promise$$internal$$noop);lib$es6$promise$$internal$$reject(promise,reason);return promise}var lib$es6$promise$promise$reject$$default=lib$es6$promise$promise$reject$$reject;var lib$es6$promise$promise$$counter=0;function lib$es6$promise$promise$$needsResolver(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function lib$es6$promise$promise$$needsNew(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var lib$es6$promise$promise$$default=lib$es6$promise$promise$$Promise;function lib$es6$promise$promise$$Promise(resolver){this._id=lib$es6$promise$promise$$counter++;this._state=undefined;this._result=undefined;this._subscribers=[];if(lib$es6$promise$$internal$$noop!==resolver){if(!lib$es6$promise$utils$$isFunction(resolver)){lib$es6$promise$promise$$needsResolver()}if(!(this instanceof lib$es6$promise$promise$$Promise)){lib$es6$promise$promise$$needsNew()}lib$es6$promise$$internal$$initializePromise(this,resolver)}}lib$es6$promise$promise$$Promise.all=lib$es6$promise$promise$all$$default;lib$es6$promise$promise$$Promise.race=lib$es6$promise$promise$race$$default;lib$es6$promise$promise$$Promise.resolve=lib$es6$promise$promise$resolve$$default;lib$es6$promise$promise$$Promise.reject=lib$es6$promise$promise$reject$$default;lib$es6$promise$promise$$Promise._setScheduler=lib$es6$promise$asap$$setScheduler;lib$es6$promise$promise$$Promise._setAsap=lib$es6$promise$asap$$setAsap;lib$es6$promise$promise$$Promise._asap=lib$es6$promise$asap$$asap;lib$es6$promise$promise$$Promise.prototype={constructor:lib$es6$promise$promise$$Promise,then:function(onFulfillment,onRejection){var parent=this;var state=parent._state;if(state===lib$es6$promise$$internal$$FULFILLED&&!onFulfillment||state===lib$es6$promise$$internal$$REJECTED&&!onRejection){return this}var child=new this.constructor(lib$es6$promise$$internal$$noop);var result=parent._result;if(state){var callback=arguments[state-1];lib$es6$promise$asap$$asap(function(){lib$es6$promise$$internal$$invokeCallback(state,child,callback,result)})}else{lib$es6$promise$$internal$$subscribe(parent,child,onFulfillment,onRejection)}return child},"catch":function(onRejection){return this.then(null,onRejection)}};function lib$es6$promise$polyfill$$polyfill(){var local;if(typeof global!=="undefined"){local=global}else if(typeof self!=="undefined"){local=self}else{try{local=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}}var P=local.Promise;if(P&&Object.prototype.toString.call(P.resolve())==="[object Promise]"&&!P.cast){return}local.Promise=lib$es6$promise$promise$$default}var lib$es6$promise$polyfill$$default=lib$es6$promise$polyfill$$polyfill;var lib$es6$promise$umd$$ES6Promise={Promise:lib$es6$promise$promise$$default,polyfill:lib$es6$promise$polyfill$$default};if(typeof define==="function"&&define["amd"]){define('castle-url/libs/es6-promise/promise.min',[],function(){return lib$es6$promise$umd$$ES6Promise})}else if(typeof module!=="undefined"&&module["exports"]){module["exports"]=lib$es6$promise$umd$$ES6Promise}else if(typeof this!=="undefined"){this["ES6Promise"]=lib$es6$promise$umd$$ES6Promise}lib$es6$promise$polyfill$$default()}).call(this);
define('castle-url/libs/object-assign',[], function(){
  'use strict';
  function ToObject(val) {
    if (val === null) {
        throw new TypeError('Object.assign cannot be called with null or undefined');
    }

    return Object(val);
  }
  return Object.assign || function (target) {
    var from;
    var keys;
    var to = ToObject(target);

    for (var s = 1; s < arguments.length; s++) {
        from = arguments[s];
        keys = Object.keys(Object(from));

        for (var i = 0; i < keys.length; i++) {
            to[keys[i]] = from[keys[i]];
        }
    }

    return to;
  };
});

define('castle-url/libs/dispatcher',[
  'jquery',
  'castle-url/libs/es6-promise/promise.min',
  'castle-url/libs/object-assign'
], function($, promise, assign) {
  'use strict';

  var _callbacks = [];
  var _promises = [];

  var Dispatcher = function() {};
  Dispatcher.prototype = assign({}, Dispatcher.prototype, {

    /**
     * Register a Store's callback so that it may be invoked by an action.
     * @param {function} callback The callback to be registered.
     * @return {number} The index of the callback within the _callbacks array.
     */
    register: function(callback) {
      _callbacks.push(callback);
      return _callbacks.length - 1; // index
    },

    /**
     * dispatch
     * @param  {object} payload The data from the action.
     */
    dispatch: function(payload) {
      // First create array of promises for callbacks to reference.
      var resolves = [];
      var rejects = [];
      _promises = _callbacks.map(function(_, i) {
        return new promise.Promise(function(resolve, reject) {
          resolves[i] = resolve;
          rejects[i] = reject;
        });
      });
      // Dispatch to callbacks and resolve/reject promises.
      _callbacks.forEach(function(callback, i) {
        // Callback can return an obj, to resolve, or a promise, to chain.
        // See waitFor() for why this might be useful.
        promise.Promise.resolve(callback(payload)).then(function() {
          resolves[i](payload);
        }, function() {
          rejects[i](new Error('Dispatcher callback unsuccessful'));
        });
      });
      _promises = [];
    },
    /**
     * A bridge function between the views and the dispatcher, marking the action
     * as a view action.  Another variant here could be handleServerAction.
     * @param  {object} action The data coming from the view.
     */
    handleViewAction: function(action) {
      this.dispatch(action);
    }
  });

  return Dispatcher;
});

/*!
 * EventEmitter v4.2.11 - git.io/ee
 * Unlicense - http://unlicense.org/
 * Oliver Caldwell - http://oli.me.uk/
 * @preserve
 */
(function(){"use strict";function t(){}function i(t,n){for(var e=t.length;e--;)if(t[e].listener===n)return e;return-1}function n(e){return function(){return this[e].apply(this,arguments)}}var e=t.prototype,r=this,s=r.EventEmitter;e.getListeners=function(n){var r,e,t=this._getEvents();if(n instanceof RegExp){r={};for(e in t)t.hasOwnProperty(e)&&n.test(e)&&(r[e]=t[e])}else r=t[n]||(t[n]=[]);return r},e.flattenListeners=function(t){var e,n=[];for(e=0;e<t.length;e+=1)n.push(t[e].listener);return n},e.getListenersAsObject=function(n){var e,t=this.getListeners(n);return t instanceof Array&&(e={},e[n]=t),e||t},e.addListener=function(r,e){var t,n=this.getListenersAsObject(r),s="object"==typeof e;for(t in n)n.hasOwnProperty(t)&&-1===i(n[t],e)&&n[t].push(s?e:{listener:e,once:!1});return this},e.on=n("addListener"),e.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},e.once=n("addOnceListener"),e.defineEvent=function(e){return this.getListeners(e),this},e.defineEvents=function(t){for(var e=0;e<t.length;e+=1)this.defineEvent(t[e]);return this},e.removeListener=function(r,s){var n,e,t=this.getListenersAsObject(r);for(e in t)t.hasOwnProperty(e)&&(n=i(t[e],s),-1!==n&&t[e].splice(n,1));return this},e.off=n("removeListener"),e.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},e.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},e.manipulateListeners=function(r,t,i){var e,n,s=r?this.removeListener:this.addListener,o=r?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(e=i.length;e--;)s.call(this,t,i[e]);else for(e in t)t.hasOwnProperty(e)&&(n=t[e])&&("function"==typeof n?s.call(this,e,n):o.call(this,e,n));return this},e.removeEvent=function(e){var t,r=typeof e,n=this._getEvents();if("string"===r)delete n[e];else if(e instanceof RegExp)for(t in n)n.hasOwnProperty(t)&&e.test(t)&&delete n[t];else delete this._events;return this},e.removeAllListeners=n("removeEvent"),e.emitEvent=function(t,u){var n,e,r,i,o,s=this.getListenersAsObject(t);for(i in s)if(s.hasOwnProperty(i))for(n=s[i].slice(0),r=n.length;r--;)e=n[r],e.once===!0&&this.removeListener(t,e.listener),o=e.listener.apply(this,u||[]),o===this._getOnceReturnValue()&&this.removeListener(t,e.listener);return this},e.trigger=n("emitEvent"),e.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},e.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},e._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},e._getEvents=function(){return this._events||(this._events={})},t.noConflict=function(){return r.EventEmitter=s,t},"function"==typeof define&&define.amd?define('castle-url/libs/eventEmitter/EventEmitter.min',[],function(){return t}):"object"==typeof module&&module.exports?module.exports=t:r.EventEmitter=t}).call(this);
define('castle-url/patterns/querystring/store',[
  'castle-url/libs/dispatcher',
  'castle-url/libs/eventEmitter/EventEmitter.min',
  'castle-url/libs/object-assign',
  'castle-url/components/utils'
], function(Dispatcher, EventEmitter, assign, cutils) {
  'use strict';

  var Store = assign({}, EventEmitter.prototype, {

    data: null,
    initialize: function(){
      this.data = {
        sortOn: '',
        reversed: false,
        criterias: []
      };
    },

    setData: function(data){
      this.data = data;
    },

    getData: function(){
      return this.data;
    },

    getAllCriterias: function() {
      return this.data.criterias || [];
    },

    getCriteria: function(idx){
      return this.data.criterias[idx];
    },

    addCriteria: function(data){
      if(!this.data.criterias){
        this.data.criterias = [];
      }
      this.data.criterias.push(data);
    },

    update: function(data){
      var changes = false;
      if(data.sortOn !== this.data.sortOn || data.reversed !== this.data.reversed){
        changes = true;
      }
      this.data = cutils.extend(this.data, data);
      return changes;
    },

    updateCriteria: function(idx, data){
      if(!this.data.criterias || !this.data.criterias[idx]){
        return;
      }
      var changes = false;
      var original = this.data.criterias[idx];
      for(var key in data){
        if(original[key] !== data[key]){
          changes = true;
        }
      }
      this.data.criterias[idx] = cutils.extend(this.data.criterias[idx], data);
      return changes;
    },

    removeCriteria: function(idx){
      if(!this.data.criterias || !this.data.criterias[idx]){
        return;
      }
      this.data.criterias.splice(idx, 1);
    },

    /**
     * @param {function} callback
     */
    addChangeListener: function(event, callback) {
      this.on(event, callback);
    },

    /**
     * @param {function} callback
     */
    removeChangeListener: function(event, callback) {
      this.removeListener(event, callback);
    }

  });


  return function(){
    var store = assign({}, Store);
    var dispatcher = new Dispatcher();
    store.initialize();

    // Register callback to handle all updates
    dispatcher.register(function(action) {
      switch(action.actionType) {
        case 'addCriteria':
          store.addCriteria(action.data);
          store.emit('change', action);
          break;

        case 'updateCriteria':

          if(store.updateCriteria(action.idx, action.data) || action.force){
            store.emit('change', action);
          }
          break;

        case 'removeCriteria':
          store.removeCriteria(action.idx);
          store.emit('change', action);
          break;

        case 'update':
          if(store.update(action.data)){
            store.emit('change', action);
          }
          break;

        default:
          // no op
      }
    });
    return {
      store: store,
      dispatcher: dispatcher
    };
  };

});

/*
XXX
this is a work-in-progress
*not* active
*/
/* Querystring pattern.
 *
 * Options:
 *    criteria(object): options to pass into criteria ({})
 *    indexOptionsUrl(string): URL to grab index option data from. Must contain "sortable_indexes" and "indexes" data in JSON object. (null)
 *    previewURL(string): URL used to pass in a plone.app.querystring-formatted HTTP querystring and get an HTML list of results ('portal_factory/@@querybuilder_html_results')
 *    previewCountURL(string): URL used to pass in a plone.app.querystring-formatted HTTP querystring and get an HTML string of the total number of records found with the query ('portal_factory/@@querybuildernumberofresults')
 *    classWrapperName(string): CSS class to apply to the wrapper element ('querystring-wrapper')
 *    classSortLabelName(string): CSS class to apply to the sort on label ('querystring-sort-label')
 *    classSortReverseName(string): CSS class to apply to the sort order label and checkbox container ('querystring-sortreverse')
 *    classSortReverseLabelName(string): CSS class to apply to the sort order label ('querystring-sortreverse-label')
 *    classPreviewCountWrapperName(string): TODO ('querystring-previewcount-wrapper')
 *    classPreviewResultsWrapperName(string): CSS class to apply to the results wrapper ('querystring-previewresults-wrapper')
 *    classPreviewWrapperName(string): CSS class to apply to the preview wrapper ('querystring-preview-wrapper')
 *    classPreviewName(string): CSS class to apply to the preview pane ('querystring-preview')
 *    classPreviewTitleName(string): CSS class to apply to the preview title ('querystring-preview-title')
 *    classPreviewDescriptionName(string): CSS class to apply to the preview description ('querystring-preview-description')
 *    classSortWrapperName(string): CSS class to apply to the sort order and sort on wrapper ('querystring-sort-wrapper')
 *    showPreviews(boolean): Should previews be shown? (true)
 *
 * Documentation:
 *    # Default
 *
 *    {{ example-1 }}
 *
 *    # Without Previews
 *
 *    {{ example-2 }}
 *
 * Example: example-1
 *    <input class="pat-querystring"
 *           data-pat-querystring="indexOptionsUrl: /tests/json/queryStringCriteria.json" />
 *
 * Example: example-2
 *    <input class="pat-querystring"
 *           data-pat-querystring="indexOptionsUrl: /tests/json/queryStringCriteria.json;
 *                                 showPreviews: false;" />
 *
 */


define('mockup-patterns-querystring',[
  'jquery',
  'pat-base',
  'castle-url/libs/react/react.min',
  'castle-url/patterns/querystring/querystring',
  'castle-url/patterns/querystring/store'
], function($, Base, R, QueryStringComponent, StorageFactory) {
  'use strict';

  var QueryString = Base.extend({
    name: 'querystring',
    trigger: '.pat-querystring',
    parser: 'mockup',
    defaults: {
      indexes: [],
      classWrapperName: 'querystring-wrapper',
      criteria: {},
      indexOptionsUrl: null,
      previewURL: 'portal_factory/@@querybuilder_html_results', // base url to use to request preview information from
      previewCountURL: 'portal_factory/@@querybuildernumberofresults',
      classSortLabelName: 'querystring-sort-label',
      classSortReverseName: 'querystring-sortreverse',
      classSortReverseLabelName: 'querystring-sortreverse-label',
      classPreviewCountWrapperName: 'querystring-previewcount-wrapper',
      classPreviewResultsWrapperName: 'querystring-previewresults-wrapper',
      classPreviewWrapperName: 'querystring-preview-wrapper',
      classPreviewName: 'querystring-preview',
      classPreviewTitleName: 'querystring-preview-title',
      classPreviewDescriptionName: 'querystring-preview-description',
      classSortWrapperName: 'querystring-sort-wrapper',
      classAddCriteriaName: 'querystring-add-criteria-wrapper',
      showPreviews: true
    },
    init: function() {
      var self = this;

      // hide input element
      self.$el.hide();

      // create wrapper for out criteria
      self.$wrapper = $('<div/>');
      self.$el.after(self.$wrapper);

      // initialization can be detailed if by ajax
      self.initialized = false;

      self.findRelatedFields();

      if (self.options.indexOptionsUrl) {
        $.ajax({
          url: self.options.indexOptionsUrl,
          success: function(data) {
            self.options.indexes = data.indexes;
            self.options['sortable_indexes'] = data['sortable_indexes']; // jshint ignore:line
            self._init();
          },
          error: function(xhr) {
            // XXX handle this...
          }
        });
      } else {
        self._init();
      }
    },

    findRelatedFields: function(){
      var that = this;
      that.$originalSortOn = that.$originalReversed = null;
      var $form = that.$el.closest('form');
      if($form.size() === 0){
        return;
      }
      var $sortOn = $('input[id*="-sort_on"]', $form);
      if($sortOn.size() > 0){
        that.$originalSortOn = $sortOn;
        that.$originalSortOn.closest('.field').hide();
      }
      var $reversed = $('input[id*="-sort_reversed"]', $form);
      if($reversed.size() > 0){
        that.$originalReversed = $reversed;
        that.$originalReversed.closest('.field').hide();
      }
    },

    _init: function() {
      var that = this;
      that.timer = null;

      that.reversedValue = false;
      that.sortOnValue = false;

      this.storage = StorageFactory();
      this.options.storage = this.storage;

      that.options.afterChange = function(){
        if(that.timer){
          clearTimeout(that.timer);
        }
        that.timer = setTimeout(function(){
          if(that.sortOnValue !== that.component.state.sortOn){
            that.$sortOn.trigger('change');
          }
          if(that.reversedValue !== that.component.state.reversed){
            that.$sortOrder.trigger('change');
          }
          that.$el.val(JSON.stringify(that.component.getQueryString()));
          that.$el.trigger('change');
          that.reversedValue = that.component.state.reversed;
          that.sortOnValue = that.component.state.sortOn;

          if(that.$originalSortOn){
            that.$originalSortOn.val(that.sortOnValue);
            that.$originalSortOn.trigger('change');
          }
          if(that.$originalReversed){
            that.$originalReversed[0].checked = that.reversedValue;
            that.$originalReversed.trigger('change');
          }
        }, 300);
      };

      var component = R.render(
        R.createElement(QueryStringComponent, this.options), this.$wrapper[0]
      );

      that.component = that.$el[0].component = component;
      that.$sortOn = $(that.component.refs.sortOn.refs.select.getDOMNode());
      that.$sortOrder = $(that.component.refs.sortOrder.getDOMNode());

      // check if it has initial values...
      var data = {};
      var value = that.$el.val();
      if(value){
        try{
          data.criterias = JSON.parse(value);
        }catch(e){}
      }
      if(that.$originalSortOn){
        data.sortOn = that.$originalSortOn.val();
      }
      if(that.$originalReversed){
        data.reversed = that.$originalReversed[0].checked;
      }
      that.storage.store.setData(data);
      component.setState(data);

      that.$el.trigger('initialized', that);
    }
  });

  return QueryString;

});

(function(root) {
define("resource-plone-app-jquerytools-js", ["jquery"], function() {
  return (function() {
/**
 * @license 
 * jQuery Tools @VERSION Overlay - Overlay base. Extend it.
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/overlay/
 *
 * Since: March 2008
 * Date: @DATE 
 */
(function($) { 

	// static constructs
	$.tools = $.tools || {version: '@VERSION'};
	
	$.tools.overlay = {
		
		addEffect: function(name, loadFn, closeFn) {
			effects[name] = [loadFn, closeFn];	
		},
	
		conf: {  
			close: null,	
			closeOnClick: true,
			closeOnEsc: true,			
			closeSpeed: 'fast',
			effect: 'default',
			
			// since 1.2. fixed positioning not supported by IE6
			fixed: !/msie/.test(navigator.userAgent.toLowerCase()) || navigator.appVersion > 6, 
			
			left: 'center',		
			load: false, // 1.2
			mask: null,  
			oneInstance: true,
			speed: 'normal',
			target: null, // target element to be overlayed. by default taken from [rel]
			top: '10%'
		}
	};

	
	var instances = [], effects = {};
		
	// the default effect. nice and easy!
	$.tools.overlay.addEffect('default', 
		
		/* 
			onLoad/onClose functions must be called otherwise none of the 
			user supplied callback methods won't be called
		*/
		function(pos, onLoad) {
			
			var conf = this.getConf(),
				 w = $(window);				 
				
			if (!conf.fixed)  {
				pos.top += w.scrollTop();
				pos.left += w.scrollLeft();
			} 
				
			pos.position = conf.fixed ? 'fixed' : 'absolute';
			this.getOverlay().css(pos).fadeIn(conf.speed, onLoad); 
			
		}, function(onClose) {
			this.getOverlay().fadeOut(this.getConf().closeSpeed, onClose); 			
		}		
	);		

	
	function Overlay(trigger, conf) {		
		
		// private variables
		var self = this,
			 fire = trigger.add(self),
			 w = $(window), 
			 closers,            
			 overlay,
			 opened,
			 maskConf = $.tools.expose && (conf.mask || conf.expose),
			 uid = Math.random().toString().slice(10);		
		
			 
		// mask configuration
		if (maskConf) {			
			if (typeof maskConf == 'string') { maskConf = {color: maskConf}; }
			maskConf.closeOnClick = maskConf.closeOnEsc = false;
		}			 
		 
		// get overlay and trigger
		var jq = conf.target || trigger.attr("rel");
		overlay = jq ? $(jq) : null || trigger;	
		
		// overlay not found. cannot continue
		if (!overlay.length) { throw "Could not find Overlay: " + jq; }
		
		// trigger's click event
		if (trigger && trigger.index(overlay) == -1) {
			trigger.click(function(e) {				
				self.load(e);
				return e.preventDefault();
			});
		}   			
		
		// API methods  
		$.extend(self, {

			load: function(e) {
				
				// can be opened only once
				if (self.isOpened()) { return self; }
				
				// find the effect
		 		var eff = effects[conf.effect];
		 		if (!eff) { throw "Overlay: cannot find effect : \"" + conf.effect + "\""; }
				
				// close other instances?
				if (conf.oneInstance) {
					$.each(instances, function() {
						this.close(e);
					});
				}
				
				// onBeforeLoad
				e = e || $.Event();
				e.type = "onBeforeLoad";
				fire.trigger(e);				
				if (e.isDefaultPrevented()) { return self; }				

				// opened
				opened = true;
				
				// possible mask effect
				if (maskConf) { $(overlay).expose(maskConf); }				
				
				// position & dimensions 
				var top = conf.top,					
					 left = conf.left,
					 oWidth = overlay.outerWidth(true),
					 oHeight = overlay.outerHeight(true); 
				
				if (typeof top == 'string')  {
					top = top == 'center' ? Math.max((w.height() - oHeight) / 2, 0) : 
						parseInt(top, 10) / 100 * w.height();			
				}				
				
				if (left == 'center') { left = Math.max((w.width() - oWidth) / 2, 0); }

				
		 		// load effect  		 		
				eff[0].call(self, {top: top, left: left}, function() {					
					if (opened) {
						e.type = "onLoad";
						fire.trigger(e);
					}
				}); 				

				// mask.click closes overlay
				if (maskConf && conf.closeOnClick) {
					$.mask.getMask().one("click", self.close); 
				}
				
				// when window is clicked outside overlay, we close
				if (conf.closeOnClick) {
					$(document).on("click." + uid, function(e) { 
						if (!$(e.target).parents(overlay).length) { 
							self.close(e); 
						}
					});						
				}						
			
				// keyboard::escape
				if (conf.closeOnEsc) { 

					// one callback is enough if multiple instances are loaded simultaneously
					$(document).on("keydown." + uid, function(e) {
						if (e.keyCode == 27) { 
							self.close(e);	 
						}
					});			
				}

				
				return self; 
			}, 
			
			close: function(e) {

				if (!self.isOpened()) { return self; }
				
				e = e || $.Event();
				e.type = "onBeforeClose";
				fire.trigger(e);				
				if (e.isDefaultPrevented()) { return; }				
				
				opened = false;
				
				// close effect
				effects[conf.effect][1].call(self, function() {
					e.type = "onClose";
					fire.trigger(e); 
				});
				
				// unbind the keyboard / clicking actions
				$(document).off("click." + uid + " keydown." + uid);		  
				
				if (maskConf) {
					$.mask.close();		
				}
				 
				return self;
			}, 
			
			getOverlay: function() {
				return overlay;	
			},
			
			getTrigger: function() {
				return trigger;	
			},
			
			getClosers: function() {
				return closers;	
			},			

			isOpened: function()  {
				return opened;
			},
			
			// manipulate start, finish and speeds
			getConf: function() {
				return conf;	
			}			
			
		});
		
		// callbacks	
		$.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","), function(i, name) {
				
			// configuration
			if ($.isFunction(conf[name])) { 
				$(self).on(name, conf[name]); 
			}

			// API
			self[name] = function(fn) {
				if (fn) { $(self).on(name, fn); }
				return self;
			};
		});
		
		// close button
		closers = overlay.find(conf.close || ".close");		
		
		if (!closers.length && !conf.close) {
			closers = $('<a class="close"></a>');
			overlay.prepend(closers);	
		}		
		
		closers.click(function(e) { 
			self.close(e);  
		});	
		
		// autoload
		if (conf.load) { self.load(); }
		
	}
	
	// jQuery plugin initialization
	$.fn.overlay = function(conf) {   
		
		// already constructed --> return API
		var el = this.data("overlay");
		if (el) { return el; }	  		 
		
		if ($.isFunction(conf)) {
			conf = {onBeforeLoad: conf};	
		}

		conf = $.extend(true, {}, $.tools.overlay.conf, conf);
		
		this.each(function() {		
			el = new Overlay($(this), conf);
			instances.push(el);
			$(this).data("overlay", el);	
		});
		
		return conf.api ? el: this;		
	}; 
	
})(jQuery);



/**
 * @license 
 * jQuery Tools @VERSION Scrollable - New wave UI design
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/scrollable.html
 *
 * Since: March 2008
 * Date: @DATE 
 */
(function($) { 

	// static constructs
	$.tools = $.tools || {version: '@VERSION'};
	
	$.tools.scrollable = {
		
		conf: {	
			activeClass: 'active',
			circular: false,
			clonedClass: 'cloned',
			disabledClass: 'disabled',
			easing: 'swing',
			initialIndex: 0,
			item: '> *',
			items: '.items',
			keyboard: true,
			mousewheel: false,
			next: '.next',   
			prev: '.prev', 
			size: 1,
			speed: 400,
			vertical: false,
			touch: true,
			wheelSpeed: 0
		} 
	};
					
	// get hidden element's width or height even though it's hidden
	function dim(el, key) {
		var v = parseInt(el.css(key), 10);
		if (v) { return v; }
		var s = el[0].currentStyle; 
		return s && s.width && parseInt(s.width, 10);	
	}

	function find(root, query) { 
		var el = $(query);
		return el.length < 2 ? el : root.parent().find(query);
	}
	
	var current;		
	
	// constructor
	function Scrollable(root, conf) {   
		
		// current instance
		var self = this, 
			 fire = root.add(self),
			 itemWrap = root.children(),
			 index = 0,
			 vertical = conf.vertical;
				
		if (!current) { current = self; } 
		if (itemWrap.length > 1) { itemWrap = $(conf.items, root); }
		
		
		// in this version circular not supported when size > 1
		if (conf.size > 1) { conf.circular = false; } 
		
		// methods
		$.extend(self, {
				
			getConf: function() {
				return conf;	
			},			
			
			getIndex: function() {
				return index;	
			}, 

			getSize: function() {
				return self.getItems().size();	
			},

			getNaviButtons: function() {
				return prev.add(next);	
			},
			
			getRoot: function() {
				return root;	
			},
			
			getItemWrap: function() {
				return itemWrap;	
			},
			
			getItems: function() {
				return itemWrap.find(conf.item).not("." + conf.clonedClass);	
			},
							
			move: function(offset, time) {
				return self.seekTo(index + offset, time);
			},
			
			next: function(time) {
				return self.move(conf.size, time);	
			},
			
			prev: function(time) {
				return self.move(-conf.size, time);	
			},
			
			begin: function(time) {
				return self.seekTo(0, time);	
			},
			
			end: function(time) {
				return self.seekTo(self.getSize() -1, time);	
			},	
			
			focus: function() {
				current = self;
				return self;
			},
			
			addItem: function(item) {
				item = $(item);
				
				if (!conf.circular)  {
					itemWrap.append(item);
					next.removeClass("disabled");
					
				} else {
					itemWrap.children().last().before(item);
					itemWrap.children().first().replaceWith(item.clone().addClass(conf.clonedClass)); 						
				}
				
				fire.trigger("onAddItem", [item]);
				return self;
			},
			
			
			/* all seeking functions depend on this */		
			seekTo: function(i, time, fn) {	
				
				// ensure numeric index
				if (!i.jquery) { i *= 1; }
				
				// avoid seeking from end clone to the beginning
				if (conf.circular && i === 0 && index == -1 && time !== 0) { return self; }
				
				// check that index is sane				
				if (!conf.circular && i < 0 || i > self.getSize() || i < -1) { return self; }
				
				var item = i;
			
				if (i.jquery) {
					i = self.getItems().index(i);	
					
				} else {
					item = self.getItems().eq(i);
				}  
				
				// onBeforeSeek
				var e = $.Event("onBeforeSeek"); 
				if (!fn) {
					fire.trigger(e, [i, time]);				
					if (e.isDefaultPrevented() || !item.length) { return self; }			
				}  
	
				var props = vertical ? {top: -item.position().top} : {left: -item.position().left};  
				
				index = i;
				current = self;  
				if (time === undefined) { time = conf.speed; }   
				
				itemWrap.animate(props, time, conf.easing, fn || function() { 
					fire.trigger("onSeek", [i]);		
				});	 
				
				return self; 
			}					
			
		});
				
		// callbacks	
		$.each(['onBeforeSeek', 'onSeek', 'onAddItem'], function(i, name) {
				
			// configuration
			if ($.isFunction(conf[name])) { 
				$(self).on(name, conf[name]); 
			}
			
			self[name] = function(fn) {
				if (fn) { $(self).on(name, fn); }
				return self;
			};
		});  
		
		// circular loop
		if (conf.circular) {
			
			var cloned1 = self.getItems().slice(-1).clone().prependTo(itemWrap),
				 cloned2 = self.getItems().eq(1).clone().appendTo(itemWrap);

			cloned1.add(cloned2).addClass(conf.clonedClass);
			
			self.onBeforeSeek(function(e, i, time) {
				
				if (e.isDefaultPrevented()) { return; }
				
				/*
					1. animate to the clone without event triggering
					2. seek to correct position with 0 speed
				*/
				if (i == -1) {
					self.seekTo(cloned1, time, function()  {
						self.end(0);		
					});          
					return e.preventDefault();
					
				} else if (i == self.getSize()) {
					self.seekTo(cloned2, time, function()  {
						self.begin(0);		
					});	
				}
				
			});

			// seek over the cloned item

			// if the scrollable is hidden the calculations for seekTo position
			// will be incorrect (eg, if the scrollable is inside an overlay).
			// ensure the elements are shown, calculate the correct position,
			// then re-hide the elements. This must be done synchronously to
			// prevent the hidden elements being shown to the user.

			// See: https://github.com/jquerytools/jquerytools/issues#issue/87

			var hidden_parents = root.parents().add(root).filter(function () {
				if ($(this).css('display') === 'none') {
					return true;
				}
			});
			if (hidden_parents.length) {
				hidden_parents.show();
				self.seekTo(0, 0, function() {});
				hidden_parents.hide();
			}
			else {
				self.seekTo(0, 0, function() {});
			}

		}
		
		// next/prev buttons
		var prev = find(root, conf.prev).click(function(e) { e.stopPropagation(); self.prev(); }),
			 next = find(root, conf.next).click(function(e) { e.stopPropagation(); self.next(); }); 
		
		if (!conf.circular) {
			self.onBeforeSeek(function(e, i) {
				setTimeout(function() {
					if (!e.isDefaultPrevented()) {
						prev.toggleClass(conf.disabledClass, i <= 0);
						next.toggleClass(conf.disabledClass, i >= self.getSize() -1);
					}
				}, 1);
			});
			
			if (!conf.initialIndex) {
				prev.addClass(conf.disabledClass);	
			}			
		}
			
		if (self.getSize() < 2) {
			prev.add(next).addClass(conf.disabledClass);	
		}
			
		// mousewheel support
		if (conf.mousewheel && $.fn.mousewheel) {
			root.mousewheel(function(e, delta)  {
				if (conf.mousewheel) {
					self.move(delta < 0 ? 1 : -1, conf.wheelSpeed || 50);
					return false;
				}
			});			
		}
		
		// touch event
		if (conf.touch) {
			var touch = {};
			
			itemWrap[0].ontouchstart = function(e) {
				var t = e.touches[0];
				touch.x = t.clientX;
				touch.y = t.clientY;
			};
			
			itemWrap[0].ontouchmove = function(e) {
				
				// only deal with one finger
				if (e.touches.length == 1 && !itemWrap.is(":animated")) {			
					var t = e.touches[0],
						 deltaX = touch.x - t.clientX,
						 deltaY = touch.y - t.clientY;
	
					self[vertical && deltaY > 0 || !vertical && deltaX > 0 ? 'next' : 'prev']();				
					e.preventDefault();
				}
			};
		}
		
		if (conf.keyboard)  {
			
			$(document).on("keydown.scrollable", function(evt) {

				// skip certain conditions
				if (!conf.keyboard || evt.altKey || evt.ctrlKey || evt.metaKey || $(evt.target).is(":input")) { 
					return; 
				}
				
				// does this instance have focus?
				if (conf.keyboard != 'static' && current != self) { return; }
					
				var key = evt.keyCode;
			
				if (vertical && (key == 38 || key == 40)) {
					self.move(key == 38 ? -1 : 1);
					return evt.preventDefault();
				}
				
				if (!vertical && (key == 37 || key == 39)) {					
					self.move(key == 37 ? -1 : 1);
					return evt.preventDefault();
				}	  
				
			});  
		}
		
		// initial index
		if (conf.initialIndex) {
			self.seekTo(conf.initialIndex, 0, function() {});
		}
	} 

		
	// jQuery plugin implementation
	$.fn.scrollable = function(conf) { 
			
		// already constructed --> return API
		var el = this.data("scrollable");
		if (el) { return el; }		 

		conf = $.extend({}, $.tools.scrollable.conf, conf); 
		
		this.each(function() {			
			el = new Scrollable($(this), conf);
			$(this).data("scrollable", el);	
		});
		
		return conf.api ? el: this; 
		
	};
			
	
})(jQuery);


/**
 * @license 
 * jQuery Tools @VERSION Tabs- The basics of UI design.
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/tabs/
 *
 * Since: November 2008
 * Date: @DATE 
 */  
(function($) {
		
	// static constructs
	$.tools = $.tools || {version: '@VERSION'};
	
	$.tools.tabs = {
		
		conf: {
			tabs: 'a',
			current: 'current',
			onBeforeClick: null,
			onClick: null, 
			effect: 'default',
			initialEffect: false,   // whether or not to show effect in first init of tabs
			initialIndex: 0,			
			event: 'click',
			rotate: false,
			
      // slide effect
      slideUpSpeed: 400,
      slideDownSpeed: 400,
			
			// 1.2
			history: false
		},
		
		addEffect: function(name, fn) {
			effects[name] = fn;
		}
		
	};
	
	var effects = {
		
		// simple "toggle" effect
		'default': function(i, done) { 
			this.getPanes().hide().eq(i).show();
			done.call();
		}, 
		
		/*
			configuration:
				- fadeOutSpeed (positive value does "crossfading")
				- fadeInSpeed
		*/
		fade: function(i, done) {		
			
			var conf = this.getConf(),
				 speed = conf.fadeOutSpeed,
				 panes = this.getPanes();
			
			if (speed) {
				panes.fadeOut(speed);	
			} else {
				panes.hide();	
			}

			panes.eq(i).fadeIn(conf.fadeInSpeed, done);	
		},
		
		// for basic accordions
		slide: function(i, done) {
		  var conf = this.getConf();
		  
			this.getPanes().slideUp(conf.slideUpSpeed);
			this.getPanes().eq(i).slideDown(conf.slideDownSpeed, done);			 
		}, 

		/**
		 * AJAX effect
		 */
		ajax: function(i, done)  {			
			this.getPanes().eq(0).load(this.getTabs().eq(i).attr("href"), done);	
		}		
	};   	
	
	/**
	 * Horizontal accordion
	 * 
	 * @deprecated will be replaced with a more robust implementation
	*/
	
	var
	  /**
	  *   @type {Boolean}
	  *
	  *   Mutex to control horizontal animation
	  *   Disables clicking of tabs while animating
	  *   They mess up otherwise as currentPane gets set *after* animation is done
	  */
	  animating,
	  /**
	  *   @type {Number}
	  *   
	  *   Initial width of tab panes
	  */
	  w;
	 
	$.tools.tabs.addEffect("horizontal", function(i, done) {
	  if (animating) return;    // don't allow other animations
	  
	  var nextPane = this.getPanes().eq(i),
	      currentPane = this.getCurrentPane();
	      
		// store original width of a pane into memory
		w || ( w = this.getPanes().eq(0).width() );
		animating = true;
		
		nextPane.show(); // hidden by default
		
		// animate current pane's width to zero
    // animate next pane's width at the same time for smooth animation
    currentPane.animate({width: 0}, {
      step: function(now){
        nextPane.css("width", w-now);
      },
      complete: function(){
        $(this).hide();
        done.call();
        animating = false;
     }
    });
    // Dirty hack...  onLoad, currentPant will be empty and nextPane will be the first pane
    // If this is the case, manually run callback since the animation never occured, and reset animating
    if (!currentPane.length){ 
      done.call(); 
      animating = false;
    }
	});	

	
	function Tabs(root, paneSelector, conf) {
		
		var self = this,
        trigger = root.add(this),
        tabs = root.find(conf.tabs),
        panes = paneSelector.jquery ? paneSelector : root.children(paneSelector),
        current;
			 
		
		// make sure tabs and panes are found
		if (!tabs.length)  { tabs = root.children(); }
		if (!panes.length) { panes = root.parent().find(paneSelector); }
		if (!panes.length) { panes = $(paneSelector); }
		
		
		// public methods
		$.extend(this, {				
			click: function(i, e) {
			  
				var tab = tabs.eq(i),
				    firstRender = !root.data('tabs');
				
				if (typeof i == 'string' && i.replace("#", "")) {
					tab = tabs.filter("[href*=\"" + i.replace("#", "") + "\"]");
					i = Math.max(tabs.index(tab), 0);
				}
								
				if (conf.rotate) {
					var last = tabs.length -1; 
					if (i < 0) { return self.click(last, e); }
					if (i > last) { return self.click(0, e); }						
				}
				
				if (!tab.length) {
					if (current >= 0) { return self; }
					i = conf.initialIndex;
					tab = tabs.eq(i);
				}				
				
				// current tab is being clicked
				if (i === current) { return self; }
				
				// possibility to cancel click action				
				e = e || $.Event();
				e.type = "onBeforeClick";
				trigger.trigger(e, [i]);				
				if (e.isDefaultPrevented()) { return; }
				
        // if firstRender, only run effect if initialEffect is set, otherwise default
				var effect = firstRender ? conf.initialEffect && conf.effect || 'default' : conf.effect;

				// call the effect
				effects[effect].call(self, i, function() {
					current = i;
					// onClick callback
					e.type = "onClick";
					trigger.trigger(e, [i]);
				});			
				
				// default behaviour
				tabs.removeClass(conf.current);	
				tab.addClass(conf.current);				
				
				return self;
			},
			
			getConf: function() {
				return conf;	
			},

			getTabs: function() {
				return tabs;	
			},
			
			getPanes: function() {
				return panes;	
			},
			
			getCurrentPane: function() {
				return panes.eq(current);	
			},
			
			getCurrentTab: function() {
				return tabs.eq(current);	
			},
			
			getIndex: function() {
				return current;	
			}, 
			
			next: function() {
				return self.click(current + 1);
			},
			
			prev: function() {
				return self.click(current - 1);	
			},
			
			destroy: function() {
				tabs.off(conf.event).removeClass(conf.current);
				panes.find("a[href^=\"#\"]").off("click.T"); 
				return self;
			}
		
		});

		// callbacks	
		$.each("onBeforeClick,onClick".split(","), function(i, name) {
				
			// configuration
			if ($.isFunction(conf[name])) {
				$(self).on(name, conf[name]); 
			}

			// API
			self[name] = function(fn) {
				if (fn) { $(self).on(name, fn); }
				return self;	
			};
		});
	
		
		if (conf.history && $.fn.history) {
			$.tools.history.init(tabs);
			conf.event = 'history';
		}	
		
		// setup click actions for each tab
		tabs.each(function(i) { 				
			$(this).on(conf.event, function(e) {
				self.click(i, e);
				return e.preventDefault();
			});			
		});
		
		// cross tab anchor link
		panes.find("a[href^=\"#\"]").on("click.T", function(e) {
			self.click($(this).attr("href"), e);		
		}); 
		
		// open initial tab
		if (location.hash && conf.tabs == "a" && root.find("[href=\"" +location.hash+ "\"]").length) {
			self.click(location.hash);

		} else {
			if (conf.initialIndex === 0 || conf.initialIndex > 0) {
				self.click(conf.initialIndex);
			}
		}				
		
	}
	
	
	// jQuery plugin implementation
	$.fn.tabs = function(paneSelector, conf) {
		
		// return existing instance
		var el = this.data("tabs");
		if (el) { 
			el.destroy();	
			this.removeData("tabs");
		}

		if ($.isFunction(conf)) {
			conf = {onBeforeClick: conf};
		}
		
		// setup conf
		conf = $.extend({}, $.tools.tabs.conf, conf);		
		
		
		this.each(function() {				
			el = new Tabs($(this), paneSelector, conf);
			$(this).data("tabs", el); 
		});		
		
		return conf.api ? el: this;		
	};		
		
}) (jQuery); 




/**
 * @license 
 * jQuery Tools @VERSION History "Back button for AJAX apps"
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/toolbox/history.html
 * 
 * Since: Mar 2010
 * Date: @DATE 
 */
(function($) {
		
	var hash, iframe, links, inited;		
	
	$.tools = $.tools || {version: '@VERSION'};
	
	$.tools.history = {
	
		init: function(els) {
			
			if (inited) { return; }
			
			// IE
			if ($.browser.msie && $.browser.version < '8') {
				
				// create iframe that is constantly checked for hash changes
				if (!iframe) {
					iframe = $("<iframe/>").attr("src", "javascript:false;").hide().get(0);
					$("body").append(iframe);
									
					setInterval(function() {
						var idoc = iframe.contentWindow.document, 
							 h = idoc.location.hash;
					
						if (hash !== h) {						
							$(window).trigger("hash", h);
						}
					}, 100);
					
					setIframeLocation(location.hash || '#');
				}

				
			// other browsers scans for location.hash changes directly without iframe hack
			} else { 
				setInterval(function() {
					var h = location.hash;
					if (h !== hash) {
						$(window).trigger("hash", h);
					}						
				}, 100);
			}

			links = !links ? els : links.add(els);
			
			els.click(function(e) {
				var href = $(this).attr("href");
				if (iframe) { setIframeLocation(href); }
				
				// handle non-anchor links
				if (href.slice(0, 1) != "#") {
					location.href = "#" + href;
					return e.preventDefault();		
				}
				
			}); 
			
			inited = true;
		}	
	};  
	

	function setIframeLocation(h) {
		if (h) {
			var doc = iframe.contentWindow.document;
			doc.open().close();	
			doc.location.hash = h;
		}
	} 
		 
	// global histroy change listener
	$(window).on("hash", function(e, h)  { 
		if (h) {
			links.filter(function() {
			  var href = $(this).attr("href");
			  return href == h || href == h.replace("#", ""); 
			}).trigger("history", [h]);	
		} else {
			links.eq(0).trigger("history", [h]);	
		}

		hash = h;

	});
		
	
	// jQuery plugin implementation
	$.fn.history = function(fn) {
			
		$.tools.history.init(this);

		// return jQuery
		return this.on("history", fn);		
	};	
		
})(jQuery); 



/**
 * @license 
 * jQuery Tools @VERSION / Expose - Dim the lights
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/toolbox/expose.html
 *
 * Since: Mar 2010
 * Date: @DATE 
 */
(function($) { 	

	// static constructs
	$.tools = $.tools || {version: '@VERSION'};
	
	var tool;
	
	tool = $.tools.expose = {
		
		conf: {	
			maskId: 'exposeMask',
			loadSpeed: 'slow',
			closeSpeed: 'fast',
			closeOnClick: true,
			closeOnEsc: true,
			
			// css settings
			zIndex: 9998,
			opacity: 0.8,
			startOpacity: 0,
			color: '#fff',
			
			// callbacks
			onLoad: null,
			onClose: null
		}
	};

	/* one of the greatest headaches in the tool. finally made it */
	function viewport() {
				
		// the horror case
		if (/msie/.test(navigator.userAgent.toLowerCase())) {
			
			// if there are no scrollbars then use window.height
			var d = $(document).height(), w = $(window).height();
			
			return [
				window.innerWidth || 							// ie7+
				document.documentElement.clientWidth || 	// ie6  
				document.body.clientWidth, 					// ie6 quirks mode
				d - w < 20 ? w : d
			];
		} 
		
		// other well behaving browsers
		return [$(document).width(), $(document).height()]; 
	} 
	
	function call(fn) {
		if (fn) { return fn.call($.mask); }
	}
	
	var mask, exposed, loaded, config, overlayIndex;		
	
	
	$.mask = {
		
		load: function(conf, els) {
			
			// already loaded ?
			if (loaded) { return this; }			
			
			// configuration
			if (typeof conf == 'string') {
				conf = {color: conf};	
			}
			
			// use latest config
			conf = conf || config;
			
			config = conf = $.extend($.extend({}, tool.conf), conf);

			// get the mask
			mask = $("#" + conf.maskId);
				
			// or create it
			if (!mask.length) {
				mask = $('<div/>').attr("id", conf.maskId);
				$("body").append(mask);
			}
			
			// set position and dimensions 			
			var size = viewport();
				
			mask.css({				
				position:'absolute', 
				top: 0, 
				left: 0,
				width: size[0],
				height: size[1],
				display: 'none',
				opacity: conf.startOpacity,					 		
				zIndex: conf.zIndex 
			});
			
			if (conf.color) {
				mask.css("backgroundColor", conf.color);	
			}			
			
			// onBeforeLoad
			if (call(conf.onBeforeLoad) === false) {
				return this;
			}
			
			// esc button
			if (conf.closeOnEsc) {						
				$(document).on("keydown.mask", function(e) {							
					if (e.keyCode == 27) {
						$.mask.close(e);	
					}		
				});			
			}
			
			// mask click closes
			if (conf.closeOnClick) {
				mask.on("click.mask", function(e)  {
					$.mask.close(e);		
				});					
			}			
			
			// resize mask when window is resized
			$(window).on("resize.mask", function() {
				$.mask.fit();
			});
			
			// exposed elements
			if (els && els.length) {
				
				overlayIndex = els.eq(0).css("zIndex");

				// make sure element is positioned absolutely or relatively
				$.each(els, function() {
					var el = $(this);
					if (!/relative|absolute|fixed/i.test(el.css("position"))) {
						el.css("position", "relative");		
					}					
				});
			 
				// make elements sit on top of the mask
				exposed = els.css({ zIndex: Math.max(conf.zIndex + 1, overlayIndex == 'auto' ? 0 : overlayIndex)});			
			}	
			
			// reveal mask
			mask.css({display: 'block'}).fadeTo(conf.loadSpeed, conf.opacity, function() {
				$.mask.fit(); 
				call(conf.onLoad);
				loaded = "full";
			});
			
			loaded = true;			
			return this;				
		},
		
		close: function() {
			if (loaded) {
				
				// onBeforeClose
				if (call(config.onBeforeClose) === false) { return this; }
					
				mask.fadeOut(config.closeSpeed, function()  {										
					if (exposed) {
						exposed.css({zIndex: overlayIndex});						
					}				
					loaded = false;
					call(config.onClose);
				});				
				
				// unbind various event listeners
				$(document).off("keydown.mask");
				mask.off("click.mask");
				$(window).off("resize.mask");  
			}
			
			return this; 
		},
		
		fit: function() {
			if (loaded) {
				var size = viewport();				
				mask.css({width: size[0], height: size[1]});
			}				
		},
		
		getMask: function() {
			return mask;	
		},
		
		isLoaded: function(fully) {
			return fully ? loaded == 'full' : loaded;	
		}, 
		
		getConf: function() {
			return config;	
		},
		
		getExposed: function() {
			return exposed;	
		}		
	};
	
	$.fn.mask = function(conf) {
		$.mask.load(conf);
		return this;		
	};			
	
	$.fn.expose = function(conf) {
		$.mask.load(conf, this);
		return this;			
	};


})(jQuery);


/**
 * @license 
 * jQuery Tools @VERSION Tooltip - UI essentials
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/tooltip/
 *
 * Since: November 2008
 * Date: @DATE 
 */
(function($) { 	
	// static constructs
	$.tools = $.tools || {version: '@VERSION'};
	
	$.tools.tooltip = {
		
		conf: { 
			
			// default effect variables
			effect: 'toggle',			
			fadeOutSpeed: "fast",
			predelay: 0,
			delay: 30,
			opacity: 1,			
			tip: 0,
            fadeIE: false, // enables fade effect in IE
			
			// 'top', 'bottom', 'right', 'left', 'center'
			position: ['top', 'center'], 
			offset: [0, 0],
			relative: false,
			cancelDefault: true,
			
			// type to event mapping 
			events: {
				def: 			"mouseenter,mouseleave",
				input: 		"focus,blur",
				widget:		"focus mouseenter,blur mouseleave",
				tooltip:		"mouseenter,mouseleave"
			},
			
			// 1.2
			layout: '<div/>',
			tipClass: 'tooltip'
		},
		
		addEffect: function(name, loadFn, hideFn) {
			effects[name] = [loadFn, hideFn];	
		} 
	};
	
	
	var effects = { 
		toggle: [ 
			function(done) { 
				var conf = this.getConf(), tip = this.getTip(), o = conf.opacity;
				if (o < 1) { tip.css({opacity: o}); }
				tip.show();
				done.call();
			},
			
			function(done) { 
				this.getTip().hide();
				done.call();
			} 
		],
		
		fade: [
			function(done) {
				var conf = this.getConf();
				if (!/msie/.test(navigator.userAgent.toLowerCase()) || conf.fadeIE) {
					this.getTip().fadeTo(conf.fadeInSpeed, conf.opacity, done);
				}
				else {
					this.getTip().show();
					done();
				}
			},
			function(done) {
				var conf = this.getConf();
				if (!/msie/.test(navigator.userAgent.toLowerCase()) || conf.fadeIE) {
					this.getTip().fadeOut(conf.fadeOutSpeed, done);
				}
				else {
					this.getTip().hide();
					done();
				}
			}
		]		
	};   

		
	/* calculate tip position relative to the trigger */  	
	function getPosition(trigger, tip, conf) {	

		
		// get origin top/left position 
		var top = conf.relative ? trigger.position().top : trigger.offset().top, 
			 left = conf.relative ? trigger.position().left : trigger.offset().left,
			 pos = conf.position[0];

		top  -= tip.outerHeight() - conf.offset[0];
		left += trigger.outerWidth() + conf.offset[1];
		
		// iPad position fix
		if (/iPad/i.test(navigator.userAgent)) {
			top -= $(window).scrollTop();
		}
		
		// adjust Y		
		var height = tip.outerHeight() + trigger.outerHeight();
		if (pos == 'center') 	{ top += height / 2; }
		if (pos == 'bottom') 	{ top += height; }
		
		
		// adjust X
		pos = conf.position[1]; 	
		var width = tip.outerWidth() + trigger.outerWidth();
		if (pos == 'center') 	{ left -= width / 2; }
		if (pos == 'left')   	{ left -= width; }	 
		
		return {top: top, left: left};
	}		

	
	
	function Tooltip(trigger, conf) {

		var self = this, 
			 fire = trigger.add(self),
			 tip,
			 timer = 0,
			 pretimer = 0, 
			 title = trigger.attr("title"),
			 tipAttr = trigger.attr("data-tooltip"),
			 effect = effects[conf.effect],
			 shown,
				 
			 // get show/hide configuration
			 isInput = trigger.is(":input"), 
			 isWidget = isInput && trigger.is(":checkbox, :radio, select, :button, :submit"),			
			 type = trigger.attr("type"),
			 evt = conf.events[type] || conf.events[isInput ? (isWidget ? 'widget' : 'input') : 'def']; 
		
		
		// check that configuration is sane
		if (!effect) { throw "Nonexistent effect \"" + conf.effect + "\""; }					
		
		evt = evt.split(/,\s*/); 
		if (evt.length != 2) { throw "Tooltip: bad events configuration for " + type; } 
		
		
		// trigger --> show  
		trigger.on(evt[0], function(e) {

			clearTimeout(timer);
			if (conf.predelay) {
				pretimer = setTimeout(function() { self.show(e); }, conf.predelay);	
				
			} else {
				self.show(e);	
			}
			
		// trigger --> hide
		}).on(evt[1], function(e)  {
			clearTimeout(pretimer);
			if (conf.delay)  {
				timer = setTimeout(function() { self.hide(e); }, conf.delay);	
				
			} else {
				self.hide(e);		
			}
			
		}); 
		
		
		// remove default title
		if (title && conf.cancelDefault) { 
			trigger.removeAttr("title");
			trigger.data("title", title);			
		}		
		
		$.extend(self, {
				
			show: function(e) {  

				// tip not initialized yet
				if (!tip) {
					
					// data-tooltip 
					if (tipAttr) {
						tip = $(tipAttr);

					// single tip element for all
					} else if (conf.tip) { 
						tip = $(conf.tip).eq(0);
						
					// autogenerated tooltip
					} else if (title) { 
						tip = $(conf.layout).addClass(conf.tipClass).appendTo(document.body)
							.hide().append(title);

					// manual tooltip
					} else {	
						tip = trigger.find('.' + conf.tipClass);
						if (!tip.length) { tip = trigger.next(); }
						if (!tip.length) { tip = trigger.parent().next(); } 	 
					}
					
					if (!tip.length) { throw "Cannot find tooltip for " + trigger;	}
				} 
			 	
			 	if (self.isShown()) { return self; }  
				
			 	// stop previous animation
			 	tip.stop(true, true); 			 	
			 	
				// get position
				var pos = getPosition(trigger, tip, conf);			
		
				// restore title for single tooltip element
				if (conf.tip) {
					tip.html(trigger.data("title"));
				}

				// onBeforeShow
				e = $.Event();
				e.type = "onBeforeShow";
				fire.trigger(e, [pos]);				
				if (e.isDefaultPrevented()) { return self; }
		
				
				// onBeforeShow may have altered the configuration
				pos = getPosition(trigger, tip, conf);
				
				// set position
				tip.css({position:'absolute', top: pos.top, left: pos.left});					
				
				shown = true;
				
				// invoke effect 
				effect[0].call(self, function() {
					e.type = "onShow";
					shown = 'full';
					fire.trigger(e);		 
				});					

	 	
				// tooltip events       
				var event = conf.events.tooltip.split(/,\s*/);

				if (!tip.data("__set")) {
					
					tip.off(event[0]).on(event[0], function() { 
						clearTimeout(timer);
						clearTimeout(pretimer);
					});
					
					if (event[1] && !trigger.is("input:not(:checkbox, :radio), textarea")) { 					
						tip.off(event[1]).on(event[1], function(e) {
	
							// being moved to the trigger element
							if (e.relatedTarget != trigger[0]) {
								trigger.trigger(evt[1].split(" ")[0]);
							}
						}); 
					} 
					
					// bind agein for if same tip element
					if (!conf.tip) tip.data("__set", true);
				}
				
				return self;
			},
			
			hide: function(e) {

				if (!tip || !self.isShown()) { return self; }
			
				// onBeforeHide
				e = $.Event();
				e.type = "onBeforeHide";
				fire.trigger(e);				
				if (e.isDefaultPrevented()) { return; }
	
				shown = false;
				
				effects[conf.effect][1].call(self, function() {
					e.type = "onHide";
					fire.trigger(e);		 
				});
				
				return self;
			},
			
			isShown: function(fully) {
				return fully ? shown == 'full' : shown;	
			},
				
			getConf: function() {
				return conf;	
			},
				
			getTip: function() {
				return tip;	
			},
			
			getTrigger: function() {
				return trigger;	
			}		

		});		

		// callbacks	
		$.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","), function(i, name) {
				
			// configuration
			if ($.isFunction(conf[name])) { 
				$(self).on(name, conf[name]); 
			}

			// API
			self[name] = function(fn) {
				if (fn) { $(self).on(name, fn); }
				return self;
			};
		});
		
	}
		
	
	// jQuery plugin implementation
	$.fn.tooltip = function(conf) {
		
		// return existing instance
		var api = this.data("tooltip");
		if (api) { return api; }

		conf = $.extend(true, {}, $.tools.tooltip.conf, conf);
		
		// position can also be given as string
		if (typeof conf.position == 'string') {
			conf.position = conf.position.split(/,?\s/);	
		}
		
		// install tooltip for each entry in jQuery object
		this.each(function() {
			api = new Tooltip($(this), conf); 
			$(this).data("tooltip", api); 
		});
		
		return conf.api ? api: this;		 
	};
		
}) (jQuery);

		



  }).apply(root, arguments);
});
}(this));

(function(root) {
define("resource-plone-app-jquerytools-dateinput-js", ["jquery"], function() {
  return (function() {
!function($,undefined){function dayAm(year,month){return new Date(year,month+1,0).getDate()}function zeropad(val,len){for(val=""+val,len=len||2;val.length<len;)val="0"+val;return val}function format(formatter,date,text,lang){var d=date.getDate(),D=date.getDay(),m=date.getMonth(),y=date.getFullYear(),flags={d:d,dd:zeropad(d),ddd:LABELS[lang].shortDays[D],dddd:LABELS[lang].days[D],m:m+1,mm:zeropad(m+1),mmm:LABELS[lang].shortMonths[m],mmmm:LABELS[lang].months[m],yy:String(y).slice(2),yyyy:y},ret=formatters[formatter](text,date,flags,lang);return tmpTag.html(ret).html()}function integer(val){return parseInt(val,10)}function isSameDay(d1,d2){return d1.getFullYear()===d2.getFullYear()&&d1.getMonth()==d2.getMonth()&&d1.getDate()==d2.getDate()}function parseDate(val){if(val!==undefined){if(val.constructor==Date)return val;if("string"==typeof val){var els=val.split("-");if(3==els.length)return new Date(integer(els[0]),integer(els[1])-1,integer(els[2]));if(!/^-?\d+$/.test(val))return;val=integer(val)}var date=new Date;return date.setDate(date.getDate()+val),date}}function Dateinput(input,conf){function select(date,conf,e){return input.attr("readonly")?void self.hide(e):(value=date,currYear=date.getFullYear(),currMonth=date.getMonth(),currDay=date.getDate(),e||(e=$.Event("api")),"click"!=e.type||/msie/.test(navigator.userAgent.toLowerCase())||input.focus(),e.type="beforeChange",fire.trigger(e,[date]),void(e.isDefaultPrevented()||(input.val(format(conf.formatter,date,conf.format,conf.lang)),e.type="change",e.target=input[0],fire.trigger(e),input.data("date",date),self.hide(e))))}function onShow(ev){ev.type="onShow",fire.trigger(ev),$(document).on("keydown.d",function(e){if(e.ctrlKey)return!0;var key=e.keyCode;if(8==key||46==key)return input.val(""),self.hide(e);if(27==key||9==key)return self.hide(e);if($(KEYS).index(key)>=0){if(!opened)return self.show(e),e.preventDefault();var days=$("#"+css.weeks+" a"),el=$("."+css.focus),index=days.index(el);return el.removeClass(css.focus),74==key||40==key?index+=7:75==key||38==key?index-=7:76==key||39==key?index+=1:(72==key||37==key)&&(index-=1),index>41?(self.addMonth(),el=$("#"+css.weeks+" a:eq("+(index-42)+")")):0>index?(self.addMonth(-1),el=$("#"+css.weeks+" a:eq("+(index+42)+")")):el=days.eq(index),el.addClass(css.focus),e.preventDefault()}return 34==key?self.addMonth():33==key?self.addMonth(-1):36==key?self.today():(13==key&&($(e.target).is("select")||$("."+css.focus).click()),$([16,17,18,9]).index(key)>=0)}),$(document).on("click.d",function(e){var el=e.target;el.id==css.root||$(el).parents("#"+css.root).length||el==input[0]||trigger&&el==trigger[0]||self.hide(e)})}var trigger,pm,nm,currYear,currMonth,currDay,opened,original,self=this,now=new Date,yearNow=now.getFullYear(),css=conf.css,labels=LABELS[conf.lang],root=$("#"+css.root),title=root.find("#"+css.title),value=input.attr("data-value")||conf.value||input.val(),min=input.attr("min")||conf.min,max=input.attr("max")||conf.max;if(0===min&&(min="0"),value=parseDate(value)||now,min=parseDate(min||new Date(yearNow+conf.yearRange[0],1,1)),max=parseDate(max||new Date(yearNow+conf.yearRange[1]+1,1,-1)),!labels)throw"Dateinput: invalid language: "+conf.lang;if("date"==input.attr("type")){var original=input.clone(),def=original.wrap("<div/>").parent().html(),clone=$(def.replace(/type/i,"type=text data-orig-type"));conf.value&&clone.val(conf.value),input.replaceWith(clone),input=clone}input.addClass(css.input);var fire=input.add(self);if(!root.length){if(root=$("<div><div><a/><div/><a/></div><div><div/><div/></div></div>").hide().css({position:"absolute"}).attr("id",css.root),root.children().eq(0).attr("id",css.head).end().eq(1).attr("id",css.body).children().eq(0).attr("id",css.days).end().eq(1).attr("id",css.weeks).end().end().end().find("a").eq(0).attr("id",css.prev).end().eq(1).attr("id",css.next),title=root.find("#"+css.head).find("div").attr("id",css.title),conf.selectors){var monthSelector=$("<select/>").attr("id",css.month),yearSelector=$("<select/>").attr("id",css.year);title.html(monthSelector.add(yearSelector))}for(var days=root.find("#"+css.days),d=0;7>d;d++)days.append($("<span/>").text(labels.shortDays[(d+conf.firstDay)%7]));$("body").append(root)}conf.trigger&&(trigger=$("<a/>").attr("href","#").addClass(css.trigger).click(function(e){return conf.toggle?self.toggle():self.show(),e.preventDefault()}).insertAfter(input));var weeks=root.find("#"+css.weeks);yearSelector=root.find("#"+css.year),monthSelector=root.find("#"+css.month),$.extend(self,{show:function(e){if(!input.attr("disabled")&&!opened&&(e=e||$.Event(),e.type="onBeforeShow",fire.trigger(e),!e.isDefaultPrevented())){$.each(instances,function(){this.hide()}),opened=!0,monthSelector.off("change").change(function(){self.setValue(integer(yearSelector.val()),integer($(this).val()))}),yearSelector.off("change").change(function(){self.setValue(integer($(this).val()),integer(monthSelector.val()))}),pm=root.find("#"+css.prev).off("click").click(function(){return pm.hasClass(css.disabled)||self.addMonth(-1),!1}),nm=root.find("#"+css.next).off("click").click(function(){return nm.hasClass(css.disabled)||self.addMonth(),!1}),self.setValue(value);var pos=input.offset();return/iPad/i.test(navigator.userAgent)&&(pos.top-=$(window).scrollTop()),root.css({top:pos.top+input.outerHeight(!0)+conf.offset[0],left:pos.left+conf.offset[1]}),conf.speed?root.show(conf.speed,function(){onShow(e)}):(root.show(),onShow(e)),self}},setValue:function(year,month,day){var date=integer(month)>=-1?new Date(integer(year),integer(month),integer(day==undefined||isNaN(day)?1:day)):year||value;if(min>date?date=min:date>max&&(date=max),"string"==typeof year&&(date=parseDate(year)),year=date.getFullYear(),month=date.getMonth(),day=date.getDate(),-1==month?(month=11,year--):12==month&&(month=0,year++),!opened)return select(date,conf),self;currMonth=month,currYear=year,currDay=day;var week,tmp=new Date(year,month,1-conf.firstDay),begin=tmp.getDay(),days=dayAm(year,month),prevDays=dayAm(year,month-1);if(conf.selectors){monthSelector.empty(),$.each(labels.months,function(i,m){min<new Date(year,i+1,1)&&max>new Date(year,i,0)&&monthSelector.append($("<option/>").html(m).attr("value",i))}),yearSelector.empty();for(var yearNow=now.getFullYear(),i=yearNow+conf.yearRange[0];i<yearNow+conf.yearRange[1];i++)min<new Date(i+1,0,1)&&max>new Date(i,0,0)&&yearSelector.append($("<option/>").text(i));monthSelector.val(month),yearSelector.val(year)}else title.html(labels.months[month]+" "+year);weeks.empty(),pm.add(nm).removeClass(css.disabled);for(var a,num,j=begin?0:-7;(begin?42:35)>j;j++)a=$("<a/>"),j%7===0&&(week=$("<div/>").addClass(css.week),weeks.append(week)),begin>j?(a.addClass(css.off),num=prevDays-begin+j+1,date=new Date(year,month-1,num)):j>=begin+days?(a.addClass(css.off),num=j-days-begin+1,date=new Date(year,month+1,num)):(num=j-begin+1,date=new Date(year,month,num),isSameDay(value,date)?a.attr("id",css.current).addClass(css.focus):isSameDay(now,date)&&a.attr("id",css.today)),min&&min>date&&a.add(pm).addClass(css.disabled),max&&date>max&&a.add(nm).addClass(css.disabled),a.attr("href","#"+num).text(num).data("date",date),week.append(a);return weeks.find("a").click(function(e){var el=$(this);return el.hasClass(css.disabled)||($("#"+css.current).removeAttr("id"),el.attr("id",css.current),select(el.data("date"),conf,e)),!1}),css.sunday&&weeks.find("."+css.week).each(function(){var beg=conf.firstDay?7-conf.firstDay:0;$(this).children().slice(beg,beg+1).addClass(css.sunday)}),self},setMin:function(val,fit){return min=parseDate(val),fit&&min>value&&self.setValue(min),self},setMax:function(val,fit){return max=parseDate(val),fit&&value>max&&self.setValue(max),self},today:function(){return self.setValue(now)},addDay:function(amount){return this.setValue(currYear,currMonth,currDay+(amount||1))},addMonth:function(amount){var targetMonth=currMonth+(amount||1),daysInTargetMonth=dayAm(currYear,targetMonth),targetDay=daysInTargetMonth>=currDay?currDay:daysInTargetMonth;return this.setValue(currYear,targetMonth,targetDay)},addYear:function(amount){return this.setValue(currYear+(amount||1),currMonth,currDay)},destroy:function(){input.add(document).off("click.d keydown.d"),root.add(trigger).remove(),input.removeData("dateinput").removeClass(css.input),original&&input.replaceWith(original)},hide:function(e){if(opened){if(e=$.Event(),e.type="onHide",fire.trigger(e),e.isDefaultPrevented())return;$(document).off("click.d keydown.d"),root.hide(),opened=!1}return self},toggle:function(){return self.isOpen()?self.hide():self.show()},getConf:function(){return conf},getInput:function(){return input},getCalendar:function(){return root},getValue:function(dateFormat){return dateFormat?format(conf.formatter,value,dateFormat,conf.lang):value},isOpen:function(){return opened}}),$.each(["onBeforeShow","onShow","change","onHide"],function(i,name){$.isFunction(conf[name])&&$(self).on(name,conf[name]),self[name]=function(fn){return fn&&$(self).on(name,fn),self}}),conf.editable||input.on("focus.d click.d",self.show).keydown(function(e){var key=e.keyCode;return!opened&&$(KEYS).index(key)>=0?(self.show(e),e.preventDefault()):((8==key||46==key)&&input.val(""),e.shiftKey||e.ctrlKey||e.altKey||9==key?!0:e.preventDefault())}),parseDate(input.val())&&select(value,conf)}$.tools=$.tools||{version:"@VERSION"};var tool,instances=[],formatters={},KEYS=[75,76,38,39,74,72,40,37],LABELS={};tool=$.tools.dateinput={conf:{format:"mm/dd/yy",formatter:"default",selectors:!1,yearRange:[-5,5],lang:"en",offset:[0,0],speed:0,firstDay:0,min:undefined,max:undefined,trigger:0,toggle:0,editable:0,css:{prefix:"cal",input:"date",root:0,head:0,title:0,prev:0,next:0,month:0,year:0,days:0,body:0,weeks:0,today:0,current:0,week:0,off:0,sunday:0,focus:0,disabled:0,trigger:0}},addFormatter:function(name,fn){formatters[name]=fn},localize:function(language,labels){$.each(labels,function(key,val){labels[key]=val.split(",")}),LABELS[language]=labels}},tool.localize("en",{months:"January,February,March,April,May,June,July,August,September,October,November,December",shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",days:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",shortDays:"Sun,Mon,Tue,Wed,Thu,Fri,Sat"});var tmpTag=$("<a/>");tool.addFormatter("default",function(text,date,flags){return text.replace(/d{1,4}|m{1,4}|yy(?:yy)?|"[^"]*"|'[^']*'/g,function($0){return $0 in flags?flags[$0]:$0})}),tool.addFormatter("prefixed",function(text,date,flags){return text.replace(/%(d{1,4}|m{1,4}|yy(?:yy)?|"[^"]*"|'[^']*')/g,function($0,$1){return $1 in flags?flags[$1]:$0})}),$.expr[":"].date=function(el){var type=el.getAttribute("type");return type&&"date"==type||!!$(el).data("dateinput")},$.fn.dateinput=function(conf){if(this.data("dateinput"))return this;conf=$.extend(!0,{},tool.conf,conf),$.each(conf.css,function(key,val){val||"prefix"==key||(conf.css[key]=(conf.css.prefix||"")+(val||key))});var els;return this.each(function(){var el=new Dateinput($(this),conf);instances.push(el);var input=el.getInput().data("dateinput",el);els=els?els.add(input):input}),els?els:this}}(jQuery);

  }).apply(root, arguments);
});
}(this));

(function(root) {
define("jquery.tmpl", ["jquery"], function() {
  return (function() {
/*
 * jQuery Templating Plugin
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function( jQuery, undefined ){
	var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
		newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];

	function newTmplItem( options, parentItem, fn, data ) {
		// Returns a template item data structure for a new rendered instance of a template (a 'template item').
		// The content field is a hierarchical array of strings and nested items (to be
		// removed and replaced by nodes field of dom elements, once inserted in DOM).
		var newItem = {
			data: data || (parentItem ? parentItem.data : {}),
			_wrap: parentItem ? parentItem._wrap : null,
			tmpl: null,
			parent: parentItem || null,
			nodes: [],
			calls: tiCalls,
			nest: tiNest,
			wrap: tiWrap,
			html: tiHtml,
			update: tiUpdate
		};
		if ( options ) {
			jQuery.extend( newItem, options, { nodes: [], parent: parentItem } );
		}
		if ( fn ) {
			// Build the hierarchical content to be used during insertion into DOM
			newItem.tmpl = fn;
			newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
			newItem.key = ++itemKey;
			// Keep track of new template item, until it is stored as jQuery Data on DOM element
			(stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
		}
		return newItem;
	}

	// Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
	jQuery.each({
		appendTo: "append",
		prependTo: "prepend",
		insertBefore: "before",
		insertAfter: "after",
		replaceAll: "replaceWith"
	}, function( name, original ) {
		jQuery.fn[ name ] = function( selector ) {
			var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
				parent = this.length === 1 && this[0].parentNode;

			appendToTmplItems = newTmplItems || {};
			if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
				insert[ original ]( this[0] );
				ret = this;
			} else {
				for ( i = 0, l = insert.length; i < l; i++ ) {
					cloneIndex = i;
					elems = (i > 0 ? this.clone(true) : this).get();
					jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
					ret = ret.concat( elems );
				}
				cloneIndex = 0;
				ret = this.pushStack( ret, name, insert.selector );
			}
			tmplItems = appendToTmplItems;
			appendToTmplItems = null;
			jQuery.tmpl.complete( tmplItems );
			return ret;
		};
	});

	jQuery.fn.extend({
		// Use first wrapped element as template markup.
		// Return wrapped set of template items, obtained by rendering template against data.
		tmpl: function( data, options, parentItem ) {
			return jQuery.tmpl( this[0], data, options, parentItem );
		},

		// Find which rendered template item the first wrapped DOM element belongs to
		tmplItem: function() {
			return jQuery.tmplItem( this[0] );
		},

		// Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
		template: function( name ) {
			return jQuery.template( name, this[0] );
		},

		domManip: function( args, table, callback, options ) {
			// This appears to be a bug in the appendTo, etc. implementation
			// it should be doing .call() instead of .apply(). See #6227
			if ( args[0] && args[0].nodeType ) {
				var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem;
				while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {}
				if ( argsLength > 1 ) {
					dmArgs[0] = [jQuery.makeArray( args )];
				}
				if ( tmplItem && cloneIndex ) {
					dmArgs[2] = function( fragClone ) {
						// Handler called by oldManip when rendered template has been inserted into DOM.
						jQuery.tmpl.afterManip( this, fragClone, callback );
					};
				}
				oldManip.apply( this, dmArgs );
			} else {
				oldManip.apply( this, arguments );
			}
			cloneIndex = 0;
			if ( !appendToTmplItems ) {
				jQuery.tmpl.complete( newTmplItems );
			}
			return this;
		}
	});

	jQuery.extend({
		// Return wrapped set of template items, obtained by rendering template against data.
		tmpl: function( tmpl, data, options, parentItem ) {
			var ret, topLevel = !parentItem;
			if ( topLevel ) {
				// This is a top-level tmpl call (not from a nested template using {{tmpl}})
				parentItem = topTmplItem;
				tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
				wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
			} else if ( !tmpl ) {
				// The template item is already associated with DOM - this is a refresh.
				// Re-evaluate rendered template for the parentItem
				tmpl = parentItem.tmpl;
				newTmplItems[parentItem.key] = parentItem;
				parentItem.nodes = [];
				if ( parentItem.wrapped ) {
					updateWrapped( parentItem, parentItem.wrapped );
				}
				// Rebuild, without creating a new template item
				return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
			}
			if ( !tmpl ) {
				return []; // Could throw...
			}
			if ( typeof data === "function" ) {
				data = data.call( parentItem || {} );
			}
			if ( options && options.wrapped ) {
				updateWrapped( options, options.wrapped );
			}
			ret = jQuery.isArray( data ) ? 
				jQuery.map( data, function( dataItem ) {
					return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
				}) :
				[ newTmplItem( options, parentItem, tmpl, data ) ];
			return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
		},

		// Return rendered template item for an element.
		tmplItem: function( elem ) {
			var tmplItem;
			if ( elem instanceof jQuery ) {
				elem = elem[0];
			}
			while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
			return tmplItem || topTmplItem;
		},

		// Set:
		// Use $.template( name, tmpl ) to cache a named template,
		// where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
		// Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.

		// Get:
		// Use $.template( name ) to access a cached template.
		// Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
		// will return the compiled template, without adding a name reference.
		// If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
		// to $.template( null, templateString )
		template: function( name, tmpl ) {
			if (tmpl) {
				// Compile template and associate with name
				if ( typeof tmpl === "string" ) {
					// This is an HTML string being passed directly in.
					tmpl = buildTmplFn( tmpl )
				} else if ( tmpl instanceof jQuery ) {
					tmpl = tmpl[0] || {};
				}
				if ( tmpl.nodeType ) {
					// If this is a template block, use cached copy, or generate tmpl function and cache.
					tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
				}
				return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
			}
			// Return named compiled template
			return name ? (typeof name !== "string" ? jQuery.template( null, name ): 
				(jQuery.template[name] || 
					// If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) 
					jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; 
		},

		encode: function( text ) {
			// Do HTML encoding replacing < > & and ' and " by corresponding entities.
			return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
		}
	});

	jQuery.extend( jQuery.tmpl, {
		tag: {
			"tmpl": {
				_default: { $2: "null" },
				open: "if($notnull_1){_=_.concat($item.nest($1,$2));}"
				// tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
				// This means that {{tmpl foo}} treats foo as a template (which IS a function). 
				// Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
			},
			"wrap": {
				_default: { $2: "null" },
				open: "$item.calls(_,$1,$2);_=[];",
				close: "call=$item.calls();_=call._.concat($item.wrap(call,_));"
			},
			"each": {
				_default: { $2: "$index, $value" },
				open: "if($notnull_1){$.each($1a,function($2){with(this){",
				close: "}});}"
			},
			"if": {
				open: "if(($notnull_1) && $1a){",
				close: "}"
			},
			"else": {
				_default: { $1: "true" },
				open: "}else if(($notnull_1) && $1a){"
			},
			"html": {
				// Unecoded expression evaluation. 
				open: "if($notnull_1){_.push($1a);}"
			},
			"=": {
				// Encoded expression evaluation. Abbreviated form is ${}.
				_default: { $1: "$data" },
				open: "if($notnull_1){_.push($.encode($1a));}"
			},
			"!": {
				// Comment tag. Skipped by parser
				open: ""
			}
		},

		// This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
		complete: function( items ) {
			newTmplItems = {};
		},

		// Call this from code which overrides domManip, or equivalent
		// Manage cloning/storing template items etc.
		afterManip: function afterManip( elem, fragClone, callback ) {
			// Provides cloned fragment ready for fixup prior to and after insertion into DOM
			var content = fragClone.nodeType === 11 ?
				jQuery.makeArray(fragClone.childNodes) :
				fragClone.nodeType === 1 ? [fragClone] : [];

			// Return fragment to original caller (e.g. append) for DOM insertion
			callback.call( elem, fragClone );

			// Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
			storeTmplItems( content );
			cloneIndex++;
		}
	});

	//========================== Private helper functions, used by code above ==========================

	function build( tmplItem, nested, content ) {
		// Convert hierarchical content into flat string array 
		// and finally return array of fragments ready for DOM insertion
		var frag, ret = content ? jQuery.map( content, function( item ) {
			return (typeof item === "string") ? 
				// Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
				(tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
				// This is a child template item. Build nested template.
				build( item, tmplItem, item._ctnt );
		}) : 
		// If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. 
		tmplItem;
		if ( nested ) {
			return ret;
		}

		// top-level template
		ret = ret.join("");

		// Support templates which have initial or final text nodes, or consist only of text
		// Also support HTML entities within the HTML markup.
		ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
			frag = jQuery( middle ).get();

			storeTmplItems( frag );
			if ( before ) {
				frag = unencode( before ).concat(frag);
			}
			if ( after ) {
				frag = frag.concat(unencode( after ));
			}
		});
		return frag ? frag : unencode( ret );
	}

	function unencode( text ) {
		// Use createElement, since createTextNode will not render HTML entities correctly
		var el = document.createElement( "div" );
		el.innerHTML = text;
		return jQuery.makeArray(el.childNodes);
	}

	// Generate a reusable function that will serve to render a template against data
	function buildTmplFn( markup ) {
		return new Function("jQuery","$item",
			"var $=jQuery,call,_=[],$data=$item.data;" +

			// Introduce the data as local variables using with(){}
			"with($data){_.push('" +

			// Convert the template into pure JavaScript
			jQuery.trim(markup)
				.replace( /([\\'])/g, "\\$1" )
				.replace( /[\r\t\n]/g, " " )
				.replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
				.replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
				function( all, slash, type, fnargs, target, parens, args ) {
					var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
					if ( !tag ) {
						throw "Template command not found: " + type;
					}
					def = tag._default || [];
					if ( parens && !/\w$/.test(target)) {
						target += parens;
						parens = "";
					}
					if ( target ) {
						target = unescape( target ); 
						args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
						// Support for target being things like a.toLowerCase();
						// In that case don't call with template item as 'this' pointer. Just evaluate...
						expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target;
						exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
					} else {
						exprAutoFnDetect = expr = def.$1 || "null";
					}
					fnargs = unescape( fnargs );
					return "');" + 
						tag[ slash ? "close" : "open" ]
							.split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
							.split( "$1a" ).join( exprAutoFnDetect )
							.split( "$1" ).join( expr )
							.split( "$2" ).join( fnargs ?
								fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) {
									params = params ? ("," + params + ")") : (parens ? ")" : "");
									return params ? ("(" + name + ").call($item" + params) : all;
								})
								: (def.$2||"")
							) +
						"_.push('";
				}) +
			"');}return _;"
		);
	}
	function updateWrapped( options, wrapped ) {
		// Build the wrapped content. 
		options._wrap = build( options, true, 
			// Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
			jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
		).join("");
	}

	function unescape( args ) {
		return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
	}
	function outerHtml( elem ) {
		var div = document.createElement("div");
		div.appendChild( elem.cloneNode(true) );
		return div.innerHTML;
	}

	// Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
	function storeTmplItems( content ) {
		var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
		for ( i = 0, l = content.length; i < l; i++ ) {
			if ( (elem = content[i]).nodeType !== 1 ) {
				continue;
			}
			elems = elem.getElementsByTagName("*");
			for ( m = elems.length - 1; m >= 0; m-- ) {
				processItemKey( elems[m] );
			}
			processItemKey( elem );
		}
		function processItemKey( el ) {
			var pntKey, pntNode = el, pntItem, tmplItem, key;
			// Ensure that each rendered template inserted into the DOM has its own template item,
			if ( (key = el.getAttribute( tmplItmAtt ))) {
				while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
				if ( pntKey !== key ) {
					// The next ancestor with a _tmplitem expando is on a different key than this one.
					// So this is a top-level element within this template item
					// Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
					pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0;
					if ( !(tmplItem = newTmplItems[key]) ) {
						// The item is for wrapped content, and was copied from the temporary parent wrappedItem.
						tmplItem = wrappedItems[key];
						tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true );
						tmplItem.key = ++itemKey;
						newTmplItems[itemKey] = tmplItem;
					}
					if ( cloneIndex ) {
						cloneTmplItem( key );
					}
				}
				el.removeAttribute( tmplItmAtt );
			} else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
				// This was a rendered element, cloned during append or appendTo etc.
				// TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
				cloneTmplItem( tmplItem.key );
				newTmplItems[tmplItem.key] = tmplItem;
				pntNode = jQuery.data( el.parentNode, "tmplItem" );
				pntNode = pntNode ? pntNode.key : 0;
			}
			if ( tmplItem ) {
				pntItem = tmplItem;
				// Find the template item of the parent element. 
				// (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
				while ( pntItem && pntItem.key != pntNode ) { 
					// Add this element as a top-level node for this rendered template item, as well as for any
					// ancestor items between this item and the item of its parent element
					pntItem.nodes.push( el );
					pntItem = pntItem.parent;
				}
				// Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
				delete tmplItem._ctnt;
				delete tmplItem._wrap;
				// Store template item as jQuery data on the element
				jQuery.data( el, "tmplItem", tmplItem );
			}
			function cloneTmplItem( key ) {
				key = key + keySuffix;
				tmplItem = newClonedItems[key] = 
					(newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true ));
			}
		}
	}

	//---- Helper functions for template item ----

	function tiCalls( content, tmpl, data, options ) {
		if ( !content ) {
			return stack.pop();
		}
		stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
	}

	function tiNest( tmpl, data, options ) {
		// nested template, using {{tmpl}} tag
		return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
	}

	function tiWrap( call, wrapped ) {
		// nested template, using {{wrap}} tag
		var options = call.options || {};
		options.wrapped = wrapped;
		// Apply the template, which may incorporate wrapped content, 
		return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
	}

	function tiHtml( filter, textOnly ) {
		var wrapped = this._wrap;
		return jQuery.map(
			jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
			function(e) {
				return textOnly ?
					e.innerText || e.textContent :
					e.outerHTML || outerHtml(e);
			});
	}

	function tiUpdate() {
		var coll = this.nodes;
		jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
		jQuery( coll ).remove();
	}
})( jQuery );


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("jquery.recurrenceinput", ["jquery","resource-plone-app-jquerytools-js","resource-plone-app-jquerytools-dateinput-js","jquery.tmpl"], function() {
  return (function() {
/*jslint regexp: false, continue: true, indent: 4 */
/*global $, alert, jQuery */


(function ($) {
    $.tools = $.tools || {version: '@VERSION'};

    var tool;
    var LABELS = {};

    tool = $.tools.recurrenceinput = {
        conf: {
            lang: 'en',
            readOnly: false,
            firstDay: 0,

            // "REMOTE" FIELD
            startField: null,
            startFieldYear: null,
            startFieldMonth: null,
            startFieldDay: null,
            ajaxURL: null,
            ajaxContentType: 'application/json; charset=utf8',
            ributtonExtraClass: '',

            // INPUT CONFIGURATION
            hasRepeatForeverButton: true,

            // FORM OVERLAY
            formOverlay: {
                speed: 'fast',
                fixed: false
            },

            // JQUERY TEMPLATE NAMES
            template: {
                form: '#jquery-recurrenceinput-form-tmpl',
                display: '#jquery-recurrenceinput-display-tmpl'
            },

            // RECURRENCE TEMPLATES
            rtemplate: {
                daily: {
                    rrule: 'FREQ=DAILY',
                    fields: [
                        'ridailyinterval',
                        'rirangeoptions'
                    ]
                },
                mondayfriday: {
                    rrule: 'FREQ=WEEKLY;BYDAY=MO,FR',
                    fields: [
                        'rirangeoptions'
                    ]
                },
                weekdays: {
                    rrule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR',
                    fields: [
                        'rirangeoptions'
                    ]
                },
                weekly: {
                    rrule: 'FREQ=WEEKLY',
                    fields: [
                        'riweeklyinterval',
                        'riweeklyweekdays',
                        'rirangeoptions'
                    ]
                },
                monthly: {
                    rrule: 'FREQ=MONTHLY',
                    fields: [
                        'rimonthlyinterval',
                        'rimonthlyoptions',
                        'rirangeoptions'
                    ]
                },
                yearly: {
                    rrule: 'FREQ=YEARLY',
                    fields: [
                        'riyearlyinterval',
                        'riyearlyoptions',
                        'rirangeoptions'
                    ]
                }
            }
        },

        localize: function (language, labels) {
            LABELS[language] = labels;
        },

        setTemplates: function (templates, titles) {
            var lang, template;
            tool.conf.rtemplate = templates;
            for (lang in titles) {
                if (titles.hasOwnProperty(lang)) {
                    for (template in titles[lang]) {
                        if (titles[lang].hasOwnProperty(template)) {
                            LABELS[lang].rtemplate[template] = titles[lang][template];
                        }
                    }
                }
            }
        }

    };

    tool.localize("en", {
        displayUnactivate: 'Does not repeat',
        displayActivate: 'Repeats every',
        add_rules: 'Add',
        edit_rules: 'Edit',
        delete_rules: 'Delete',
        add:  'Add',
        refresh: 'Refresh',

        title: 'Repeat',
        preview: 'Selected dates',
        addDate: 'Add date',

        recurrenceType: 'Repeats:',

        dailyInterval1: 'Repeat every:',
        dailyInterval2: 'days',

        weeklyInterval1: 'Repeat every:',
        weeklyInterval2: 'week(s)',
        weeklyWeekdays: 'Repeat on:',
        weeklyWeekdaysHuman: 'on:',

        monthlyInterval1: 'Repeat every:',
        monthlyInterval2: 'month(s)',
        monthlyDayOfMonth1: 'Day',
        monthlyDayOfMonth1Human: 'on day',
        monthlyDayOfMonth2: 'of the month',
        monthlyDayOfMonth3: 'month(s)',
        monthlyWeekdayOfMonth1: 'The',
        monthlyWeekdayOfMonth1Human: 'on the',
        monthlyWeekdayOfMonth2: '',
        monthlyWeekdayOfMonth3: 'of the month',
        monthlyRepeatOn: 'Repeat on:',

        yearlyInterval1: 'Repeat every:',
        yearlyInterval2: 'year(s)',
        yearlyDayOfMonth1: 'Every',
        yearlyDayOfMonth1Human: 'on',
        yearlyDayOfMonth2: '',
        yearlyDayOfMonth3: '',
        yearlyWeekdayOfMonth1: 'The',
        yearlyWeekdayOfMonth1Human: 'on the',
        yearlyWeekdayOfMonth2: '',
        yearlyWeekdayOfMonth3: 'of',
        yearlyWeekdayOfMonth4: '',
        yearlyRepeatOn: 'Repeat on:',

        range: 'End recurrence:',
        rangeNoEnd: 'Never',
        rangeByOccurrences1: 'After',
        rangeByOccurrences1Human: 'ends after',
        rangeByOccurrences2: 'occurrence(s)',
        rangeByEndDate: 'On',
        rangeByEndDateHuman: 'ends on',

        including: ', and also',
        except: ', except for',

        cancel: 'Cancel',
        save: 'Save',

        recurrenceStart: 'Start of the recurrence',
        additionalDate: 'Additional date',
        include: 'Include',
        exclude: 'Exclude',
        remove: 'Remove',

        orderIndexes: ['first', 'second', 'third', 'fourth', 'last'],
        months: [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'],
        shortMonths: [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        weekdays: [
            'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
            'Friday', 'Saturday'],
        shortWeekdays: [
            'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],

        longDateFormat: 'mmmm dd, yyyy',
        shortDateFormat: 'mm/dd/yyyy',

        unsupportedFeatures: 'Warning: This event uses recurrence features not ' +
                              'supported by this widget. Saving the recurrence ' +
                              'may change the recurrence in unintended ways:',
        noTemplateMatch: 'No matching recurrence template',
        multipleDayOfMonth: 'This widget does not support multiple days in monthly or yearly recurrence',
        bysetpos: 'BYSETPOS is not supported',
        noRule: 'No RRULE in RRULE data',
        noRepeatEvery: 'Error: The "Repeat every"-field must be between 1 and 1000',
        noEndDate: 'Error: End date is not set. Please set a correct value',
        noRepeatOn: 'Error: "Repeat on"-value must be selected',
        pastEndDate: 'Error: End date cannot be before start date',
        noEndAfterNOccurrences: 'Error: The "After N occurrences"-field must be between 1 and 1000',
        alreadyAdded: 'This date was already added',

        rtemplate: {
            daily: 'Daily',
            mondayfriday: 'Monday and Friday',
            weekdays: 'Weekday',
            weekly: 'Weekly',
            monthly: 'Monthly',
            yearly: 'Yearly'
        }
    });


    var OCCURRENCETMPL = ['<div class="rioccurrences">',
        '{{each occurrences}}',
            '<div class="occurrence ${occurrences[$index].type}">',
                '<span>',
                    '${occurrences[$index].formattedDate}',
                    '{{if occurrences[$index].type === "start"}}',
                        '<span class="rlabel">${i18n.recurrenceStart}</span>',
                    '{{/if}}',
                    '{{if occurrences[$index].type === "rdate"}}',
                        '<span class="rlabel">${i18n.additionalDate}</span>',
                    '{{/if}}',
                '</span>',
                '{{if !readOnly}}',
                    '<span class="action">',
                        '{{if occurrences[$index].type === "rrule"}}',
                            '<a date="${occurrences[$index].date}" href="#"',
                               'class="${occurrences[$index].type}" title="${i18n.exclude}">',
                                '${i18n.exclude}',
                            '</a>',
                        '{{/if}}',
                        '{{if occurrences[$index].type === "rdate"}}',
                            '<a date="${occurrences[$index].date}" href="#"',
                               'class="${occurrences[$index].type}" title="${i18n.remove}" >',
                                '${i18n.remove}',
                            '</a>',
                        '{{/if}}',
                        '{{if occurrences[$index].type === "exdate"}}',
                            '<a date="${occurrences[$index].date}" href="#"',
                               'class="${occurrences[$index].type}" title="${i18n.include}">',
                                '${i18n.include}',
                            '</a>',
                        '{{/if}}',
                    '</span>',
                '{{/if}}',
            '</div>',
        '{{/each}}',
        '<div class="batching">',
            '{{each batch.batches}}',
                '{{if $index === batch.currentBatch}}<span class="current">{{/if}}',
                    '<a href="#" start="${batch.batches[$index][0]}">[${batch.batches[$index][0]} - ${batch.batches[$index][1]}]</a>',
                '{{if $index === batch.currentBatch}}</span>{{/if}}',
            '{{/each}}',
        '</div></div>'].join('\n');

    $.template('occurrenceTmpl', OCCURRENCETMPL);

    var DISPLAYTMPL = ['<div class="ridisplay">',
        '<div class="rimain">',
            '{{if !readOnly}}',
                '<button name="riedit">${i18n.add_rules}</button>',
                '<button name="ridelete" style="display:none">${i18n.delete_rules}</button>',
            '{{/if}}',
            '<label class="ridisplay">${i18n.displayUnactivate}</label>',
        '</div>',
        '<div class="rioccurrences" style="display:none" /></div>'].join('\n');

    $.template('displayTmpl', DISPLAYTMPL);

    var FORMTMPL = ['<div class="riform">',
            '<form>',
                '<h1>${i18n.title}</h1>',
                '<div id="messagearea" style="display: none;">',
                '</div>',
                '<div id="rirtemplate">',
                    '<label for="${name}rtemplate" class="label">',
                        '${i18n.recurrenceType}',
                    '</label>',
                    '<select id="rirtemplate" name="rirtemplate" class="field">',
                        '{{each rtemplate}}',
                            '<option value="${$index}">${i18n.rtemplate[$index]}</value>',
                        '{{/each}}',
                    '</select>',
                '<div>',
                '<div id="riformfields">',
                    '<div id="ridailyinterval" class="rifield">',
                        '<label for="${name}dailyinterval" class="label">',
                            '${i18n.dailyInterval1}',
                        '</label>',
                        '<div class="field">',
                            '<input type="text" size="2"',
                                'value="1"',
                                'name="ridailyinterval"',
                                'id="${name}dailyinterval" />',
                            '${i18n.dailyInterval2}',
                        '</div>',
                    '</div>',
                    '<div id="riweeklyinterval" class="rifield">',
                        '<label for="${name}weeklyinterval" class="label">',
                            '${i18n.weeklyInterval1}',
                        '</label>',
                        '<div class="field">',
                            '<input type="text" size="2"',
                                'value="1"',
                                'name="riweeklyinterval"',
                                'id="${name}weeklyinterval"/>',
                            '${i18n.weeklyInterval2}',
                        '</div>',
                    '</div>',
                    '<div id="riweeklyweekdays" class="rifield">',
                        '<label for="${name}weeklyinterval" class="label">${i18n.weeklyWeekdays}</label>',
                        '<div class="field">',
                            '{{each orderedWeekdays}}',
                                '<div class="riweeklyweekday">',
                                    '<input type="checkbox"',
                                        'name="riweeklyweekdays${weekdays[$value]}"',
                                        'id="${name}weeklyWeekdays${weekdays[$value]}"',
                                        'value="${weekdays[$value]}" />',
                                    '<label for="${name}weeklyWeekdays${weekdays[$value]}">${i18n.shortWeekdays[$value]}</label>',
                                '</div>',
                            '{{/each}}',
                        '</div>',
                    '</div>',
                    '<div id="rimonthlyinterval" class="rifield">',
                        '<label for="rimonthlyinterval" class="label">${i18n.monthlyInterval1}</label>',
                        '<div class="field">',
                            '<input type="text" size="2"',
                                'value="1" ',
                                'name="rimonthlyinterval"/>',
                            '${i18n.monthlyInterval2}',
                        '</div>',
                    '</div>',
                    '<div id="rimonthlyoptions" class="rifield">',
                        '<label for="rimonthlytype" class="label">${i18n.monthlyRepeatOn}</label>',
                        '<div class="field">',
                            '<div>',
                                '<input',
                                    'type="radio"',
                                    'value="DAYOFMONTH"',
                                    'name="rimonthlytype"',
                                    'id="${name}monthlytype:DAYOFMONTH" />',
                                '<label for="${name}monthlytype:DAYOFMONTH">',
                                    '${i18n.monthlyDayOfMonth1}',
                                '</label>',
                                '<select name="rimonthlydayofmonthday"',
                                    'id="${name}monthlydayofmonthday">',
                                '{{each [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,',
                                        '18,19,20,21,22,23,24,25,26,27,28,29,30,31]}}',
                                    '<option value="${$value}">${$value}</option>',
                                '{{/each}}',
                                '</select>',
                                '${i18n.monthlyDayOfMonth2}',
                            '</div>',
                            '<div>',
                                '<input',
                                    'type="radio"',
                                    'value="WEEKDAYOFMONTH"',
                                    'name="rimonthlytype"',
                                    'id="${name}monthlytype:WEEKDAYOFMONTH" />',
                                '<label for="${name}monthlytype:WEEKDAYOFMONTH">',
                                    '${i18n.monthlyWeekdayOfMonth1}',
                                '</label>',
                                '<select name="rimonthlyweekdayofmonthindex">',
                                    '{{each i18n.orderIndexes}}',
                                        '<option value="${orderIndexes[$index]}">${$value}</option>',
                                    '{{/each}}',
                                '</select>',
                                '${i18n.monthlyWeekdayOfMonth2}',
                                '<select name="rimonthlyweekdayofmonth">',
                                    '{{each orderedWeekdays}}',
                                        '<option value="${weekdays[$value]}">${i18n.weekdays[$value]}</option>',
                                    '{{/each}}',
                                '</select>',
                                '${i18n.monthlyWeekdayOfMonth3}',
                            '</div>',
                        '</div>',
                    '</div>',
                    '<div id="riyearlyinterval" class="rifield">',
                        '<label for="riyearlyinterval" class="label">${i18n.yearlyInterval1}</label>',
                        '<div class="field">',
                            '<input type="text" size="2"',
                                'value="1" ',
                                'name="riyearlyinterval"/>',
                            '${i18n.yearlyInterval2}',
                        '</div>',
                    '</div>',
                    '<div id="riyearlyoptions" class="rifield">',
                        '<label for="riyearlyType" class="label">${i18n.yearlyRepeatOn}</label>',
                        '<div class="field">',
                            '<div>',
                                '<input',
                                    'type="radio"',
                                    'value="DAYOFMONTH"',
                                    'name="riyearlyType"',
                                    'id="${name}yearlytype:DAYOFMONTH" />',
                                '<label for="${name}yearlytype:DAYOFMONTH">',
                                    '${i18n.yearlyDayOfMonth1}',
                                '</label>',
                                '<select name="riyearlydayofmonthmonth">',
                                '{{each i18n.months}}',
                                    '<option value="${$index+1}">${$value}</option>',
                                '{{/each}}',
                                '</select>',
                                '${i18n.yearlyDayOfMonth2}',
                                '<select name="riyearlydayofmonthday">',
                                '{{each [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,',
                                        '18,19,20,21,22,23,24,25,26,27,28,29,30,31]}}',
                                    '<option value="${$value}">${$value}</option>',
                                '{{/each}}',
                                '</select>',
                                '${i18n.yearlyDayOfMonth3}',
                            '</div>',
                            '<div>',
                                '<input',
                                    'type="radio"',
                                    'value="WEEKDAYOFMONTH"',
                                    'name="riyearlyType"',
                                    'id="${name}yearlytype:WEEKDAYOFMONTH"/>',
                                '<label for="${name}yearlytype:WEEKDAYOFMONTH">',
                                    '${i18n.yearlyWeekdayOfMonth1}',
                                '</label>',
                                '<select name="riyearlyweekdayofmonthindex">',
                                '{{each i18n.orderIndexes}}',
                                    '<option value="${orderIndexes[$index]}">${$value}</option>',
                                '{{/each}}',
                                '</select>',
                                '<label for="${name}yearlytype:WEEKDAYOFMONTH">',
                                    '${i18n.yearlyWeekdayOfMonth2}',
                                '</label>',
                                '<select name="riyearlyweekdayofmonthday">',
                                '{{each orderedWeekdays}}',
                                    '<option value="${weekdays[$value]}">${i18n.weekdays[$value]}</option>',
                                '{{/each}}',
                                '</select>',
                                '${i18n.yearlyWeekdayOfMonth3}',
                                '<select name="riyearlyweekdayofmonthmonth">',
                                '{{each i18n.months}}',
                                    '<option value="${$index+1}">${$value}</option>',
                                '{{/each}}',
                                '</select>',
                                '${i18n.yearlyWeekdayOfMonth4}',
                            '</div>',
                        '</div>',
                    '</div>',
                    '<div id="rirangeoptions" class="rifield">',
                        '<label class="label">${i18n.range}</label>',
                        '<div class="field">',
                          '{{if hasRepeatForeverButton}}',
                            '<div>',
                                '<input',
                                    'type="radio"',
                                    'value="NOENDDATE"',
                                    'name="rirangetype"',
                                    'id="${name}rangetype:NOENDDATE"/>',
                                '<label for="${name}rangetype:NOENDDATE">',
                                    '${i18n.rangeNoEnd}',
                                '</label>',
                            '</div>',
                          '{{/if}}',
                            '<div>',
                                '<input',
                                    'type="radio"',
                                    'checked="checked"',
                                    'value="BYOCCURRENCES"',
                                    'name="rirangetype"',
                                    'id="${name}rangetype:BYOCCURRENCES"/>',
                                '<label for="${name}rangetype:BYOCCURRENCES">',
                                    '${i18n.rangeByOccurrences1}',
                                '</label>',
                                '<input',
                                    'type="text" size="3"',
                                    'value="7"',
                                    'name="rirangebyoccurrencesvalue" />',
                                '${i18n.rangeByOccurrences2}',
                            '</div>',
                            '<div>',
                                '<input',
                                    'type="radio"',
                                    'value="BYENDDATE"',
                                    'name="rirangetype"',
                                    'id="${name}rangetype:BYENDDATE"/>',
                                '<label for="${name}rangetype:BYENDDATE">',
                                    '${i18n.rangeByEndDate}',
                                '</label>',
                                '<input',
                                    'type="date"',
                                    'name="rirangebyenddatecalendar" />',
                            '</div>',
                        '</div>',
                    '</div>',
                '</div>',
                '<div class="rioccurrencesactions">',
                    '<div class="rioccurancesheader">',
                        '<h2>${i18n.preview}</h2>',
                        '<span class="refreshbutton action">',
                            '<a class="rirefreshbutton" href="#" title="${i18n.refresh}">',
                                '${i18n.refresh}',
                            '</a>',
                        '</span>',
                    '</div>',
                '</div>',
                '<div class="rioccurrences">',
                '</div>',
                '<div class="rioccurrencesactions">',
                    '<div class="rioccurancesheader">',
                        '<h2>${i18n.addDate}</h2>',
                    '</div>',
                    '<div class="riaddoccurrence">',
                        '<div class="errorarea"></div>',
                        '<input type="date" name="adddate" id="adddate" />',
                        '<input type="button" name="addaction" id="addaction" value="${i18n.add}">',
                    '</div>',
                '</div>',

                '<div class="ributtons">',
                    '<input',
                        'type="submit"',
                        'class="ricancelbutton ${ributtonExtraClass}"',
                        'value="${i18n.cancel}" />',
                    '<input',
                        'type="submit"',
                        'class="risavebutton ${ributtonExtraClass}"',
                        'value="${i18n.save}" />',
                '</div>',
            '</form></div>'].join('\n');

    $.template('formTmpl', FORMTMPL);

    // Formatting function (mostly) from jQueryTools dateinput
    var Re = /d{1,4}|m{1,4}|yy(?:yy)?|"[^"]*"|'[^']*'/g;

    function zeropad(val, len) {
        val = val.toString();
        len = len || 2;
        while (val.length < len) { val = "0" + val; }
        return val;
    }

    function format(date, fmt, conf) {
        var d = date.getDate(),
            D = date.getDay(),
            m = date.getMonth(),
            y = date.getFullYear(),

            flags = {
                d:    d,
                dd:   zeropad(d),
                ddd:  conf.i18n.shortWeekdays[D],
                dddd: conf.i18n.weekdays[D],
                m:    m + 1,
                mm:   zeropad(m + 1),
                mmm:  conf.i18n.shortMonths[m],
                mmmm: conf.i18n.months[m],
                yy:   String(y).slice(2),
                yyyy: y
            };

        var result = fmt.replace(Re, function ($0) {
            return flags.hasOwnProperty($0) ? flags[$0] : $0.slice(1, $0.length - 1);
        });

        return result;

    }

    /**
     * Parsing RFC5545 from widget
     */
    function widgetSaveToRfc5545(form, conf, tz) {
        var value = form.find('select[name=rirtemplate]').val();
        var rtemplate = conf.rtemplate[value];
        var result = rtemplate.rrule;
        var human = conf.i18n.rtemplate[value];
        var field, input, weekdays, i18nweekdays, i, j, index, tmp;
        var day, month, year, interval, yearlyType, occurrences, date;

        for (i = 0; i < rtemplate.fields.length; i++) {
            field = form.find('#' + rtemplate.fields[i]);

            switch (field.attr('id')) {

            case 'ridailyinterval':
                interval = field.find('input[name=ridailyinterval]').val();
                if (interval !== '1') {
                    result += ';INTERVAL=' + interval;
                }
                human = interval + ' ' + conf.i18n.dailyInterval2;
                break;

            case 'riweeklyinterval':
                interval = field.find('input[name=riweeklyinterval]').val();
                if (interval !== '1') {
                    result += ';INTERVAL=' + interval;
                }
                human = interval + ' ' + conf.i18n.weeklyInterval2;
                break;

            case 'riweeklyweekdays':
                weekdays = '';
                i18nweekdays = '';
                for (j = 0; j < conf.weekdays.length; j++) {
                    input = field.find('input[name=riweeklyweekdays' + conf.weekdays[j] + ']');
                    if (input.is(':checked')) {
                        if (weekdays) {
                            weekdays += ',';
                            i18nweekdays += ', ';
                        }
                        weekdays += conf.weekdays[j];
                        i18nweekdays += conf.i18n.weekdays[j];
                    }
                }
                if (weekdays) {
                    result += ';BYDAY=' + weekdays;
                    human += ' ' + conf.i18n.weeklyWeekdaysHuman + ' ' + i18nweekdays;
                }
                break;

            case 'rimonthlyinterval':
                interval = field.find('input[name=rimonthlyinterval]').val();
                if (interval !== '1') {
                    result += ';INTERVAL=' + interval;
                }
                human = interval + ' ' + conf.i18n.monthlyInterval2;
                break;

            case 'rimonthlyoptions':
                var monthlyType = $('input[name=rimonthlytype]:checked', form).val();
                switch (monthlyType) {

                case 'DAYOFMONTH':
                    day = $('select[name=rimonthlydayofmonthday]', form).val();
                    result += ';BYMONTHDAY=' + day;
                    human += ', ' + conf.i18n.monthlyDayOfMonth1Human + ' ' + day + ' ' + conf.i18n.monthlyDayOfMonth2;
                    break;
                case 'WEEKDAYOFMONTH':
                    index = $('select[name=rimonthlyweekdayofmonthindex]', form).val();
                    day = $('select[name=rimonthlyweekdayofmonth]', form).val();
                    if ($.inArray(day, ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']) > -1) {
                        result += ';BYDAY=' + index + day;
                        human += ', ' + conf.i18n.monthlyWeekdayOfMonth1Human + ' ';
                        human += ' ' + conf.i18n.orderIndexes[$.inArray(index, conf.orderIndexes)];
                        human += ' ' + conf.i18n.monthlyWeekdayOfMonth2;
                        human += ' ' + conf.i18n.weekdays[$.inArray(day, conf.weekdays)];
                        human += ' ' + conf.i18n.monthlyDayOfMonth2;
                    }
                    break;
                }
                break;

            case 'riyearlyinterval':
                interval = field.find('input[name=riyearlyinterval]').val();
                if (interval !== '1') {
                    result += ';INTERVAL=' + interval;
                }
                human = interval + ' ' + conf.i18n.yearlyInterval2;
                break;

            case 'riyearlyoptions':
                yearlyType = $('input[name=riyearlyType]:checked', form).val();
                switch (yearlyType) {

                case 'DAYOFMONTH':
                    month = $('select[name=riyearlydayofmonthmonth]', form).val();
                    day = $('select[name=riyearlydayofmonthday]', form).val();
                    result += ';BYMONTH=' + month;
                    result += ';BYMONTHDAY=' + day;
                    human += ', ' + conf.i18n.yearlyDayOfMonth1Human + ' ' + conf.i18n.months[month - 1] + ' ' + day;
                    break;
                case 'WEEKDAYOFMONTH':
                    index = $('select[name=riyearlyweekdayofmonthindex]', form).val();
                    day = $('select[name=riyearlyweekdayofmonthday]', form).val();
                    month = $('select[name=riyearlyweekdayofmonthmonth]', form).val();
                    result += ';BYMONTH=' + month;
                    if ($.inArray(day, ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']) > -1) {
                        result += ';BYDAY=' + index + day;
                        human += ', ' + conf.i18n.yearlyWeekdayOfMonth1Human;
                        human += ' ' + conf.i18n.orderIndexes[$.inArray(index, conf.orderIndexes)];
                        human += ' ' + conf.i18n.yearlyWeekdayOfMonth2;
                        human += ' ' + conf.i18n.weekdays[$.inArray(day, conf.weekdays)];
                        human += ' ' + conf.i18n.yearlyWeekdayOfMonth3;
                        human += ' ' + conf.i18n.months[month - 1];
                        human += ' ' + conf.i18n.yearlyWeekdayOfMonth4;
                    }
                    break;
                }
                break;

            case 'rirangeoptions':
                var rangeType = form.find('input[name=rirangetype]:checked').val();
                switch (rangeType) {

                case 'BYOCCURRENCES':
                    occurrences = form.find('input[name=rirangebyoccurrencesvalue]').val();
                    result += ';COUNT=' + occurrences;
                    human += ', ' + conf.i18n.rangeByOccurrences1Human;
                    human += ' ' + occurrences;
                    human += ' ' + conf.i18n.rangeByOccurrences2;
                    break;
                case 'BYENDDATE':
                    field = form.find('input[name=rirangebyenddatecalendar]');
                    date = field.data('dateinput').getValue('yyyymmdd');
                    result += ';UNTIL=' + date + 'T000000';
                    if (tz === true) {
                        // Make it UTC:
                        result += 'Z';
                    }
                    human += ', ' + conf.i18n.rangeByEndDateHuman;
                    human += ' ' + field.data('dateinput').getValue(conf.i18n.longDateFormat);
                    break;
                }
                break;
            }
        }

        if (form.ical.RDATE !== undefined && form.ical.RDATE.length > 0) {
            form.ical.RDATE.sort();
            tmp = [];
            for (i = 0; i < form.ical.RDATE.length; i++) {
                if (form.ical.RDATE[i] !== '') {
                    year = parseInt(form.ical.RDATE[i].substring(0, 4), 10);
                    month = parseInt(form.ical.RDATE[i].substring(4, 6), 10) - 1;
                    day = parseInt(form.ical.RDATE[i].substring(6, 8), 10);
                    tmp.push(format(new Date(year, month, day), conf.i18n.longDateFormat, conf));
                }
            }
            if (tmp.length !== 0) {
                human = human + conf.i18n.including + ' ' + tmp.join('; ');
            }
        }

        if (form.ical.EXDATE !== undefined && form.ical.EXDATE.length > 0) {
            form.ical.EXDATE.sort();
            tmp = [];
            for (i = 0; i < form.ical.EXDATE.length; i++) {
                if (form.ical.EXDATE[i] !== '') {
                    year = parseInt(form.ical.EXDATE[i].substring(0, 4), 10);
                    month = parseInt(form.ical.EXDATE[i].substring(4, 6), 10) - 1;
                    day = parseInt(form.ical.EXDATE[i].substring(6, 8), 10);
                    tmp.push(format(new Date(year, month, day), conf.i18n.longDateFormat, conf));
                }
            }
            if (tmp.length !== 0) {
                human = human + conf.i18n.except + ' ' + tmp.join('; ');
            }
        }
        result = 'RRULE:' + result;
        if (form.ical.EXDATE !== undefined && form.ical.EXDATE.join() !== "") {
            tmp = $.map(form.ical.EXDATE, function (x) {
                if (x.length === 8) { // DATE format. Make it DATE-TIME
                    x += 'T000000';
                }
                if (tz === true) {
                    // Make it UTC:
                    x += 'Z';
                }
                return x;
            });
            result = result + '\nEXDATE:' + tmp;
        }
        if (form.ical.RDATE !== undefined && form.ical.RDATE.join() !== "") {
            tmp = $.map(form.ical.RDATE, function (x) {
                if (x.length === 8) { // DATE format. Make it DATE-TIME
                    x += 'T000000';
                }
                if (tz === true) {
                    // Make it UTC:
                    x += 'Z';
                }
                return x;
            });
            result = result + '\nRDATE:' + tmp;
        }
        return {result: result, description: human};
    }

    function parseLine(icalline) {
        var result = {};
        var pos = icalline.indexOf(':');
        var property = icalline.substring(0, pos);
        result.value = icalline.substring(pos + 1);

        if (property.indexOf(';') !== -1) {
            pos = property.indexOf(';');
            result.parameters = property.substring(pos + 1);
            result.property = property.substring(0, pos);
        } else {
            result.parameters = null;
            result.property = property;
        }
        return result;
    }

    function cleanDates(dates) {
        // Get rid of timezones
        // TODO: We could parse dates and range here, maybe?
        var result = [];
        var splitDates = dates.split(',');
        var date;

        for (date in splitDates) {
            if (splitDates.hasOwnProperty(date)) {
                if (splitDates[date].indexOf('Z') !== -1) {
                    result.push(splitDates[date].substring(0, 15));
                } else {
                    result.push(splitDates[date]);
                }
            }
        }
        return result;
    }

    function parseIcal(icaldata) {
        var lines = [];
        var result = {};
        var propAndValue = [];
        var line = null;
        var nextline;

        lines = icaldata.split('\n');
        lines.reverse();
        while (true) {
            if (lines.length > 0) {
                nextline = lines.pop();
                if (nextline.charAt(0) === ' ' || nextline.charAt(0) === '\t') {
                    // Line continuation:
                    line = line + nextline;
                    continue;
                }
            } else {
                nextline = '';
            }

            // New line; the current one is finished, add it to the result.
            if (line !== null) {
                line = parseLine(line);
                 // We ignore properties for now
                if (line.property === 'RDATE' || line.property === 'EXDATE') {
                    result[line.property] = cleanDates(line.value);
                } else {
                    result[line.property] = line.value;
                }
            }

            line = nextline;
            if (line === '') {
                break;
            }
        }
        return result;
    }

    function widgetLoadFromRfc5545(form, conf, icaldata, force) {
        var unsupportedFeatures = [];
        var i, matches, match, matchIndex, rtemplate, d, input, index;
        var selector, selectors, field, radiobutton, start, end;
        var interval, byday, bymonth, bymonthday, count, until;
        var day, month, year, weekday, ical;

        form.ical = parseIcal(icaldata);
        if (form.ical.RRULE === undefined) {
            unsupportedFeatures.push(conf.i18n.noRule);
            if (!force) {
                return -1; // Fail!
            }
        } else {


            matches = /INTERVAL=([0-9]+);?/.exec(form.ical.RRULE);
            if (matches) {
                interval = matches[1];
            } else {
                interval = '1';
            }

            matches = /BYDAY=([^;]+);?/.exec(form.ical.RRULE);
            if (matches) {
                byday = matches[1];
            } else {
                byday = '';
            }

            matches = /BYMONTHDAY=([^;]+);?/.exec(form.ical.RRULE);
            if (matches) {
                bymonthday = matches[1].split(",");
            } else {
                bymonthday = null;
            }

            matches = /BYMONTH=([^;]+);?/.exec(form.ical.RRULE);
            if (matches) {
                bymonth = matches[1].split(",");
            } else {
                bymonth = null;
            }

            matches = /COUNT=([0-9]+);?/.exec(form.ical.RRULE);
            if (matches) {
                count = matches[1];
            } else {
                count = null;
            }

            matches = /UNTIL=([0-9T]+);?/.exec(form.ical.RRULE);
            if (matches) {
                until = matches[1];
            } else {
                until = null;
            }

            matches = /BYSETPOS=([^;]+);?/.exec(form.ical.RRULE);
            if (matches) {
                unsupportedFeatures.push(conf.i18n.bysetpos);
            }

            // Find the best rule:
            match = '';
            matchIndex = null;
            for (i in conf.rtemplate) {
                if (conf.rtemplate.hasOwnProperty(i)) {
                    rtemplate = conf.rtemplate[i];
                    if (form.ical.RRULE.indexOf(rtemplate.rrule) === 0) {
                        if (form.ical.RRULE.length > match.length) {
                            // This is the best match so far
                            match = form.ical.RRULE;
                            matchIndex = i;
                        }
                    }
                }
            }

            if (match) {
                rtemplate = conf.rtemplate[matchIndex];
                // Set the selector:
                selector = form.find('select[name=rirtemplate]').val(matchIndex);
            } else {
                for (rtemplate in conf.rtemplate) {
                    if (conf.rtemplate.hasOwnProperty(rtemplate)) {
                        rtemplate = conf.rtemplate[rtemplate];
                        break;
                    }
                }
                unsupportedFeatures.push(conf.i18n.noTemplateMatch);
            }

            for (i = 0; i < rtemplate.fields.length; i++) {
                field = form.find('#' + rtemplate.fields[i]);
                switch (field.attr('id')) {

                case 'ridailyinterval':
                    field.find('input[name=ridailyinterval]').val(interval);
                    break;

                case 'riweeklyinterval':
                    field.find('input[name=riweeklyinterval]').val(interval);
                    break;

                case 'riweeklyweekdays':
                    byday = byday.split(",");
                    for (d = 0; d < conf.weekdays.length; d++) {
                        day = conf.weekdays[d];
                        input = field.find('input[name=riweeklyweekdays' + day + ']');
                        input.attr('checked', $.inArray(day, byday) !== -1);
                    }
                    break;

                case 'rimonthlyinterval':
                    field.find('input[name=rimonthlyinterval]').val(interval);
                    break;

                case 'rimonthlyoptions':
                    var monthlyType = 'DAYOFMONTH'; // Default to using BYMONTHDAY

                    if (bymonthday) {
                        monthlyType = 'DAYOFMONTH';
                        if (bymonthday.length > 1) {
                            // No support for multiple days in one month
                            unsupportedFeatures.push(conf.i18n.multipleDayOfMonth);
                            // Just keep the first
                            bymonthday = bymonthday[0];
                        }
                        field.find('select[name=rimonthlydayofmonthday]').val(bymonthday);
                    }

                    if (byday) {
                        monthlyType = 'WEEKDAYOFMONTH';

                        if (byday.indexOf(',') !== -1) {
                            // No support for multiple days in one month
                            unsupportedFeatures.push(conf.i18n.multipleDayOfMonth);
                            byday = byday.split(",")[0];
                        }
                        index = byday.slice(0, -2);
                        if (index.charAt(0) !== '+' && index.charAt(0) !== '-') {
                            index = '+' + index;
                        }
                        weekday = byday.slice(-2);
                        field.find('select[name=rimonthlyweekdayofmonthindex]').val(index);
                        field.find('select[name=rimonthlyweekdayofmonth]').val(weekday);
                    }

                    selectors = field.find('input[name=rimonthlytype]');
                    for (index = 0; index < selectors.length; index++) {
                        radiobutton = selectors[index];
                        $(radiobutton).attr('checked', radiobutton.value === monthlyType);
                    }
                    break;

                case 'riyearlyinterval':
                    field.find('input[name=riyearlyinterval]').val(interval);
                    break;

                case 'riyearlyoptions':
                    var yearlyType = 'DAYOFMONTH'; // Default to using BYMONTHDAY

                    if (bymonthday) {
                        yearlyType = 'DAYOFMONTH';
                        if (bymonthday.length > 1) {
                            // No support for multiple days in one month
                            unsupportedFeatures.push(conf.i18n.multipleDayOfMonth);
                            bymonthday = bymonthday[0];
                        }
                        field.find('select[name=riyearlydayofmonthmonth]').val(bymonth);
                        field.find('select[name=riyearlydayofmonthday]').val(bymonthday);
                    }

                    if (byday) {
                        yearlyType = 'WEEKDAYOFMONTH';

                        if (byday.indexOf(',') !== -1) {
                            // No support for multiple days in one month
                            unsupportedFeatures.push(conf.i18n.multipleDayOfMonth);
                            byday = byday.split(",")[0];
                        }
                        index = byday.slice(0, -2);
                        if (index.charAt(0) !== '+' && index.charAt(0) !== '-') {
                            index = '+' + index;
                        }
                        weekday = byday.slice(-2);
                        field.find('select[name=riyearlyweekdayofmonthindex]').val(index);
                        field.find('select[name=riyearlyweekdayofmonthday]').val(weekday);
                        field.find('select[name=riyearlyweekdayofmonthmonth]').val(bymonth);
                    }

                    selectors = field.find('input[name=riyearlyType]');
                    for (index = 0; index < selectors.length; index++) {
                        radiobutton = selectors[index];
                        $(radiobutton).attr('checked', radiobutton.value === yearlyType);
                    }
                    break;

                case 'rirangeoptions':
                    var rangeType = 'NOENDDATE';

                    if (count) {
                        rangeType = 'BYOCCURRENCES';
                        field.find('input[name=rirangebyoccurrencesvalue]').val(count);
                    }

                    if (until) {
                        rangeType = 'BYENDDATE';
                        input = field.find('input[name=rirangebyenddatecalendar]');
                        year = until.slice(0, 4);
                        month = until.slice(4, 6);
                        month = parseInt(month, 10) - 1;
                        day = until.slice(6, 8);
                        input.data('dateinput').setValue(new Date(year, month, day));
                    }

                    selectors = field.find('input[name=rirangetype]');
                    for (index = 0; index <  selectors.length; index++) {
                        radiobutton = selectors[index];
                        $(radiobutton).attr('checked', radiobutton.value === rangeType);
                    }
                    break;
                }
            }
        }

        var messagearea = form.find('#messagearea');
        if (unsupportedFeatures.length !== 0) {
            messagearea.text(conf.i18n.unsupportedFeatures + ' ' + unsupportedFeatures.join('; '));
            messagearea.show();
            return 1;
        } else {
            messagearea.text('');
            messagearea.hide();
            return 0;
        }

    }

    /**
     * RecurrenceInput - form, display and tools for recurrenceinput widget
     */
    function RecurrenceInput(conf, textarea) {

        var self = this;
        var form, display;

        // Extend conf with non-configurable data used by templates.
        var orderedWeekdays = [];
        var index, i;
        for (i = 0; i < 7; i++) {
            index = i + conf.firstDay;
            if (index > 6) {
                index = index - 7;
            }
            orderedWeekdays.push(index);
        }

        $.extend(conf, {
            orderIndexes: ['+1', '+2', '+3', '+4', '-1'],
            weekdays: ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'],
            orderedWeekdays: orderedWeekdays
        });

        // The recurrence type dropdown should show certain fields depending
        // on selection:
        function displayFields(selector) {
            var i;
            // First hide all the fields
            form.find('.rifield').hide();
            // Then show the ones that should be shown.
            var value = selector.val();
            if (value) {
                var rtemplate = conf.rtemplate[value];
                for (i = 0; i < rtemplate.fields.length; i++) {
                    form.find('#' + rtemplate.fields[i]).show();
                }
            }
        }

        function occurrenceExclude(event) {
            event.preventDefault();
            if (form.ical.EXDATE === undefined) {
                form.ical.EXDATE = [];
            }
            form.ical.EXDATE.push(this.attributes.date.value);
            var $this = $(this);
            $this.attr('class', 'exdate');
            $this.parent().parent().addClass('exdate');
            $this.unbind(event);
            $this.click(occurrenceInclude); // Jslint warns here, but that's OK.
        }

        function occurrenceInclude(event) {
            event.preventDefault();
            form.ical.EXDATE.splice($.inArray(this.attributes.date.value, form.ical.EXDATE), 1);
            var $this = $(this);
            $this.attr('class', 'rrule');
            $this.parent().parent().removeClass('exdate');
            $this.unbind(event);
            $this.click(occurrenceExclude);
        }

        function occurrenceDelete(event) {
            event.preventDefault();
            form.ical.RDATE.splice($.inArray(this.attributes.date.value, form.ical.RDATE), 1);
            $(this).parent().parent().hide('slow', function () {
                $(this).remove();
            });
        }

        function occurrenceAdd(event) {
            event.preventDefault();
            var dateinput = form
                .find('.riaddoccurrence input#adddate')
                .data('dateinput');
            var datevalue = dateinput.getValue('yyyymmddT000000');
            if (form.ical.RDATE === undefined) {
                form.ical.RDATE = [];
            }
            var errorarea = form.find('.riaddoccurrence div.errorarea');
            errorarea.text('');
            errorarea.hide();

            // Add date only if it is not already in RDATE
            if ($.inArray(datevalue, form.ical.RDATE) === -1) {
                form.ical.RDATE.push(datevalue);
                var html = ['<div class="occurrence rdate" style="display: none;">',
                        '<span class="rdate">',
                            dateinput.getValue(conf.i18n.longDateFormat),
                            '<span class="rlabel">' + conf.i18n.additionalDate + '</span>',
                        '</span>',
                        '<span class="action">',
                            '<a date="' + datevalue + '" href="#" class="rdate" >',
                                'Include',
                            '</a>',
                        '</span>',
                        '</div>'].join('\n');
                form.find('div.rioccurrences').prepend(html);
                $(form.find('div.rioccurrences div')[0]).slideDown();
                $(form.find('div.rioccurrences .action a.rdate')[0]).click(occurrenceDelete);
            } else {
                errorarea.text(conf.i18n.alreadyAdded).show();
            }
        }

        // element is where to find the tag in question. Can be the form
        // or the display widget. Defaults to the form.
        function loadOccurrences(startdate, rfc5545, start, readonly) {
            var element, occurrenceDiv;

            if (!readonly) {
                element = form;
            } else {
                element = display;
            }

            occurrenceDiv = element.find('.rioccurrences');
            occurrenceDiv.hide();

            var year, month, day;
            year = startdate.getFullYear();
            month = startdate.getMonth() + 1;
            day = startdate.getDate();

            var data = {year: year,
                       month: month, // Sending January as 0? I think not.
                       day: day,
                       rrule: rfc5545,
                       format: conf.i18n.longDateFormat,
                       start: start};

            var dict = {
                url: conf.ajaxURL,
                async: false, // Can't be tested if it's asynchronous, annoyingly.
                type: 'post',
                dataType: 'json',
                contentType: conf.ajaxContentType,
                cache: false,
                data: data,
                success: function (data, status, jqXHR) {
                    var result, element;

                    if (!readonly) {
                        element = form;
                    } else {
                        element = display;
                    }
                    data.readOnly = readonly;
                    data.i18n = conf.i18n;

                    // Format dates:
                    var occurrence, date, y, m, d, each;
                    for (each in data.occurrences) {
                        if (data.occurrences.hasOwnProperty(each)) {
                            occurrence = data.occurrences[each];
                            date = occurrence.date;
                            y = parseInt(date.substring(0, 4), 10);
                            m = parseInt(date.substring(4, 6), 10) - 1; // jan=0
                            d = parseInt(date.substring(6, 8), 10);
                            occurrence.formattedDate = format(new Date(y, m, d), conf.i18n.longDateFormat, conf);
                        }
                    }

                    result = $.tmpl('occurrenceTmpl', data);
                    occurrenceDiv = element.find('.rioccurrences');
                    occurrenceDiv.replaceWith(result);

                    // Add the batch actions:
                    element.find('.rioccurrences .batching a').click(
                        function (event) {
                            event.preventDefault();
                            loadOccurrences(startdate, rfc5545, this.attributes.start.value, readonly);
                        }
                    );

                    // Add the delete/undelete actions:
                    if (!readonly) {
                        element.find('.rioccurrences .action a.rrule').click(occurrenceExclude);
                        element.find('.rioccurrences .action a.exdate').click(occurrenceInclude);
                        element.find('.rioccurrences .action a.rdate').click(occurrenceDelete);
                    }
                    // Show the new div
                    element.find('.rioccurrences').show();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus);
                }
            };

            $.ajax(dict);
        }

        function getField(field) {
            // See if it is a field already
            var realField = $(field);
            if (!realField.length) {
                // Otherwise, we assume it's an id:
                realField = $('#' + field);
            }
            if (!realField.length) {
                // Still not? Then it's a name.
                realField = $("input[name='" + field + "']");
            }
            return realField;
        }
        function findStartDate() {
            var startdate = null;
            var startField, startFieldYear, startFieldMonth, startFieldDay;

            // Find the default byday and bymonthday from the start date, if any:
            if (conf.startField) {
                startField = getField(conf.startField);
                if (!startField.length) {
                    // Field not found
                    return null;
                }
                // Now we have a field, see if it is a dateinput field:
                startdate = startField.data('dateinput');
                if (!startdate) {
                    //No, it wasn't, just try to interpret it with Date()
                    startdate = startField.val();
                    if (startdate === "") {
                        // Probably not an input at all. Try to see if it contains a date
                        startdate = startField.text();
                    }
                } else {
                    // Yes it was, get the date:
                    startdate = startdate.getValue();
                }

                if (typeof startdate === 'string') {
                    // convert human readable, non ISO8601 dates, like
                    // '2014-04-24 19:00', where the 'T' separator is missing.
                    startdate = startdate.replace(' ', 'T');
                }

                startdate = new Date(startdate);
            } else if (conf.startFieldYear &&
                       conf.startFieldMonth &&
                       conf.startFieldDay) {
                startFieldYear = getField(conf.startFieldYear);
                startFieldMonth = getField(conf.startFieldMonth);
                startFieldDay = getField(conf.startFieldDay);
                if (!startFieldYear.length &&
                    !startFieldMonth.length &&
                    !startFieldDay.length) {
                    // Field not found
                    return null;
                }
                startdate = new Date(startFieldYear.val(),
                                     startFieldMonth.val() - 1,
                                     startFieldDay.val());
            }
            if (startdate === null) {
                return null;
            }
            // We have some sort of startdate:
            if (isNaN(startdate)) {
                return null;
            }
            return startdate;
        }
        function findEndDate(form) {
            var endField, enddate;

            endField = form.find('input[name=rirangebyenddatecalendar]');

            // Now we have a field, see if it is a dateinput field:
            enddate = endField.data('dateinput');
            if (!enddate) {
                //No, it wasn't, just try to interpret it with Date()
                enddate = endField.val();
            } else {
                // Yes it was, get the date:
                enddate = enddate.getValue();
            }
            enddate = new Date(enddate);

            // if the end date is incorrect or the field is left empty
            if (isNaN(enddate) || endField.val() === "") {
                return null;
            }
            return enddate;
        }
        function findIntField(fieldName, form) {
            var field, num, isInt;

            field = form.find('input[name=' + fieldName + ']');

            num = field.val();

            // if it's not a number or the field is left empty
            if (isNaN(num) || (num.toString().indexOf('.') !== -1) || field.val() === "") {
                return null;
            }
            return num;
        }

        // Loading (populating) display and form widget with
        // passed RFC5545 string (data)
        function loadData(rfc5545) {
            var selector, format, startdate, dayindex, day;

            if (rfc5545) {
                widgetLoadFromRfc5545(form, conf, rfc5545, true);
            }

            startdate = findStartDate();

            if (startdate !== null) {
                // If the date is a real date, set the defaults in the form
                form.find('select[name=rimonthlydayofmonthday]').val(startdate.getDate());
                dayindex = conf.orderIndexes[Math.floor((startdate.getDate() - 1) / 7)];
                day = conf.weekdays[startdate.getDay()];
                form.find('select[name=rimonthlyweekdayofmonthindex]').val(dayindex);
                form.find('select[name=rimonthlyweekdayofmonth]').val(day);

                form.find('select[name=riyearlydayofmonthmonth]').val(startdate.getMonth() + 1);
                form.find('select[name=riyearlydayofmonthday]').val(startdate.getDate());
                form.find('select[name=riyearlyweekdayofmonthindex]').val(dayindex);
                form.find('select[name=riyearlyweekdayofmonthday]').val(day);
                form.find('select[name=riyearlyweekdayofmonthmonth]').val(startdate.getMonth() + 1);

                // Now when we have a start date, we can also do an ajax call to calculate occurrences:
                loadOccurrences(startdate, widgetSaveToRfc5545(form, conf, false).result, 0, false);

                // Show the add and refresh buttons:
                form.find('div.rioccurrencesactions').show();

            } else {
                // No EXDATE/RDATE support
                form.find('div.rioccurrencesactions').hide();
            }


            selector = form.find('select[name=rirtemplate]');
            displayFields(selector);
        }

        function recurrenceOn() {
            var RFC5545 = widgetSaveToRfc5545(form, conf, false);
            var label = display.find('label[class=ridisplay]');
            label.text(conf.i18n.displayActivate + ' ' + RFC5545.description);
            textarea.val(RFC5545.result).change();
            var startdate = findStartDate();
            if (startdate !== null) {
                loadOccurrences(startdate, widgetSaveToRfc5545(form, conf, false).result, 0, true);
            }
            display.find('button[name="riedit"]').text(conf.i18n.edit_rules);
            display.find('button[name="ridelete"]').show();
        }

        function recurrenceOff() {
            var label = display.find('label[class=ridisplay]');
            label.text(conf.i18n.displayUnactivate);
            textarea.val('').change();  // Clear the textarea.
            display.find('.rioccurrences').hide();
            display.find('button[name="riedit"]').text(conf.i18n.add_rules);
            display.find('button[name="ridelete"]').hide();
        }

        function checkFields(form) {
            var startDate, endDate, num, messagearea;
            startDate = findStartDate();

            // Hide any error message from before
            messagearea = form.find('#messagearea');
            messagearea.text('');
            messagearea.hide();

            // Hide add field errors
            form.find('.riaddoccurrence div.errorarea').text('').hide();

            // Repeats Daily
            if (form.find('#ridailyinterval').css('display') === 'block') {
                // Check repeat every field
                num = findIntField('ridailyinterval', form);
                if (!num || num < 1 || num > 1000) {
                    messagearea.text(conf.i18n.noRepeatEvery).show();
                    return false;
                }
            }

            // Repeats Weekly
            if (form.find('#riweeklyinterval').css('display') === 'block') {
                // Check repeat every field
                num = findIntField('riweeklyinterval', form);
                if (!num || num < 1 || num > 1000) {
                    messagearea.text(conf.i18n.noRepeatEvery).show();
                    return false;
                }
            }

            // Repeats Monthly
            if (form.find('#rimonthlyinterval').css('display') === 'block') {
                // Check repeat every field
                num = findIntField('rimonthlyinterval', form);
                if (!num || num < 1 || num > 1000) {
                    messagearea.text(conf.i18n.noRepeatEvery).show();
                    return false;
                }

                // Check repeat on
                if (form.find('#rimonthlyoptions input:checked').length === 0) {
                    messagearea.text(conf.i18n.noRepeatOn).show();
                    return false;
                }
            }

            // Repeats Yearly
            if (form.find('#riyearlyinterval').css('display') === 'block') {
                // Check repeat every field
                num = findIntField('riyearlyinterval', form);
                if (!num || num < 1 || num > 1000) {
                    messagearea.text(conf.i18n.noRepeatEvery).show();
                    return false;
                }

                // Check repeat on
                if (form.find('#riyearlyoptions input:checked').length === 0) {
                    messagearea.text(conf.i18n.noRepeatOn).show();
                    return false;
                }
            }

            // End recurrence fields

            // If after N occurences is selected, check its value
            if (form.find('input[value="BYOCCURRENCES"]:visible:checked').length > 0) {
                num = findIntField('rirangebyoccurrencesvalue', form);
                if (!num || num < 1 || num > 1000) {
                    messagearea.text(conf.i18n.noEndAfterNOccurrences).show();
                    return false;
                }
            }

            // If end date is selected, check its value
            if (form.find('input[value="BYENDDATE"]:visible:checked').length > 0) {
                endDate = findEndDate(form);
                if (!endDate) {
                    // if endDate is null that means the field is empty
                    messagearea.text(conf.i18n.noEndDate).show();
                    return false;
                } else if (endDate < startDate) {
                    // the end date cannot be before start date
                    messagearea.text(conf.i18n.pastEndDate).show();
                    return false;
                }
            }

            return true;
        }

        function save(event) {
            event.preventDefault();
            // if no field errors, process the request
            if (checkFields(form)) {
                // close overlay
                form.overlay().close();
                recurrenceOn();
            }
        }

        function cancel(event) {
            event.preventDefault();
            // close overlay
            form.overlay().close();
        }

        function updateOccurances() {
            var startDate;
            startDate = findStartDate();

            // if no field errors, process the request
            if (checkFields(form)) {
                loadOccurrences(startDate,
                    widgetSaveToRfc5545(form, conf, false).result,
                    0,
                    false);
            }
        }

        /*
          Load the templates
        */

        display = $.tmpl('displayTmpl', conf);
        form = $.tmpl('formTmpl', conf);

        // Make an overlay and hide it
        form.overlay(conf.formOverlay).hide();
        form.ical = {RDATE: [], EXDATE: []};

        $.tools.dateinput.localize(conf.lang,  {
            months:      LABELS[conf.lang].months.join(),
            shortMonths: LABELS[conf.lang].shortMonths.join(),
            days:        LABELS[conf.lang].weekdays.join(),
            shortDays:   LABELS[conf.lang].shortWeekdays.join()
        });

        // Make the date input into a calendar dateinput()
        form.find('input[name=rirangebyenddatecalendar]').dateinput({
            selectors: true,
            lang: conf.lang,
            format: conf.i18n.shortDateFormat,
            firstDay: conf.firstDay,
            yearRange: [-5, 10]
        }).data('dateinput').setValue(new Date());

        if (textarea.val()) {
            var result = widgetLoadFromRfc5545(form, conf, textarea.val(), false);
            if (result === -1) {
                var label = display.find('label[class=ridisplay]');
                label.text(conf.i18n.noRule);
            } else {
                recurrenceOn();
            }
        }

        /*
          Do all the GUI stuff:
        */

        // When you click "Delete...", the recurrence rules should be cleared.
        display.find('button[name=ridelete]').click(function (e) {
            e.preventDefault();
            recurrenceOff();
        });

        // Show form overlay when you click on the "Edit..." link
        display.find('button[name=riedit]').click(
            function (e) {
                // Load the form to set up the right fields to show, etc.
                loadData(textarea.val());
                e.preventDefault();
                form.overlay().load();
            }
        );

        // Pop up the little add form when clicking "Add"
        form.find('div.riaddoccurrence input#adddate').dateinput({
            selectors: true,
            lang: conf.lang,
            format: conf.i18n.shortDateFormat,
            firstDay: conf.firstDay,
            yearRange: [-5, 10]
        }).data('dateinput').setValue(new Date());
        form.find('input#addaction').click(occurrenceAdd);

        // When the reload button is clicked, reload
        form.find('a.rirefreshbutton').click(
            function (event) {
                event.preventDefault();
                updateOccurances();
            }
        );

        // When selecting template, update what fieldsets are visible.
        form.find('select[name=rirtemplate]').change(
            function (e) {
                displayFields($(this));
            }
        );

        // When focus goes to a drop-down, select the relevant radiobutton.
        form.find('select').change(
            function (e) {
                $(this).parent().find('> input').click().change();
            }
        );
        form.find('input[name=rirangebyoccurrencesvalue]').change(
            function (e) {
                $(this).parent().find('input[name=rirangetype]').click().change();
            }
        );
        form.find('input[name=rirangebyenddatecalendar]').change(function () {
            // Update only if the occurances are shown
            $(this).parent().find('input[name=rirangetype]').click();
            if (form.find('.rioccurrencesactions:visible').length !== 0) {
                updateOccurances();
            }
        });
        // Update the selected dates section
        form.find('input:radio, .riweeklyweekday > input, input[name=ridailyinterval], input[name=riweeklyinterval], input[name=rimonthlyinterval], input[name=riyearlyinterval]').change(
            function (e) {
                // Update only if the occurances are shown
                if (form.find('.rioccurrencesactions:visible').length !== 0) {
                    updateOccurances();
                }
            }
        );

        /*
          Save and cancel methods:
        */
        form.find('.ricancelbutton').click(cancel);
        form.find('.risavebutton').click(save);

        /*
         * Public API of RecurrenceInput
         */

        $.extend(self, {
            display: display,
            form: form,
            loadData: loadData, //Used by tests.
            save: save //Used by tests.
        });

    }


    /*
     * jQuery plugin implementation
     */
    $.fn.recurrenceinput = function (conf) {
        if (this.data('recurrenceinput')) {
            // plugin already installed
            return this.data('recurrenceinput');
        }

        // "compile" configuration for widget
        var config = $.extend({}, tool.conf);
        $.extend(config, conf);
        $.extend(config, {i18n: LABELS[config.lang], name: this.attr('name')});

        // our recurrenceinput widget instance
        var recurrenceinput = new RecurrenceInput(config, this);
        // hide textarea and place display widget after textarea
        recurrenceinput.form.appendTo('body');
        this.after(recurrenceinput.display);

        // hide the textarea
        this.hide();

        // save the data for next call
        this.data('recurrenceinput', recurrenceinput);
        return recurrenceinput;
    };

}(jQuery));


  }).apply(root, arguments);
});
}(this));

/* Recurrence pattern.
 *
 * Options:
 *    localization(object): Customizations to locatizations. Default to null
 *    configuration(object): recurrent input widget configuration
 *
 * Documentation:
 *
 *    # Simple
 *
 *    {{ example-1 }}
 *
 * Example: example-1
 *    <textarea class="pat-recurrence"></textarea>
 *
 *
 */


define('mockup-patterns-recurrence',[
  'jquery',
  'pat-base',
  'jquery.recurrenceinput'
], function($, Base) {
  'use strict';

  var Recurrence = Base.extend({
    name: 'recurrence',
    trigger: '.pat-recurrence',
    parser: 'mockup',
    defaults: {
      // just passed onto the widget
      language: 'en',
      localization: null,
      configuration: {}
    },
    init: function() {
      this.$el.addClass('recurrence-widget');
      if (this.options.localization) {
        $.tools.recurrenceinput.localize(this.options.language, this.options.localization);
      }
      this.$el.recurrenceinput(this.options.configuration);
    }
  });

  return Recurrence;

});

(function(root) {
define("jqtree", ["jquery"], function() {
  return (function() {
/*!
 * JqTree 1.4.1
 * 
 * Copyright 2017 Marco Braak
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
/******/ (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;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// 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 = 19);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var Position;
(function (Position) {
    Position[Position["Before"] = 1] = "Before";
    Position[Position["After"] = 2] = "After";
    Position[Position["Inside"] = 3] = "Inside";
    Position[Position["None"] = 4] = "None";
})(Position = exports.Position || (exports.Position = {}));
exports.position_names = {
    before: Position.Before,
    after: Position.After,
    inside: Position.Inside,
    none: Position.None
};
function getPositionName(position) {
    for (var name_1 in exports.position_names) {
        if (exports.position_names.hasOwnProperty(name_1)) {
            if (exports.position_names[name_1] === position) {
                return name_1;
            }
        }
    }
    return "";
}
exports.getPositionName = getPositionName;
function getPosition(name) {
    return exports.position_names[name];
}
exports.getPosition = getPosition;
var Node = (function () {
    function Node(o, is_root, node_class) {
        if (is_root === void 0) { is_root = false; }
        if (node_class === void 0) { node_class = Node; }
        this.name = "";
        this.setData(o);
        this.children = [];
        this.parent = null;
        if (is_root) {
            this.id_mapping = {};
            this.tree = this;
            this.node_class = node_class;
        }
    }
    /*
    Set the data of this node.

    setData(string): set the name of the node
    setdata(object): set attributes of the node

    Examples:
        setdata('node1')

        setData({ name: 'node1', id: 1});

        setData({ name: 'node2', id: 2, color: 'green'});

    * This is an internal function; it is not in the docs
    * Does not remove existing node values
    */
    Node.prototype.setData = function (o) {
        var _this = this;
        var setName = function (name) {
            if (name != null) {
                _this.name = name;
            }
        };
        if (!o) {
            return;
        }
        else if (typeof o !== "object") {
            setName(o);
        }
        else {
            for (var key in o) {
                if (o.hasOwnProperty(key)) {
                    var value = o[key];
                    if (key === "label") {
                        // You can use the 'label' key instead of 'name'; this is a legacy feature
                        setName(value);
                    }
                    else if (key !== "children") {
                        // You can't update the children using this function
                        this[key] = value;
                    }
                }
            }
        }
    };
    /*
    Create tree from data.

    Structure of data is:
    [
        {
            label: 'node1',
            children: [
                { label: 'child1' },
                { label: 'child2' }
            ]
        },
        {
            label: 'node2'
        }
    ]
    */
    Node.prototype.loadFromData = function (data) {
        this.removeChildren();
        for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
            var o = data_1[_i];
            var node = new this.tree.node_class(o);
            this.addChild(node);
            if (typeof o === "object" && o["children"]) {
                node.loadFromData(o["children"]);
            }
        }
    };
    /*
    Add child.

    tree.addChild(
        new Node('child1')
    );
    */
    Node.prototype.addChild = function (node) {
        this.children.push(node);
        node._setParent(this);
    };
    /*
    Add child at position. Index starts at 0.

    tree.addChildAtPosition(
        new Node('abc'),
        1
    );
    */
    Node.prototype.addChildAtPosition = function (node, index) {
        this.children.splice(index, 0, node);
        node._setParent(this);
    };
    /*
    Remove child. This also removes the children of the node.

    tree.removeChild(tree.children[0]);
    */
    Node.prototype.removeChild = function (node) {
        // remove children from the index
        node.removeChildren();
        this._removeChild(node);
    };
    /*
    Get child index.

    var index = getChildIndex(node);
    */
    Node.prototype.getChildIndex = function (node) {
        return $.inArray(node, this.children);
    };
    /*
    Does the tree have children?

    if (tree.hasChildren()) {
        //
    }
    */
    Node.prototype.hasChildren = function () {
        return this.children.length !== 0;
    };
    Node.prototype.isFolder = function () {
        return this.hasChildren() || this.load_on_demand;
    };
    /*
    Iterate over all the nodes in the tree.

    Calls callback with (node, level).

    The callback must return true to continue the iteration on current node.

    tree.iterate(
        function(node, level) {
           console.log(node.name);

           // stop iteration after level 2
           return (level <= 2);
        }
    );

    */
    Node.prototype.iterate = function (callback) {
        var _iterate = function (node, level) {
            if (node.children) {
                for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
                    var child = _a[_i];
                    var result = callback(child, level);
                    if (result && child.hasChildren()) {
                        _iterate(child, level + 1);
                    }
                }
            }
        };
        _iterate(this, 0);
    };
    /*
    Move node relative to another node.

    Argument position: Position.BEFORE, Position.AFTER or Position.Inside

    // move node1 after node2
    tree.moveNode(node1, node2, Position.AFTER);
    */
    Node.prototype.moveNode = function (moved_node, target_node, position) {
        if (!moved_node.parent || moved_node.isParentOf(target_node)) {
            // - Node is parent of target node
            // - Or, parent is empty
            return;
        }
        else {
            moved_node.parent._removeChild(moved_node);
            if (position === Position.After) {
                if (target_node.parent) {
                    target_node.parent.addChildAtPosition(moved_node, target_node.parent.getChildIndex(target_node) + 1);
                }
            }
            else if (position === Position.Before) {
                if (target_node.parent) {
                    target_node.parent.addChildAtPosition(moved_node, target_node.parent.getChildIndex(target_node));
                }
            }
            else if (position === Position.Inside) {
                // move inside as first child
                target_node.addChildAtPosition(moved_node, 0);
            }
        }
    };
    /*
    Get the tree as data.
    */
    Node.prototype.getData = function (include_parent) {
        if (include_parent === void 0) { include_parent = false; }
        function getDataFromNodes(nodes) {
            return nodes.map(function (node) {
                var tmp_node = {};
                for (var k in node) {
                    if (["parent", "children", "element", "tree"].indexOf(k) === -1 &&
                        Object.prototype.hasOwnProperty.call(node, k)) {
                        var v = node[k];
                        tmp_node[k] = v;
                    }
                }
                if (node.hasChildren()) {
                    tmp_node["children"] = getDataFromNodes(node.children);
                }
                return tmp_node;
            });
        }
        if (include_parent) {
            return getDataFromNodes([this]);
        }
        else {
            return getDataFromNodes(this.children);
        }
    };
    Node.prototype.getNodeByName = function (name) {
        return this.getNodeByCallback(function (node) { return node.name === name; });
    };
    Node.prototype.getNodeByCallback = function (callback) {
        var result = null;
        this.iterate(function (node) {
            if (callback(node)) {
                result = node;
                return false;
            }
            else {
                return true;
            }
        });
        return result;
    };
    Node.prototype.addAfter = function (node_info) {
        if (!this.parent) {
            return null;
        }
        else {
            var node = new this.tree.node_class(node_info);
            var child_index = this.parent.getChildIndex(this);
            this.parent.addChildAtPosition(node, child_index + 1);
            if (typeof node_info === "object" && node_info["children"] && node_info["children"].length) {
                node.loadFromData(node_info["children"]);
            }
            return node;
        }
    };
    Node.prototype.addBefore = function (node_info) {
        if (!this.parent) {
            return null;
        }
        else {
            var node = new this.tree.node_class(node_info);
            var child_index = this.parent.getChildIndex(this);
            this.parent.addChildAtPosition(node, child_index);
            if (typeof node_info === "object" && node_info["children"] && node_info["children"].length) {
                node.loadFromData(node_info["children"]);
            }
            return node;
        }
    };
    Node.prototype.addParent = function (node_info) {
        if (!this.parent) {
            return null;
        }
        else {
            var new_parent = new this.tree.node_class(node_info);
            new_parent._setParent(this.tree);
            var original_parent = this.parent;
            for (var _i = 0, _a = original_parent.children; _i < _a.length; _i++) {
                var child = _a[_i];
                new_parent.addChild(child);
            }
            original_parent.children = [];
            original_parent.addChild(new_parent);
            return new_parent;
        }
    };
    Node.prototype.remove = function () {
        if (this.parent) {
            this.parent.removeChild(this);
            this.parent = null;
        }
    };
    Node.prototype.append = function (node_info) {
        var node = new this.tree.node_class(node_info);
        this.addChild(node);
        if (typeof node_info === "object" && node_info["children"] && node_info["children"].length) {
            node.loadFromData(node_info["children"]);
        }
        return node;
    };
    Node.prototype.prepend = function (node_info) {
        var node = new this.tree.node_class(node_info);
        this.addChildAtPosition(node, 0);
        if (typeof node_info === "object" && node_info["children"] && node_info["children"].length) {
            node.loadFromData(node_info["children"]);
        }
        return node;
    };
    Node.prototype.isParentOf = function (node) {
        var parent = node.parent;
        while (parent) {
            if (parent === this) {
                return true;
            }
            parent = parent.parent;
        }
        return false;
    };
    Node.prototype.getLevel = function () {
        var level = 0;
        var node = this;
        while (node.parent) {
            level += 1;
            node = node.parent;
        }
        return level;
    };
    Node.prototype.getNodeById = function (node_id) {
        return this.id_mapping[node_id];
    };
    Node.prototype.addNodeToIndex = function (node) {
        if (node.id != null) {
            this.id_mapping[node.id] = node;
        }
    };
    Node.prototype.removeNodeFromIndex = function (node) {
        if (node.id != null) {
            delete this.id_mapping[node.id];
        }
    };
    Node.prototype.removeChildren = function () {
        var _this = this;
        this.iterate(function (child) {
            _this.tree.removeNodeFromIndex(child);
            return true;
        });
        this.children = [];
    };
    Node.prototype.getPreviousSibling = function () {
        if (!this.parent) {
            return null;
        }
        else {
            var previous_index = this.parent.getChildIndex(this) - 1;
            if (previous_index >= 0) {
                return this.parent.children[previous_index];
            }
            else {
                return null;
            }
        }
    };
    Node.prototype.getNextSibling = function () {
        if (!this.parent) {
            return null;
        }
        else {
            var next_index = this.parent.getChildIndex(this) + 1;
            if (next_index < this.parent.children.length) {
                return this.parent.children[next_index];
            }
            else {
                return null;
            }
        }
    };
    Node.prototype.getNodesByProperty = function (key, value) {
        return this.filter(function (node) { return node[key] === value; });
    };
    Node.prototype.filter = function (f) {
        var result = [];
        this.iterate(function (node) {
            if (f(node)) {
                result.push(node);
            }
            return true;
        });
        return result;
    };
    Node.prototype.getNextNode = function (include_children) {
        if (include_children === void 0) { include_children = true; }
        if (include_children && this.hasChildren() && this.is_open) {
            // First child
            return this.children[0];
        }
        else {
            if (!this.parent) {
                return null;
            }
            else {
                var next_sibling = this.getNextSibling();
                if (next_sibling) {
                    // Next sibling
                    return next_sibling;
                }
                else {
                    // Next node of parent
                    return this.parent.getNextNode(false);
                }
            }
        }
    };
    Node.prototype.getPreviousNode = function () {
        if (!this.parent) {
            return null;
        }
        else {
            var previous_sibling = this.getPreviousSibling();
            if (previous_sibling) {
                if (!previous_sibling.hasChildren() || !previous_sibling.is_open) {
                    // Previous sibling
                    return previous_sibling;
                }
                else {
                    // Last child of previous sibling
                    return previous_sibling.getLastChild();
                }
            }
            else {
                return this.getParent();
            }
        }
    };
    Node.prototype.getParent = function () {
        // Return parent except if it is the root node
        if (!this.parent) {
            return null;
        }
        else if (!this.parent.parent) {
            // Root node -> null
            return null;
        }
        else {
            return this.parent;
        }
    };
    Node.prototype.getLastChild = function () {
        if (!this.hasChildren()) {
            return null;
        }
        else {
            var last_child = this.children[this.children.length - 1];
            if (!last_child.hasChildren() || !last_child.is_open) {
                return last_child;
            }
            else {
                return last_child.getLastChild();
            }
        }
    };
    // Init Node from data without making it the root of the tree
    Node.prototype.initFromData = function (data) {
        var _this = this;
        var addNode = function (node_data) {
            _this.setData(node_data);
            if (node_data["children"]) {
                addChildren(node_data["children"]);
            }
        };
        var addChildren = function (children_data) {
            for (var _i = 0, children_data_1 = children_data; _i < children_data_1.length; _i++) {
                var child = children_data_1[_i];
                var node = new _this.tree.node_class("");
                node.initFromData(child);
                _this.addChild(node);
            }
        };
        addNode(data);
    };
    Node.prototype._setParent = function (parent) {
        this.parent = parent;
        this.tree = parent.tree;
        this.tree.addNodeToIndex(this);
    };
    Node.prototype._removeChild = function (node) {
        this.children.splice(this.getChildIndex(node), 1);
        this.tree.removeNodeFromIndex(node);
    };
    return Node;
}());
exports.Node = Node;


/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
function isInt(n) {
    return typeof n === "number" && n % 1 === 0;
}
exports.isInt = isInt;
function isFunction(v) {
    return typeof v === "function";
}
exports.isFunction = isFunction;
// Escape a string for HTML interpolation; copied from underscore js
function html_escape(text) {
    return ("" + text)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#x27;")
        .replace(/\//g, "&#x2F;");
}
exports.html_escape = html_escape;
function getBoolString(value) {
    if (value) {
        return "true";
    }
    else {
        return "false";
    }
}
exports.getBoolString = getBoolString;


/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var SimpleWidget = (function () {
    function SimpleWidget(el, options) {
        this.$el = $(el);
        var defaults = this.constructor.defaults;
        this.options = $.extend({}, defaults, options);
    }
    SimpleWidget.register = function (widget_class, widget_name) {
        var getDataKey = function () { return "simple_widget_" + widget_name; };
        function getWidgetData(el, data_key) {
            var widget = $.data(el, data_key);
            if (widget && (widget instanceof SimpleWidget)) {
                return widget;
            }
            else {
                return null;
            }
        }
        function createWidget($el, options) {
            var data_key = getDataKey();
            for (var _i = 0, _a = $el.get(); _i < _a.length; _i++) {
                var el = _a[_i];
                var existing_widget = getWidgetData(el, data_key);
                if (!existing_widget) {
                    var widget = new widget_class(el, options);
                    if (!$.data(el, data_key)) {
                        $.data(el, data_key, widget);
                    }
                    // Call init after setting data, so we can call methods
                    widget._init();
                }
            }
            return $el;
        }
        function destroyWidget($el) {
            var data_key = getDataKey();
            for (var _i = 0, _a = $el.get(); _i < _a.length; _i++) {
                var el = _a[_i];
                var widget = getWidgetData(el, data_key);
                if (widget) {
                    widget.destroy();
                }
                $.removeData(el, data_key);
            }
        }
        function callFunction($el, function_name, args) {
            var result = null;
            for (var _i = 0, _a = $el.get(); _i < _a.length; _i++) {
                var el = _a[_i];
                var widget = $.data(el, getDataKey());
                if (widget && (widget instanceof SimpleWidget)) {
                    var widget_function = widget[function_name];
                    if (widget_function && (typeof widget_function === "function")) {
                        result = widget_function.apply(widget, args);
                    }
                }
            }
            return result;
        }
        // tslint:disable-next-line: only-arrow-functions
        $.fn[widget_name] = function (argument1) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            var $el = this;
            if (argument1 === undefined || typeof argument1 === "object") {
                var options = argument1;
                return createWidget($el, options);
            }
            else if (typeof argument1 === "string" && argument1[0] !== "_") {
                var function_name = argument1;
                if (function_name === "destroy") {
                    return destroyWidget($el);
                }
                else if (function_name === "get_widget_class") {
                    return widget_class;
                }
                else {
                    return callFunction($el, function_name, args);
                }
            }
        };
    };
    SimpleWidget.prototype.destroy = function () {
        this._deinit();
    };
    SimpleWidget.prototype._init = function () {
        //
    };
    SimpleWidget.prototype._deinit = function () {
        //
    };
    return SimpleWidget;
}());
SimpleWidget.defaults = {};
exports["default"] = SimpleWidget;


/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {



var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
exports.__esModule = true;
var version_1 = __webpack_require__(12);
var drag_and_drop_handler_1 = __webpack_require__(4);
var elements_renderer_1 = __webpack_require__(5);
var key_handler_1 = __webpack_require__(6);
var mouse_widget_1 = __webpack_require__(7);
var save_state_handler_1 = __webpack_require__(9);
var scroll_handler_1 = __webpack_require__(10);
var select_node_handler_1 = __webpack_require__(11);
var simple_widget_1 = __webpack_require__(2);
var node_1 = __webpack_require__(0);
var util_1 = __webpack_require__(1);
var node_element_1 = __webpack_require__(8);
var JqTreeWidget = (function (_super) {
    __extends(JqTreeWidget, _super);
    function JqTreeWidget() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    JqTreeWidget.prototype.toggle = function (node, slide_param) {
        var slide = slide_param == null ? this.options.slide : slide_param;
        if (node.is_open) {
            this.closeNode(node, slide);
        }
        else {
            this.openNode(node, slide);
        }
        return this.element;
    };
    JqTreeWidget.prototype.getTree = function () {
        return this.tree;
    };
    JqTreeWidget.prototype.selectNode = function (node) {
        this._selectNode(node, false);
        return this.element;
    };
    JqTreeWidget.prototype.getSelectedNode = function () {
        if (this.select_node_handler) {
            return this.select_node_handler.getSelectedNode();
        }
        else {
            return false;
        }
    };
    JqTreeWidget.prototype.toJson = function () {
        return JSON.stringify(this.tree.getData());
    };
    JqTreeWidget.prototype.loadData = function (data, parent_node) {
        this._loadData(data, parent_node);
        return this.element;
    };
    /*
    signatures:
    - loadDataFromUrl(url, parent_node=null, on_finished=null)
        loadDataFromUrl('/my_data');
        loadDataFromUrl('/my_data', node1);
        loadDataFromUrl('/my_data', node1, function() { console.log('finished'); });
        loadDataFromUrl('/my_data', null, function() { console.log('finished'); });

    - loadDataFromUrl(parent_node=null, on_finished=null)
        loadDataFromUrl();
        loadDataFromUrl(node1);
        loadDataFromUrl(null, function() { console.log('finished'); });
        loadDataFromUrl(node1, function() { console.log('finished'); });
    */
    JqTreeWidget.prototype.loadDataFromUrl = function (param1, param2, param3) {
        if ($.type(param1) === "string") {
            // first parameter is url
            this._loadDataFromUrl(param1, param2, param3);
        }
        else {
            // first parameter is not url
            this._loadDataFromUrl(null, param1, param2);
        }
        return this.element;
    };
    JqTreeWidget.prototype.reload = function (on_finished) {
        this._loadDataFromUrl(null, null, on_finished);
        return this.element;
    };
    JqTreeWidget.prototype.getNodeById = function (node_id) {
        return this.tree.getNodeById(node_id);
    };
    JqTreeWidget.prototype.getNodeByName = function (name) {
        return this.tree.getNodeByName(name);
    };
    JqTreeWidget.prototype.getNodesByProperty = function (key, value) {
        return this.tree.getNodesByProperty(key, value);
    };
    JqTreeWidget.prototype.getNodeByHtmlElement = function (element) {
        return this._getNode($(element));
    };
    JqTreeWidget.prototype.getNodeByCallback = function (callback) {
        return this.tree.getNodeByCallback(callback);
    };
    JqTreeWidget.prototype.openNode = function (node, param1, param2) {
        var _this = this;
        var parseParams = function () {
            var on_finished;
            var slide;
            if (util_1.isFunction(param1)) {
                on_finished = param1;
                slide = null;
            }
            else {
                slide = param1;
                on_finished = param2;
            }
            if (slide == null) {
                slide = _this.options.slide;
            }
            return [slide, on_finished];
        };
        var _a = parseParams(), slide = _a[0], on_finished = _a[1];
        if (node) {
            this._openNode(node, slide, on_finished);
        }
        return this.element;
    };
    JqTreeWidget.prototype.closeNode = function (node, slide_param) {
        var slide = slide_param == null ? this.options.slide : slide_param;
        if (node.isFolder()) {
            new node_element_1.FolderElement(node, this).close(slide);
            this._saveState();
        }
        return this.element;
    };
    JqTreeWidget.prototype.isDragging = function () {
        if (this.dnd_handler) {
            return this.dnd_handler.is_dragging;
        }
        else {
            return false;
        }
    };
    JqTreeWidget.prototype.refreshHitAreas = function () {
        if (this.dnd_handler) {
            this.dnd_handler.refresh();
        }
        return this.element;
    };
    JqTreeWidget.prototype.addNodeAfter = function (new_node_info, existing_node) {
        var new_node = existing_node.addAfter(new_node_info);
        if (new_node) {
            this._refreshElements(existing_node.parent);
        }
        return new_node;
    };
    JqTreeWidget.prototype.addNodeBefore = function (new_node_info, existing_node) {
        var new_node = existing_node.addBefore(new_node_info);
        if (new_node) {
            this._refreshElements(existing_node.parent);
        }
        return new_node;
    };
    JqTreeWidget.prototype.addParentNode = function (new_node_info, existing_node) {
        var new_node = existing_node.addParent(new_node_info);
        if (new_node) {
            this._refreshElements(new_node.parent);
        }
        return new_node;
    };
    JqTreeWidget.prototype.removeNode = function (node) {
        if (node.parent && this.select_node_handler) {
            this.select_node_handler.removeFromSelection(node, true); // including children
            node.remove();
            this._refreshElements(node.parent);
        }
        return this.element;
    };
    JqTreeWidget.prototype.appendNode = function (new_node_info, parent_node_param) {
        var parent_node = parent_node_param || this.tree;
        var node = parent_node.append(new_node_info);
        this._refreshElements(parent_node);
        return node;
    };
    JqTreeWidget.prototype.prependNode = function (new_node_info, parent_node_param) {
        var parent_node = !parent_node_param ? this.tree : parent_node_param;
        var node = parent_node.prepend(new_node_info);
        this._refreshElements(parent_node);
        return node;
    };
    JqTreeWidget.prototype.updateNode = function (node, data) {
        var id_is_changed = data.id && data.id !== node.id;
        if (id_is_changed) {
            this.tree.removeNodeFromIndex(node);
        }
        node.setData(data);
        if (id_is_changed) {
            this.tree.addNodeToIndex(node);
        }
        if (typeof data === "object" && data.children) {
            node.removeChildren();
            if (data.children.length) {
                node.loadFromData(data.children);
            }
        }
        this.renderer.renderFromNode(node);
        this._selectCurrentNode();
        return this.element;
    };
    JqTreeWidget.prototype.moveNode = function (node, target_node, position) {
        var position_index = node_1.getPosition(position);
        this.tree.moveNode(node, target_node, position_index);
        this._refreshElements(null);
        return this.element;
    };
    JqTreeWidget.prototype.getStateFromStorage = function () {
        if (this.save_state_handler) {
            return this.save_state_handler.getStateFromStorage();
        }
    };
    JqTreeWidget.prototype.addToSelection = function (node) {
        if (node && this.select_node_handler) {
            this.select_node_handler.addToSelection(node);
            this._getNodeElementForNode(node).select();
            this._saveState();
        }
        return this.element;
    };
    JqTreeWidget.prototype.getSelectedNodes = function () {
        if (!this.select_node_handler) {
            return [];
        }
        else {
            return this.select_node_handler.getSelectedNodes();
        }
    };
    JqTreeWidget.prototype.isNodeSelected = function (node) {
        if (!this.select_node_handler) {
            return false;
        }
        else {
            return this.select_node_handler.isNodeSelected(node);
        }
    };
    JqTreeWidget.prototype.removeFromSelection = function (node) {
        if (this.select_node_handler) {
            this.select_node_handler.removeFromSelection(node);
            this._getNodeElementForNode(node).deselect();
            this._saveState();
        }
        return this.element;
    };
    JqTreeWidget.prototype.scrollToNode = function (node) {
        if (this.scroll_handler) {
            var $element = $(node.element);
            var top_1 = $element.offset().top - this.$el.offset().top;
            this.scroll_handler.scrollTo(top_1);
        }
        return this.element;
    };
    JqTreeWidget.prototype.getState = function () {
        if (this.save_state_handler) {
            return this.save_state_handler.getState();
        }
    };
    JqTreeWidget.prototype.setState = function (state) {
        if (this.save_state_handler) {
            this.save_state_handler.setInitialState(state);
            this._refreshElements(null);
        }
        return this.element;
    };
    JqTreeWidget.prototype.setOption = function (option, value) {
        this.options[option] = value;
        return this.element;
    };
    JqTreeWidget.prototype.moveDown = function () {
        if (this.key_handler) {
            this.key_handler.moveDown();
        }
        return this.element;
    };
    JqTreeWidget.prototype.moveUp = function () {
        if (this.key_handler) {
            this.key_handler.moveUp();
        }
        return this.element;
    };
    JqTreeWidget.prototype.getVersion = function () {
        return version_1["default"];
    };
    JqTreeWidget.prototype.testGenerateHitAreas = function (moving_node) {
        if (!this.dnd_handler) {
            return [];
        }
        else {
            this.dnd_handler.current_item = this._getNodeElementForNode(moving_node);
            this.dnd_handler.generateHitAreas();
            return this.dnd_handler.hit_areas;
        }
    };
    JqTreeWidget.prototype._triggerEvent = function (event_name, values) {
        var event = $.Event(event_name);
        $.extend(event, values);
        this.element.trigger(event);
        return event;
    };
    JqTreeWidget.prototype._openNode = function (node, slide, on_finished) {
        var _this = this;
        if (slide === void 0) { slide = true; }
        var doOpenNode = function (_node, _slide, _on_finished) {
            var folder_element = new node_element_1.FolderElement(_node, _this);
            folder_element.open(_on_finished, _slide);
        };
        if (node.isFolder()) {
            if (node.load_on_demand) {
                this._loadFolderOnDemand(node, slide, on_finished);
            }
            else {
                var parent_1 = node.parent;
                while (parent_1) {
                    // nb: do not open root element
                    if (parent_1.parent) {
                        doOpenNode(parent_1, false, null);
                    }
                    parent_1 = parent_1.parent;
                }
                doOpenNode(node, slide, on_finished);
                this._saveState();
            }
        }
    };
    /*
    Redraw the tree or part of the tree.
     from_node: redraw this subtree
    */
    JqTreeWidget.prototype._refreshElements = function (from_node) {
        this.renderer.render(from_node);
        this._triggerEvent("tree.refresh");
    };
    JqTreeWidget.prototype._getNodeElementForNode = function (node) {
        if (node.isFolder()) {
            return new node_element_1.FolderElement(node, this);
        }
        else {
            return new node_element_1.NodeElement(node, this);
        }
    };
    JqTreeWidget.prototype._getNodeElement = function ($element) {
        var node = this._getNode($element);
        if (node) {
            return this._getNodeElementForNode(node);
        }
        else {
            return null;
        }
    };
    JqTreeWidget.prototype._containsElement = function (element) {
        var node = this._getNode($(element));
        return node != null && node.tree === this.tree;
    };
    JqTreeWidget.prototype._init = function () {
        _super.prototype._init.call(this);
        this.element = this.$el;
        this.mouse_delay = 300;
        this.is_initialized = false;
        this.options.rtl = this._getRtlOption();
        if (!this.options.closedIcon) {
            this.options.closedIcon = this._getDefaultClosedIcon();
        }
        this.renderer = new elements_renderer_1["default"](this);
        if (save_state_handler_1["default"] != null) {
            this.save_state_handler = new save_state_handler_1["default"](this);
        }
        else {
            this.options.saveState = false;
        }
        if (select_node_handler_1["default"] != null) {
            this.select_node_handler = new select_node_handler_1["default"](this);
        }
        if (drag_and_drop_handler_1.DragAndDropHandler != null) {
            this.dnd_handler = new drag_and_drop_handler_1.DragAndDropHandler(this);
        }
        else {
            this.options.dragAndDrop = false;
        }
        if (scroll_handler_1["default"] != null) {
            this.scroll_handler = new scroll_handler_1["default"](this);
        }
        if (key_handler_1["default"] != null && select_node_handler_1["default"] != null) {
            this.key_handler = new key_handler_1["default"](this);
        }
        this._initData();
        this.element.click($.proxy(this._click, this));
        this.element.dblclick($.proxy(this._dblclick, this));
        if (this.options.useContextMenu) {
            this.element.on("contextmenu", $.proxy(this._contextmenu, this));
        }
    };
    JqTreeWidget.prototype._deinit = function () {
        this.element.empty();
        this.element.off();
        if (this.key_handler) {
            this.key_handler.deinit();
        }
        this.tree = new node_1.Node({}, true);
        _super.prototype._deinit.call(this);
    };
    JqTreeWidget.prototype._mouseCapture = function (position_info) {
        if (this.options.dragAndDrop && this.dnd_handler) {
            return this.dnd_handler.mouseCapture(position_info);
        }
        else {
            return false;
        }
    };
    JqTreeWidget.prototype._mouseStart = function (position_info) {
        if (this.options.dragAndDrop && this.dnd_handler) {
            return this.dnd_handler.mouseStart(position_info);
        }
        else {
            return false;
        }
    };
    JqTreeWidget.prototype._mouseDrag = function (position_info) {
        if (this.options.dragAndDrop && this.dnd_handler) {
            var result = this.dnd_handler.mouseDrag(position_info);
            if (this.scroll_handler) {
                this.scroll_handler.checkScrolling();
            }
            return result;
        }
        else {
            return false;
        }
    };
    JqTreeWidget.prototype._mouseStop = function (position_info) {
        if (this.options.dragAndDrop && this.dnd_handler) {
            return this.dnd_handler.mouseStop(position_info);
        }
        else {
            return false;
        }
    };
    JqTreeWidget.prototype._initData = function () {
        if (this.options.data) {
            this._loadData(this.options.data, null);
        }
        else {
            var data_url = this._getDataUrlInfo(null);
            if (data_url) {
                this._loadDataFromUrl(null, null, null);
            }
            else {
                this._loadData([], null);
            }
        }
    };
    JqTreeWidget.prototype._getDataUrlInfo = function (node) {
        var _this = this;
        var data_url = this.options.dataUrl || this.element.data("url");
        var getUrlFromString = function () {
            var url_info = { url: data_url };
            if (node && node.id) {
                // Load on demand of a subtree; add node parameter
                var data = { node: node.id };
                // tslint:disable-next-line: no-string-literal
                url_info["data"] = data;
            }
            else {
                // Add selected_node parameter
                var selected_node_id = _this._getNodeIdToBeSelected();
                if (selected_node_id) {
                    var data = { selected_node: selected_node_id };
                    // tslint:disable-next-line: no-string-literal
                    url_info["data"] = data;
                }
            }
            return url_info;
        };
        if ($.isFunction(data_url)) {
            return data_url(node);
        }
        else if ($.type(data_url) === "string") {
            return getUrlFromString();
        }
        else {
            return data_url;
        }
    };
    JqTreeWidget.prototype._getNodeIdToBeSelected = function () {
        if (this.options.saveState && this.save_state_handler) {
            return this.save_state_handler.getNodeIdToBeSelected();
        }
        else {
            return null;
        }
    };
    JqTreeWidget.prototype._initTree = function (data) {
        var _this = this;
        var doInit = function () {
            if (!_this.is_initialized) {
                _this.is_initialized = true;
                _this._triggerEvent("tree.init");
            }
        };
        this.tree = new this.options.nodeClass(null, true, this.options.nodeClass);
        if (this.select_node_handler) {
            this.select_node_handler.clear();
        }
        this.tree.loadFromData(data);
        var must_load_on_demand = this._setInitialState();
        this._refreshElements(null);
        if (!must_load_on_demand) {
            doInit();
        }
        else {
            // Load data on demand and then init the tree
            this._setInitialStateOnDemand(doInit);
        }
    };
    // Set initial state, either by restoring the state or auto-opening nodes
    // result: must load nodes on demand?
    JqTreeWidget.prototype._setInitialState = function () {
        var _this = this;
        var restoreState = function () {
            // result: is state restored, must load on demand?
            if (!(_this.options.saveState && _this.save_state_handler)) {
                return [false, false];
            }
            else {
                var state = _this.save_state_handler.getStateFromStorage();
                if (!state) {
                    return [false, false];
                }
                else {
                    var must_load_on_demand_1 = _this.save_state_handler.setInitialState(state);
                    // return true: the state is restored
                    return [true, must_load_on_demand_1];
                }
            }
        };
        var autoOpenNodes = function () {
            // result: must load on demand?
            if (_this.options.autoOpen === false) {
                return false;
            }
            var max_level = _this._getAutoOpenMaxLevel();
            var must_load_on_demand = false;
            _this.tree.iterate(function (node, level) {
                if (node.load_on_demand) {
                    must_load_on_demand = true;
                    return false;
                }
                else if (!node.hasChildren()) {
                    return false;
                }
                else {
                    node.is_open = true;
                    return (level !== max_level);
                }
            });
            return must_load_on_demand;
        };
        // tslint:disable-next-line: prefer-const
        var _a = restoreState(), is_restored = _a[0], must_load_on_demand = _a[1];
        if (!is_restored) {
            must_load_on_demand = autoOpenNodes();
        }
        return must_load_on_demand;
    };
    // Set the initial state for nodes that are loaded on demand
    // Call cb_finished when done
    JqTreeWidget.prototype._setInitialStateOnDemand = function (cb_finished) {
        var _this = this;
        var restoreState = function () {
            if (!(_this.options.saveState && _this.save_state_handler)) {
                return false;
            }
            else {
                var state = _this.save_state_handler.getStateFromStorage();
                if (!state) {
                    return false;
                }
                else {
                    _this.save_state_handler.setInitialStateOnDemand(state, cb_finished);
                    return true;
                }
            }
        };
        var autoOpenNodes = function () {
            var max_level = _this._getAutoOpenMaxLevel();
            var loading_count = 0;
            var loadAndOpenNode = function (node) {
                loading_count += 1;
                _this._openNode(node, false, function () {
                    loading_count -= 1;
                    openNodes();
                });
            };
            var openNodes = function () {
                _this.tree.iterate(function (node, level) {
                    if (node.load_on_demand) {
                        if (!node.is_loading) {
                            loadAndOpenNode(node);
                        }
                        return false;
                    }
                    else {
                        _this._openNode(node, false, null);
                        return (level !== max_level);
                    }
                });
                if (loading_count === 0) {
                    cb_finished();
                }
            };
            openNodes();
        };
        if (!restoreState()) {
            autoOpenNodes();
        }
    };
    JqTreeWidget.prototype._getAutoOpenMaxLevel = function () {
        if (this.options.autoOpen === true) {
            return -1;
        }
        else {
            return parseInt(this.options.autoOpen, 10);
        }
    };
    JqTreeWidget.prototype._click = function (e) {
        var click_target = this._getClickTarget(e.target);
        if (click_target) {
            if (click_target.type === "button") {
                this.toggle(click_target.node, this.options.slide);
                e.preventDefault();
                e.stopPropagation();
            }
            else if (click_target.type === "label") {
                var node = click_target.node;
                var event_1 = this._triggerEvent("tree.click", {
                    node: node,
                    click_event: e
                });
                if (!event_1.isDefaultPrevented()) {
                    this._selectNode(node, true);
                }
            }
        }
    };
    JqTreeWidget.prototype._dblclick = function (e) {
        var click_target = this._getClickTarget(e.target);
        if (click_target && click_target.type === "label") {
            this._triggerEvent("tree.dblclick", {
                node: click_target.node,
                click_event: e
            });
        }
    };
    JqTreeWidget.prototype._getClickTarget = function (element) {
        var $target = $(element);
        var $button = $target.closest(".jqtree-toggler");
        if ($button.length) {
            var node = this._getNode($button);
            if (node) {
                return {
                    type: "button",
                    node: node
                };
            }
        }
        else {
            var $el = $target.closest(".jqtree-element");
            if ($el.length) {
                var node = this._getNode($el);
                if (node) {
                    return {
                        type: "label",
                        node: node
                    };
                }
            }
        }
        return null;
    };
    JqTreeWidget.prototype._getNode = function ($element) {
        var $li = $element.closest("li.jqtree_common");
        if ($li.length === 0) {
            return null;
        }
        else {
            return $li.data("node");
        }
    };
    JqTreeWidget.prototype._contextmenu = function (e) {
        var $div = $(e.target).closest("ul.jqtree-tree .jqtree-element");
        if ($div.length) {
            var node = this._getNode($div);
            if (node) {
                e.preventDefault();
                e.stopPropagation();
                this._triggerEvent("tree.contextmenu", {
                    node: node,
                    click_event: e
                });
                return false;
            }
        }
        return null;
    };
    JqTreeWidget.prototype._saveState = function () {
        if (this.options.saveState && this.save_state_handler) {
            this.save_state_handler.saveState();
        }
    };
    JqTreeWidget.prototype._selectCurrentNode = function () {
        var node = this.getSelectedNode();
        if (node) {
            var node_element = this._getNodeElementForNode(node);
            if (node_element) {
                node_element.select();
            }
        }
    };
    JqTreeWidget.prototype._deselectCurrentNode = function () {
        var node = this.getSelectedNode();
        if (node) {
            this.removeFromSelection(node);
        }
    };
    JqTreeWidget.prototype._getDefaultClosedIcon = function () {
        if (this.options.rtl) {
            // triangle to the left
            return "&#x25c0;";
        }
        else {
            // triangle to the right
            return "&#x25ba;";
        }
    };
    JqTreeWidget.prototype._getRtlOption = function () {
        if (this.options.rtl != null) {
            return this.options.rtl;
        }
        else {
            var data_rtl = this.element.data("rtl");
            if (data_rtl != null && data_rtl !== false) {
                return true;
            }
            else {
                return false;
            }
        }
    };
    JqTreeWidget.prototype._notifyLoading = function (is_loading, node, $el) {
        if (this.options.onLoading) {
            this.options.onLoading(is_loading, node, $el);
        }
    };
    JqTreeWidget.prototype._selectNode = function (node, must_toggle) {
        var _this = this;
        if (must_toggle === void 0) { must_toggle = false; }
        if (!this.select_node_handler) {
            return;
        }
        var canSelect = function () {
            if (_this.options.onCanSelectNode) {
                return _this.options.selectable && _this.options.onCanSelectNode(node);
            }
            else {
                return _this.options.selectable;
            }
        };
        var openParents = function () {
            var parent = node.parent;
            if (parent && parent.parent && !parent.is_open) {
                _this.openNode(parent, false);
            }
        };
        var saveState = function () {
            if (_this.options.saveState && _this.save_state_handler) {
                _this.save_state_handler.saveState();
            }
        };
        if (!node) {
            // Called with empty node -> deselect current node
            this._deselectCurrentNode();
            saveState();
            return;
        }
        if (!canSelect()) {
            return;
        }
        if (this.select_node_handler.isNodeSelected(node)) {
            if (must_toggle) {
                this._deselectCurrentNode();
                this._triggerEvent("tree.select", {
                    node: null,
                    previous_node: node
                });
            }
        }
        else {
            var deselected_node = this.getSelectedNode();
            this._deselectCurrentNode();
            this.addToSelection(node);
            this._triggerEvent("tree.select", {
                node: node,
                deselected_node: deselected_node
            });
            openParents();
        }
        saveState();
    };
    JqTreeWidget.prototype._loadData = function (data, parent_node) {
        if (!data) {
            return;
        }
        else {
            this._triggerEvent("tree.load_data", { tree_data: data });
            if (parent_node) {
                this._deselectNodes(parent_node);
                this._loadSubtree(data, parent_node);
            }
            else {
                this._initTree(data);
            }
            if (this.isDragging() && this.dnd_handler) {
                this.dnd_handler.refresh();
            }
        }
    };
    JqTreeWidget.prototype._deselectNodes = function (parent_node) {
        if (this.select_node_handler) {
            var selected_nodes_under_parent = this.select_node_handler.getSelectedNodesUnder(parent_node);
            for (var _i = 0, selected_nodes_under_parent_1 = selected_nodes_under_parent; _i < selected_nodes_under_parent_1.length; _i++) {
                var n = selected_nodes_under_parent_1[_i];
                this.select_node_handler.removeFromSelection(n);
            }
        }
    };
    JqTreeWidget.prototype._loadSubtree = function (data, parent_node) {
        parent_node.loadFromData(data);
        parent_node.load_on_demand = false;
        parent_node.is_loading = false;
        this._refreshElements(parent_node);
    };
    JqTreeWidget.prototype._loadDataFromUrl = function (url_info_param, parent_node, on_finished) {
        var _this = this;
        var $el = null;
        var url_info = url_info_param;
        var addLoadingClass = function () {
            $el = parent_node ? $(parent_node.element) : _this.element;
            $el.addClass("jqtree-loading");
            _this._notifyLoading(true, parent_node, $el);
        };
        var removeLoadingClass = function () {
            if ($el) {
                $el.removeClass("jqtree-loading");
                _this._notifyLoading(false, parent_node, $el);
            }
        };
        var parseUrlInfo = function () {
            if ($.type(url_info) === "string") {
                return { url: url_info };
            }
            if (!url_info.method) {
                url_info.method = "get";
            }
            return url_info;
        };
        var handeLoadData = function (data) {
            removeLoadingClass();
            _this._loadData(data, parent_node);
            if (on_finished && $.isFunction(on_finished)) {
                on_finished();
            }
        };
        var getDataFromResponse = function (response) { return ($.isArray(response) || typeof response === "object"
            ? response
            : response != null ? $.parseJSON(response) : []); };
        var filterData = function (data) { return (_this.options.dataFilter ? _this.options.dataFilter(data) : data); };
        var handleSuccess = function (response) {
            var data = filterData(getDataFromResponse(response));
            handeLoadData(data);
        };
        var handleError = function (response) {
            removeLoadingClass();
            if (_this.options.onLoadFailed) {
                _this.options.onLoadFailed(response);
            }
        };
        var loadDataFromUrlInfo = function () {
            var _url_info = parseUrlInfo();
            $.ajax($.extend({}, _url_info, {
                method: url_info.method != null ? url_info.method.toUpperCase() : "GET",
                cache: false,
                dataType: "json",
                success: handleSuccess,
                error: handleError
            }));
        };
        if (!url_info_param) {
            // Generate url for node
            url_info = this._getDataUrlInfo(parent_node);
        }
        addLoadingClass();
        if (!url_info) {
            removeLoadingClass();
            return;
        }
        else if ($.isArray(url_info)) {
            handeLoadData(url_info);
            return;
        }
        else {
            loadDataFromUrlInfo();
            return;
        }
    };
    JqTreeWidget.prototype._loadFolderOnDemand = function (node, slide, on_finished) {
        var _this = this;
        if (slide === void 0) { slide = true; }
        node.is_loading = true;
        this._loadDataFromUrl(null, node, function () {
            _this._openNode(node, slide, on_finished);
        });
    };
    return JqTreeWidget;
}(mouse_widget_1["default"]));
JqTreeWidget.defaults = {
    autoOpen: false,
    saveState: false,
    dragAndDrop: false,
    selectable: true,
    useContextMenu: true,
    onCanSelectNode: null,
    onSetStateFromStorage: null,
    onGetStateFromStorage: null,
    onCreateLi: null,
    onIsMoveHandle: null,
    // Can this node be moved?
    onCanMove: null,
    // Can this node be moved to this position? function(moved_node, target_node, position)
    onCanMoveTo: null,
    onLoadFailed: null,
    autoEscape: true,
    dataUrl: null,
    // The symbol to use for a closed node - ► BLACK RIGHT-POINTING POINTER
    // http://www.fileformat.info/info/unicode/char/25ba/index.htm
    closedIcon: null,
    // The symbol to use for an open node - ▼ BLACK DOWN-POINTING TRIANGLE
    // http://www.fileformat.info/info/unicode/char/25bc/index.htm
    openedIcon: "&#x25bc;",
    slide: true,
    nodeClass: node_1.Node,
    dataFilter: null,
    keyboardSupport: true,
    openFolderDelay: 500,
    rtl: false,
    onDragMove: null,
    onDragStop: null,
    buttonLeft: true,
    onLoading: null
};
simple_widget_1["default"].register(JqTreeWidget, "tree");


/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {



var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
exports.__esModule = true;
var node_1 = __webpack_require__(0);
var util_1 = __webpack_require__(1);
var DragAndDropHandler = (function () {
    function DragAndDropHandler(tree_widget) {
        this.tree_widget = tree_widget;
        this.hovered_area = null;
        this.$ghost = null;
        this.hit_areas = [];
        this.is_dragging = false;
        this.current_item = null;
    }
    DragAndDropHandler.prototype.mouseCapture = function (position_info) {
        var $element = $(position_info.target);
        if (!this.mustCaptureElement($element)) {
            return null;
        }
        if (this.tree_widget.options.onIsMoveHandle && !this.tree_widget.options.onIsMoveHandle($element)) {
            return null;
        }
        var node_element = this.tree_widget._getNodeElement($element);
        if (node_element && this.tree_widget.options.onCanMove) {
            if (!this.tree_widget.options.onCanMove(node_element.node)) {
                node_element = null;
            }
        }
        this.current_item = node_element;
        return (this.current_item != null);
    };
    DragAndDropHandler.prototype.generateHitAreas = function () {
        if (!this.current_item) {
            this.hit_areas = [];
        }
        else {
            var hit_areas_generator = new HitAreasGenerator(this.tree_widget.tree, this.current_item.node, this.getTreeDimensions().bottom);
            this.hit_areas = hit_areas_generator.generate();
        }
    };
    DragAndDropHandler.prototype.mouseStart = function (position_info) {
        if (!this.current_item) {
            return false;
        }
        else {
            this.refresh();
            var offset = $(position_info.target).offset();
            var node = this.current_item.node;
            var node_name = this.tree_widget.options.autoEscape ? util_1.html_escape(node.name) : node.name;
            this.drag_element = new DragElement(node_name, position_info.page_x - offset.left, position_info.page_y - offset.top, this.tree_widget.element);
            this.is_dragging = true;
            this.current_item.$element.addClass("jqtree-moving");
            return true;
        }
    };
    DragAndDropHandler.prototype.mouseDrag = function (position_info) {
        if (!this.current_item || !this.drag_element) {
            return false;
        }
        else {
            this.drag_element.move(position_info.page_x, position_info.page_y);
            var area = this.findHoveredArea(position_info.page_x, position_info.page_y);
            var can_move_to = this.canMoveToArea(area);
            if (can_move_to && area) {
                if (!area.node.isFolder()) {
                    this.stopOpenFolderTimer();
                }
                if (this.hovered_area !== area) {
                    this.hovered_area = area;
                    // If this is a closed folder, start timer to open it
                    if (this.mustOpenFolderTimer(area)) {
                        this.startOpenFolderTimer(area.node);
                    }
                    else {
                        this.stopOpenFolderTimer();
                    }
                    this.updateDropHint();
                }
            }
            else {
                this.removeHover();
                this.removeDropHint();
                this.stopOpenFolderTimer();
            }
            if (!area) {
                if (this.tree_widget.options.onDragMove) {
                    this.tree_widget.options.onDragMove(this.current_item.node, position_info.original_event);
                }
            }
            return true;
        }
    };
    DragAndDropHandler.prototype.mouseStop = function (position_info) {
        this.moveItem(position_info);
        this.clear();
        this.removeHover();
        this.removeDropHint();
        this.removeHitAreas();
        var current_item = this.current_item;
        if (this.current_item) {
            this.current_item.$element.removeClass("jqtree-moving");
            this.current_item = null;
        }
        this.is_dragging = false;
        if (!this.hovered_area && current_item) {
            if (this.tree_widget.options.onDragStop) {
                this.tree_widget.options.onDragStop(current_item.node, position_info.original_event);
            }
        }
        return false;
    };
    DragAndDropHandler.prototype.refresh = function () {
        this.removeHitAreas();
        if (this.current_item) {
            this.generateHitAreas();
            this.current_item = this.tree_widget._getNodeElementForNode(this.current_item.node);
            if (this.is_dragging) {
                this.current_item.$element.addClass("jqtree-moving");
            }
        }
    };
    DragAndDropHandler.prototype.mustCaptureElement = function ($element) {
        return !$element.is("input,select,textarea");
    };
    DragAndDropHandler.prototype.canMoveToArea = function (area) {
        if (!area || !this.current_item) {
            return false;
        }
        else if (this.tree_widget.options.onCanMoveTo) {
            var position_name = node_1.getPositionName(area.position);
            return this.tree_widget.options.onCanMoveTo(this.current_item.node, area.node, position_name);
        }
        else {
            return true;
        }
    };
    DragAndDropHandler.prototype.removeHitAreas = function () {
        this.hit_areas = [];
    };
    DragAndDropHandler.prototype.clear = function () {
        if (this.drag_element) {
            this.drag_element.remove();
            this.drag_element = null;
        }
    };
    DragAndDropHandler.prototype.removeDropHint = function () {
        if (this.previous_ghost) {
            this.previous_ghost.remove();
        }
    };
    DragAndDropHandler.prototype.removeHover = function () {
        this.hovered_area = null;
    };
    DragAndDropHandler.prototype.findHoveredArea = function (x, y) {
        var dimensions = this.getTreeDimensions();
        if (x < dimensions.left ||
            y < dimensions.top ||
            x > dimensions.right ||
            y > dimensions.bottom) {
            return null;
        }
        var low = 0;
        var high = this.hit_areas.length;
        while (low < high) {
            // tslint:disable-next-line: no-bitwise
            var mid = (low + high) >> 1;
            var area = this.hit_areas[mid];
            if (y < area.top) {
                high = mid;
            }
            else if (y > area.bottom) {
                low = mid + 1;
            }
            else {
                return area;
            }
        }
        return null;
    };
    DragAndDropHandler.prototype.mustOpenFolderTimer = function (area) {
        var node = area.node;
        return (node.isFolder() &&
            !node.is_open &&
            area.position === node_1.Position.Inside);
    };
    DragAndDropHandler.prototype.updateDropHint = function () {
        if (!this.hovered_area) {
            return;
        }
        // remove previous drop hint
        this.removeDropHint();
        // add new drop hint
        var node_element = this.tree_widget._getNodeElementForNode(this.hovered_area.node);
        this.previous_ghost = node_element.addDropHint(this.hovered_area.position);
    };
    DragAndDropHandler.prototype.startOpenFolderTimer = function (folder) {
        var _this = this;
        var openFolder = function () {
            _this.tree_widget._openNode(folder, _this.tree_widget.options.slide, function () {
                _this.refresh();
                _this.updateDropHint();
            });
        };
        this.stopOpenFolderTimer();
        this.open_folder_timer = setTimeout(openFolder, this.tree_widget.options.openFolderDelay);
    };
    DragAndDropHandler.prototype.stopOpenFolderTimer = function () {
        if (this.open_folder_timer) {
            clearTimeout(this.open_folder_timer);
            this.open_folder_timer = null;
        }
    };
    DragAndDropHandler.prototype.moveItem = function (position_info) {
        var _this = this;
        if (this.current_item &&
            this.hovered_area &&
            this.hovered_area.position !== node_1.Position.None &&
            this.canMoveToArea(this.hovered_area)) {
            var moved_node_1 = this.current_item.node;
            var target_node_1 = this.hovered_area.node;
            var position_1 = this.hovered_area.position;
            var previous_parent = moved_node_1.parent;
            if (position_1 === node_1.Position.Inside) {
                this.hovered_area.node.is_open = true;
            }
            var doMove = function () {
                _this.tree_widget.tree.moveNode(moved_node_1, target_node_1, position_1);
                _this.tree_widget.element.empty();
                _this.tree_widget._refreshElements(null);
            };
            var event_1 = this.tree_widget._triggerEvent("tree.move", {
                move_info: {
                    moved_node: moved_node_1,
                    target_node: target_node_1,
                    position: node_1.getPositionName(position_1),
                    previous_parent: previous_parent,
                    do_move: doMove,
                    original_event: position_info.original_event
                }
            });
            if (!event_1.isDefaultPrevented()) {
                doMove();
            }
        }
    };
    DragAndDropHandler.prototype.getTreeDimensions = function () {
        // Return the dimensions of the tree. Add a margin to the bottom to allow
        // for some to drag-and-drop the last element.
        var offset = this.tree_widget.element.offset();
        return {
            left: offset.left,
            top: offset.top,
            right: offset.left + this.tree_widget.element.width(),
            bottom: offset.top + this.tree_widget.element.height() + 16
        };
    };
    return DragAndDropHandler;
}());
exports.DragAndDropHandler = DragAndDropHandler;
var VisibleNodeIterator = (function () {
    function VisibleNodeIterator(tree) {
        this.tree = tree;
    }
    VisibleNodeIterator.prototype.iterate = function () {
        var _this = this;
        var is_first_node = true;
        var _iterateNode = function (node, next_node) {
            var must_iterate_inside = ((node.is_open || !node.element) && node.hasChildren());
            var $element = null;
            if (node.element) {
                $element = $(node.element);
                if (!$element.is(":visible")) {
                    return;
                }
                if (is_first_node) {
                    _this.handleFirstNode(node);
                    is_first_node = false;
                }
                if (!node.hasChildren()) {
                    _this.handleNode(node, next_node, $element);
                }
                else if (node.is_open) {
                    if (!_this.handleOpenFolder(node, $element)) {
                        must_iterate_inside = false;
                    }
                }
                else {
                    _this.handleClosedFolder(node, next_node, $element);
                }
            }
            if (must_iterate_inside) {
                var children_length_1 = node.children.length;
                node.children.forEach(function (_, i) {
                    if (i === (children_length_1 - 1)) {
                        _iterateNode(node.children[i], null);
                    }
                    else {
                        _iterateNode(node.children[i], node.children[i + 1]);
                    }
                });
                if (node.is_open && $element) {
                    _this.handleAfterOpenFolder(node, next_node);
                }
            }
        };
        _iterateNode(this.tree, null);
    };
    return VisibleNodeIterator;
}());
var HitAreasGenerator = (function (_super) {
    __extends(HitAreasGenerator, _super);
    function HitAreasGenerator(tree, current_node, tree_bottom) {
        var _this = _super.call(this, tree) || this;
        _this.current_node = current_node;
        _this.tree_bottom = tree_bottom;
        return _this;
    }
    HitAreasGenerator.prototype.generate = function () {
        this.positions = [];
        this.last_top = 0;
        this.iterate();
        return this.generateHitAreas(this.positions);
    };
    HitAreasGenerator.prototype.generateHitAreas = function (positions) {
        var previous_top = -1;
        var group = [];
        var hit_areas = [];
        for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
            var position = positions_1[_i];
            if (position.top !== previous_top && group.length) {
                if (group.length) {
                    this.generateHitAreasForGroup(hit_areas, group, previous_top, position.top);
                }
                previous_top = position.top;
                group = [];
            }
            group.push(position);
        }
        this.generateHitAreasForGroup(hit_areas, group, previous_top, this.tree_bottom);
        return hit_areas;
    };
    HitAreasGenerator.prototype.handleOpenFolder = function (node, $element) {
        if (node === this.current_node) {
            // Cannot move inside current item
            // Stop iterating
            return false;
        }
        // Cannot move before current item
        if (node.children[0] !== this.current_node) {
            this.addPosition(node, node_1.Position.Inside, this.getTop($element));
        }
        // Continue iterating
        return true;
    };
    HitAreasGenerator.prototype.handleClosedFolder = function (node, next_node, $element) {
        var top = this.getTop($element);
        if (node === this.current_node) {
            // Cannot move after current item
            this.addPosition(node, node_1.Position.None, top);
        }
        else {
            this.addPosition(node, node_1.Position.Inside, top);
            // Cannot move before current item
            if (next_node !== this.current_node) {
                this.addPosition(node, node_1.Position.After, top);
            }
        }
    };
    HitAreasGenerator.prototype.handleFirstNode = function (node) {
        if (node !== this.current_node) {
            this.addPosition(node, node_1.Position.Before, this.getTop($(node.element)));
        }
    };
    HitAreasGenerator.prototype.handleAfterOpenFolder = function (node, next_node) {
        if (node === this.current_node ||
            next_node === this.current_node) {
            // Cannot move before or after current item
            this.addPosition(node, node_1.Position.None, this.last_top);
        }
        else {
            this.addPosition(node, node_1.Position.After, this.last_top);
        }
    };
    HitAreasGenerator.prototype.handleNode = function (node, next_node, $element) {
        var top = this.getTop($element);
        if (node === this.current_node) {
            // Cannot move inside current item
            this.addPosition(node, node_1.Position.None, top);
        }
        else {
            this.addPosition(node, node_1.Position.Inside, top);
        }
        if (next_node === this.current_node ||
            node === this.current_node) {
            // Cannot move before or after current item
            this.addPosition(node, node_1.Position.None, top);
        }
        else {
            this.addPosition(node, node_1.Position.After, top);
        }
    };
    HitAreasGenerator.prototype.getTop = function ($element) {
        return $element.offset().top;
    };
    HitAreasGenerator.prototype.addPosition = function (node, position, top) {
        var area = {
            top: top,
            bottom: 0,
            node: node,
            position: position
        };
        this.positions.push(area);
        this.last_top = top;
    };
    HitAreasGenerator.prototype.generateHitAreasForGroup = function (hit_areas, positions_in_group, top, bottom) {
        // limit positions in group
        var position_count = Math.min(positions_in_group.length, 4);
        var area_height = Math.round((bottom - top) / position_count);
        var area_top = top;
        var i = 0;
        while (i < position_count) {
            var position = positions_in_group[i];
            hit_areas.push({
                top: area_top,
                bottom: area_top + area_height,
                node: position.node,
                position: position.position
            });
            area_top += area_height;
            i += 1;
        }
    };
    return HitAreasGenerator;
}(VisibleNodeIterator));
exports.HitAreasGenerator = HitAreasGenerator;
var DragElement = (function () {
    function DragElement(node_name, offset_x, offset_y, $tree) {
        this.offset_x = offset_x;
        this.offset_y = offset_y;
        this.$element = $("<span class=\"jqtree-title jqtree-dragging\">" + node_name + "</span>");
        this.$element.css("position", "absolute");
        $tree.append(this.$element);
    }
    DragElement.prototype.move = function (page_x, page_y) {
        this.$element.offset({
            left: page_x - this.offset_x,
            top: page_y - this.offset_y
        });
    };
    DragElement.prototype.remove = function () {
        this.$element.remove();
    };
    return DragElement;
}());
exports.DragElement = DragElement;


/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var util_1 = __webpack_require__(1);
var ElementsRenderer = (function () {
    function ElementsRenderer(tree_widget) {
        this.tree_widget = tree_widget;
        this.opened_icon_element = this.createButtonElement(tree_widget.options.openedIcon);
        this.closed_icon_element = this.createButtonElement(tree_widget.options.closedIcon);
    }
    ElementsRenderer.prototype.render = function (from_node) {
        if (from_node && from_node.parent) {
            this.renderFromNode(from_node);
        }
        else {
            this.renderFromRoot();
        }
    };
    ElementsRenderer.prototype.renderFromRoot = function () {
        var $element = this.tree_widget.element;
        $element.empty();
        this.createDomElements($element[0], this.tree_widget.tree.children, true, 1);
    };
    ElementsRenderer.prototype.renderFromNode = function (node) {
        // remember current li
        var $previous_li = $(node.element);
        // create element
        var li = this.createLi(node, node.getLevel());
        this.attachNodeData(node, li);
        // add element to dom
        $previous_li.after(li);
        // remove previous li
        $previous_li.remove();
        // create children
        if (node.children) {
            this.createDomElements(li, node.children, false, node.getLevel() + 1);
        }
    };
    ElementsRenderer.prototype.createDomElements = function (element, children, is_root_node, level) {
        var ul = this.createUl(is_root_node);
        element.appendChild(ul);
        for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
            var child = children_1[_i];
            var li = this.createLi(child, level);
            ul.appendChild(li);
            this.attachNodeData(child, li);
            if (child.hasChildren()) {
                this.createDomElements(li, child.children, false, level + 1);
            }
        }
    };
    ElementsRenderer.prototype.attachNodeData = function (node, li) {
        node.element = li;
        $(li).data("node", node);
    };
    ElementsRenderer.prototype.createUl = function (is_root_node) {
        var class_string;
        var role;
        if (!is_root_node) {
            class_string = "";
            role = "group";
        }
        else {
            class_string = "jqtree-tree";
            role = "tree";
            if (this.tree_widget.options.rtl) {
                class_string += " jqtree-rtl";
            }
        }
        var ul = document.createElement("ul");
        ul.className = "jqtree_common " + class_string;
        ul.setAttribute("role", role);
        return ul;
    };
    ElementsRenderer.prototype.createLi = function (node, level) {
        var is_selected = Boolean(this.tree_widget.select_node_handler &&
            this.tree_widget.select_node_handler.isNodeSelected(node));
        var li = node.isFolder()
            ? this.createFolderLi(node, level, is_selected)
            : this.createNodeLi(node, level, is_selected);
        if (this.tree_widget.options.onCreateLi) {
            this.tree_widget.options.onCreateLi(node, $(li), is_selected);
        }
        return li;
    };
    ElementsRenderer.prototype.createFolderLi = function (node, level, is_selected) {
        var button_classes = this.getButtonClasses(node);
        var folder_classes = this.getFolderClasses(node, is_selected);
        var icon_element = node.is_open ? this.opened_icon_element : this.closed_icon_element;
        // li
        var li = document.createElement("li");
        li.className = "jqtree_common " + folder_classes;
        li.setAttribute("role", "presentation");
        // div
        var div = document.createElement("div");
        div.className = "jqtree-element jqtree_common";
        div.setAttribute("role", "presentation");
        li.appendChild(div);
        // button link
        var button_link = document.createElement("a");
        button_link.className = button_classes;
        button_link.appendChild(icon_element.cloneNode(false));
        button_link.setAttribute("role", "presentation");
        button_link.setAttribute("aria-hidden", "true");
        if (this.tree_widget.options.buttonLeft) {
            div.appendChild(button_link);
        }
        // title span
        div.appendChild(this.createTitleSpan(node.name, level, is_selected, node.is_open, true));
        if (!this.tree_widget.options.buttonLeft) {
            div.appendChild(button_link);
        }
        return li;
    };
    ElementsRenderer.prototype.createNodeLi = function (node, level, is_selected) {
        var li_classes = ["jqtree_common"];
        if (is_selected) {
            li_classes.push("jqtree-selected");
        }
        var class_string = li_classes.join(" ");
        // li
        var li = document.createElement("li");
        li.className = class_string;
        li.setAttribute("role", "presentation");
        // div
        var div = document.createElement("div");
        div.className = "jqtree-element jqtree_common";
        div.setAttribute("role", "presentation");
        li.appendChild(div);
        // title span
        div.appendChild(this.createTitleSpan(node.name, level, is_selected, node.is_open, false));
        return li;
    };
    ElementsRenderer.prototype.createTitleSpan = function (node_name, level, is_selected, is_open, is_folder) {
        var title_span = document.createElement("span");
        var classes = "jqtree-title jqtree_common";
        if (is_folder) {
            classes += " jqtree-title-folder";
        }
        title_span.className = classes;
        title_span.setAttribute("role", "treeitem");
        title_span.setAttribute("aria-level", "" + level);
        title_span.setAttribute("aria-selected", util_1.getBoolString(is_selected));
        title_span.setAttribute("aria-expanded", util_1.getBoolString(is_open));
        if (is_selected) {
            title_span.setAttribute("tabindex", "0");
        }
        title_span.innerHTML = this.escapeIfNecessary(node_name);
        return title_span;
    };
    ElementsRenderer.prototype.getButtonClasses = function (node) {
        var classes = ["jqtree-toggler", "jqtree_common"];
        if (!node.is_open) {
            classes.push("jqtree-closed");
        }
        if (this.tree_widget.options.buttonLeft) {
            classes.push("jqtree-toggler-left");
        }
        else {
            classes.push("jqtree-toggler-right");
        }
        return classes.join(" ");
    };
    ElementsRenderer.prototype.getFolderClasses = function (node, is_selected) {
        var classes = ["jqtree-folder"];
        if (!node.is_open) {
            classes.push("jqtree-closed");
        }
        if (is_selected) {
            classes.push("jqtree-selected");
        }
        if (node.is_loading) {
            classes.push("jqtree-loading");
        }
        return classes.join(" ");
    };
    ElementsRenderer.prototype.escapeIfNecessary = function (value) {
        if (this.tree_widget.options.autoEscape) {
            return util_1.html_escape(value);
        }
        else {
            return value;
        }
    };
    ElementsRenderer.prototype.createButtonElement = function (value) {
        if (typeof value === "string") {
            // convert value to html
            var div = document.createElement("div");
            div.innerHTML = value;
            return document.createTextNode(div.innerHTML);
        }
        else {
            return $(value)[0];
        }
    };
    return ElementsRenderer;
}());
exports["default"] = ElementsRenderer;


/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var KeyHandler = (function () {
    function KeyHandler(tree_widget) {
        this.tree_widget = tree_widget;
        if (tree_widget.options.keyboardSupport) {
            $(document).on("keydown.jqtree", $.proxy(this.handleKeyDown, this));
        }
    }
    KeyHandler.prototype.deinit = function () {
        $(document).off("keydown.jqtree");
    };
    KeyHandler.prototype.moveDown = function () {
        var node = this.tree_widget.getSelectedNode();
        if (node) {
            return this.selectNode(node.getNextNode());
        }
        else {
            return false;
        }
    };
    KeyHandler.prototype.moveUp = function () {
        var node = this.tree_widget.getSelectedNode();
        if (node) {
            return this.selectNode(node.getPreviousNode());
        }
        else {
            return false;
        }
    };
    KeyHandler.prototype.moveRight = function () {
        var node = this.tree_widget.getSelectedNode();
        if (!node) {
            return true;
        }
        else if (!node.isFolder()) {
            return true;
        }
        else {
            // folder node
            if (node.is_open) {
                // Right moves to the first child of an open node
                return this.selectNode(node.getNextNode());
            }
            else {
                // Right expands a closed node
                this.tree_widget.openNode(node);
                return false;
            }
        }
    };
    KeyHandler.prototype.moveLeft = function () {
        var node = this.tree_widget.getSelectedNode();
        if (!node) {
            return true;
        }
        else if (node.isFolder() && node.is_open) {
            // Left on an open node closes the node
            this.tree_widget.closeNode(node);
            return false;
        }
        else {
            // Left on a closed or end node moves focus to the node's parent
            return this.selectNode(node.getParent());
        }
    };
    KeyHandler.prototype.handleKeyDown = function (e) {
        if (!this.canHandleKeyboard()) {
            return true;
        }
        else {
            var key = e.which;
            switch (key) {
                case KeyHandler.DOWN:
                    return this.moveDown();
                case KeyHandler.UP:
                    return this.moveUp();
                case KeyHandler.RIGHT:
                    return this.moveRight();
                case KeyHandler.LEFT:
                    return this.moveLeft();
                default:
                    return true;
            }
        }
    };
    KeyHandler.prototype.selectNode = function (node) {
        if (!node) {
            return true;
        }
        else {
            this.tree_widget.selectNode(node);
            if (this.tree_widget.scroll_handler &&
                (!this.tree_widget.scroll_handler.isScrolledIntoView($(node.element).find(".jqtree-element")))) {
                this.tree_widget.scrollToNode(node);
            }
            return false;
        }
    };
    KeyHandler.prototype.canHandleKeyboard = function () {
        return (this.tree_widget.options.keyboardSupport &&
            this.isFocusOnTree() &&
            this.tree_widget.getSelectedNode() != null);
    };
    KeyHandler.prototype.isFocusOnTree = function () {
        var active_element = document.activeElement;
        return (active_element &&
            active_element.tagName === "SPAN" &&
            this.tree_widget._containsElement(active_element));
    };
    return KeyHandler;
}());
KeyHandler.LEFT = 37;
KeyHandler.UP = 38;
KeyHandler.RIGHT = 39;
KeyHandler.DOWN = 40;
exports["default"] = KeyHandler;


/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {



var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
exports.__esModule = true;
/*
This widget does the same a the mouse widget in jqueryui.
*/
var simple_widget_1 = __webpack_require__(2);
var MouseWidget = (function (_super) {
    __extends(MouseWidget, _super);
    function MouseWidget() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MouseWidget.prototype.setMouseDelay = function (mouse_delay) {
        this.mouse_delay = mouse_delay;
    };
    MouseWidget.prototype._init = function () {
        this.$el.on("mousedown.mousewidget", $.proxy(this._mouseDown, this));
        this.$el.on("touchstart.mousewidget", $.proxy(this._touchStart, this));
        this.is_mouse_started = false;
        this.mouse_delay = 0;
        this._mouse_delay_timer = null;
        this._is_mouse_delay_met = true;
        this.mouse_down_info = null;
    };
    MouseWidget.prototype._deinit = function () {
        this.$el.off("mousedown.mousewidget");
        this.$el.off("touchstart.mousewidget");
        var $document = $(document);
        $document.off("mousemove.mousewidget");
        $document.off("mouseup.mousewidget");
    };
    MouseWidget.prototype._mouseDown = function (e) {
        // Is left mouse button?
        if (e.which !== 1) {
            return;
        }
        var result = this._handleMouseDown(this._getPositionInfo(e));
        if (result) {
            e.preventDefault();
        }
        return result;
    };
    MouseWidget.prototype._handleMouseDown = function (position_info) {
        // We may have missed mouseup (out of window)
        if (this.is_mouse_started) {
            this._handleMouseUp(position_info);
        }
        this.mouse_down_info = position_info;
        if (!this._mouseCapture(position_info)) {
            return;
        }
        this._handleStartMouse();
        return true;
    };
    MouseWidget.prototype._handleStartMouse = function () {
        var $document = $(document);
        $document.on("mousemove.mousewidget", $.proxy(this._mouseMove, this));
        $document.on("touchmove.mousewidget", $.proxy(this._touchMove, this));
        $document.on("mouseup.mousewidget", $.proxy(this._mouseUp, this));
        $document.on("touchend.mousewidget", $.proxy(this._touchEnd, this));
        if (this.mouse_delay) {
            this._startMouseDelayTimer();
        }
    };
    MouseWidget.prototype._startMouseDelayTimer = function () {
        var _this = this;
        if (this._mouse_delay_timer) {
            clearTimeout(this._mouse_delay_timer);
        }
        this._mouse_delay_timer = setTimeout(function () {
            _this._is_mouse_delay_met = true;
        }, this.mouse_delay);
        this._is_mouse_delay_met = false;
    };
    MouseWidget.prototype._mouseMove = function (e) {
        return this._handleMouseMove(e, this._getPositionInfo(e));
    };
    MouseWidget.prototype._handleMouseMove = function (e, position_info) {
        if (this.is_mouse_started) {
            this._mouseDrag(position_info);
            return e.preventDefault();
        }
        if (this.mouse_delay && !this._is_mouse_delay_met) {
            return true;
        }
        if (this.mouse_down_info) {
            this.is_mouse_started = this._mouseStart(this.mouse_down_info) !== false;
        }
        if (this.is_mouse_started) {
            this._mouseDrag(position_info);
        }
        else {
            this._handleMouseUp(position_info);
        }
        return !this.is_mouse_started;
    };
    MouseWidget.prototype._getPositionInfo = function (e) {
        return {
            page_x: e.pageX,
            page_y: e.pageY,
            target: e.target,
            original_event: e
        };
    };
    MouseWidget.prototype._mouseUp = function (e) {
        return this._handleMouseUp(this._getPositionInfo(e));
    };
    MouseWidget.prototype._handleMouseUp = function (position_info) {
        var $document = $(document);
        $document.off("mousemove.mousewidget");
        $document.off("touchmove.mousewidget");
        $document.off("mouseup.mousewidget");
        $document.off("touchend.mousewidget");
        if (this.is_mouse_started) {
            this.is_mouse_started = false;
            this._mouseStop(position_info);
        }
    };
    MouseWidget.prototype._touchStart = function (e) {
        var touch_event = e.originalEvent;
        if (touch_event.touches.length > 1) {
            return;
        }
        var touch = touch_event.changedTouches[0];
        return this._handleMouseDown(this._getPositionInfo(touch));
    };
    MouseWidget.prototype._touchMove = function (e) {
        var touch_event = e.originalEvent;
        if (touch_event.touches.length > 1) {
            return;
        }
        var touch = touch_event.changedTouches[0];
        return this._handleMouseMove(e, this._getPositionInfo(touch));
    };
    MouseWidget.prototype._touchEnd = function (e) {
        var touch_event = e.originalEvent;
        if (touch_event.touches.length > 1) {
            return;
        }
        var touch = touch_event.changedTouches[0];
        return this._handleMouseUp(this._getPositionInfo(touch));
    };
    return MouseWidget;
}(simple_widget_1["default"]));
exports["default"] = MouseWidget;


/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {



var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
exports.__esModule = true;
var node_1 = __webpack_require__(0);
var NodeElement = (function () {
    function NodeElement(node, tree_widget) {
        this.init(node, tree_widget);
    }
    NodeElement.prototype.init = function (node, tree_widget) {
        this.node = node;
        this.tree_widget = tree_widget;
        if (!node.element) {
            node.element = this.tree_widget.element.get(0);
        }
        this.$element = $(node.element);
    };
    NodeElement.prototype.addDropHint = function (position) {
        if (position === node_1.Position.Inside) {
            return new BorderDropHint(this.$element);
        }
        else {
            return new GhostDropHint(this.node, this.$element, position);
        }
    };
    NodeElement.prototype.select = function () {
        var $li = this.getLi();
        $li.addClass("jqtree-selected");
        $li.attr("aria-selected", "true");
        var $span = this.getSpan();
        $span.attr("tabindex", 0);
        $span.focus();
    };
    NodeElement.prototype.deselect = function () {
        var $li = this.getLi();
        $li.removeClass("jqtree-selected");
        $li.attr("aria-selected", "false");
        var $span = this.getSpan();
        $span.attr("tabindex", -1);
        $span.blur();
    };
    NodeElement.prototype.getUl = function () {
        return this.$element.children("ul:first");
    };
    NodeElement.prototype.getSpan = function () {
        return this.$element.children(".jqtree-element").find("span.jqtree-title");
    };
    NodeElement.prototype.getLi = function () {
        return this.$element;
    };
    return NodeElement;
}());
exports.NodeElement = NodeElement;
var FolderElement = (function (_super) {
    __extends(FolderElement, _super);
    function FolderElement() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FolderElement.prototype.open = function (on_finished, slide) {
        var _this = this;
        if (slide === void 0) { slide = true; }
        if (!this.node.is_open) {
            this.node.is_open = true;
            var $button = this.getButton();
            $button.removeClass("jqtree-closed");
            $button.html("");
            var button_el = $button.get(0);
            if (button_el) {
                var icon = this.tree_widget.renderer.opened_icon_element.cloneNode(false);
                button_el.appendChild(icon);
            }
            var doOpen = function () {
                var $li = _this.getLi();
                $li.removeClass("jqtree-closed");
                var $span = _this.getSpan();
                $span.attr("aria-expanded", "true");
                if (on_finished) {
                    on_finished(_this.node);
                }
                _this.tree_widget._triggerEvent("tree.open", { node: _this.node });
            };
            if (slide) {
                this.getUl().slideDown("fast", doOpen);
            }
            else {
                this.getUl().show();
                doOpen();
            }
        }
    };
    FolderElement.prototype.close = function (slide) {
        var _this = this;
        if (slide === void 0) { slide = true; }
        if (this.node.is_open) {
            this.node.is_open = false;
            var $button = this.getButton();
            $button.addClass("jqtree-closed");
            $button.html("");
            var button_el = $button.get(0);
            if (button_el) {
                var icon = this.tree_widget.renderer.closed_icon_element.cloneNode(false);
                button_el.appendChild(icon);
            }
            var doClose = function () {
                var $li = _this.getLi();
                $li.addClass("jqtree-closed");
                var $span = _this.getSpan();
                $span.attr("aria-expanded", "false");
                _this.tree_widget._triggerEvent("tree.close", { node: _this.node });
            };
            if (slide) {
                this.getUl().slideUp("fast", doClose);
            }
            else {
                this.getUl().hide();
                doClose();
            }
        }
    };
    FolderElement.prototype.addDropHint = function (position) {
        if (!this.node.is_open && position === node_1.Position.Inside) {
            return new BorderDropHint(this.$element);
        }
        else {
            return new GhostDropHint(this.node, this.$element, position);
        }
    };
    FolderElement.prototype.getButton = function () {
        return this.$element.children(".jqtree-element").find("a.jqtree-toggler");
    };
    return FolderElement;
}(NodeElement));
exports.FolderElement = FolderElement;
var BorderDropHint = (function () {
    function BorderDropHint($element) {
        var $div = $element.children(".jqtree-element");
        var width = $element.width() - 4;
        this.$hint = $('<span class="jqtree-border"></span>');
        $div.append(this.$hint);
        this.$hint.css({
            width: width,
            height: $div.outerHeight() - 4
        });
    }
    BorderDropHint.prototype.remove = function () {
        this.$hint.remove();
    };
    return BorderDropHint;
}());
exports.BorderDropHint = BorderDropHint;
var GhostDropHint = (function () {
    function GhostDropHint(node, $element, position) {
        this.$element = $element;
        this.node = node;
        this.$ghost = $("<li class=\"jqtree_common jqtree-ghost\"><span class=\"jqtree_common jqtree-circle\"></span>\n            <span class=\"jqtree_common jqtree-line\"></span></li>");
        if (position === node_1.Position.After) {
            this.moveAfter();
        }
        else if (position === node_1.Position.Before) {
            this.moveBefore();
        }
        else if (position === node_1.Position.Inside) {
            if (node.isFolder() && node.is_open) {
                this.moveInsideOpenFolder();
            }
            else {
                this.moveInside();
            }
        }
    }
    GhostDropHint.prototype.remove = function () {
        this.$ghost.remove();
    };
    GhostDropHint.prototype.moveAfter = function () {
        this.$element.after(this.$ghost);
    };
    GhostDropHint.prototype.moveBefore = function () {
        this.$element.before(this.$ghost);
    };
    GhostDropHint.prototype.moveInsideOpenFolder = function () {
        $(this.node.children[0].element).before(this.$ghost);
    };
    GhostDropHint.prototype.moveInside = function () {
        this.$element.after(this.$ghost);
        this.$ghost.addClass("jqtree-inside");
    };
    return GhostDropHint;
}());
exports.GhostDropHint = GhostDropHint;


/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var util_1 = __webpack_require__(1);
var SaveStateHandler = (function () {
    function SaveStateHandler(tree_widget) {
        this.tree_widget = tree_widget;
    }
    SaveStateHandler.prototype.saveState = function () {
        var state = JSON.stringify(this.getState());
        if (this.tree_widget.options.onSetStateFromStorage) {
            this.tree_widget.options.onSetStateFromStorage(state);
        }
        else if (this.supportsLocalStorage()) {
            localStorage.setItem(this.getKeyName(), state);
        }
    };
    SaveStateHandler.prototype.getStateFromStorage = function () {
        var json_data = this._loadFromStorage();
        if (json_data) {
            return this._parseState(json_data);
        }
        else {
            return null;
        }
    };
    SaveStateHandler.prototype.getState = function () {
        var _this = this;
        var getOpenNodeIds = function () {
            var open_nodes = [];
            _this.tree_widget.tree.iterate(function (node) {
                if (node.is_open &&
                    node.id &&
                    node.hasChildren()) {
                    open_nodes.push(node.id);
                }
                return true;
            });
            return open_nodes;
        };
        var getSelectedNodeIds = function () { return _this.tree_widget.getSelectedNodes().map(function (n) { return n.id; }); };
        return {
            open_nodes: getOpenNodeIds(),
            selected_node: getSelectedNodeIds()
        };
    };
    /*
    Set initial state
    Don't handle nodes that are loaded on demand

    result: must load on demand
    */
    SaveStateHandler.prototype.setInitialState = function (state) {
        if (!state) {
            return false;
        }
        else {
            var must_load_on_demand = false;
            if (state.open_nodes) {
                must_load_on_demand = this._openInitialNodes(state.open_nodes);
            }
            if (state.selected_node) {
                this._resetSelection();
                this._selectInitialNodes(state.selected_node);
            }
            return must_load_on_demand;
        }
    };
    SaveStateHandler.prototype.setInitialStateOnDemand = function (state, cb_finished) {
        if (state) {
            this._setInitialStateOnDemand(state.open_nodes, state.selected_node, cb_finished);
        }
        else {
            cb_finished();
        }
    };
    SaveStateHandler.prototype.getNodeIdToBeSelected = function () {
        var state = this.getStateFromStorage();
        if (state && state.selected_node) {
            return state.selected_node[0];
        }
        else {
            return null;
        }
    };
    SaveStateHandler.prototype._parseState = function (json_data) {
        var state = $.parseJSON(json_data);
        // Check if selected_node is an int (instead of an array)
        if (state && state.selected_node && util_1.isInt(state.selected_node)) {
            // Convert to array
            state.selected_node = [state.selected_node];
        }
        return state;
    };
    SaveStateHandler.prototype._loadFromStorage = function () {
        if (this.tree_widget.options.onGetStateFromStorage) {
            return this.tree_widget.options.onGetStateFromStorage();
        }
        else if (this.supportsLocalStorage()) {
            return localStorage.getItem(this.getKeyName());
        }
    };
    SaveStateHandler.prototype._openInitialNodes = function (node_ids) {
        var must_load_on_demand = false;
        for (var _i = 0, node_ids_1 = node_ids; _i < node_ids_1.length; _i++) {
            var node_id = node_ids_1[_i];
            var node = this.tree_widget.getNodeById(node_id);
            if (node) {
                if (!node.load_on_demand) {
                    node.is_open = true;
                }
                else {
                    must_load_on_demand = true;
                }
            }
        }
        return must_load_on_demand;
    };
    SaveStateHandler.prototype._selectInitialNodes = function (node_ids) {
        var select_count = 0;
        for (var _i = 0, node_ids_2 = node_ids; _i < node_ids_2.length; _i++) {
            var node_id = node_ids_2[_i];
            var node = this.tree_widget.getNodeById(node_id);
            if (node) {
                select_count += 1;
                if (this.tree_widget.select_node_handler) {
                    this.tree_widget.select_node_handler.addToSelection(node);
                }
            }
        }
        return select_count !== 0;
    };
    SaveStateHandler.prototype._resetSelection = function () {
        var select_node_handler = this.tree_widget.select_node_handler;
        if (select_node_handler) {
            var selected_nodes = select_node_handler.getSelectedNodes();
            selected_nodes.forEach(function (node) {
                select_node_handler.removeFromSelection(node);
            });
        }
    };
    SaveStateHandler.prototype._setInitialStateOnDemand = function (node_ids_param, selected_nodes, cb_finished) {
        var _this = this;
        var loading_count = 0;
        var node_ids = node_ids_param;
        var openNodes = function () {
            var new_nodes_ids = [];
            for (var _i = 0, node_ids_3 = node_ids; _i < node_ids_3.length; _i++) {
                var node_id = node_ids_3[_i];
                var node = _this.tree_widget.getNodeById(node_id);
                if (!node) {
                    new_nodes_ids.push(node_id);
                }
                else {
                    if (!node.is_loading) {
                        if (node.load_on_demand) {
                            loadAndOpenNode(node);
                        }
                        else {
                            _this.tree_widget._openNode(node, false, null);
                        }
                    }
                }
            }
            node_ids = new_nodes_ids;
            if (_this._selectInitialNodes(selected_nodes)) {
                _this.tree_widget._refreshElements(null);
            }
            if (loading_count === 0) {
                cb_finished();
            }
        };
        var loadAndOpenNode = function (node) {
            loading_count += 1;
            _this.tree_widget._openNode(node, false, function () {
                loading_count -= 1;
                openNodes();
            });
        };
        openNodes();
    };
    SaveStateHandler.prototype.getKeyName = function () {
        if (typeof this.tree_widget.options.saveState === "string") {
            return this.tree_widget.options.saveState;
        }
        else {
            return "tree";
        }
    };
    SaveStateHandler.prototype.supportsLocalStorage = function () {
        var testSupport = function () {
            // Is local storage supported?
            if (localStorage == null) {
                return false;
            }
            else {
                // Check if it's possible to store an item. Safari does not allow this in private browsing mode.
                try {
                    var key = "_storage_test";
                    sessionStorage.setItem(key, "value");
                    sessionStorage.removeItem(key);
                }
                catch (error) {
                    return false;
                }
                return true;
            }
        };
        if (this._supportsLocalStorage == null) {
            this._supportsLocalStorage = testSupport();
        }
        return this._supportsLocalStorage;
    };
    return SaveStateHandler;
}());
exports["default"] = SaveStateHandler;


/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var ScrollHandler = (function () {
    function ScrollHandler(tree_widget) {
        this.tree_widget = tree_widget;
        this.previous_top = -1;
        this.is_initialized = false;
    }
    ScrollHandler.prototype.checkScrolling = function () {
        this._ensureInit();
        if (this.tree_widget.dnd_handler) {
            var hovered_area = this.tree_widget.dnd_handler.hovered_area;
            if (hovered_area && hovered_area.top !== this.previous_top) {
                this.previous_top = hovered_area.top;
                if (this.$scroll_parent) {
                    this._handleScrollingWithScrollParent(hovered_area);
                }
                else {
                    this._handleScrollingWithDocument(hovered_area);
                }
            }
        }
    };
    ScrollHandler.prototype.scrollTo = function (top) {
        this._ensureInit();
        if (this.$scroll_parent) {
            this.$scroll_parent[0].scrollTop = top;
        }
        else {
            var tree_top = this.tree_widget.$el.offset().top;
            $(document).scrollTop(top + tree_top);
        }
    };
    ScrollHandler.prototype.isScrolledIntoView = function ($element) {
        this._ensureInit();
        var element_bottom;
        var view_bottom;
        var element_top;
        var view_top;
        if (this.$scroll_parent) {
            view_top = 0;
            view_bottom = this.$scroll_parent.height();
            element_top = $element.offset().top - this.scroll_parent_top;
            element_bottom = element_top + $element.height();
        }
        else {
            view_top = $(window).scrollTop();
            view_bottom = view_top + $(window).height();
            element_top = $element.offset().top;
            element_bottom = element_top + $element.height();
        }
        return ((element_bottom <= view_bottom) && (element_top >= view_top));
    };
    ScrollHandler.prototype._initScrollParent = function () {
        var _this = this;
        var getParentWithOverflow = function () {
            var css_attributes = ["overflow", "overflow-y"];
            var hasOverFlow = function ($el) {
                for (var _i = 0, css_attributes_1 = css_attributes; _i < css_attributes_1.length; _i++) {
                    var attr = css_attributes_1[_i];
                    var overflow_value = $el.css(attr);
                    if (overflow_value === "auto" || overflow_value === "scroll") {
                        return true;
                    }
                }
                return false;
            };
            if (hasOverFlow(_this.tree_widget.$el)) {
                return _this.tree_widget.$el;
            }
            for (var _i = 0, _a = _this.tree_widget.$el.parents().get(); _i < _a.length; _i++) {
                var el = _a[_i];
                var $el = $(el);
                if (hasOverFlow($el)) {
                    return $el;
                }
            }
            return null;
        };
        var setDocumentAsScrollParent = function () {
            _this.scroll_parent_top = 0;
            _this.$scroll_parent = null;
        };
        if (this.tree_widget.$el.css("position") === "fixed") {
            setDocumentAsScrollParent();
        }
        var $scroll_parent = getParentWithOverflow();
        if ($scroll_parent && $scroll_parent.length && $scroll_parent[0].tagName !== "HTML") {
            this.$scroll_parent = $scroll_parent;
            this.scroll_parent_top = this.$scroll_parent.offset().top;
        }
        else {
            setDocumentAsScrollParent();
        }
        this.is_initialized = true;
    };
    ScrollHandler.prototype._ensureInit = function () {
        if (!this.is_initialized) {
            this._initScrollParent();
        }
    };
    ScrollHandler.prototype._handleScrollingWithScrollParent = function (area) {
        if (!this.$scroll_parent) {
            return;
        }
        else {
            var distance_bottom = this.scroll_parent_top + this.$scroll_parent[0].offsetHeight - area.bottom;
            if (distance_bottom < 20) {
                this.$scroll_parent[0].scrollTop += 20;
                this.tree_widget.refreshHitAreas();
                this.previous_top = -1;
            }
            else if ((area.top - this.scroll_parent_top) < 20) {
                this.$scroll_parent[0].scrollTop -= 20;
                this.tree_widget.refreshHitAreas();
                this.previous_top = -1;
            }
        }
    };
    ScrollHandler.prototype._handleScrollingWithDocument = function (area) {
        var distance_top = area.top - $(document).scrollTop();
        if (distance_top < 20) {
            $(document).scrollTop($(document).scrollTop() - 20);
        }
        else if ($(window).height() - (area.bottom - $(document).scrollTop()) < 20) {
            $(document).scrollTop($(document).scrollTop() + 20);
        }
    };
    return ScrollHandler;
}());
exports["default"] = ScrollHandler;


/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var SelectNodeHandler = (function () {
    function SelectNodeHandler(tree_widget) {
        this.tree_widget = tree_widget;
        this.clear();
    }
    SelectNodeHandler.prototype.getSelectedNode = function () {
        var selected_nodes = this.getSelectedNodes();
        if (selected_nodes.length) {
            return selected_nodes[0];
        }
        else {
            return false;
        }
    };
    SelectNodeHandler.prototype.getSelectedNodes = function () {
        if (this.selected_single_node) {
            return [this.selected_single_node];
        }
        else {
            var selected_nodes = [];
            for (var id in this.selected_nodes) {
                if (this.selected_nodes.hasOwnProperty(id)) {
                    var node = this.tree_widget.getNodeById(id);
                    if (node) {
                        selected_nodes.push(node);
                    }
                }
            }
            return selected_nodes;
        }
    };
    SelectNodeHandler.prototype.getSelectedNodesUnder = function (parent) {
        if (this.selected_single_node) {
            if (parent.isParentOf(this.selected_single_node)) {
                return [this.selected_single_node];
            }
            else {
                return [];
            }
        }
        else {
            var selected_nodes = [];
            for (var id in this.selected_nodes) {
                if (this.selected_nodes.hasOwnProperty(id)) {
                    var node = this.tree_widget.getNodeById(id);
                    if (node && parent.isParentOf(node)) {
                        selected_nodes.push(node);
                    }
                }
            }
            return selected_nodes;
        }
    };
    SelectNodeHandler.prototype.isNodeSelected = function (node) {
        if (!node) {
            return false;
        }
        else if (node.id != null) {
            if (this.selected_nodes[node.id]) {
                return true;
            }
            else {
                return false;
            }
        }
        else if (this.selected_single_node) {
            return this.selected_single_node.element === node.element;
        }
        else {
            return false;
        }
    };
    SelectNodeHandler.prototype.clear = function () {
        this.selected_nodes = {};
        this.selected_single_node = null;
    };
    SelectNodeHandler.prototype.removeFromSelection = function (node, include_children) {
        var _this = this;
        if (include_children === void 0) { include_children = false; }
        if (node.id == null) {
            if (this.selected_single_node && node.element === this.selected_single_node.element) {
                this.selected_single_node = null;
            }
        }
        else {
            delete this.selected_nodes[node.id];
            if (include_children) {
                node.iterate(function () {
                    delete _this.selected_nodes[node.id];
                    return true;
                });
            }
        }
    };
    SelectNodeHandler.prototype.addToSelection = function (node) {
        if (node.id != null) {
            this.selected_nodes[node.id] = true;
        }
        else {
            this.selected_single_node = node;
        }
    };
    return SelectNodeHandler;
}());
exports["default"] = SelectNodeHandler;


/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {



exports.__esModule = true;
var version = "1.4.1";
exports["default"] = version;


/***/ }),
/* 13 */,
/* 14 */,
/* 15 */,
/* 16 */,
/* 17 */,
/* 18 */,
/* 19 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(3);


/***/ })
/******/ ]);

  }).apply(root, arguments);
});
}(this));

/* Tree pattern.
 *
 * Options:
 * data(jSON): load data structure directly into tree (undefined)
 * dataUrl(jSON): Load data from remote url (undefined)
 * autoOpen(boolean): auto open tree contents (false)
 * dragAndDrop(boolean): node drag and drop support (false)
 * selectable(boolean): if nodes can be selectable (true)
 * keyboardSupport(boolean): if keyboard naviation is allowed (true)
 *
 * Documentation: # JSON node data
 *
 *    {{ example-1 }}
 *
 *    # Remote data URL
 *
 *    {{ example-2 }}
 *
 *    # Drag and drop
 *
 *    {{ example-3 }}
 *
 * Example: example-1
 *    <div class="pat-tree"
 *         data-pat-tree='data:[
 *          { "label": "node1",
 *            "children": [
 *              { "label": "child1" },
 *              { "label": "child2" }
 *            ]
 *          },
 *          { "label": "node2",
 *            "children": [
 *              { "label": "child3" }
 *            ]
 *          }
 *        ];'> </div>
 *
 * Example: example-2
 *    <div class="pat-tree"
 *         data-pat-tree="dataUrl:/docs/dev/tests/json/fileTree.json;
 *                        autoOpen:true"></div>
 *
 * Example: example-3
 *    <div class="pat-tree"
 *         data-pat-tree="dataUrl:/docs/dev/tests/json/fileTree.json;
 *                        dragAndDrop: true;
 *                        autoOpen: true"></div>
 *
 */


define('mockup-patterns-tree',[
  'jquery',
  'pat-base',
  'mockup-utils',
  'jqtree'
], function($, Base, utils) {
  'use strict';

  var Tree = Base.extend({
    name: 'tree',
    trigger: '.pat-tree',
    parser: 'mockup',
    defaults: {
      dragAndDrop: false,
      autoOpen: false,
      selectable: true,
      keyboardSupport: true,
      onLoad: null
    },
    init: function() {
      var self = this;
      /* convert all bool options */
      for (var optionKey in self.options) {
        var def = self.defaults[optionKey];
        if (def !== undefined && typeof(def) === 'boolean') {
          self.options[optionKey] = utils.bool(self.options[optionKey]);
        }
      }

      if (self.options.dragAndDrop && self.options.onCanMoveTo === undefined) {
        self.options.onCanMoveTo = function(moved, target, position) {
          /* if not using folder option, just allow, otherwise, only allow if folder */
          return target.folder === undefined || target.folder === true;
        };
      }

      if (self.options.data && typeof(self.options.data) === 'string') {
        self.options.data = $.parseJSON(self.options.data);
      }
      if (self.options.onLoad !== null){
        // delay generating tree...
        var options = $.extend({}, self.options);
        $.getJSON(options.dataUrl, function(data) {
          options.data = data;
          delete options.dataUrl;
          self.tree = self.$el.tree(options);
          self.options.onLoad(self);
        });
      } else {
        self.tree = self.$el.tree(self.options);
      }
    }
  });


  return Tree;

});

/* ========================================================================
 * Bootstrap: modal.js v3.3.4
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // MODAL CLASS DEFINITION
  // ======================

  var Modal = function (element, options) {
    this.options             = options
    this.$body               = $(document.body)
    this.$element            = $(element)
    this.$dialog             = this.$element.find('.modal-dialog')
    this.$backdrop           = null
    this.isShown             = null
    this.originalBodyPad     = null
    this.scrollbarWidth      = 0
    this.ignoreBackdropClick = false

    if (this.options.remote) {
      this.$element
        .find('.modal-content')
        .load(this.options.remote, $.proxy(function () {
          this.$element.trigger('loaded.bs.modal')
        }, this))
    }
  }

  Modal.VERSION  = '3.3.4'

  Modal.TRANSITION_DURATION = 300
  Modal.BACKDROP_TRANSITION_DURATION = 150

  Modal.DEFAULTS = {
    backdrop: true,
    keyboard: true,
    show: true
  }

  Modal.prototype.toggle = function (_relatedTarget) {
    return this.isShown ? this.hide() : this.show(_relatedTarget)
  }

  Modal.prototype.show = function (_relatedTarget) {
    var that = this
    var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })

    this.$element.trigger(e)

    if (this.isShown || e.isDefaultPrevented()) return

    this.isShown = true

    this.checkScrollbar()
    this.setScrollbar()
    this.$body.addClass('modal-open')

    this.escape()
    this.resize()

    this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))

    this.$dialog.on('mousedown.dismiss.bs.modal', function () {
      that.$element.one('mouseup.dismiss.bs.modal', function (e) {
        if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
      })
    })

    this.backdrop(function () {
      var transition = $.support.transition && that.$element.hasClass('fade')

      if (!that.$element.parent().length) {
        that.$element.appendTo(that.$body) // don't move modals dom position
      }

      that.$element
        .show()
        .scrollTop(0)

      that.adjustDialog()

      if (transition) {
        that.$element[0].offsetWidth // force reflow
      }

      that.$element
        .addClass('in')
        .attr('aria-hidden', false)

      that.enforceFocus()

      var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })

      transition ?
        that.$dialog // wait for modal to slide in
          .one('bsTransitionEnd', function () {
            that.$element.trigger('focus').trigger(e)
          })
          .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
        that.$element.trigger('focus').trigger(e)
    })
  }

  Modal.prototype.hide = function (e) {
    if (e) e.preventDefault()

    e = $.Event('hide.bs.modal')

    this.$element.trigger(e)

    if (!this.isShown || e.isDefaultPrevented()) return

    this.isShown = false

    this.escape()
    this.resize()

    $(document).off('focusin.bs.modal')

    this.$element
      .removeClass('in')
      .attr('aria-hidden', true)
      .off('click.dismiss.bs.modal')
      .off('mouseup.dismiss.bs.modal')

    this.$dialog.off('mousedown.dismiss.bs.modal')

    $.support.transition && this.$element.hasClass('fade') ?
      this.$element
        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
        .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
      this.hideModal()
  }

  Modal.prototype.enforceFocus = function () {
    $(document)
      .off('focusin.bs.modal') // guard against infinite focus loop
      .on('focusin.bs.modal', $.proxy(function (e) {
        if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
          this.$element.trigger('focus')
        }
      }, this))
  }

  Modal.prototype.escape = function () {
    if (this.isShown && this.options.keyboard) {
      this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
        e.which == 27 && this.hide()
      }, this))
    } else if (!this.isShown) {
      this.$element.off('keydown.dismiss.bs.modal')
    }
  }

  Modal.prototype.resize = function () {
    if (this.isShown) {
      $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
    } else {
      $(window).off('resize.bs.modal')
    }
  }

  Modal.prototype.hideModal = function () {
    var that = this
    this.$element.hide()
    this.backdrop(function () {
      that.$body.removeClass('modal-open')
      that.resetAdjustments()
      that.resetScrollbar()
      that.$element.trigger('hidden.bs.modal')
    })
  }

  Modal.prototype.removeBackdrop = function () {
    this.$backdrop && this.$backdrop.remove()
    this.$backdrop = null
  }

  Modal.prototype.backdrop = function (callback) {
    var that = this
    var animate = this.$element.hasClass('fade') ? 'fade' : ''

    if (this.isShown && this.options.backdrop) {
      var doAnimate = $.support.transition && animate

      this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
        .appendTo(this.$body)

      this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
        if (this.ignoreBackdropClick) {
          this.ignoreBackdropClick = false
          return
        }
        if (e.target !== e.currentTarget) return
        this.options.backdrop == 'static'
          ? this.$element[0].focus()
          : this.hide()
      }, this))

      if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

      this.$backdrop.addClass('in')

      if (!callback) return

      doAnimate ?
        this.$backdrop
          .one('bsTransitionEnd', callback)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callback()

    } else if (!this.isShown && this.$backdrop) {
      this.$backdrop.removeClass('in')

      var callbackRemove = function () {
        that.removeBackdrop()
        callback && callback()
      }
      $.support.transition && this.$element.hasClass('fade') ?
        this.$backdrop
          .one('bsTransitionEnd', callbackRemove)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callbackRemove()

    } else if (callback) {
      callback()
    }
  }

  // these following methods are used to handle overflowing modals

  Modal.prototype.handleUpdate = function () {
    this.adjustDialog()
  }

  Modal.prototype.adjustDialog = function () {
    var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight

    this.$element.css({
      paddingLeft:  !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
      paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
    })
  }

  Modal.prototype.resetAdjustments = function () {
    this.$element.css({
      paddingLeft: '',
      paddingRight: ''
    })
  }

  Modal.prototype.checkScrollbar = function () {
    var fullWindowWidth = window.innerWidth
    if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
      var documentElementRect = document.documentElement.getBoundingClientRect()
      fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
    }
    this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
    this.scrollbarWidth = this.measureScrollbar()
  }

  Modal.prototype.setScrollbar = function () {
    var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
    this.originalBodyPad = document.body.style.paddingRight || ''
    if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
  }

  Modal.prototype.resetScrollbar = function () {
    this.$body.css('padding-right', this.originalBodyPad)
  }

  Modal.prototype.measureScrollbar = function () { // thx walsh
    var scrollDiv = document.createElement('div')
    scrollDiv.className = 'modal-scrollbar-measure'
    this.$body.append(scrollDiv)
    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
    this.$body[0].removeChild(scrollDiv)
    return scrollbarWidth
  }


  // MODAL PLUGIN DEFINITION
  // =======================

  function Plugin(option, _relatedTarget) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.modal')
      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

      if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
      if (typeof option == 'string') data[option](_relatedTarget)
      else if (options.show) data.show(_relatedTarget)
    })
  }

  var old = $.fn.modal

  $.fn.modal             = Plugin
  $.fn.modal.Constructor = Modal


  // MODAL NO CONFLICT
  // =================

  $.fn.modal.noConflict = function () {
    $.fn.modal = old
    return this
  }


  // MODAL DATA-API
  // ==============

  $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
    var $this   = $(this)
    var href    = $this.attr('href')
    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
    var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())

    if ($this.is('a')) e.preventDefault()

    $target.one('show.bs.modal', function (showEvent) {
      if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
      $target.one('hidden.bs.modal', function () {
        $this.is(':visible') && $this.trigger('focus')
      })
    })
    Plugin.call($target, option, this)
  })

}(jQuery);

define("castle-url/libs/bootstrap/js/modal", function(){});

/* jshint quotmark: false */


define('castle-url/components/modal',[
  'jquery',
  'castle-url/libs/react/react.min',
  'mockup-patterns-modal',
  'mockup-utils',
  'castle-url/libs/bootstrap/js/modal'
], function($, R, PloneModal, utils) {
  'use strict';

  /* XXX with escape keys, need one place to manage all the overlays and escaping them.
     This is nasty and requires escape key by default being off for plone modal */
  if(PloneModal && PloneModal.prototype._hide === undefined){
    PloneModal.prototype._hide = PloneModal.prototype.hide;
    PloneModal.prototype.hide = function(){
      var $modalWrapper = this.$modal.closest('.plone-modal-wrapper');
      var thisZIndex = parseInt($modalWrapper.css('zIndex'));
      var $modals = $(".plone-modal-wrapper:visible,.modal-open .castle-modal-wrapper .modal:visible");
      if($modals.size() > 1 && $.mosaic && $.mosaic.overlay && $.mosaic.overlay.app){
        // make sure this isn't the top-most one
        var maxZIndex = 0;
        $modals.each(function(){
          var zIndex = parseInt($(this).css('zIndex'));
          if(zIndex > maxZIndex){
            maxZIndex = zIndex;
          }
        });
        // skip out here, we'll close when it's the last one
        if(maxZIndex > thisZIndex){
          return;
        }
      }
      PloneModal.prototype._hide.apply(this, []);
    };
  }

  $(document).keyup(function(e) {
    if (e.keyCode == 27) {
      // need to find the top most modal that is currently open
      utils.loading.hide();
      var max = 0;
      var $found;
      $(".plone-modal-wrapper:visible,.modal-open .castle-modal-wrapper .modal:visible").each(function(){
        var zIndex = parseInt($(this).css('zIndex')) + 0;
        if(zIndex > max){
          max = zIndex;
          $found = $(this);
        }
      });
      if($found){
        if($found.hasClass('plone-modal-wrapper')) {
          if($found.hasClass('mosaic-overlay')){
            $.mosaic.overlay.close();
          }else {
            var pattern = $found.find('.plone-modal').data('pattern-plone-modal');
            if(pattern){
              pattern.hide();
            }
          }
        } else {
          $('button.close', $found).trigger('click');
        }
      }
    }
  });


  var D = R.DOM;
  var div = D.div;
  var button = D.button;
  var span = D.span;

  var Modal = {
    getInitialState: function(){
      return {
        zIndex: 3000,
        shown: false,
        preventClose: false
      };
    },

    show: function(){
      $(this.refs.modal.getDOMNode()).modal('show');
    },

    hide: function(e){
      if(e){
        e.preventDefault();
      }
      $(this.refs.modal.getDOMNode()).modal('hide');
    },

    getModalEl: function(){
      return $(this.refs.modal.getDOMNode());
    },

    componentDidMount: function() {
      var self = this;
      var $el = self.getModalEl();

      $el.on('shown.bs.modal', function(e){
        if(self.props.onShown){
          self.props.onShown(e, self);
        }
      });

      $el.on('show.bs.modal', function(){
        self.state.shown = true;
      });

      $el.modal(this.props.modalOptions);

      $el.on('hide.bs.modal', function(e){
        if(self.state.preventClose){
          e.preventDefault();
          return;
        }
        self.state.shown = false;
      });

      $el.on('hidden.bs.modal', function(e){
        if(self.props.onHidden){
          self.props.onHidden(e, self);
        }
        var $el = $(self.getDOMNode());
        if($('.castle-modal-wrapper,.plone-modal-wrapper').size() === 0){
          // otherwise, modals stick around...
          $('.plone-modal-backdrop').remove();
        }
        if($('.modal:visible').size() > 0){
          // need to re-add 'modal-open' class
          $('body').addClass('modal-open');
        }

        setTimeout(function(){
          // perform cleanup in delay because DOM node still may be necessary
          // for react to do some things and throw errors;
          $el.remove();
        }, 1000);
      });

      var zIndex = 3001;
      $(".plone-modal-wrapper,.plone-modal-backdrop,.modal-open .castle-modal-wrapper .modal").each(function(){
        zIndex = Math.max(zIndex, parseInt($(this).css('zIndex')) + 1 || 3001);
      });
      self.state.zIndex = zIndex;
      self.setModalZIndex();
    },

    componentDidUpdate: function(){
      this.setModalZIndex();
    },

    setModalZIndex: function(){
      $(this.refs.modal.getDOMNode()).css({'z-index': this.state.zIndex});
    },

    getId: function(){
      return this.props.id;
    },

    getTitle: function(){
      return this.props.title;
    },

    render: function(){
      var attrs = { ref: 'modal', className: 'modal fade'};
      var id = this.getId();
      if(id){
        attrs.id = id;
      }
      var modalStyles = {};
      if(this.props.width){
        modalStyles.width = this.props.width;
      }
      return div({ className: 'castle-modal-wrapper', ref: 'container' }, div(attrs, [
        div({ className: 'modal-dialog', style: modalStyles}, this.renderContentContainer())
      ]));
    },

    renderContentContainer: function(){
      return div({ className: 'modal-content' }, [
        div({ className: 'modal-header' }, this.renderHeader()),
        div({ className: 'modal-body'}, this.renderContent()),
        div({ className: 'modal-footer'}, this.renderFooter())
      ]);
    },

    renderHeader: function(){
      return [
        button({ type: 'button', className: 'close', onClick: this.hide }, [
          div({ className: 'close-button' }),
          span({ 'aria-hidden': 'true' }, '\u00d7')
        ]),
        D.h4({}, this.getTitle())
      ];
    },

    renderContent: function(){
      return div({});
    },

    renderFooter: function(){
      return '';
    },

    getDefaultProps: function(){
      return {
        id: null,
        title: 'Modal title',
        modalOptions: {
          backdrop: 'static',
          show: true
        },
        onHidden: function(){},
        onShown: function(){},
        width: null
      };
    }
  };

  return Modal;
});

define('mockup-ui-url/views/base',[
  'jquery',
  'underscore',
  'backbone',
  'translate'
], function($, _, Backbone, _t) {
  'use strict';

  var BaseView = Backbone.View.extend({
    isUIView: true,
    eventPrefix: 'ui',
    template: null,
    idPrefix: 'base-',
    appendInContainer: true,
    initialize: function(options) {
      this.options = options;
      for (var key in this.options) {
        this[key] = this.options[key];
      }
      this.options._t = _t;
    },
    render: function() {
      this.applyTemplate();

      this.trigger('render', this);
      this.afterRender();

      if (this.options.id) {
        // apply id to element
        this.$el.attr('id', this.idPrefix + this.options.id);
      }
      return this;
    },
    afterRender: function() {

    },
    serializedModel: function() {
      return this.options;
    },
    applyTemplate: function() {
      if (this.template !== null) {
        var data = $.extend({_t: _t}, this.options, this.serializedModel());
        var template = this.template;
        if(typeof(template) === 'string'){
          template = _.template(template);
        }
        this.$el.html(template(data));
      }
    },
    propagateEvent: function(eventName) {
      if (eventName.indexOf(':') > 0) {
        var eventId = eventName.split(':')[0];
        if (this.eventPrefix !== '') {
          if (eventId === this.eventPrefix ||
              eventId === this.eventPrefix + '.' + this.id) { return true; }
        }
      }
      return false;
    },
    uiEventTrigger: function(name) {
      var args = [].slice.call(arguments, 0);

      if (this.eventPrefix !== '') {
        args[0] = this.eventPrefix + ':' + name;
        Backbone.View.prototype.trigger.apply(this, args);
        if (this.id) {
          args[0] =  this.eventPrefix + '.' + this.id + ':' + name;
          Backbone.View.prototype.trigger.apply(this, args);
        }
      }
    }
  });

  return BaseView;
});

define('mockup-ui-url/views/container',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/base'
], function($, _, BaseView) {
  'use strict';

  var Container = BaseView.extend({
    id: '',
    items: [],
    itemContainer: null,
    isOffsetParent: true,
    idPrefix: 'container-',
    render: function() {
      if (this.options.id) {
        this.$el.attr('id', this.idPrefix + this.options.id);
      }

      this.applyTemplate();

      this.renderItems();
      this.bindEvents();

      if (this.isOffsetParent) {
        this.$el.addClass('ui-offset-parent');
      }

      this.trigger('render', this);

      this.afterRender();

      this.$el.data('component', this);
      return this;
    },
    renderItems: function() {
      var $container;

      if (this.itemContainer !== null) {
        $container = $(this.itemContainer, this.$el);
        if ($container.length === 0) {
          throw 'Item Container element not found.';
        }
      } else {
        $container = this.$el;
      }
      _.each(this.items, function(view) {
        if (view.appendInContainer === true) {
          $container.append(view.render().$el);
        } else {
          view.render();
        }
      }, this);
    },
    bindEvents: function() {
      var self = this;
      _.each(this.items, function(view) {
        view.on('all', function() {
          var slice = [].slice;
          var eventName = arguments[0];
          var eventTarget;
          var newName = self.id !== '' ? self.id + '.' + eventName : eventName;
          if (arguments.length > 1) {
            eventTarget = arguments[1];
          }
          if (newName !== eventName) {
            var newArgs = slice.call(arguments, 0);
            newArgs[0] = newName;
            self.trigger.apply(self, newArgs);
          }
          if (eventTarget !== undefined && eventTarget.isUIView === true) {
            if (eventTarget.propagateEvent(eventName) === true) {
              self.trigger.apply(self, arguments);
            }
          }
        });
      });
    },
    get: function(id) {
      // Remove the recursive part because it was confusing if two children had the
      // same id
      return _.findWhere(this.items, {'id': id});
    },
    add: function(item) {
      if (item.id !== undefined && this.get(item.id)) {
        throw 'Another item with the same `id` already exists.';
      }
      this.items.push(item);
    }
  });

  return Container;
});

/**
 * @license RequireJS text 2.0.12 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/requirejs/text for details
 */
/*jslint regexp: true */
/*global require, XMLHttpRequest, ActiveXObject,
  define, window, process, Packages,
  java, location, Components, FileUtils */

define('text',['module'], function (module) {
    'use strict';

    var text, fs, Cc, Ci, xpcIsWindows,
        progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
        xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
        bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
        hasLocation = typeof location !== 'undefined' && location.href,
        defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''),
        defaultHostName = hasLocation && location.hostname,
        defaultPort = hasLocation && (location.port || undefined),
        buildMap = {},
        masterConfig = (module.config && module.config()) || {};

    text = {
        version: '2.0.12',

        strip: function (content) {
            //Strips <?xml ...?> declarations so that external SVG and XML
            //documents can be added to a document without worry. Also, if the string
            //is an HTML document, only the part inside the body tag is returned.
            if (content) {
                content = content.replace(xmlRegExp, "");
                var matches = content.match(bodyRegExp);
                if (matches) {
                    content = matches[1];
                }
            } else {
                content = "";
            }
            return content;
        },

        jsEscape: function (content) {
            return content.replace(/(['\\])/g, '\\$1')
                .replace(/[\f]/g, "\\f")
                .replace(/[\b]/g, "\\b")
                .replace(/[\n]/g, "\\n")
                .replace(/[\t]/g, "\\t")
                .replace(/[\r]/g, "\\r")
                .replace(/[\u2028]/g, "\\u2028")
                .replace(/[\u2029]/g, "\\u2029");
        },

        createXhr: masterConfig.createXhr || function () {
            //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
            var xhr, i, progId;
            if (typeof XMLHttpRequest !== "undefined") {
                return new XMLHttpRequest();
            } else if (typeof ActiveXObject !== "undefined") {
                for (i = 0; i < 3; i += 1) {
                    progId = progIds[i];
                    try {
                        xhr = new ActiveXObject(progId);
                    } catch (e) {}

                    if (xhr) {
                        progIds = [progId];  // so faster next time
                        break;
                    }
                }
            }

            return xhr;
        },

        /**
         * Parses a resource name into its component parts. Resource names
         * look like: module/name.ext!strip, where the !strip part is
         * optional.
         * @param {String} name the resource name
         * @returns {Object} with properties "moduleName", "ext" and "strip"
         * where strip is a boolean.
         */
        parseName: function (name) {
            var modName, ext, temp,
                strip = false,
                index = name.indexOf("."),
                isRelative = name.indexOf('./') === 0 ||
                             name.indexOf('../') === 0;

            if (index !== -1 && (!isRelative || index > 1)) {
                modName = name.substring(0, index);
                ext = name.substring(index + 1, name.length);
            } else {
                modName = name;
            }

            temp = ext || modName;
            index = temp.indexOf("!");
            if (index !== -1) {
                //Pull off the strip arg.
                strip = temp.substring(index + 1) === "strip";
                temp = temp.substring(0, index);
                if (ext) {
                    ext = temp;
                } else {
                    modName = temp;
                }
            }

            return {
                moduleName: modName,
                ext: ext,
                strip: strip
            };
        },

        xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/,

        /**
         * Is an URL on another domain. Only works for browser use, returns
         * false in non-browser environments. Only used to know if an
         * optimized .js version of a text resource should be loaded
         * instead.
         * @param {String} url
         * @returns Boolean
         */
        useXhr: function (url, protocol, hostname, port) {
            var uProtocol, uHostName, uPort,
                match = text.xdRegExp.exec(url);
            if (!match) {
                return true;
            }
            uProtocol = match[2];
            uHostName = match[3];

            uHostName = uHostName.split(':');
            uPort = uHostName[1];
            uHostName = uHostName[0];

            return (!uProtocol || uProtocol === protocol) &&
                   (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) &&
                   ((!uPort && !uHostName) || uPort === port);
        },

        finishLoad: function (name, strip, content, onLoad) {
            content = strip ? text.strip(content) : content;
            if (masterConfig.isBuild) {
                buildMap[name] = content;
            }
            onLoad(content);
        },

        load: function (name, req, onLoad, config) {
            //Name has format: some.module.filext!strip
            //The strip part is optional.
            //if strip is present, then that means only get the string contents
            //inside a body tag in an HTML string. For XML/SVG content it means
            //removing the <?xml ...?> declarations so the content can be inserted
            //into the current doc without problems.

            // Do not bother with the work if a build and text will
            // not be inlined.
            if (config && config.isBuild && !config.inlineText) {
                onLoad();
                return;
            }

            masterConfig.isBuild = config && config.isBuild;

            var parsed = text.parseName(name),
                nonStripName = parsed.moduleName +
                    (parsed.ext ? '.' + parsed.ext : ''),
                url = req.toUrl(nonStripName),
                useXhr = (masterConfig.useXhr) ||
                         text.useXhr;

            // Do not load if it is an empty: url
            if (url.indexOf('empty:') === 0) {
                onLoad();
                return;
            }

            //Load the text. Use XHR if possible and in a browser.
            if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) {
                text.get(url, function (content) {
                    text.finishLoad(name, parsed.strip, content, onLoad);
                }, function (err) {
                    if (onLoad.error) {
                        onLoad.error(err);
                    }
                });
            } else {
                //Need to fetch the resource across domains. Assume
                //the resource has been optimized into a JS module. Fetch
                //by the module name + extension, but do not include the
                //!strip part to avoid file system issues.
                req([nonStripName], function (content) {
                    text.finishLoad(parsed.moduleName + '.' + parsed.ext,
                                    parsed.strip, content, onLoad);
                });
            }
        },

        write: function (pluginName, moduleName, write, config) {
            if (buildMap.hasOwnProperty(moduleName)) {
                var content = text.jsEscape(buildMap[moduleName]);
                write.asModule(pluginName + "!" + moduleName,
                               "define(function () { return '" +
                                   content +
                               "';});\n");
            }
        },

        writeFile: function (pluginName, moduleName, req, write, config) {
            var parsed = text.parseName(moduleName),
                extPart = parsed.ext ? '.' + parsed.ext : '',
                nonStripName = parsed.moduleName + extPart,
                //Use a '.js' file name so that it indicates it is a
                //script that can be loaded across domains.
                fileName = req.toUrl(parsed.moduleName + extPart) + '.js';

            //Leverage own load() method to load plugin value, but only
            //write out values that do not have the strip argument,
            //to avoid any potential issues with ! in file names.
            text.load(nonStripName, req, function (value) {
                //Use own write() method to construct full module value.
                //But need to create shell that translates writeFile's
                //write() to the right interface.
                var textWrite = function (contents) {
                    return write(fileName, contents);
                };
                textWrite.asModule = function (moduleName, contents) {
                    return write.asModule(moduleName, fileName, contents);
                };

                text.write(pluginName, nonStripName, textWrite, config);
            }, config);
        }
    };

    if (masterConfig.env === 'node' || (!masterConfig.env &&
            typeof process !== "undefined" &&
            process.versions &&
            !!process.versions.node &&
            !process.versions['node-webkit'])) {
        //Using special require.nodeRequire, something added by r.js.
        fs = require.nodeRequire('fs');

        text.get = function (url, callback, errback) {
            try {
                var file = fs.readFileSync(url, 'utf8');
                //Remove BOM (Byte Mark Order) from utf8 files if it is there.
                if (file.indexOf('\uFEFF') === 0) {
                    file = file.substring(1);
                }
                callback(file);
            } catch (e) {
                if (errback) {
                    errback(e);
                }
            }
        };
    } else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
            text.createXhr())) {
        text.get = function (url, callback, errback, headers) {
            var xhr = text.createXhr(), header;
            xhr.open('GET', url, true);

            //Allow plugins direct access to xhr headers
            if (headers) {
                for (header in headers) {
                    if (headers.hasOwnProperty(header)) {
                        xhr.setRequestHeader(header.toLowerCase(), headers[header]);
                    }
                }
            }

            //Allow overrides specified in config
            if (masterConfig.onXhr) {
                masterConfig.onXhr(xhr, url);
            }

            xhr.onreadystatechange = function (evt) {
                var status, err;
                //Do not explicitly handle errors, those should be
                //visible via console output in the browser.
                if (xhr.readyState === 4) {
                    status = xhr.status || 0;
                    if (status > 399 && status < 600) {
                        //An http 4xx or 5xx error. Signal an error.
                        err = new Error(url + ' HTTP status: ' + status);
                        err.xhr = xhr;
                        if (errback) {
                            errback(err);
                        }
                    } else {
                        callback(xhr.responseText);
                    }

                    if (masterConfig.onXhrComplete) {
                        masterConfig.onXhrComplete(xhr, url);
                    }
                }
            };
            xhr.send(null);
        };
    } else if (masterConfig.env === 'rhino' || (!masterConfig.env &&
            typeof Packages !== 'undefined' && typeof java !== 'undefined')) {
        //Why Java, why is this so awkward?
        text.get = function (url, callback) {
            var stringBuffer, line,
                encoding = "utf-8",
                file = new java.io.File(url),
                lineSeparator = java.lang.System.getProperty("line.separator"),
                input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
                content = '';
            try {
                stringBuffer = new java.lang.StringBuffer();
                line = input.readLine();

                // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
                // http://www.unicode.org/faq/utf_bom.html

                // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
                if (line && line.length() && line.charAt(0) === 0xfeff) {
                    // Eat the BOM, since we've already found the encoding on this file,
                    // and we plan to concatenating this buffer with others; the BOM should
                    // only appear at the top of a file.
                    line = line.substring(1);
                }

                if (line !== null) {
                    stringBuffer.append(line);
                }

                while ((line = input.readLine()) !== null) {
                    stringBuffer.append(lineSeparator);
                    stringBuffer.append(line);
                }
                //Make sure we return a JavaScript string and not a Java string.
                content = String(stringBuffer.toString()); //String
            } finally {
                input.close();
            }
            callback(content);
        };
    } else if (masterConfig.env === 'xpconnect' || (!masterConfig.env &&
            typeof Components !== 'undefined' && Components.classes &&
            Components.interfaces)) {
        //Avert your gaze!
        Cc = Components.classes;
        Ci = Components.interfaces;
        Components.utils['import']('resource://gre/modules/FileUtils.jsm');
        xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc);

        text.get = function (url, callback) {
            var inStream, convertStream, fileObj,
                readData = {};

            if (xpcIsWindows) {
                url = url.replace(/\//g, '\\');
            }

            fileObj = new FileUtils.File(url);

            //XPCOM, you so crazy
            try {
                inStream = Cc['@mozilla.org/network/file-input-stream;1']
                           .createInstance(Ci.nsIFileInputStream);
                inStream.init(fileObj, 1, 0, false);

                convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
                                .createInstance(Ci.nsIConverterInputStream);
                convertStream.init(inStream, "utf-8", inStream.available(),
                Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);

                convertStream.readString(inStream.available(), readData);
                convertStream.close();
                inStream.close();
                callback(readData.value);
            } catch (e) {
                throw new Error((fileObj && fileObj.path || '') + ': ' + e);
            }
        };
    }
    return text;
});


define('text!mockup-ui-url/templates/popover.xml',[],function () { return '<div class="arrow"></div>\n<div class="popover-title">\n</div>\n<div class="items popover-content">\n</div>\n\n';});

define('mockup-ui-url/views/popover',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/container',
  'mockup-patterns-backdrop',
  'text!mockup-ui-url/templates/popover.xml',
], function($, _, ContainerView, Backdrop, PopoverTemplate) {
  'use strict';

  var PopoverView = ContainerView.extend({
    tagName: 'div',
    className: 'popover',
    eventPrefix: 'popover',
    template: PopoverTemplate,
    content: null,
    title: null,
    triggerView: null,
    idPrefix: 'popover-',
    triggerEvents: {
      'button:click': 'toggle'
    },
    placement: 'bottom',
    events: {
    },
    opened: false,
    closeOnOutClick: true,
    appendInContainer: true,
    backdrop: undefined,
    $backdrop: null,
    useBackdrop: true,
    backdropOptions: {
      zIndex: '1009',
      opacity: '0.4',
      className: 'backdrop backdrop-popover',
      classActiveName: 'backdrop-active',
      closeOnEsc: false,
      closeOnClick: true
    },
    initialize: function(options) {
      ContainerView.prototype.initialize.apply(this, [options]);
      this.bindTriggerEvents();

      this.on('render', function() {
        this.$el.attr('role', 'tooltip').attr('aria-hidden', 'false');
        this.renderTitle();
        this.renderContent();
      }, this);
    },
    afterRender: function () {
    },
    getTemplateOptions: function(){
      return this.options;
    },
    renderTitle: function() {
      var title = this.title;
      if(typeof(title) === 'function'){
        title = title(this.getTemplateOptions());
      }
      this.$('.popover-title').empty().append(title);
    },
    renderContent: function() {
      this.$('.popover-content').empty().append(this.content(this.getTemplateOptions()));
    },
    bindTriggerEvents: function() {
      if (this.triggerView) {
        _.each(this.triggerEvents, function(func, event) {
          var method = this[func];
          if (!method) {
            $.error('Function not found.');
          }
          this.stopListening(this.triggerView, event);
          this.listenTo(this.triggerView, event, method);
        }, this);
      }
    },

    getPosition: function() {
      var $el = this.triggerView.$el;
      return $.extend({}, {
        width: $el[0].offsetWidth,
        height: $el[0].offsetHeight
      }, $el.offset());
    },

    getBodyClassName: function(){
      var name = 'popover-';
      if(this.options.id){
        name += this.options.id + '-';
      }
      name += 'active';
      return name;
    },

    show: function() {
      /* hide existing */
      $('.popover:visible').each(function(){
        var popover = $(this).data('component');
        if(popover){
          popover.hide();
        }
      });

      this.position();

      this.setBackdrop();
      if (this.useBackdrop === true) {
        this.backdrop.show();
      }

      this.opened = true;

      if (this.triggerView) {
        this.triggerView.$el.addClass('active');
      }

      this.uiEventTrigger('show', this);
      this.$el.attr('aria-hidden', 'false');
      $('body').addClass(this.getBodyClassName());
    },

    position: function(){
      var pos = this.getPosition();
      var $tip = this.$el, tp, placement, actualWidth, actualHeight;

      placement = this.placement;

      $tip.css({ top: 0, left: 0 }).addClass('active');

      actualWidth = $tip[0].offsetWidth;
      actualHeight = $tip[0].offsetHeight;

      switch (placement) {
        case 'bottom':
          tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
          break;
        case 'top':
          tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
          break;
        case 'left':
          tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
          break;
        case 'right':
          tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
          break;
      }

      this.applyPlacement(tp, placement);
    },

    applyPlacement: function(offset, placement) {
      var $el = this.$el,
        $tip = this.$el,
        width = $tip[0].offsetWidth,
        height = $tip[0].offsetHeight,
        actualWidth,
        actualHeight,
        delta,
        replace;

      $el.removeClass(placement);

      $el.offset(offset)
        .addClass(placement)
        .addClass('active');

      actualWidth = $tip[0].offsetWidth;
      actualHeight = $tip[0].offsetHeight;

      if (placement === 'top' && actualHeight !== height) {
        offset.top = offset.top + height - actualHeight;
        replace = true;
      }

      if (placement === 'bottom' || placement === 'top') {
        delta = 0;

        if (offset.left < 0) {
          delta = offset.left * -2;
          offset.left = 0;
          $el.removeClass(placement);
          $el.offset(offset).addClass(placement);
          actualWidth = $tip[0].offsetWidth;
          actualHeight = $tip[0].offsetHeight;
        }

        this.positionArrow(delta - width + actualWidth, actualWidth, 'left');

      } else {
        this.positionArrow(actualHeight - height, actualHeight, 'top');
      }

      if (replace) {
        $el.offset(offset);
      }
    },
    positionArrow: function(delta, dimension, position) {
      var $arrow = this.$('.arrow');
      $arrow.css(position, delta ? (50 * (1 - delta / dimension) + '%') : '');
    },
    hide: function() {
      this.opened = false;
      this.$el.removeClass('active');
      if (this.triggerView) {
        this.triggerView.$el.removeClass('active');
        this.triggerView.$el.attr('aria-hidden', 'true');
      }
      this.uiEventTrigger('hide', this);
      this.$el.attr('aria-hidden', 'true');
      $('body').removeClass(this.getBodyClassName());
    },
    toggle: function(button, e) {
      if (this.opened) {
        this.hide();
      } else {
        this.show();
      }
    },
    setBackdrop: function() {
      if (this.useBackdrop === true && this.backdrop === undefined) {
        var self = this;
        this.$backdrop = this.$el.closest('.ui-backdrop-element');
        if (this.$backdrop.length === 0) {
          this.$backdrop = $('body');
        }

        this.backdrop = new Backdrop(this.$backdrop, this.backdropOptions);
        this.backdrop.$el.on('hidden.backdrop.patterns', function(e) {
          if (e.namespace === 'backdrop.patterns') {
            e.stopPropagation();
            if (self.opened === true) {
              self.hide();
            }
          }
        });
        this.on('popover:hide', function() {
          this.backdrop.hide();
        }, this);
      }
    }
  });

  return PopoverView;
});

/* global define */

define('castle-url/components/content-browser',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-url/components/utils',
  'mockup-ui-url/views/popover',
  'mockup-patterns-querystring'
], function($, Base, _, R, utils, Modal, cutils,
            PopoverView, QueryString) {
  'use strict';
  var D = R.DOM;


  var TableListingView = R.createClass({

    allSelected: function(){
      var that = this;
      var items = that.props.parent.state.items;
      var selected = this.getAllSelected();
      for(var i=0; i<items.length; i++){
        var item = items[i];
        if(selected.indexOf(item.UID) === -1){
          return false;
        }
      }
      return true;
    },

    getAllSelected: function(){
      var that = this;
      var selected = [];
      that.props.parent.state.selected.forEach(function(item){
        selected.push(item.UID);
      });
      return selected;
    },

    selectAllClicked: function(e){
      var that = this;
      var items = that.props.parent.state.items;
      var selected = this.getAllSelected();
      for(var i=0; i<items.length; i++){
        var item = items[i];
        if(selected.indexOf(item.UID) === -1){
          that.props.onItemSelected.bind(that.props.parent, item)(e);
        }
      }
    },

    render: function(){
      var that = this;
      var props = that.props;
      var parent = props.parent;
      var items = parent.state.items;

      var selectAllCheckbox = '';
      if(parent.props.multiple){
        selectAllCheckbox = D.input({ type: 'checkbox', checked: that.allSelected(),
                                      onClick: that.selectAllClicked });
      }

      return D.table({className: 'contents table'}, [
        D.thead({}, D.tr({}, [
          D.th({}, selectAllCheckbox),
          D.th({}, 'Title'),
          D.th({}, 'Type'),
          D.th({}, 'State')
        ])),
        D.tbody({}, items.map(function(item){
          var iconClass = 'contenttype-document contenttype-' + item.portal_type.toLowerCase();
          if(item.portal_type === 'Folder'){
            iconClass = 'contenttype-folder';
          }
          var icon = D.span({className: iconClass, key: item.UID + '-icon'});

          var selected = false;
          _.each(parent.state.selected, function(existingItem){
            if(existingItem.UID === item.UID){
              selected = true;
            }
          });
          var className = '';
          var onClick = props.onItemSelected.bind(parent, item);
          var clickText = 'Select';
          if(selected){
            className += ' active';
            clickText = 'Remove';
            onClick = props.onItemRemoved.bind(parent, item);
          }
          var title = [icon, D.span({ className: 'content-title'}, item.Title)];
          if(item.is_folderish){
            title = D.a({className: 'folderBox', href: '#2',
                         onClick: props.onFolderSelected.bind(parent, item)},
                        title);
          }
          className += 'state-' + item.review_state;
          var checkbox = '';
          if(parent.props.selectableTypes === null ||
              parent.props.selectableTypes.indexOf(item.portal_type) !== -1){
            checkbox = D.input({type: 'checkbox', checked: selected, onClick: onClick});
          }
          return D.tr({ key: item.UID, className: className }, [
            D.td({}, checkbox),
            D.td({}, title),
            D.td({}, item.portal_type),
            D.td({}, item.review_state)
          ]);
        }))
      ]);
    },
    getDefaultProps: function(){
      return {
        parent: null,
        onItemSelected: function(){},
        onItemRemoved: function(){},
        onFolderSelected: function(){}
      };
    }
  });

  var ImageListingView = R.createClass({
    render: function(){
      var that = this;
      var props = that.props;
      var parent = props.parent;
      var items = parent.state.items;

      // hasImage
      var placeHolderUrl = $('body').attr('data-portal-url') + '/++plone++castle/images/placeholder-image.png';
      var folderPlaceholderUrl = $('body').attr('data-portal-url') + '/++plone++castle/images/placeholder-folder.png';
      return D.div({className: 'row images-container'}, items.map(function(item){
        var imgUrl = placeHolderUrl;
        if(item.hasImage){
          imgUrl = item.getURL + '/@@images/image/preview';
        }
        if(!item.hasImage && item.is_folderish){
          imgUrl = folderPlaceholderUrl;
        }
        var img = D.div({ className: 'image-responsive', style: {'background-image': 'url("' + imgUrl + '")' }});
        if(item.is_folderish){
          img = D.a({ href: '#', onClick: props.onFolderSelected.bind(parent, item)}, img);
        }else{
          img = D.a({ href: '#', onClick: props.onItemSelected.bind(parent, item)}, img);
        }

        var selected = false;
        parent.state.selected.forEach(function(existingItem){
          if(existingItem.UID === item.UID){
            selected = true;
          }
        });

        return D.div({ className: 'col-md-3 image-item', key: item.UID}, D.div({ className: 'image-wrapper'}, [
          img,
          D.p({ className: 'image-title'}, [
            D.label({ htmlFor: item.UID + '-imageselect'},[
              D.input({type: 'checkbox', checked: selected,
                       onClick: props.onItemSelected.bind(parent, item),
                       id: item.UID + '-imageselect' }),
              item.Title
            ])
          ]),
        ]));
      }));
    }
  });

  var ContentBrowserComponent = cutils.Class([Modal], {
    getInitialState: function(){
      return {
        error: false,
        items: [],
        page: 1,
        total: 0,
        filter: '',
        selected: [],
        sort_on: 'modified',
        sort_order: 'reverse',
        view: 'table',
        showQuery: false,
        criterias: [],
      };
    },
    componentDidMount: function(){
      var that = this;
      Modal.componentDidMount.apply(this);

      // default to current path..
      var basePath = $('body').attr('data-base-path');
      if((that.props.query.currentPath === '/' || that.props.query.pattern.currentPath === '/') &&
          basePath){
        that.setPath(basePath);
      }

      that.load();

      var btnEl = that.refs.query_btn.getDOMNode();
      var $btnEl = $(btnEl);
      var el = that.refs.query_popover.getDOMNode();
      var $el = $(el);

      that.props.query_popover = new PopoverView({
        id: 'content-browser-query',
        title: 'Query',
        useBackdrop: false,
        content: _.template('<input class="pat-querystring" />'),
        placement: 'left'
      });
      that.props.query_popover.getPosition = function() {
        return $.extend({}, {
          width: btnEl.offsetWidth,
          height: btnEl.offsetHeight
        }, $btnEl.offset());
      };
      $el.append(that.props.query_popover.render().el);
      that.props.query_popover.$el.addClass('query');
      var $queryString = that.props.query_popover.$('input.pat-querystring');
      var queryString = new QueryString(
        $queryString, {
          indexOptionsUrl: $('body').attr('data-portal-url') + '/@@qsOptions',
          showPreviews: false
        }
      );

      queryString.$el.on('change', function() {
        if (that._qsTimeout) {
          clearTimeout(that._qsTimeout);
        }
        that._qsTimeout = setTimeout(function() {
          var criterias = $.parseJSON($queryString.val());
          that.setStateReload({
            criterias: criterias,
            page: 1
          });
        }, 200);
      });
      queryString.$el.on('initialized', function() {
        queryString.$sortOn.on('change', function() {
          that.setStateReload({
            sort_on: queryString.$sortOn.val(),
            page: 1
          });
        });
        queryString.$sortOrder.change(function() {
          var order = 'ascending';
          if (queryString.$sortOrder[0].checked) {
            order = 'reverse'; // jshint ignore:line
          }
          that.setStateReload({
            sort_order: order,
            page: 1
          });
        });

        queryString.component.props.storage.dispatcher.handleViewAction({
          actionType: 'update',
          data: {
            sortOn: that.state.sort_on,
            reversed: that.state.sort_order === 'reverse'
          }
        });
        queryString.component.setState({
          sortOn: that.state.sort_on,
          reversed: that.state.sort_order === 'reverse'
        });
      });
    },

    load: function(){
      var that = this;
      utils.loading.show();
      $.ajax({
        url: that.getQueryUrl(),
        dataType: 'json'
      }).done(function(data){
        that.setState({
          items: data.results,
          total: data.total
        });
      }).fail(function(){
        that.setState({
          error: true,
          items: [],
          total: 0
        });
      }).always(function(){
        utils.loading.hide();
      });
    },
    getQueryUrl: function(){
      var that = this;
      var query = that.props.query;

      if(query.options.attributes.indexOf('getURL') === -1){
        query.options.attributes.push('getURL');
      }
      if(query.options.attributes.indexOf('hasImage') === -1){
        query.options.attributes.push('hasImage');
      }
      if(query.options.attributes.indexOf('is_folderish') === -1){
        query.options.attributes.push('is_folderish');
      }

      query.options.sort_on = this.state.sort_on;
      query.options.sort_order = this.state.sort_order;
      query.options.useBaseCriteria = true;
      var baseCriteria = this.props.baseCriteria.slice();
      query.options.baseCriteria = baseCriteria.concat(that.state.criterias.slice());
      if(that.state.filter){
        query.options.baseCriteria.push({
          i: 'Title',
          o: 'plone.app.querystring.operation.string.contains',
          v: that.state.filter
        });
      }
      if(!query.options.sort_on){
        query.options.sort_on = 'getObjPositionInParent';
      }

      var params = query.getQueryData();
      params.batch = JSON.stringify(query.getBatch(that.state.page));

      var url = query.options.vocabularyUrl;
      if (url.indexOf('?') === -1) {
        url += '?';
      } else {
        url += '&';
      }
      return url + $.param(params);
    },

    itemSelected: function(item, e){
      var that = this;
      if(e.target.nodeName !== 'INPUT'){
        e.preventDefault();
      }
      if(that.props.multiple){
        var selected = that.state.selected;
        var found = false;
        that.state.selected.forEach(function(existing){
          if(existing.UID === item.UID){
            found = true;
          }
        });
        if(found){
          this.removeSelected(item);

        }else{
          selected.push(item);
          that.setState({
            selected: selected
          });
        }
      }else{
        that.props.onSelectItem(item);
        that.hide();
      }
    },

    removeSelected: function(item){
      var newSelected = [];
      _.each(this.state.selected, function(existingItem){
        if(existingItem.UID !== item.UID){
          newSelected.push(existingItem);
        }
      });
      this.setState({
        selected: newSelected
      });
    },

    folderSelected: function(item, e){
      e.preventDefault();
      var that = this;
      that.setPath(item.path);
      that.state.filter = '';
      that.state.page = 1;
      that.load();
    },

    setPath: function(path){
      var that = this;
      that.props.query.currentPath = path;
      if(that.props.query.pattern){
        that.props.query.pattern.currentPath = path;
      }
    },

    renderItems: function(){
      if(this.state.view === 'table'){
        return R.createElement(TableListingView, {
          parent: this,
          onItemSelected: this.itemSelected,
          onItemRemoved: this.removeSelected,
          onFolderSelected: this.folderSelected
        });
      }else if(this.state.view === 'image'){
        return R.createElement(ImageListingView, {
          parent: this,
          onItemSelected: this.itemSelected,
          onItemRemoved: this.removeSelected,
          onFolderSelected: this.folderSelected
        });
      }
      return [];
    },

    crumbClicked: function(path, e){
      e.preventDefault();
      this.setPath(path);
      this.state.filter = '';
      this.state.page = 1;
      this.load();
    },

    renderBreadcrumbs: function(){
      var that = this;
      var paths = that.props.query.getCurrentPath().split('/');
      paths[0] = '/';
      var itemPath = '';
      var crumbs = [];
      _.each(paths, function(node, idx) {
        if (node !== '') {
          var name = node;
          var path = '/';
          if(node === '/'){
            name = 'Home';
          }else{
            itemPath = itemPath + '/' + node;
            path = itemPath;
          }
          if(idx < paths.length - 1){
            crumbs.push(D.li({},
              D.a({ href: '#', onClick: that.crumbClicked.bind(that, path)}, name)));
          }else{
            crumbs.push(D.li({}, name));
          }
        }
      });
      return D.ol({ className: 'breadcrumb' }, crumbs);
    },

    filterChanged: function(e){
      var that = this;

      that.setStateReload({
        filter: e.target.value,
        page: 1
      });
    },

    setStateReload: function(state){
      var that = this;
      that.setState(state, function(){
        if(that._timeout){
          clearTimeout(that._timeout);
        }
        that._timeout = setTimeout(that.load, 300);
      });
    },

    queryClicked: function(e){
      var that = this;
      e.preventDefault();
      this.setState({
        showQuery: !this.state.showQuery
      }, function(){
        that.props.query_popover.toggle();
      });
    },

    renderFilter: function(){
      var queryStyle = {display: 'block'};
      if(!this.state.showQuery){
        queryStyle.display = 'none';
      }
      var className = 'castle-filter-container';
      if(this.state.criterias.length > 0 || this.state.filter.length > 0){
        className += ' active-filter';
      }
      return D.div({ className: className}, [
        D.div({className: 'input-group input-group-sm filter-group'}, [
          D.input({ type: 'text', className: 'form-control', placeholder: 'Filter',
                    onChange: this.filterChanged, value: this.state.filter}),
          D.span({ className: "input-group-btn" }, [
            D.a({ href: "#", className: "btn btn-default", id: 'castle-query-filter',
                  ref: 'query_btn', onClick: this.queryClicked }, [
              D.span({ className: "glyphicon glyphicon-search"}),
              'Query'
            ])
          ])
        ]),
        D.div({ className: 'castle-content-browser-filter-popover',
                ref: 'query_popover', style: queryStyle})
      ]);
    },

    renderContent: function(){
      var that = this;
      return D.div({ className: 'castle-content-browser'}, [
        D.div({ className: 'row top'}, [
          D.div({ className: 'col-md-5 castle-breadcrumbs-container'}, that.renderBreadcrumbs()),
          D.div({ className: 'listing-type-selector col-md-3 col-md-offset-1'}, that.renderViewSelection()),
          D.div({ className: 'col-md-3'}, that.renderFilter()),
        ]),
        that.renderItems(),
        that.renderPaging()
      ]);
    },
    pageClicked: function(page, e){
      e.preventDefault();
      this.state.page = page;
      this.load();
    },

    changeView: function(view, e){
      e.preventDefault();
      this.setState({
        view: view
      });
    },

    renderViewSelection: function(){
      return [
        D.span({ className: 'label'}, 'View as:'),
        D.button({ className: 'plone-btn plone-btn-default',
                   disabled: this.state.view === 'table',
                   onClick: this.changeView.bind(this, 'table')}, D.span({
          className: 'glyphicon glyphicon-list'
        })),
        D.button({ className: 'plone-btn plone-btn-default',
                   disabled: this.state.view === 'image',
                   onClick: this.changeView.bind(this, 'image')}, D.span({
          className: 'glyphicon glyphicon-th-large'
        }))
      ];
    },

    getPageNumbers: function (currentPageNumber, totalPageCount) {
      var maxPageButtonCount = this.props.maxPageButtonCount;
      var maxAdditionalPageButtons = maxPageButtonCount - 4;
      var distanceToEnd = totalPageCount - currentPageNumber;
      //currentPageNumber is, ideally, the center
      var desiredOffsetFromCurrent = Math.floor( ( maxAdditionalPageButtons - 1 ) / 2 );
      var endOffsetCorrection = Math.max(desiredOffsetFromCurrent - distanceToEnd, 0);
      var startPageNumber = Math.max(
        currentPageNumber - desiredOffsetFromCurrent - endOffsetCorrection,
        1
      );
      var endPageNumber = Math.min(
        startPageNumber + maxAdditionalPageButtons,
        totalPageCount + 1
      );
      var pageNumbers = _.range(startPageNumber, endPageNumber);
      var pageButtonCount = pageNumbers.length;
      if ( totalPageCount <= pageButtonCount) {
        return pageNumbers;
      }
      if ( pageNumbers[ 0 ] !== 1 ) {
        pageNumbers[ 0 ] = 1;
        pageNumbers[ 1 ] = '...';
      }
      if ( pageNumbers[ pageButtonCount - 1 ] !== totalPageCount ) {
        pageNumbers[ pageButtonCount - 1 ] = totalPageCount;
        pageNumbers[ pageButtonCount - 2 ] = '...';
      }
      return pageNumbers;
    },

    getMapPageNumberToPageButtonFunction: function(getPagingButtonFunction){
      return function(pageNumber, index, pageNumbers){
        var isNumber = !!parseInt( pageNumber );
        return getPagingButtonFunction(
          isNumber ? pageNumber : Math.floor((pageNumbers[index - 1] + pageNumbers[index + 1]) / 2),
          pageNumber
        );
      }
    },

    getPagingButton: function ( staticPageStats, targetPageNumber, buttonText ) {
      var currentPageNumber = staticPageStats.currentPageNumber;
      var totalPageCount = staticPageStats.totalPageCount;
      var isNumber = !!parseInt( buttonText );
      var isCurrent = isNumber && ( currentPageNumber === targetPageNumber );
      var isDisabled = (
        isCurrent ||
        ( currentPageNumber === 1 && [ '<','«'].includes(buttonText)) ||
        (currentPageNumber === totalPageCount && ['>','»'].includes(buttonText))
      );
      var className = [].concat(
        isCurrent ? [ 'current' ] : [],
        isDisabled ? [ 'disabled' ] : []
      ).join( ' ' );
      var onClick = this.pageClicked.bind( this, targetPageNumber );
      var showToolTip = !isDisabled && [ '«', '<', '>', '»', '...' ].includes( buttonText );
      return D.li(
        Object.assign(
          {key: `page-${ buttonText }-${ targetPageNumber }`},
          showToolTip ? {title: targetPageNumber} : {},
          className ? { className } : {}
        ),
        D.a(
          Object.assign(
            {href: '#'},
            isDisabled ? {} : {onClick}
          ),
          buttonText
        )
      );
    },

    renderPaging: function(){
      var that = this;
      var batchSize = that.props.query.options.batchSize;
      var currentPageNumber = that.state.page;
      var totalResults = that.state.total;
      if ( totalResults <= batchSize){
        return '';
      }
      var totalPageCount = Math.ceil( totalResults / batchSize );
      var previousPageNumber = Math.max( 1, currentPageNumber - 1 );
      var nextPageNumber = Math.min( totalPageCount, currentPageNumber + 1 );
      var pageNumbers = that.getPageNumbers(currentPageNumber, totalPageCount);
      var getPagingButton = that.getPagingButton.bind(
        that,
        {currentPageNumber, totalPageCount}
      )
      return D.div(
        { className: 'pagination-centered'},
        D.ul(
          { className: 'castle-pagination pagination-sm pagination-centered'},
          [].concat(
            [getPagingButton( 1, '«' )],
            [getPagingButton( previousPageNumber, '<' )],
            pageNumbers.map(
              that.getMapPageNumberToPageButtonFunction(getPagingButton)
            ),
            [getPagingButton( nextPageNumber, '>' )],
            [getPagingButton( totalPageCount, '»' )]
          )
        )
      );
    },

    doneClicked: function(e){
      e.preventDefault();
      this.props.onSelectItems(this.state.selected);
      this.hide();
    },

    renderFooter: function(){
      var buttons = [D.button({ type: 'button', className: 'btn btn-default btn-danger',
                                onClick: this.hide }, 'Done')];
      if(this.props.multiple){
        buttons.push(D.button({
          type: 'button', className: 'btn btn-default btn-primary',
          onClick: this.doneClicked},
          'Select (' + this.state.selected.length + ')'));
      }
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'content-browser-modal',
        title: 'Select content',
        multiple: false,
        selectableTypes: null,
        onSelectItem: function(){},
        onSelectItems: function(){},
        baseCriteria: [],
        maxPageButtonCount: 11,
      });
    }
  });

  return ContentBrowserComponent;
});

/*!
 * Cropper v0.11.1
 * https://github.com/fengyuanchen/cropper
 *
 * Copyright (c) 2014-2015 Fengyuan Chen and contributors
 * Released under the MIT license
 *
 * Date: 2015-08-22T04:55:04.780Z
 */
!function(t){"function"==typeof define&&define.amd?define('castle-url/libs/cropper/dist/cropper.min',["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){"use strict";function i(t){return"number"==typeof t&&!isNaN(t)}function e(t){return"undefined"==typeof t}function h(t,e){var h=[];return i(e)&&h.push(e),h.slice.apply(t,h)}function s(t,i){var e=h(arguments,2);return function(){return t.apply(i,e.concat(h(arguments)))}}function o(t){var i=t.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i);return i&&(i[1]!==u.protocol||i[2]!==u.hostname||i[3]!==u.port)}function a(t){var i="timestamp="+(new Date).getTime();return t+(-1===t.indexOf("?")?"?":"&")+i}function n(t){var i,e=t.naturalWidth,h=t.naturalHeight;return e||(i=new Image,i.src=t.src,e=i.width,h=i.height),{naturalWidth:e,naturalHeight:h,aspectRatio:e/h}}function r(t){var e=[],h=t.rotate,s=t.scaleX,o=t.scaleY;return i(h)&&e.push("rotate("+h+"deg)"),i(s)&&i(o)&&e.push("scale("+s+","+o+")"),e.length?e.join(" "):"none"}function p(t,i){var e,h,s=st(t.degree)%180,o=(s>90?180-s:s)*Math.PI/180,a=ot(o),n=at(o),r=t.width,p=t.height,d=t.aspectRatio;return i?(e=r/(n+a/d),h=e/d):(e=r*n+p*a,h=r*a+p*n),{width:e,height:h}}function d(e,h){var s,o,a,n=t("<canvas>")[0],r=n.getContext("2d"),d=0,c=0,l=h.naturalWidth,g=h.naturalHeight,u=h.rotate,m=h.scaleX,f=h.scaleY,v=i(m)&&i(f)&&(1!==m||1!==f),x=i(u)&&0!==u,w=x||v,b=l,C=g;return v&&(s=l/2,o=g/2),x&&(a=p({width:l,height:g,degree:u}),b=a.width,C=a.height,s=a.width/2,o=a.height/2),n.width=b,n.height=C,w&&(d=-l/2,c=-g/2,r.save(),r.translate(s,o)),x&&r.rotate(u*Math.PI/180),v&&r.scale(m,f),r.drawImage(e,d,c,l,g),w&&r.restore(),n}function c(i,e){this.$element=t(i),this.options=t.extend({},c.DEFAULTS,t.isPlainObject(e)&&e),this.ready=!1,this.built=!1,this.complete=!1,this.rotated=!1,this.cropped=!1,this.disabled=!1,this.replaced=!1,this.isImg=!1,this.originalUrl="",this.canvas=null,this.cropBox=null,this.init()}var l=t(window),g=t(document),u=window.location,m="cropper",f="preview."+m,v="cropper-modal",x="cropper-hide",w="cropper-hidden",b="cropper-invisible",C="cropper-move",y="cropper-crop",$="cropper-disabled",B="cropper-bg",D="mousedown touchstart pointerdown MSPointerDown",W="mousemove touchmove pointermove MSPointerMove",T="mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel",H="wheel mousewheel DOMMouseScroll",k="dblclick",Y="load."+m,L="error."+m,M="resize."+m,X="build."+m,R="built."+m,z="cropstart."+m,I="cropmove."+m,E="cropend."+m,F="crop."+m,P="zoom."+m,O=/^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/,S="e",j="w",A="s",U="n",Z="se",_="sw",q="ne",N="nw",K="all",Q="crop",G="move",J="zoom",V="none",tt=t.isFunction(t("<canvas>")[0].getContext),it=Math.sqrt,et=Math.min,ht=Math.max,st=Math.abs,ot=Math.sin,at=Math.cos,nt=parseFloat,rt={};t.extend(rt,{init:function(){var t,i=this.$element;if(i.is("img")){if(this.isImg=!0,this.originalUrl=t=i.attr("src"),!t)return;t=i.prop("src")}else i.is("canvas")&&tt&&(t=i[0].toDataURL());this.load(t)},trigger:function(i,e){var h=t.Event(i,e);return this.$element.trigger(h),h.isDefaultPrevented()},load:function(i){var e,h,s=this.options,n=this.$element,r="";i&&(this.url=i,n.one(X,s.build),this.trigger(X)||(s.checkImageOrigin&&o(i)&&(r=' crossOrigin="anonymous"',n.prop("crossOrigin")||(e=a(i))),this.$clone=h=t("<img"+r+' src="'+(e||i)+'">'),this.isImg?n[0].complete?this.start():n.one(Y,t.proxy(this.start,this)):h.one(Y,t.proxy(this.start,this)).one(L,t.proxy(this.stop,this)).addClass(x).insertAfter(n)))},start:function(){this.image=n(this.isImg?this.$element[0]:this.$clone[0]),this.ready=!0,this.build()},stop:function(){this.$clone.remove(),this.$clone=null}}),t.extend(rt,{build:function(){var i,e,h,s=this.options,o=this.$element,a=this.$clone;this.ready&&(this.built&&this.unbuild(),this.$container=o.parent(),this.$cropper=i=t(c.TEMPLATE),this.$canvas=i.find(".cropper-canvas").append(a),this.$dragBox=i.find(".cropper-drag-box"),this.$cropBox=e=i.find(".cropper-crop-box"),this.$viewBox=i.find(".cropper-view-box"),this.$face=h=e.find(".cropper-face"),o.addClass(w).after(i),this.isImg||a.removeClass(x),this.initPreview(),this.bind(),s.aspectRatio=nt(s.aspectRatio)||0/0,s.autoCrop?(this.cropped=!0,s.modal&&this.$dragBox.addClass(v)):e.addClass(w),s.guides||e.find(".cropper-dashed").addClass(w),s.center||e.find(".cropper-center").addClass(w),s.cropBoxMovable&&h.addClass(C).data("action",K),s.highlight||h.addClass(b),s.background&&i.addClass(B),s.cropBoxResizable||e.find(".cropper-line, .cropper-point").addClass(w),this.setDragMode(s.dragCrop?Q:s.movable?G:V),this.render(),this.built=!0,this.setData(s.data),o.one(R,s.built),setTimeout(t.proxy(function(){this.trigger(R),this.complete=!0},this),0))},unbuild:function(){this.built&&(this.built=!1,this.initialImage=null,this.initialCanvas=null,this.initialCropBox=null,this.container=null,this.canvas=null,this.cropBox=null,this.unbind(),this.resetPreview(),this.$preview=null,this.$viewBox=null,this.$cropBox=null,this.$dragBox=null,this.$canvas=null,this.$container=null,this.$cropper.remove(),this.$cropper=null)}}),t.extend(rt,{render:function(){this.initContainer(),this.initCanvas(),this.initCropBox(),this.renderCanvas(),this.cropped&&this.renderCropBox()},initContainer:function(){var t=this.options,i=this.$element,e=this.$container,h=this.$cropper;h.addClass(w),i.removeClass(w),h.css(this.container={width:ht(e.width(),nt(t.minContainerWidth)||200),height:ht(e.height(),nt(t.minContainerHeight)||100)}),i.addClass(w),h.removeClass(w)},initCanvas:function(){var i=this.container,e=i.width,h=i.height,s=this.image,o=s.aspectRatio,a={aspectRatio:o,width:e,height:h};h*o>e?a.height=e/o:a.width=h*o,a.oldLeft=a.left=(e-a.width)/2,a.oldTop=a.top=(h-a.height)/2,this.canvas=a,this.limitCanvas(!0,!0),this.initialImage=t.extend({},s),this.initialCanvas=t.extend({},a)},limitCanvas:function(i,e){var h,s,o=this.options,a=o.strict,n=this.container,r=n.width,p=n.height,d=this.canvas,c=d.aspectRatio,l=this.cropBox,g=this.cropped&&l,u=this.initialCanvas||d,m=u.width,f=u.height;i&&(h=nt(o.minCanvasWidth)||0,s=nt(o.minCanvasHeight)||0,h?(a&&(h=ht(g?l.width:m,h)),s=h/c):s?(a&&(s=ht(g?l.height:f,s)),h=s*c):a&&(g?(h=l.width,s=l.height,s*c>h?h=s*c:s=h/c):(h=m,s=f)),t.extend(d,{minWidth:h,minHeight:s,maxWidth:1/0,maxHeight:1/0})),e&&(a?g?(d.minLeft=et(l.left,l.left+l.width-d.width),d.minTop=et(l.top,l.top+l.height-d.height),d.maxLeft=l.left,d.maxTop=l.top):(d.minLeft=et(0,r-d.width),d.minTop=et(0,p-d.height),d.maxLeft=ht(0,r-d.width),d.maxTop=ht(0,p-d.height)):(d.minLeft=-d.width,d.minTop=-d.height,d.maxLeft=r,d.maxTop=p))},renderCanvas:function(t){var i,e,h=this.options,s=this.canvas,o=this.image;this.rotated&&(this.rotated=!1,e=p({width:o.width,height:o.height,degree:o.rotate}),i=e.width/e.height,i!==s.aspectRatio&&(s.left-=(e.width-s.width)/2,s.top-=(e.height-s.height)/2,s.width=e.width,s.height=e.height,s.aspectRatio=i,this.limitCanvas(!0,!1))),(s.width>s.maxWidth||s.width<s.minWidth)&&(s.left=s.oldLeft),(s.height>s.maxHeight||s.height<s.minHeight)&&(s.top=s.oldTop),s.width=et(ht(s.width,s.minWidth),s.maxWidth),s.height=et(ht(s.height,s.minHeight),s.maxHeight),this.limitCanvas(!1,!0),s.oldLeft=s.left=et(ht(s.left,s.minLeft),s.maxLeft),s.oldTop=s.top=et(ht(s.top,s.minTop),s.maxTop),this.$canvas.css({width:s.width,height:s.height,left:s.left,top:s.top}),this.renderImage(),this.cropped&&h.strict&&this.limitCropBox(!0,!0),t&&this.output()},renderImage:function(i){var e,h=this.canvas,s=this.image;s.rotate&&(e=p({width:h.width,height:h.height,degree:s.rotate,aspectRatio:s.aspectRatio},!0)),t.extend(s,e?{width:e.width,height:e.height,left:(h.width-e.width)/2,top:(h.height-e.height)/2}:{width:h.width,height:h.height,left:0,top:0}),this.$clone.css({width:s.width,height:s.height,marginLeft:s.left,marginTop:s.top,transform:r(s)}),i&&this.output()},initCropBox:function(){var i=this.options,e=this.canvas,h=i.aspectRatio,s=nt(i.autoCropArea)||.8,o={width:e.width,height:e.height};h&&(e.height*h>e.width?o.height=o.width/h:o.width=o.height*h),this.cropBox=o,this.limitCropBox(!0,!0),o.width=et(ht(o.width,o.minWidth),o.maxWidth),o.height=et(ht(o.height,o.minHeight),o.maxHeight),o.width=ht(o.minWidth,o.width*s),o.height=ht(o.minHeight,o.height*s),o.oldLeft=o.left=e.left+(e.width-o.width)/2,o.oldTop=o.top=e.top+(e.height-o.height)/2,this.initialCropBox=t.extend({},o)},limitCropBox:function(t,i){var e,h,s=this.options,o=s.strict,a=this.container,n=a.width,r=a.height,p=this.canvas,d=this.cropBox,c=s.aspectRatio;t&&(e=nt(s.minCropBoxWidth)||0,h=nt(s.minCropBoxHeight)||0,d.minWidth=et(n,e),d.minHeight=et(r,h),d.maxWidth=et(n,o?p.width:n),d.maxHeight=et(r,o?p.height:r),c&&(d.maxHeight*c>d.maxWidth?(d.minHeight=d.minWidth/c,d.maxHeight=d.maxWidth/c):(d.minWidth=d.minHeight*c,d.maxWidth=d.maxHeight*c)),d.minWidth=et(d.maxWidth,d.minWidth),d.minHeight=et(d.maxHeight,d.minHeight)),i&&(o?(d.minLeft=ht(0,p.left),d.minTop=ht(0,p.top),d.maxLeft=et(n,p.left+p.width)-d.width,d.maxTop=et(r,p.top+p.height)-d.height):(d.minLeft=0,d.minTop=0,d.maxLeft=n-d.width,d.maxTop=r-d.height))},renderCropBox:function(){var t=this.options,i=this.container,e=i.width,h=i.height,s=this.cropBox;(s.width>s.maxWidth||s.width<s.minWidth)&&(s.left=s.oldLeft),(s.height>s.maxHeight||s.height<s.minHeight)&&(s.top=s.oldTop),s.width=et(ht(s.width,s.minWidth),s.maxWidth),s.height=et(ht(s.height,s.minHeight),s.maxHeight),this.limitCropBox(!1,!0),s.oldLeft=s.left=et(ht(s.left,s.minLeft),s.maxLeft),s.oldTop=s.top=et(ht(s.top,s.minTop),s.maxTop),t.movable&&t.cropBoxMovable&&this.$face.data("action",s.width===e&&s.height===h?G:K),this.$cropBox.css({width:s.width,height:s.height,left:s.left,top:s.top}),this.cropped&&t.strict&&this.limitCanvas(!0,!0),this.disabled||this.output()},output:function(){this.preview(),this.complete?this.trigger(F,this.getData()):this.built||this.$element.one(R,t.proxy(function(){this.trigger(F,this.getData())},this))}}),t.extend(rt,{initPreview:function(){var i=this.url;this.$preview=t(this.options.preview),this.$viewBox.html('<img src="'+i+'">'),this.$preview.each(function(){var e=t(this);e.data(f,{width:e.width(),height:e.height(),original:e.html()}),e.html('<img src="'+i+'" style="display:block;width:100%;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;image-orientation:0deg!important">')})},resetPreview:function(){this.$preview.each(function(){var i=t(this);i.html(i.data(f).original).removeData(f)})},preview:function(){var i=this.image,e=this.canvas,h=this.cropBox,s=i.width,o=i.height,a=h.left-e.left-i.left,n=h.top-e.top-i.top;this.cropped&&!this.disabled&&(this.$viewBox.find("img").css({width:s,height:o,marginLeft:-a,marginTop:-n,transform:r(i)}),this.$preview.each(function(){var e=t(this),p=e.data(f),d=p.width/h.width,c=p.width,l=h.height*d;l>p.height&&(d=p.height/h.height,c=h.width*d,l=p.height),e.width(c).height(l).find("img").css({width:s*d,height:o*d,marginLeft:-a*d,marginTop:-n*d,transform:r(i)})}))}}),t.extend(rt,{bind:function(){var i=this.options,e=this.$element,h=this.$cropper;t.isFunction(i.cropstart)&&e.on(z,i.cropstart),t.isFunction(i.cropmove)&&e.on(I,i.cropmove),t.isFunction(i.cropend)&&e.on(E,i.cropend),t.isFunction(i.crop)&&e.on(F,i.crop),t.isFunction(i.zoom)&&e.on(P,i.zoom),h.on(D,t.proxy(this.cropStart,this)),i.zoomable&&i.mouseWheelZoom&&h.on(H,t.proxy(this.wheel,this)),i.doubleClickToggle&&h.on(k,t.proxy(this.dblclick,this)),g.on(W,this._cropMove=s(this.cropMove,this)).on(T,this._cropEnd=s(this.cropEnd,this)),i.responsive&&l.on(M,this._resize=s(this.resize,this))},unbind:function(){var i=this.options,e=this.$element,h=this.$cropper;t.isFunction(i.cropstart)&&e.off(z,i.cropstart),t.isFunction(i.cropmove)&&e.off(I,i.cropmove),t.isFunction(i.cropend)&&e.off(E,i.cropend),t.isFunction(i.crop)&&e.off(F,i.crop),t.isFunction(i.zoom)&&e.off(P,i.zoom),h.off(D,this.cropStart),i.zoomable&&i.mouseWheelZoom&&h.off(H,this.wheel),i.doubleClickToggle&&h.off(k,this.dblclick),g.off(W,this._cropMove).off(T,this._cropEnd),i.responsive&&l.off(M,this._resize)}}),t.extend(rt,{resize:function(){var i,e,h,s=this.$container,o=this.container;!this.disabled&&o&&(h=s.width()/o.width,(1!==h||s.height()!==o.height)&&(i=this.getCanvasData(),e=this.getCropBoxData(),this.render(),this.setCanvasData(t.each(i,function(t,e){i[t]=e*h})),this.setCropBoxData(t.each(e,function(t,i){e[t]=i*h}))))},dblclick:function(){this.disabled||this.setDragMode(this.$dragBox.hasClass(y)?G:Q)},wheel:function(t){var i=t.originalEvent,e=i,h=nt(this.options.wheelZoomRatio)||.1,s=1;this.disabled||(t.preventDefault(),e.deltaY?s=e.deltaY>0?1:-1:e.wheelDelta?s=-e.wheelDelta/120:e.detail&&(s=e.detail>0?1:-1),this.zoom(-s*h,i))},cropStart:function(i){var e,h,s=this.options,o=i.originalEvent,a=o&&o.touches,n=i;if(!this.disabled){if(a){if(e=a.length,e>1){if(!s.zoomable||!s.touchDragZoom||2!==e)return;n=a[1],this.startX2=n.pageX,this.startY2=n.pageY,h=J}n=a[0]}if(h=h||t(n.target).data("action"),O.test(h)){if(this.trigger(z,{originalEvent:o,action:h}))return;i.preventDefault(),this.action=h,this.cropping=!1,this.startX=n.pageX||o&&o.pageX,this.startY=n.pageY||o&&o.pageY,h===Q&&(this.cropping=!0,this.$dragBox.addClass(v))}}},cropMove:function(t){var i,e=this.options,h=t.originalEvent,s=h&&h.touches,o=t,a=this.action;if(!this.disabled){if(s){if(i=s.length,i>1){if(!e.zoomable||!e.touchDragZoom||2!==i)return;o=s[1],this.endX2=o.pageX,this.endY2=o.pageY}o=s[0]}if(a){if(this.trigger(I,{originalEvent:h,action:a}))return;t.preventDefault(),this.endX=o.pageX||h&&h.pageX,this.endY=o.pageY||h&&h.pageY,this.change(o.shiftKey,a===J?h:null)}}},cropEnd:function(t){var i=t.originalEvent,e=this.action;this.disabled||e&&(t.preventDefault(),this.cropping&&(this.cropping=!1,this.$dragBox.toggleClass(v,this.cropped&&this.options.modal)),this.action="",this.trigger(E,{originalEvent:i,action:e}))}}),t.extend(rt,{change:function(t,i){var e,h,s=this.options,o=s.aspectRatio,a=this.action,n=this.container,r=this.canvas,p=this.cropBox,d=p.width,c=p.height,l=p.left,g=p.top,u=l+d,m=g+c,f=0,v=0,x=n.width,b=n.height,C=!0;switch(!o&&t&&(o=d&&c?d/c:1),s.strict&&(f=p.minLeft,v=p.minTop,x=f+et(n.width,r.width),b=v+et(n.height,r.height)),h={x:this.endX-this.startX,y:this.endY-this.startY},o&&(h.X=h.y*o,h.Y=h.x/o),a){case K:l+=h.x,g+=h.y;break;case S:if(h.x>=0&&(u>=x||o&&(v>=g||m>=b))){C=!1;break}d+=h.x,o&&(c=d/o,g-=h.Y/2),0>d&&(a=j,d=0);break;case U:if(h.y<=0&&(v>=g||o&&(f>=l||u>=x))){C=!1;break}c-=h.y,g+=h.y,o&&(d=c*o,l+=h.X/2),0>c&&(a=A,c=0);break;case j:if(h.x<=0&&(f>=l||o&&(v>=g||m>=b))){C=!1;break}d-=h.x,l+=h.x,o&&(c=d/o,g+=h.Y/2),0>d&&(a=S,d=0);break;case A:if(h.y>=0&&(m>=b||o&&(f>=l||u>=x))){C=!1;break}c+=h.y,o&&(d=c*o,l-=h.X/2),0>c&&(a=U,c=0);break;case q:if(o){if(h.y<=0&&(v>=g||u>=x)){C=!1;break}c-=h.y,g+=h.y,d=c*o}else h.x>=0?x>u?d+=h.x:h.y<=0&&v>=g&&(C=!1):d+=h.x,h.y<=0?g>v&&(c-=h.y,g+=h.y):(c-=h.y,g+=h.y);0>d&&0>c?(a=_,c=0,d=0):0>d?(a=N,d=0):0>c&&(a=Z,c=0);break;case N:if(o){if(h.y<=0&&(v>=g||f>=l)){C=!1;break}c-=h.y,g+=h.y,d=c*o,l+=h.X}else h.x<=0?l>f?(d-=h.x,l+=h.x):h.y<=0&&v>=g&&(C=!1):(d-=h.x,l+=h.x),h.y<=0?g>v&&(c-=h.y,g+=h.y):(c-=h.y,g+=h.y);0>d&&0>c?(a=Z,c=0,d=0):0>d?(a=q,d=0):0>c&&(a=_,c=0);break;case _:if(o){if(h.x<=0&&(f>=l||m>=b)){C=!1;break}d-=h.x,l+=h.x,c=d/o}else h.x<=0?l>f?(d-=h.x,l+=h.x):h.y>=0&&m>=b&&(C=!1):(d-=h.x,l+=h.x),h.y>=0?b>m&&(c+=h.y):c+=h.y;0>d&&0>c?(a=q,c=0,d=0):0>d?(a=Z,d=0):0>c&&(a=N,c=0);break;case Z:if(o){if(h.x>=0&&(u>=x||m>=b)){C=!1;break}d+=h.x,c=d/o}else h.x>=0?x>u?d+=h.x:h.y>=0&&m>=b&&(C=!1):d+=h.x,h.y>=0?b>m&&(c+=h.y):c+=h.y;0>d&&0>c?(a=N,c=0,d=0):0>d?(a=_,d=0):0>c&&(a=q,c=0);break;case G:r.left+=h.x,r.top+=h.y,this.renderCanvas(!0),C=!1;break;case J:this.zoom(function(t,i,e,h){var s=it(t*t+i*i),o=it(e*e+h*h);return(o-s)/s}(st(this.startX-this.startX2),st(this.startY-this.startY2),st(this.endX-this.endX2),st(this.endY-this.endY2)),i),this.startX2=this.endX2,this.startY2=this.endY2,C=!1;break;case Q:h.x&&h.y&&(e=this.$cropper.offset(),l=this.startX-e.left,g=this.startY-e.top,d=p.minWidth,c=p.minHeight,h.x>0?h.y>0?a=Z:(a=q,g-=c):h.y>0?(a=_,l-=d):(a=N,l-=d,g-=c),this.cropped||(this.cropped=!0,this.$cropBox.removeClass(w)))}C&&(p.width=d,p.height=c,p.left=l,p.top=g,this.action=a,this.renderCropBox()),this.startX=this.endX,this.startY=this.endY}}),t.extend(rt,{crop:function(){this.built&&!this.disabled&&(this.cropped||(this.cropped=!0,this.limitCropBox(!0,!0),this.options.modal&&this.$dragBox.addClass(v),this.$cropBox.removeClass(w)),this.setCropBoxData(this.initialCropBox))},reset:function(){this.built&&!this.disabled&&(this.image=t.extend({},this.initialImage),this.canvas=t.extend({},this.initialCanvas),this.cropBox=t.extend({},this.initialCropBox),this.renderCanvas(),this.cropped&&this.renderCropBox())},clear:function(){this.cropped&&!this.disabled&&(t.extend(this.cropBox,{left:0,top:0,width:0,height:0}),this.cropped=!1,this.renderCropBox(),this.limitCanvas(),this.renderCanvas(),this.$dragBox.removeClass(v),this.$cropBox.addClass(w))},replace:function(t){!this.disabled&&t&&(this.isImg&&this.$element.attr("src",t),this.options.data=null,this.load(t))},enable:function(){this.built&&(this.disabled=!1,this.$cropper.removeClass($))},disable:function(){this.built&&(this.disabled=!0,this.$cropper.addClass($))},destroy:function(){var t=this.$element;this.ready?(this.isImg&&t.attr("src",this.originalUrl),this.unbuild(),t.removeClass(w)):this.isImg?t.off(Y,this.start):this.$clone&&this.$clone.remove(),t.removeData(m)},move:function(t,h){var s=this.canvas;e(h)&&(h=t),t=nt(t),h=nt(h),this.built&&!this.disabled&&this.options.movable&&(s.left+=i(t)?t:0,s.top+=i(h)?h:0,this.renderCanvas(!0))},zoom:function(t,i){var e,h,s=this.canvas;if(t=nt(t),t&&this.built&&!this.disabled&&this.options.zoomable){if(this.trigger(P,{originalEvent:i,ratio:t}))return;t=0>t?1/(1-t):1+t,e=s.width*t,h=s.height*t,s.left-=(e-s.width)/2,s.top-=(h-s.height)/2,s.width=e,s.height=h,this.renderCanvas(!0),this.setDragMode(G)}},rotate:function(t){var i=this.image,e=i.rotate||0;t=nt(t)||0,this.built&&!this.disabled&&this.options.rotatable&&(i.rotate=(e+t)%360,this.rotated=!0,this.renderCanvas(!0))},scale:function(t,h){var s=this.image;e(h)&&(h=t),t=nt(t),h=nt(h),this.built&&!this.disabled&&this.options.scalable&&(s.scaleX=i(t)?t:1,s.scaleY=i(h)?h:1,this.renderImage(!0))},getData:function(i){var e,h,s=this.options,o=this.image,a=this.canvas,n=this.cropBox;return this.built&&this.cropped?(h={x:n.left-a.left,y:n.top-a.top,width:n.width,height:n.height},e=o.width/o.naturalWidth,t.each(h,function(t,s){s/=e,h[t]=i?Math.round(s):s})):h={x:0,y:0,width:0,height:0},s.rotatable&&(h.rotate=o.rotate||0),s.scalable&&(h.scaleX=o.scaleX||1,h.scaleY=o.scaleY||1),h},setData:function(e){var h,s=this.image,o=this.canvas,a={};t.isFunction(e)&&(e=e.call(this.$element)),this.built&&!this.disabled&&t.isPlainObject(e)&&(i(e.rotate)&&e.rotate!==s.rotate&&this.options.rotatable&&(s.rotate=e.rotate,this.rotated=!0,this.renderCanvas(!0)),h=s.width/s.naturalWidth,i(e.x)&&(a.left=e.x*h+o.left),i(e.y)&&(a.top=e.y*h+o.top),i(e.width)&&(a.width=e.width*h),i(e.height)&&(a.height=e.height*h),this.setCropBoxData(a))},getContainerData:function(){return this.built?this.container:{}},getImageData:function(){return this.ready?this.image:{}},getCanvasData:function(){var t,i=this.canvas;return this.built&&(t={left:i.left,top:i.top,width:i.width,height:i.height}),t||{}},setCanvasData:function(e){var h=this.canvas,s=h.aspectRatio;t.isFunction(e)&&(e=e.call(this.$element)),this.built&&!this.disabled&&t.isPlainObject(e)&&(i(e.left)&&(h.left=e.left),i(e.top)&&(h.top=e.top),i(e.width)?(h.width=e.width,h.height=e.width/s):i(e.height)&&(h.height=e.height,h.width=e.height*s),this.renderCanvas(!0))},getCropBoxData:function(){var t,i=this.cropBox;return this.built&&this.cropped&&(t={left:i.left,top:i.top,width:i.width,height:i.height}),t||{}},setCropBoxData:function(e){var h,s,o=this.cropBox,a=this.options.aspectRatio;t.isFunction(e)&&(e=e.call(this.$element)),this.built&&this.cropped&&!this.disabled&&t.isPlainObject(e)&&(i(e.left)&&(o.left=e.left),i(e.top)&&(o.top=e.top),i(e.width)&&e.width!==o.width&&(h=!0,o.width=e.width),i(e.height)&&e.height!==o.height&&(s=!0,o.height=e.height),a&&(h?o.height=o.width/a:s&&(o.width=o.height*a)),this.renderCropBox())},getCroppedCanvas:function(i){var e,h,s,o,a,n,r,p,c,l,g;return this.built&&this.cropped&&tt?(t.isPlainObject(i)||(i={}),g=this.getData(),e=g.width,h=g.height,p=e/h,t.isPlainObject(i)&&(a=i.width,n=i.height,a?(n=a/p,r=a/e):n&&(a=n*p,r=n/h)),s=a||e,o=n||h,c=t("<canvas>")[0],c.width=s,c.height=o,l=c.getContext("2d"),i.fillColor&&(l.fillStyle=i.fillColor,l.fillRect(0,0,s,o)),l.drawImage.apply(l,function(){var t,i,s,o,a,n,p=d(this.$clone[0],this.image),c=p.width,l=p.height,u=[p],m=g.x,f=g.y;return-e>=m||m>c?m=t=s=a=0:0>=m?(s=-m,m=0,t=a=et(c,e+m)):c>=m&&(s=0,t=a=et(e,c-m)),0>=t||-h>=f||f>l?f=i=o=n=0:0>=f?(o=-f,f=0,i=n=et(l,h+f)):l>=f&&(o=0,i=n=et(h,l-f)),u.push(m,f,t,i),r&&(s*=r,o*=r,a*=r,n*=r),a>0&&n>0&&u.push(s,o,a,n),u}.call(this)),c):void 0},setAspectRatio:function(t){var i=this.options;this.disabled||e(t)||(i.aspectRatio=nt(t)||0/0,this.built&&(this.initCropBox(),this.cropped&&this.renderCropBox()))},setDragMode:function(t){var i,e,h=this.options;this.ready&&!this.disabled&&(i=h.dragCrop&&t===Q,e=h.movable&&t===G,t=i||e?t:V,this.$dragBox.data("action",t).toggleClass(y,i).toggleClass(C,e),h.cropBoxMovable||this.$face.data("action",t).toggleClass(y,i).toggleClass(C,e))}}),t.extend(c.prototype,rt),c.DEFAULTS={aspectRatio:0/0,data:null,preview:"",strict:!0,responsive:!0,checkImageOrigin:!0,modal:!0,guides:!0,center:!0,highlight:!0,background:!0,autoCrop:!0,autoCropArea:.8,dragCrop:!0,movable:!0,rotatable:!0,scalable:!0,zoomable:!0,mouseWheelZoom:!0,wheelZoomRatio:.1,touchDragZoom:!0,cropBoxMovable:!0,cropBoxResizable:!0,doubleClickToggle:!0,minCanvasWidth:0,minCanvasHeight:0,minCropBoxWidth:0,minCropBoxHeight:0,minContainerWidth:200,minContainerHeight:100,build:null,built:null,cropstart:null,cropmove:null,cropend:null,crop:null,zoom:null},c.setDefaults=function(i){t.extend(c.DEFAULTS,i)},c.TEMPLATE='<div class="cropper-container"><div class="cropper-canvas"></div><div class="cropper-drag-box"></div><div class="cropper-crop-box"><span class="cropper-view-box"></span><span class="cropper-dashed dashed-h"></span><span class="cropper-dashed dashed-v"></span><span class="cropper-center"></span><span class="cropper-face"></span><span class="cropper-line line-e" data-action="e"></span><span class="cropper-line line-n" data-action="n"></span><span class="cropper-line line-w" data-action="w"></span><span class="cropper-line line-s" data-action="s"></span><span class="cropper-point point-e" data-action="e"></span><span class="cropper-point point-n" data-action="n"></span><span class="cropper-point point-w" data-action="w"></span><span class="cropper-point point-s" data-action="s"></span><span class="cropper-point point-ne" data-action="ne"></span><span class="cropper-point point-nw" data-action="nw"></span><span class="cropper-point point-sw" data-action="sw"></span><span class="cropper-point point-se" data-action="se"></span></div></div>',c.other=t.fn.cropper,t.fn.cropper=function(i){var s,o=h(arguments,1);return this.each(function(){var e,h=t(this),a=h.data(m);if(!a){if(/destroy/.test(i))return;h.data(m,a=new c(this,i))}"string"==typeof i&&t.isFunction(e=a[i])&&(s=e.apply(a,o))}),e(s)?this:s},t.fn.cropper.Constructor=c,t.fn.cropper.setDefaults=c.setDefaults,t.fn.cropper.noConflict=function(){return t.fn.cropper=c.other,this}});
/* global mOxie */

define('castle-url/components/image-editor',[
  'jquery',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/libs/cropper/dist/cropper.min'
], function($, R, utils) {
  'use strict';
  var D = R.DOM;

  var Cropper = R.createClass({
    componentDidMount: function(){
      $(this.refs.img.getDOMNode()).cropper(this.props.cropperOptions);
    },
    render: function(){
      return D.img({src: this.props.image, ref: 'img'});
    },
    getDefaultProps: function(){
      return {
        cropperOptions: {
          zoomOnWheel: false
        }
      };
    }
  });

  var CropperContainer = R.createClass({
    getInitialState: function(){
      return {
        image: null
      };
    },
    componentDidMount: function(){
      var that = this;
      var img = new mOxie.Image();
      utils.loading.show();
      img.onload = function() {
        utils.loading.hide();
        that.setState({
          image: img.getAsDataURL('image/png')
        });
      };
      img.load(that.props.file);
    },
    cancelClicked: function(e){
      e.preventDefault();
      this.props.onCancel();
    },
    saveClicked: function(e){
      var that = this;
      e.preventDefault();
      utils.loading.show();
      var canvas = $(this.refs.cropper.refs.img.getDOMNode()).cropper('getCroppedCanvas');
      var dataUrl = canvas.toDataURL();
      var img = new mOxie.Image();
      img.onload = function() {
        utils.loading.hide();
        var blob = img.getAsBlob('image/png');
        that.props.onSave(blob, img);
      };
      img.load(dataUrl);
    },
    rotateLeft: function(e){
      e.preventDefault();
      $(this.refs.cropper.refs.img.getDOMNode()).cropper('rotate', -90);
    },
    rotateRight: function(e){
      e.preventDefault();
      $(this.refs.cropper.refs.img.getDOMNode()).cropper('rotate', 90);
    },
    render: function(){
      var img = '';
      if(this.state.image){
        img = R.createElement(Cropper, { image: this.state.image, ref: 'cropper'});
      }
      return D.div({ className: 'castle-cropper-container', ref: 'container'}, [
        img,
        D.div({ className: 'plone-btn-group'}, [

          D.button({ className: 'plone-btn plone-btn-default castle-btn-rotate-left', onClick: this.rotateLeft}, 'Rotate Left'),
          D.button({ className: 'plone-btn plone-btn-default castle-btn-rotate-right', onClick: this.rotateRight}, 'Rotate Right'),
          D.button({ className: 'plone-btn plone-btn-default castle-btn-cancel', onClick: this.cancelClicked}, 'Cancel'),
          D.button({ className: 'plone-btn plone-btn-default castle-btn-save', onClick: this.saveClicked}, 'Save')
        ])
      ]);
    },
    getDefaultProps: function(){
      return {
        onCancel: function(){},
        onSave: function(){}
      };
    }
  });

  return CropperContainer;
});

define('castle-url/components/image-focal-point-selector',[
  'jquery',
  'castle-url/libs/react/react.min'
], function($, R) {
  'use strict';
  var D = R.DOM;

  var FocalPointSelector = R.createClass({
    getDefaultProps: function(){
      return {
        enabled: true,
        readOnly: false,
        url: null,
        width: '',
        fullWidth: '',
        height: '',
        fullHeight: '',
        focalPoint: [0, 0],
        pointerOffsetX: 12,
        pointerOffsetY: 12,
        onFocalSet: function(){}
      };
    },

    previewClicked: function(e){
      var offset = $(this.refs.previewImage.getDOMNode()).offset();
      var fpX = (e.pageX - offset.left) / (this.props.width / this.props.fullWidth);
      fpX = Math.min(this.props.fullWidth,  Math.max(fpX,0));
      var fpY = (e.pageY - offset.top) / (this.props.height / this.props.fullHeight);
      fpY = Math.min(this.props.fullHeight,  Math.max(fpY,0));
      this.props.onFocalSet([fpX, fpY]);
    },

    render: function(){
      var centerPoint = '';

      if(this.props.enabled){
        centerPoint = D.div({
          className: 'focalpoint-image-center'+(this.props.readOnly?' focalpoint-disabled':''),
          style: {
            left: ((this.props.width / this.props.fullWidth) * this.props.focalPoint[0]) - this.props.pointerOffsetX,
            top: ((this.props.height / this.props.fullHeight) * this.props.focalPoint[1]) - this.props.pointerOffsetY
          } });
      }
      return D.div({ className: 'focalpoint-image-container', onClick: this.previewClicked }, [
        centerPoint,
        D.img({ src: this.props.url, ref: 'previewImage'})
      ]);
    }
  });

  return FocalPointSelector;
});

;var MXI_DEBUG = true;
/**
 * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill
 * v1.4.1
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 *
 * Date: 2014-08-05
 */
/**
 * Compiled inline version. (Library mode)
 */

/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
/*globals $code */

(function(exports, undefined) {
	"use strict";

	var modules = {};

	function require(ids, callback) {
		var module, defs = [];

		for (var i = 0; i < ids.length; ++i) {
			module = modules[ids[i]] || resolve(ids[i]);
			if (!module) {
				throw 'module definition dependecy not found: ' + ids[i];
			}

			defs.push(module);
		}

		callback.apply(null, defs);
	}

	function define(id, dependencies, definition) {
		if (typeof id !== 'string') {
			throw 'invalid module definition, module id must be defined and be a string';
		}

		if (dependencies === undefined) {
			throw 'invalid module definition, dependencies must be specified';
		}

		if (definition === undefined) {
			throw 'invalid module definition, definition function must be specified';
		}

		require(dependencies, function() {
			modules[id] = definition.apply(null, arguments);
		});
	}

	function defined(id) {
		return !!modules[id];
	}

	function resolve(id) {
		var target = exports;
		var fragments = id.split(/[.\/]/);

		for (var fi = 0; fi < fragments.length; ++fi) {
			if (!target[fragments[fi]]) {
				return;
			}

			target = target[fragments[fi]];
		}

		return target;
	}

	function expose(ids) {
		for (var i = 0; i < ids.length; i++) {
			var target = exports;
			var id = ids[i];
			var fragments = id.split(/[.\/]/);

			for (var fi = 0; fi < fragments.length - 1; ++fi) {
				if (target[fragments[fi]] === undefined) {
					target[fragments[fi]] = {};
				}

				target = target[fragments[fi]];
			}

			target[fragments[fragments.length - 1]] = modules[id];
		}
	}

// Included from: src/javascript/core/utils/Basic.js

/**
 * Basic.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/core/utils/Basic', [], function() {
	/**
	Gets the true type of the built-in object (better version of typeof).
	@author Angus Croll (http://javascriptweblog.wordpress.com/)

	@method typeOf
	@for Utils
	@static
	@param {Object} o Object to check.
	@return {String} Object [[Class]]
	*/
	var typeOf = function(o) {
		var undef;

		if (o === undef) {
			return 'undefined';
		} else if (o === null) {
			return 'null';
		} else if (o.nodeType) {
			return 'node';
		}

		// the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8
		return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
	};
		
	/**
	Extends the specified object with another object.

	@method extend
	@static
	@param {Object} target Object to extend.
	@param {Object} [obj]* Multiple objects to extend with.
	@return {Object} Same as target, the extended object.
	*/
	var extend = function(target) {
		var undef;

		each(arguments, function(arg, i) {
			if (i > 0) {
				each(arg, function(value, key) {
					if (value !== undef) {
						if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) {
							extend(target[key], value);
						} else {
							target[key] = value;
						}
					}
				});
			}
		});
		return target;
	};
		
	/**
	Executes the callback function for each item in array/object. If you return false in the
	callback it will break the loop.

	@method each
	@static
	@param {Object} obj Object to iterate.
	@param {function} callback Callback function to execute for each item.
	*/
	var each = function(obj, callback) {
		var length, key, i, undef;

		if (obj) {
			if (typeOf(obj.length) === 'number') { // it might be Array, FileList or even arguments object
				// Loop array items
				for (i = 0, length = obj.length; i < length; i++) {
					if (callback(obj[i], i) === false) {
						return;
					}
				}
			} else if (typeOf(obj) === 'object') {
				// Loop object items
				for (key in obj) {
					if (obj.hasOwnProperty(key)) {
						if (callback(obj[key], key) === false) {
							return;
						}
					}
				}
			}
		}
	};

	/**
	Checks if object is empty.
	
	@method isEmptyObj
	@static
	@param {Object} o Object to check.
	@return {Boolean}
	*/
	var isEmptyObj = function(obj) {
		var prop;

		if (!obj || typeOf(obj) !== 'object') {
			return true;
		}

		for (prop in obj) {
			return false;
		}

		return true;
	};

	/**
	Recieve an array of functions (usually async) to call in sequence, each  function
	receives a callback as first argument that it should call, when it completes. Finally,
	after everything is complete, main callback is called. Passing truthy value to the
	callback as a first argument will interrupt the sequence and invoke main callback
	immediately.

	@method inSeries
	@static
	@param {Array} queue Array of functions to call in sequence
	@param {Function} cb Main callback that is called in the end, or in case of error
	*/
	var inSeries = function(queue, cb) {
		var i = 0, length = queue.length;

		if (typeOf(cb) !== 'function') {
			cb = function() {};
		}

		if (!queue || !queue.length) {
			cb();
		}

		function callNext(i) {
			if (typeOf(queue[i]) === 'function') {
				queue[i](function(error) {
					/*jshint expr:true */
					++i < length && !error ? callNext(i) : cb(error);
				});
			}
		}
		callNext(i);
	};


	/**
	Recieve an array of functions (usually async) to call in parallel, each  function
	receives a callback as first argument that it should call, when it completes. After 
	everything is complete, main callback is called. Passing truthy value to the
	callback as a first argument will interrupt the process and invoke main callback
	immediately.

	@method inParallel
	@static
	@param {Array} queue Array of functions to call in sequence
	@param {Function} cb Main callback that is called in the end, or in case of error
	*/
	var inParallel = function(queue, cb) {
		var count = 0, num = queue.length, cbArgs = new Array(num);

		each(queue, function(fn, i) {
			fn(function(error) {
				if (error) {
					return cb(error);
				}
				
				var args = [].slice.call(arguments);
				args.shift(); // strip error - undefined or not

				cbArgs[i] = args;
				count++;

				if (count === num) {
					cbArgs.unshift(null);
					cb.apply(this, cbArgs);
				} 
			});
		});
	};
	
	
	/**
	Find an element in array and return it's index if present, otherwise return -1.
	
	@method inArray
	@static
	@param {Mixed} needle Element to find
	@param {Array} array
	@return {Int} Index of the element, or -1 if not found
	*/
	var inArray = function(needle, array) {
		if (array) {
			if (Array.prototype.indexOf) {
				return Array.prototype.indexOf.call(array, needle);
			}
		
			for (var i = 0, length = array.length; i < length; i++) {
				if (array[i] === needle) {
					return i;
				}
			}
		}
		return -1;
	};


	/**
	Returns elements of first array if they are not present in second. And false - otherwise.

	@private
	@method arrayDiff
	@param {Array} needles
	@param {Array} array
	@return {Array|Boolean}
	*/
	var arrayDiff = function(needles, array) {
		var diff = [];

		if (typeOf(needles) !== 'array') {
			needles = [needles];
		}

		if (typeOf(array) !== 'array') {
			array = [array];
		}

		for (var i in needles) {
			if (inArray(needles[i], array) === -1) {
				diff.push(needles[i]);
			}	
		}
		return diff.length ? diff : false;
	};


	/**
	Find intersection of two arrays.

	@private
	@method arrayIntersect
	@param {Array} array1
	@param {Array} array2
	@return {Array} Intersection of two arrays or null if there is none
	*/
	var arrayIntersect = function(array1, array2) {
		var result = [];
		each(array1, function(item) {
			if (inArray(item, array2) !== -1) {
				result.push(item);
			}
		});
		return result.length ? result : null;
	};
	
	
	/**
	Forces anything into an array.
	
	@method toArray
	@static
	@param {Object} obj Object with length field.
	@return {Array} Array object containing all items.
	*/
	var toArray = function(obj) {
		var i, arr = [];

		for (i = 0; i < obj.length; i++) {
			arr[i] = obj[i];
		}

		return arr;
	};
	
			
	/**
	Generates an unique ID. The only way a user would be able to get the same ID is if the two persons
	at the same exact millisecond manage to get the same 5 random numbers between 0-65535; it also uses 
	a counter so each ID is guaranteed to be unique for the given page. It is more probable for the earth 
	to be hit with an asteroid.
	
	@method guid
	@static
	@param {String} prefix to prepend (by default 'o' will be prepended).
	@method guid
	@return {String} Virtually unique id.
	*/
	var guid = (function() {
		var counter = 0;
		
		return function(prefix) {
			var guid = new Date().getTime().toString(32), i;

			for (i = 0; i < 5; i++) {
				guid += Math.floor(Math.random() * 65535).toString(32);
			}
			
			return (prefix || 'o_') + guid + (counter++).toString(32);
		};
	}());
	

	/**
	Trims white spaces around the string
	
	@method trim
	@static
	@param {String} str
	@return {String}
	*/
	var trim = function(str) {
		if (!str) {
			return str;
		}
		return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, '');
	};


	/**
	Parses the specified size string into a byte value. For example 10kb becomes 10240.
	
	@method parseSizeStr
	@static
	@param {String/Number} size String to parse or number to just pass through.
	@return {Number} Size in bytes.
	*/
	var parseSizeStr = function(size) {
		if (typeof(size) !== 'string') {
			return size;
		}
		
		var muls = {
				t: 1099511627776,
				g: 1073741824,
				m: 1048576,
				k: 1024
			},
			mul;


		size = /^([0-9\.]+)([tmgk]?)$/.exec(size.toLowerCase().replace(/[^0-9\.tmkg]/g, ''));
		mul = size[2];
		size = +size[1];
		
		if (muls.hasOwnProperty(mul)) {
			size *= muls[mul];
		}
		return Math.floor(size);
	};


	/**
	 * Pseudo sprintf implementation - simple way to replace tokens with specified values.
	 *
	 * @param {String} str String with tokens
	 * @return {String} String with replaced tokens
	 */
	var sprintf = function(str) {
		var args = [].slice.call(arguments, 1);

		return str.replace(/%[a-z]/g, function() {
			var value = args.shift();
			return typeOf(value) !== 'undefined' ? value : '';
		});
	};
	

	return {
		guid: guid,
		typeOf: typeOf,
		extend: extend,
		each: each,
		isEmptyObj: isEmptyObj,
		inSeries: inSeries,
		inParallel: inParallel,
		inArray: inArray,
		arrayDiff: arrayDiff,
		arrayIntersect: arrayIntersect,
		toArray: toArray,
		trim: trim,
		sprintf: sprintf,
		parseSizeStr: parseSizeStr
	};
});

// Included from: src/javascript/core/utils/Env.js

/**
 * Env.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define("moxie/core/utils/Env", [
	"moxie/core/utils/Basic"
], function(Basic) {
	
	/**
	 * UAParser.js v0.7.7
	 * Lightweight JavaScript-based User-Agent string parser
	 * https://github.com/faisalman/ua-parser-js
	 *
	 * Copyright © 2012-2015 Faisal Salman <fyzlman@gmail.com>
	 * Dual licensed under GPLv2 & MIT
	 */
	var UAParser = (function (undefined) {

	    //////////////
	    // Constants
	    /////////////


	    var EMPTY       = '',
	        UNKNOWN     = '?',
	        FUNC_TYPE   = 'function',
	        UNDEF_TYPE  = 'undefined',
	        OBJ_TYPE    = 'object',
	        MAJOR       = 'major',
	        MODEL       = 'model',
	        NAME        = 'name',
	        TYPE        = 'type',
	        VENDOR      = 'vendor',
	        VERSION     = 'version',
	        ARCHITECTURE= 'architecture',
	        CONSOLE     = 'console',
	        MOBILE      = 'mobile',
	        TABLET      = 'tablet';


	    ///////////
	    // Helper
	    //////////


	    var util = {
	        has : function (str1, str2) {
	            return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
	        },
	        lowerize : function (str) {
	            return str.toLowerCase();
	        }
	    };


	    ///////////////
	    // Map helper
	    //////////////


	    var mapper = {

	        rgx : function () {

	            // loop through all regexes maps
	            for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) {

	                var regex = args[i],       // even sequence (0,2,4,..)
	                    props = args[i + 1];   // odd sequence (1,3,5,..)

	                // construct object barebones
	                if (typeof(result) === UNDEF_TYPE) {
	                    result = {};
	                    for (p in props) {
	                        q = props[p];
	                        if (typeof(q) === OBJ_TYPE) {
	                            result[q[0]] = undefined;
	                        } else {
	                            result[q] = undefined;
	                        }
	                    }
	                }

	                // try matching uastring with regexes
	                for (j = k = 0; j < regex.length; j++) {
	                    matches = regex[j].exec(this.getUA());
	                    if (!!matches) {
	                        for (p = 0; p < props.length; p++) {
	                            match = matches[++k];
	                            q = props[p];
	                            // check if given property is actually array
	                            if (typeof(q) === OBJ_TYPE && q.length > 0) {
	                                if (q.length == 2) {
	                                    if (typeof(q[1]) == FUNC_TYPE) {
	                                        // assign modified match
	                                        result[q[0]] = q[1].call(this, match);
	                                    } else {
	                                        // assign given value, ignore regex match
	                                        result[q[0]] = q[1];
	                                    }
	                                } else if (q.length == 3) {
	                                    // check whether function or regex
	                                    if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) {
	                                        // call function (usually string mapper)
	                                        result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
	                                    } else {
	                                        // sanitize match using given regex
	                                        result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
	                                    }
	                                } else if (q.length == 4) {
	                                        result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
	                                }
	                            } else {
	                                result[q] = match ? match : undefined;
	                            }
	                        }
	                        break;
	                    }
	                }

	                if(!!matches) break; // break the loop immediately if match found
	            }
	            return result;
	        },

	        str : function (str, map) {

	            for (var i in map) {
	                // check if array
	                if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) {
	                    for (var j = 0; j < map[i].length; j++) {
	                        if (util.has(map[i][j], str)) {
	                            return (i === UNKNOWN) ? undefined : i;
	                        }
	                    }
	                } else if (util.has(map[i], str)) {
	                    return (i === UNKNOWN) ? undefined : i;
	                }
	            }
	            return str;
	        }
	    };


	    ///////////////
	    // String map
	    //////////////


	    var maps = {

	        browser : {
	            oldsafari : {
	                major : {
	                    '1' : ['/8', '/1', '/3'],
	                    '2' : '/4',
	                    '?' : '/'
	                },
	                version : {
	                    '1.0'   : '/8',
	                    '1.2'   : '/1',
	                    '1.3'   : '/3',
	                    '2.0'   : '/412',
	                    '2.0.2' : '/416',
	                    '2.0.3' : '/417',
	                    '2.0.4' : '/419',
	                    '?'     : '/'
	                }
	            }
	        },

	        device : {
	            sprint : {
	                model : {
	                    'Evo Shift 4G' : '7373KT'
	                },
	                vendor : {
	                    'HTC'       : 'APA',
	                    'Sprint'    : 'Sprint'
	                }
	            }
	        },

	        os : {
	            windows : {
	                version : {
	                    'ME'        : '4.90',
	                    'NT 3.11'   : 'NT3.51',
	                    'NT 4.0'    : 'NT4.0',
	                    '2000'      : 'NT 5.0',
	                    'XP'        : ['NT 5.1', 'NT 5.2'],
	                    'Vista'     : 'NT 6.0',
	                    '7'         : 'NT 6.1',
	                    '8'         : 'NT 6.2',
	                    '8.1'       : 'NT 6.3',
	                    'RT'        : 'ARM'
	                }
	            }
	        }
	    };


	    //////////////
	    // Regex map
	    /////////////


	    var regexes = {

	        browser : [[
	        
	            // Presto based
	            /(opera\smini)\/([\w\.-]+)/i,                                       // Opera Mini
	            /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,                      // Opera Mobi/Tablet
	            /(opera).+version\/([\w\.]+)/i,                                     // Opera > 9.80
	            /(opera)[\/\s]+([\w\.]+)/i                                          // Opera < 9.80

	            ], [NAME, VERSION], [

	            /\s(opr)\/([\w\.]+)/i                                               // Opera Webkit
	            ], [[NAME, 'Opera'], VERSION], [

	            // Mixed
	            /(kindle)\/([\w\.]+)/i,                                             // Kindle
	            /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,
	                                                                                // Lunascape/Maxthon/Netfront/Jasmine/Blazer

	            // Trident based
	            /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,
	                                                                                // Avant/IEMobile/SlimBrowser/Baidu
	            /(?:ms|\()(ie)\s([\w\.]+)/i,                                        // Internet Explorer

	            // Webkit/KHTML based
	            /(rekonq)\/([\w\.]+)*/i,                                            // Rekonq
	            /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi)\/([\w\.-]+)/i
	                                                                                // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron
	            ], [NAME, VERSION], [

	            /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i                         // IE11
	            ], [[NAME, 'IE'], VERSION], [

	            /(edge)\/((\d+)?[\w\.]+)/i                                          // Microsoft Edge
	            ], [NAME, VERSION], [

	            /(yabrowser)\/([\w\.]+)/i                                           // Yandex
	            ], [[NAME, 'Yandex'], VERSION], [

	            /(comodo_dragon)\/([\w\.]+)/i                                       // Comodo Dragon
	            ], [[NAME, /_/g, ' '], VERSION], [

	            /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i,
	                                                                                // Chrome/OmniWeb/Arora/Tizen/Nokia
	            /(uc\s?browser|qqbrowser)[\/\s]?([\w\.]+)/i
	                                                                                // UCBrowser/QQBrowser
	            ], [NAME, VERSION], [

	            /(dolfin)\/([\w\.]+)/i                                              // Dolphin
	            ], [[NAME, 'Dolphin'], VERSION], [

	            /((?:android.+)crmo|crios)\/([\w\.]+)/i                             // Chrome for Android/iOS
	            ], [[NAME, 'Chrome'], VERSION], [

	            /XiaoMi\/MiuiBrowser\/([\w\.]+)/i                                   // MIUI Browser
	            ], [VERSION, [NAME, 'MIUI Browser']], [

	            /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)/i         // Android Browser
	            ], [VERSION, [NAME, 'Android Browser']], [

	            /FBAV\/([\w\.]+);/i                                                 // Facebook App for iOS
	            ], [VERSION, [NAME, 'Facebook']], [

	            /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i                       // Mobile Safari
	            ], [VERSION, [NAME, 'Mobile Safari']], [

	            /version\/([\w\.]+).+?(mobile\s?safari|safari)/i                    // Safari & Safari Mobile
	            ], [VERSION, NAME], [

	            /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i                     // Safari < 3.0
	            ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [

	            /(konqueror)\/([\w\.]+)/i,                                          // Konqueror
	            /(webkit|khtml)\/([\w\.]+)/i
	            ], [NAME, VERSION], [

	            // Gecko based
	            /(navigator|netscape)\/([\w\.-]+)/i                                 // Netscape
	            ], [[NAME, 'Netscape'], VERSION], [
	            /(swiftfox)/i,                                                      // Swiftfox
	            /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
	                                                                                // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
	            /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,
	                                                                                // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
	            /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,                          // Mozilla

	            // Other
	            /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf)[\/\s]?([\w\.]+)/i,
	                                                                                // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf
	            /(links)\s\(([\w\.]+)/i,                                            // Links
	            /(gobrowser)\/?([\w\.]+)*/i,                                        // GoBrowser
	            /(ice\s?browser)\/v?([\w\._]+)/i,                                   // ICE Browser
	            /(mosaic)[\/\s]([\w\.]+)/i                                          // Mosaic
	            ], [NAME, VERSION]
	        ],

	        engine : [[

	            /windows.+\sedge\/([\w\.]+)/i                                       // EdgeHTML
	            ], [VERSION, [NAME, 'EdgeHTML']], [

	            /(presto)\/([\w\.]+)/i,                                             // Presto
	            /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,     // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
	            /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,                          // KHTML/Tasman/Links
	            /(icab)[\/\s]([23]\.[\d\.]+)/i                                      // iCab
	            ], [NAME, VERSION], [

	            /rv\:([\w\.]+).*(gecko)/i                                           // Gecko
	            ], [VERSION, NAME]
	        ],

	        os : [[

	            // Windows based
	            /microsoft\s(windows)\s(vista|xp)/i                                 // Windows (iTunes)
	            ], [NAME, VERSION], [
	            /(windows)\snt\s6\.2;\s(arm)/i,                                     // Windows RT
	            /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
	            ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
	            /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
	            ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [

	            // Mobile/Embedded OS
	            /\((bb)(10);/i                                                      // BlackBerry 10
	            ], [[NAME, 'BlackBerry'], VERSION], [
	            /(blackberry)\w*\/?([\w\.]+)*/i,                                    // Blackberry
	            /(tizen)[\/\s]([\w\.]+)/i,                                          // Tizen
	            /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,
	                                                                                // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki
	            /linux;.+(sailfish);/i                                              // Sailfish OS
	            ], [NAME, VERSION], [
	            /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i                 // Symbian
	            ], [[NAME, 'Symbian'], VERSION], [
	            /\((series40);/i                                                    // Series 40
	            ], [NAME], [
	            /mozilla.+\(mobile;.+gecko.+firefox/i                               // Firefox OS
	            ], [[NAME, 'Firefox OS'], VERSION], [

	            // Console
	            /(nintendo|playstation)\s([wids3portablevu]+)/i,                    // Nintendo/Playstation

	            // GNU/Linux based
	            /(mint)[\/\s\(]?(\w+)*/i,                                           // Mint
	            /(mageia|vectorlinux)[;\s]/i,                                       // Mageia/VectorLinux
	            /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?([\w\.-]+)*/i,
	                                                                                // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
	                                                                                // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
	            /(hurd|linux)\s?([\w\.]+)*/i,                                       // Hurd/Linux
	            /(gnu)\s?([\w\.]+)*/i                                               // GNU
	            ], [NAME, VERSION], [

	            /(cros)\s[\w]+\s([\w\.]+\w)/i                                       // Chromium OS
	            ], [[NAME, 'Chromium OS'], VERSION],[

	            // Solaris
	            /(sunos)\s?([\w\.]+\d)*/i                                           // Solaris
	            ], [[NAME, 'Solaris'], VERSION], [

	            // BSD based
	            /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i                   // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
	            ], [NAME, VERSION],[

	            /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i             // iOS
	            ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [

	            /(mac\sos\sx)\s?([\w\s\.]+\w)*/i,
	            /(macintosh|mac(?=_powerpc)\s)/i                                    // Mac OS
	            ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [

	            // Other
	            /((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,                            // Solaris
	            /(haiku)\s(\w+)/i,                                                  // Haiku
	            /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,                               // AIX
	            /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,
	                                                                                // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS
	            /(unix)\s?([\w\.]+)*/i                                              // UNIX
	            ], [NAME, VERSION]
	        ]
	    };


	    /////////////////
	    // Constructor
	    ////////////////


	    var UAParser = function (uastring) {

	        var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);

	        this.getBrowser = function () {
	            return mapper.rgx.apply(this, regexes.browser);
	        };
	        this.getEngine = function () {
	            return mapper.rgx.apply(this, regexes.engine);
	        };
	        this.getOS = function () {
	            return mapper.rgx.apply(this, regexes.os);
	        };
	        this.getResult = function() {
	            return {
	                ua      : this.getUA(),
	                browser : this.getBrowser(),
	                engine  : this.getEngine(),
	                os      : this.getOS()
	            };
	        };
	        this.getUA = function () {
	            return ua;
	        };
	        this.setUA = function (uastring) {
	            ua = uastring;
	            return this;
	        };
	        this.setUA(ua);
	    };

	    return UAParser;
	})();


	function version_compare(v1, v2, operator) {
	  // From: http://phpjs.org/functions
	  // +      original by: Philippe Jausions (http://pear.php.net/user/jausions)
	  // +      original by: Aidan Lister (http://aidanlister.com/)
	  // + reimplemented by: Kankrelune (http://www.webfaktory.info/)
	  // +      improved by: Brett Zamir (http://brett-zamir.me)
	  // +      improved by: Scott Baker
	  // +      improved by: Theriault
	  // *        example 1: version_compare('8.2.5rc', '8.2.5a');
	  // *        returns 1: 1
	  // *        example 2: version_compare('8.2.50', '8.2.52', '<');
	  // *        returns 2: true
	  // *        example 3: version_compare('5.3.0-dev', '5.3.0');
	  // *        returns 3: -1
	  // *        example 4: version_compare('4.1.0.52','4.01.0.51');
	  // *        returns 4: 1

	  // Important: compare must be initialized at 0.
	  var i = 0,
	    x = 0,
	    compare = 0,
	    // vm maps textual PHP versions to negatives so they're less than 0.
	    // PHP currently defines these as CASE-SENSITIVE. It is important to
	    // leave these as negatives so that they can come before numerical versions
	    // and as if no letters were there to begin with.
	    // (1alpha is < 1 and < 1.1 but > 1dev1)
	    // If a non-numerical value can't be mapped to this table, it receives
	    // -7 as its value.
	    vm = {
	      'dev': -6,
	      'alpha': -5,
	      'a': -5,
	      'beta': -4,
	      'b': -4,
	      'RC': -3,
	      'rc': -3,
	      '#': -2,
	      'p': 1,
	      'pl': 1
	    },
	    // This function will be called to prepare each version argument.
	    // It replaces every _, -, and + with a dot.
	    // It surrounds any nonsequence of numbers/dots with dots.
	    // It replaces sequences of dots with a single dot.
	    //    version_compare('4..0', '4.0') == 0
	    // Important: A string of 0 length needs to be converted into a value
	    // even less than an unexisting value in vm (-7), hence [-8].
	    // It's also important to not strip spaces because of this.
	    //   version_compare('', ' ') == 1
	    prepVersion = function (v) {
	      v = ('' + v).replace(/[_\-+]/g, '.');
	      v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
	      return (!v.length ? [-8] : v.split('.'));
	    },
	    // This converts a version component to a number.
	    // Empty component becomes 0.
	    // Non-numerical component becomes a negative number.
	    // Numerical component becomes itself as an integer.
	    numVersion = function (v) {
	      return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
	    };

	  v1 = prepVersion(v1);
	  v2 = prepVersion(v2);
	  x = Math.max(v1.length, v2.length);
	  for (i = 0; i < x; i++) {
	    if (v1[i] == v2[i]) {
	      continue;
	    }
	    v1[i] = numVersion(v1[i]);
	    v2[i] = numVersion(v2[i]);
	    if (v1[i] < v2[i]) {
	      compare = -1;
	      break;
	    } else if (v1[i] > v2[i]) {
	      compare = 1;
	      break;
	    }
	  }
	  if (!operator) {
	    return compare;
	  }

	  // Important: operator is CASE-SENSITIVE.
	  // "No operator" seems to be treated as "<."
	  // Any other values seem to make the function return null.
	  switch (operator) {
	  case '>':
	  case 'gt':
	    return (compare > 0);
	  case '>=':
	  case 'ge':
	    return (compare >= 0);
	  case '<=':
	  case 'le':
	    return (compare <= 0);
	  case '==':
	  case '=':
	  case 'eq':
	    return (compare === 0);
	  case '<>':
	  case '!=':
	  case 'ne':
	    return (compare !== 0);
	  case '':
	  case '<':
	  case 'lt':
	    return (compare < 0);
	  default:
	    return null;
	  }
	}


	var can = (function() {
		var caps = {
				define_property: (function() {
					/* // currently too much extra code required, not exactly worth it
					try { // as of IE8, getters/setters are supported only on DOM elements
						var obj = {};
						if (Object.defineProperty) {
							Object.defineProperty(obj, 'prop', {
								enumerable: true,
								configurable: true
							});
							return true;
						}
					} catch(ex) {}

					if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
						return true;
					}*/
					return false;
				}()),

				create_canvas: (function() {
					// On the S60 and BB Storm, getContext exists, but always returns undefined
					// so we actually have to call getContext() to verify
					// github.com/Modernizr/Modernizr/issues/issue/97/
					var el = document.createElement('canvas');
					return !!(el.getContext && el.getContext('2d'));
				}()),

				return_response_type: function(responseType) {
					try {
						if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) {
							return true;
						} else if (window.XMLHttpRequest) {
							var xhr = new XMLHttpRequest();
							xhr.open('get', '/'); // otherwise Gecko throws an exception
							if ('responseType' in xhr) {
								xhr.responseType = responseType;
								// as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?)
								if (xhr.responseType !== responseType) {
									return false;
								}
								return true;
							}
						}
					} catch (ex) {}
					return false;
				},

				// ideas for this heavily come from Modernizr (http://modernizr.com/)
				use_data_uri: (function() {
					var du = new Image();

					du.onload = function() {
						caps.use_data_uri = (du.width === 1 && du.height === 1);
					};
					
					setTimeout(function() {
						du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
					}, 1);
					return false;
				}()),

				use_data_uri_over32kb: function() { // IE8
					return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9);
				},

				use_data_uri_of: function(bytes) {
					return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb());
				},

				use_fileinput: function() {
					if (navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/)) {
						return false;
					}

					var el = document.createElement('input');
					el.setAttribute('type', 'file');
					return !el.disabled;
				}
			};

		return function(cap) {
			var args = [].slice.call(arguments);
			args.shift(); // shift of cap
			return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap];
		};
	}());


	var uaResult = new UAParser().getResult();


	var Env = {
		can: can,

		uaParser: UAParser,
		
		browser: uaResult.browser.name,
		version: uaResult.browser.version,
		os: uaResult.os.name, // everybody intuitively types it in a lowercase for some reason
		osVersion: uaResult.os.version,

		verComp: version_compare,
		
		swf_url: "../flash/Moxie.swf",
		xap_url: "../silverlight/Moxie.xap",
		global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent"
	};

	// for backward compatibility
	// @deprecated Use `Env.os` instead
	Env.OS = Env.os;

	if (MXI_DEBUG) {
		Env.debug = {
			runtime: true,
			events: false
		};

		Env.log = function() {
			
			function logObj(data) {
				// TODO: this should recursively print out the object in a pretty way
				console.appendChild(document.createTextNode(data + "\n"));
			}

			var data = arguments[0];

			if (Basic.typeOf(data) === 'string') {
				data = Basic.sprintf.apply(this, arguments);
			}

			if (window && window.console && window.console.log) {
				window.console.log(data);
			} else if (document) {
				var console = document.getElementById('moxie-console');
				if (!console) {
					console = document.createElement('pre');
					console.id = 'moxie-console';
					//console.style.display = 'none';
					document.body.appendChild(console);
				}

				if (Basic.inArray(Basic.typeOf(data), ['object', 'array']) !== -1) {
					logObj(data);
				} else {
					console.appendChild(document.createTextNode(data + "\n"));
				}
			}
		};
	}

	return Env;
});

// Included from: src/javascript/core/I18n.js

/**
 * I18n.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define("moxie/core/I18n", [
	"moxie/core/utils/Basic"
], function(Basic) {
	var i18n = {};

	return {
		/**
		 * Extends the language pack object with new items.
		 *
		 * @param {Object} pack Language pack items to add.
		 * @return {Object} Extended language pack object.
		 */
		addI18n: function(pack) {
			return Basic.extend(i18n, pack);
		},

		/**
		 * Translates the specified string by checking for the english string in the language pack lookup.
		 *
		 * @param {String} str String to look for.
		 * @return {String} Translated string or the input string if it wasn't found.
		 */
		translate: function(str) {
			return i18n[str] || str;
		},

		/**
		 * Shortcut for translate function
		 *
		 * @param {String} str String to look for.
		 * @return {String} Translated string or the input string if it wasn't found.
		 */
		_: function(str) {
			return this.translate(str);
		},

		/**
		 * Pseudo sprintf implementation - simple way to replace tokens with specified values.
		 *
		 * @param {String} str String with tokens
		 * @return {String} String with replaced tokens
		 */
		sprintf: function(str) {
			var args = [].slice.call(arguments, 1);

			return str.replace(/%[a-z]/g, function() {
				var value = args.shift();
				return Basic.typeOf(value) !== 'undefined' ? value : '';
			});
		}
	};
});

// Included from: src/javascript/core/utils/Mime.js

/**
 * Mime.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define("moxie/core/utils/Mime", [
	"moxie/core/utils/Basic",
	"moxie/core/I18n"
], function(Basic, I18n) {
	
	var mimeData = "" +
		"application/msword,doc dot," +
		"application/pdf,pdf," +
		"application/pgp-signature,pgp," +
		"application/postscript,ps ai eps," +
		"application/rtf,rtf," +
		"application/vnd.ms-excel,xls xlb," +
		"application/vnd.ms-powerpoint,ppt pps pot," +
		"application/zip,zip," +
		"application/x-shockwave-flash,swf swfl," +
		"application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," +
		"application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," +
		"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," +
		"application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," +
		"application/vnd.openxmlformats-officedocument.presentationml.template,potx," +
		"application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," +
		"application/x-javascript,js," +
		"application/json,json," +
		"audio/mpeg,mp3 mpga mpega mp2," +
		"audio/x-wav,wav," +
		"audio/x-m4a,m4a," +
		"audio/ogg,oga ogg," +
		"audio/aiff,aiff aif," +
		"audio/flac,flac," +
		"audio/aac,aac," +
		"audio/ac3,ac3," +
		"audio/x-ms-wma,wma," +
		"image/bmp,bmp," +
		"image/gif,gif," +
		"image/jpeg,jpg jpeg jpe," +
		"image/photoshop,psd," +
		"image/png,png," +
		"image/svg+xml,svg svgz," +
		"image/tiff,tiff tif," +
		"text/plain,asc txt text diff log," +
		"text/html,htm html xhtml," +
		"text/css,css," +
		"text/csv,csv," +
		"text/rtf,rtf," +
		"video/mpeg,mpeg mpg mpe m2v," +
		"video/quicktime,qt mov," +
		"video/mp4,mp4," +
		"video/x-m4v,m4v," +
		"video/x-flv,flv," +
		"video/x-ms-wmv,wmv," +
		"video/avi,avi," +
		"video/webm,webm," +
		"video/3gpp,3gpp 3gp," +
		"video/3gpp2,3g2," +
		"video/vnd.rn-realvideo,rv," +
		"video/ogg,ogv," + 
		"video/x-matroska,mkv," +
		"application/vnd.oasis.opendocument.formula-template,otf," +
		"application/octet-stream,exe";
	
	
	var Mime = {

		mimes: {},

		extensions: {},

		// Parses the default mime types string into a mimes and extensions lookup maps
		addMimeType: function (mimeData) {
			var items = mimeData.split(/,/), i, ii, ext;
			
			for (i = 0; i < items.length; i += 2) {
				ext = items[i + 1].split(/ /);

				// extension to mime lookup
				for (ii = 0; ii < ext.length; ii++) {
					this.mimes[ext[ii]] = items[i];
				}
				// mime to extension lookup
				this.extensions[items[i]] = ext;
			}
		},


		extList2mimes: function (filters, addMissingExtensions) {
			var self = this, ext, i, ii, type, mimes = [];
			
			// convert extensions to mime types list
			for (i = 0; i < filters.length; i++) {
				ext = filters[i].extensions.split(/\s*,\s*/);

				for (ii = 0; ii < ext.length; ii++) {
					
					// if there's an asterisk in the list, then accept attribute is not required
					if (ext[ii] === '*') {
						return [];
					}

					type = self.mimes[ext[ii]];
					if (type && Basic.inArray(type, mimes) === -1) {
						mimes.push(type);
					}

					// future browsers should filter by extension, finally
					if (addMissingExtensions && /^\w+$/.test(ext[ii])) {
						mimes.push('.' + ext[ii]);
					} else if (!type) {
						// if we have no type in our map, then accept all
						return [];
					}
				}
			}
			return mimes;
		},


		mimes2exts: function(mimes) {
			var self = this, exts = [];
			
			Basic.each(mimes, function(mime) {
				if (mime === '*') {
					exts = [];
					return false;
				}

				// check if this thing looks like mime type
				var m = mime.match(/^(\w+)\/(\*|\w+)$/);
				if (m) {
					if (m[2] === '*') { 
						// wildcard mime type detected
						Basic.each(self.extensions, function(arr, mime) {
							if ((new RegExp('^' + m[1] + '/')).test(mime)) {
								[].push.apply(exts, self.extensions[mime]);
							}
						});
					} else if (self.extensions[mime]) {
						[].push.apply(exts, self.extensions[mime]);
					}
				}
			});
			return exts;
		},


		mimes2extList: function(mimes) {
			var accept = [], exts = [];

			if (Basic.typeOf(mimes) === 'string') {
				mimes = Basic.trim(mimes).split(/\s*,\s*/);
			}

			exts = this.mimes2exts(mimes);
			
			accept.push({
				title: I18n.translate('Files'),
				extensions: exts.length ? exts.join(',') : '*'
			});
			
			// save original mimes string
			accept.mimes = mimes;

			return accept;
		},


		getFileExtension: function(fileName) {
			var matches = fileName && fileName.match(/\.([^.]+)$/);
			if (matches) {
				return matches[1].toLowerCase();
			}
			return '';
		},

		getFileMime: function(fileName) {
			return this.mimes[this.getFileExtension(fileName)] || '';
		}
	};

	Mime.addMimeType(mimeData);

	return Mime;
});

// Included from: src/javascript/core/utils/Dom.js

/**
 * Dom.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) {

	/**
	Get DOM Element by it's id.

	@method get
	@for Utils
	@param {String} id Identifier of the DOM Element
	@return {DOMElement}
	*/
	var get = function(id) {
		if (typeof id !== 'string') {
			return id;
		}
		return document.getElementById(id);
	};

	/**
	Checks if specified DOM element has specified class.

	@method hasClass
	@static
	@param {Object} obj DOM element like object to add handler to.
	@param {String} name Class name
	*/
	var hasClass = function(obj, name) {
		if (!obj.className) {
			return false;
		}

		var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
		return regExp.test(obj.className);
	};

	/**
	Adds specified className to specified DOM element.

	@method addClass
	@static
	@param {Object} obj DOM element like object to add handler to.
	@param {String} name Class name
	*/
	var addClass = function(obj, name) {
		if (!hasClass(obj, name)) {
			obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name;
		}
	};

	/**
	Removes specified className from specified DOM element.

	@method removeClass
	@static
	@param {Object} obj DOM element like object to add handler to.
	@param {String} name Class name
	*/
	var removeClass = function(obj, name) {
		if (obj.className) {
			var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
			obj.className = obj.className.replace(regExp, function($0, $1, $2) {
				return $1 === ' ' && $2 === ' ' ? ' ' : '';
			});
		}
	};

	/**
	Returns a given computed style of a DOM element.

	@method getStyle
	@static
	@param {Object} obj DOM element like object.
	@param {String} name Style you want to get from the DOM element
	*/
	var getStyle = function(obj, name) {
		if (obj.currentStyle) {
			return obj.currentStyle[name];
		} else if (window.getComputedStyle) {
			return window.getComputedStyle(obj, null)[name];
		}
	};


	/**
	Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.

	@method getPos
	@static
	@param {Element} node HTML element or element id to get x, y position from.
	@param {Element} root Optional root element to stop calculations at.
	@return {object} Absolute position of the specified element object with x, y fields.
	*/
	var getPos = function(node, root) {
		var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;

		node = node;
		root = root || doc.body;

		// Returns the x, y cordinate for an element on IE 6 and IE 7
		function getIEPos(node) {
			var bodyElm, rect, x = 0, y = 0;

			if (node) {
				rect = node.getBoundingClientRect();
				bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
				x = rect.left + bodyElm.scrollLeft;
				y = rect.top + bodyElm.scrollTop;
			}

			return {
				x : x,
				y : y
			};
		}

		// Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
		if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) {
			nodeRect = getIEPos(node);
			rootRect = getIEPos(root);

			return {
				x : nodeRect.x - rootRect.x,
				y : nodeRect.y - rootRect.y
			};
		}

		parent = node;
		while (parent && parent != root && parent.nodeType) {
			x += parent.offsetLeft || 0;
			y += parent.offsetTop || 0;
			parent = parent.offsetParent;
		}

		parent = node.parentNode;
		while (parent && parent != root && parent.nodeType) {
			x -= parent.scrollLeft || 0;
			y -= parent.scrollTop || 0;
			parent = parent.parentNode;
		}

		return {
			x : x,
			y : y
		};
	};

	/**
	Returns the size of the specified node in pixels.

	@method getSize
	@static
	@param {Node} node Node to get the size of.
	@return {Object} Object with a w and h property.
	*/
	var getSize = function(node) {
		return {
			w : node.offsetWidth || node.clientWidth,
			h : node.offsetHeight || node.clientHeight
		};
	};

	return {
		get: get,
		hasClass: hasClass,
		addClass: addClass,
		removeClass: removeClass,
		getStyle: getStyle,
		getPos: getPos,
		getSize: getSize
	};
});

// Included from: src/javascript/core/Exceptions.js

/**
 * Exceptions.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/core/Exceptions', [
	'moxie/core/utils/Basic'
], function(Basic) {
	function _findKey(obj, value) {
		var key;
		for (key in obj) {
			if (obj[key] === value) {
				return key;
			}
		}
		return null;
	}

	return {
		RuntimeError: (function() {
			var namecodes = {
				NOT_INIT_ERR: 1,
				NOT_SUPPORTED_ERR: 9,
				JS_ERR: 4
			};

			function RuntimeError(code) {
				this.code = code;
				this.name = _findKey(namecodes, code);
				this.message = this.name + ": RuntimeError " + this.code;
			}
			
			Basic.extend(RuntimeError, namecodes);
			RuntimeError.prototype = Error.prototype;
			return RuntimeError;
		}()),
		
		OperationNotAllowedException: (function() {
			
			function OperationNotAllowedException(code) {
				this.code = code;
				this.name = 'OperationNotAllowedException';
			}
			
			Basic.extend(OperationNotAllowedException, {
				NOT_ALLOWED_ERR: 1
			});
			
			OperationNotAllowedException.prototype = Error.prototype;
			
			return OperationNotAllowedException;
		}()),

		ImageError: (function() {
			var namecodes = {
				WRONG_FORMAT: 1,
				MAX_RESOLUTION_ERR: 2,
				INVALID_META_ERR: 3
			};

			function ImageError(code) {
				this.code = code;
				this.name = _findKey(namecodes, code);
				this.message = this.name + ": ImageError " + this.code;
			}
			
			Basic.extend(ImageError, namecodes);
			ImageError.prototype = Error.prototype;

			return ImageError;
		}()),

		FileException: (function() {
			var namecodes = {
				NOT_FOUND_ERR: 1,
				SECURITY_ERR: 2,
				ABORT_ERR: 3,
				NOT_READABLE_ERR: 4,
				ENCODING_ERR: 5,
				NO_MODIFICATION_ALLOWED_ERR: 6,
				INVALID_STATE_ERR: 7,
				SYNTAX_ERR: 8
			};

			function FileException(code) {
				this.code = code;
				this.name = _findKey(namecodes, code);
				this.message = this.name + ": FileException " + this.code;
			}
			
			Basic.extend(FileException, namecodes);
			FileException.prototype = Error.prototype;
			return FileException;
		}()),
		
		DOMException: (function() {
			var namecodes = {
				INDEX_SIZE_ERR: 1,
				DOMSTRING_SIZE_ERR: 2,
				HIERARCHY_REQUEST_ERR: 3,
				WRONG_DOCUMENT_ERR: 4,
				INVALID_CHARACTER_ERR: 5,
				NO_DATA_ALLOWED_ERR: 6,
				NO_MODIFICATION_ALLOWED_ERR: 7,
				NOT_FOUND_ERR: 8,
				NOT_SUPPORTED_ERR: 9,
				INUSE_ATTRIBUTE_ERR: 10,
				INVALID_STATE_ERR: 11,
				SYNTAX_ERR: 12,
				INVALID_MODIFICATION_ERR: 13,
				NAMESPACE_ERR: 14,
				INVALID_ACCESS_ERR: 15,
				VALIDATION_ERR: 16,
				TYPE_MISMATCH_ERR: 17,
				SECURITY_ERR: 18,
				NETWORK_ERR: 19,
				ABORT_ERR: 20,
				URL_MISMATCH_ERR: 21,
				QUOTA_EXCEEDED_ERR: 22,
				TIMEOUT_ERR: 23,
				INVALID_NODE_TYPE_ERR: 24,
				DATA_CLONE_ERR: 25
			};

			function DOMException(code) {
				this.code = code;
				this.name = _findKey(namecodes, code);
				this.message = this.name + ": DOMException " + this.code;
			}
			
			Basic.extend(DOMException, namecodes);
			DOMException.prototype = Error.prototype;
			return DOMException;
		}()),
		
		EventException: (function() {
			function EventException(code) {
				this.code = code;
				this.name = 'EventException';
			}
			
			Basic.extend(EventException, {
				UNSPECIFIED_EVENT_TYPE_ERR: 0
			});
			
			EventException.prototype = Error.prototype;
			
			return EventException;
		}())
	};
});

// Included from: src/javascript/core/EventTarget.js

/**
 * EventTarget.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/core/EventTarget', [
	'moxie/core/utils/Env',
	'moxie/core/Exceptions',
	'moxie/core/utils/Basic'
], function(Env, x, Basic) {
	/**
	Parent object for all event dispatching components and objects

	@class EventTarget
	@constructor EventTarget
	*/
	function EventTarget() {
		// hash of event listeners by object uid
		var eventpool = {};
				
		Basic.extend(this, {
			
			/**
			Unique id of the event dispatcher, usually overriden by children

			@property uid
			@type String
			*/
			uid: null,
			
			/**
			Can be called from within a child  in order to acquire uniqie id in automated manner

			@method init
			*/
			init: function() {
				if (!this.uid) {
					this.uid = Basic.guid('uid_');
				}
			},

			/**
			Register a handler to a specific event dispatched by the object

			@method addEventListener
			@param {String} type Type or basically a name of the event to subscribe to
			@param {Function} fn Callback function that will be called when event happens
			@param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
			@param {Object} [scope=this] A scope to invoke event handler in
			*/
			addEventListener: function(type, fn, priority, scope) {
				var self = this, list;

				// without uid no event handlers can be added, so make sure we got one
				if (!this.hasOwnProperty('uid')) {
					this.uid = Basic.guid('uid_');
				}
				
				type = Basic.trim(type);
				
				if (/\s/.test(type)) {
					// multiple event types were passed for one handler
					Basic.each(type.split(/\s+/), function(type) {
						self.addEventListener(type, fn, priority, scope);
					});
					return;
				}
				
				type = type.toLowerCase();
				priority = parseInt(priority, 10) || 0;
				
				list = eventpool[this.uid] && eventpool[this.uid][type] || [];
				list.push({fn : fn, priority : priority, scope : scope || this});
				
				if (!eventpool[this.uid]) {
					eventpool[this.uid] = {};
				}
				eventpool[this.uid][type] = list;
			},
			
			/**
			Check if any handlers were registered to the specified event

			@method hasEventListener
			@param {String} type Type or basically a name of the event to check
			@return {Mixed} Returns a handler if it was found and false, if - not
			*/
			hasEventListener: function(type) {
				var list = type ? eventpool[this.uid] && eventpool[this.uid][type] : eventpool[this.uid];
				return list ? list : false;
			},
			
			/**
			Unregister the handler from the event, or if former was not specified - unregister all handlers

			@method removeEventListener
			@param {String} type Type or basically a name of the event
			@param {Function} [fn] Handler to unregister
			*/
			removeEventListener: function(type, fn) {
				type = type.toLowerCase();
	
				var list = eventpool[this.uid] && eventpool[this.uid][type], i;
	
				if (list) {
					if (fn) {
						for (i = list.length - 1; i >= 0; i--) {
							if (list[i].fn === fn) {
								list.splice(i, 1);
								break;
							}
						}
					} else {
						list = [];
					}
	
					// delete event list if it has become empty
					if (!list.length) {
						delete eventpool[this.uid][type];
						
						// and object specific entry in a hash if it has no more listeners attached
						if (Basic.isEmptyObj(eventpool[this.uid])) {
							delete eventpool[this.uid];
						}
					}
				}
			},
			
			/**
			Remove all event handlers from the object

			@method removeAllEventListeners
			*/
			removeAllEventListeners: function() {
				if (eventpool[this.uid]) {
					delete eventpool[this.uid];
				}
			},
			
			/**
			Dispatch the event

			@method dispatchEvent
			@param {String/Object} Type of event or event object to dispatch
			@param {Mixed} [...] Variable number of arguments to be passed to a handlers
			@return {Boolean} true by default and false if any handler returned false
			*/
			dispatchEvent: function(type) {
				var uid, list, args, tmpEvt, evt = {}, result = true, undef;
				
				if (Basic.typeOf(type) !== 'string') {
					// we can't use original object directly (because of Silverlight)
					tmpEvt = type;

					if (Basic.typeOf(tmpEvt.type) === 'string') {
						type = tmpEvt.type;

						if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event
							evt.total = tmpEvt.total;
							evt.loaded = tmpEvt.loaded;
						}
						evt.async = tmpEvt.async || false;
					} else {
						throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR);
					}
				}
				
				// check if event is meant to be dispatched on an object having specific uid
				if (type.indexOf('::') !== -1) {
					(function(arr) {
						uid = arr[0];
						type = arr[1];
					}(type.split('::')));
				} else {
					uid = this.uid;
				}
				
				type = type.toLowerCase();
								
				list = eventpool[uid] && eventpool[uid][type];

				if (list) {
					// sort event list by prority
					list.sort(function(a, b) { return b.priority - a.priority; });
					
					args = [].slice.call(arguments);
					
					// first argument will be pseudo-event object
					args.shift();
					evt.type = type;
					args.unshift(evt);

					if (MXI_DEBUG && Env.debug.events) {
						Env.log("Event '%s' fired on %u", evt.type, uid);	
					}

					// Dispatch event to all listeners
					var queue = [];
					Basic.each(list, function(handler) {
						// explicitly set the target, otherwise events fired from shims do not get it
						args[0].target = handler.scope;
						// if event is marked as async, detach the handler
						if (evt.async) {
							queue.push(function(cb) {
								setTimeout(function() {
									cb(handler.fn.apply(handler.scope, args) === false);
								}, 1);
							});
						} else {
							queue.push(function(cb) {
								cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation
							});
						}
					});
					if (queue.length) {
						Basic.inSeries(queue, function(err) {
							result = !err;
						});
					}
				}
				return result;
			},
			
			/**
			Alias for addEventListener

			@method bind
			@protected
			*/
			bind: function() {
				this.addEventListener.apply(this, arguments);
			},
			
			/**
			Alias for removeEventListener

			@method unbind
			@protected
			*/
			unbind: function() {
				this.removeEventListener.apply(this, arguments);
			},
			
			/**
			Alias for removeAllEventListeners

			@method unbindAll
			@protected
			*/
			unbindAll: function() {
				this.removeAllEventListeners.apply(this, arguments);
			},
			
			/**
			Alias for dispatchEvent

			@method trigger
			@protected
			*/
			trigger: function() {
				return this.dispatchEvent.apply(this, arguments);
			},
			

			/**
			Handle properties of on[event] type.

			@method handleEventProps
			@private
			*/
			handleEventProps: function(dispatches) {
				var self = this;

				this.bind(dispatches.join(' '), function(e) {
					var prop = 'on' + e.type.toLowerCase();
					if (Basic.typeOf(this[prop]) === 'function') {
						this[prop].apply(this, arguments);
					}
				});

				// object must have defined event properties, even if it doesn't make use of them
				Basic.each(dispatches, function(prop) {
					prop = 'on' + prop.toLowerCase(prop);
					if (Basic.typeOf(self[prop]) === 'undefined') {
						self[prop] = null; 
					}
				});
			}
			
		});
	}

	EventTarget.instance = new EventTarget(); 

	return EventTarget;
});

// Included from: src/javascript/runtime/Runtime.js

/**
 * Runtime.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/runtime/Runtime', [
	"moxie/core/utils/Env",
	"moxie/core/utils/Basic",
	"moxie/core/utils/Dom",
	"moxie/core/EventTarget"
], function(Env, Basic, Dom, EventTarget) {
	var runtimeConstructors = {}, runtimes = {};

	/**
	Common set of methods and properties for every runtime instance

	@class Runtime

	@param {Object} options
	@param {String} type Sanitized name of the runtime
	@param {Object} [caps] Set of capabilities that differentiate specified runtime
	@param {Object} [modeCaps] Set of capabilities that do require specific operational mode
	@param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested
	*/
	function Runtime(options, type, caps, modeCaps, preferredMode) {
		/**
		Dispatched when runtime is initialized and ready.
		Results in RuntimeInit on a connected component.

		@event Init
		*/

		/**
		Dispatched when runtime fails to initialize.
		Results in RuntimeError on a connected component.

		@event Error
		*/

		var self = this
		, _shim
		, _uid = Basic.guid(type + '_')
		, defaultMode = preferredMode || 'browser'
		;

		options = options || {};

		// register runtime in private hash
		runtimes[_uid] = this;

		/**
		Default set of capabilities, which can be redifined later by specific runtime

		@private
		@property caps
		@type Object
		*/
		caps = Basic.extend({
			// Runtime can: 
			// provide access to raw binary data of the file
			access_binary: false,
			// provide access to raw binary data of the image (image extension is optional) 
			access_image_binary: false,
			// display binary data as thumbs for example
			display_media: false,
			// make cross-domain requests
			do_cors: false,
			// accept files dragged and dropped from the desktop
			drag_and_drop: false,
			// filter files in selection dialog by their extensions
			filter_by_extension: true,
			// resize image (and manipulate it raw data of any file in general)
			resize_image: false,
			// periodically report how many bytes of total in the file were uploaded (loaded)
			report_upload_progress: false,
			// provide access to the headers of http response 
			return_response_headers: false,
			// support response of specific type, which should be passed as an argument
			// e.g. runtime.can('return_response_type', 'blob')
			return_response_type: false,
			// return http status code of the response
			return_status_code: true,
			// send custom http header with the request
			send_custom_headers: false,
			// pick up the files from a dialog
			select_file: false,
			// select whole folder in file browse dialog
			select_folder: false,
			// select multiple files at once in file browse dialog
			select_multiple: true,
			// send raw binary data, that is generated after image resizing or manipulation of other kind
			send_binary_string: false,
			// send cookies with http request and therefore retain session
			send_browser_cookies: true,
			// send data formatted as multipart/form-data
			send_multipart: true,
			// slice the file or blob to smaller parts
			slice_blob: false,
			// upload file without preloading it to memory, stream it out directly from disk
			stream_upload: false,
			// programmatically trigger file browse dialog
			summon_file_dialog: false,
			// upload file of specific size, size should be passed as argument
			// e.g. runtime.can('upload_filesize', '500mb')
			upload_filesize: true,
			// initiate http request with specific http method, method should be passed as argument
			// e.g. runtime.can('use_http_method', 'put')
			use_http_method: true
		}, caps);
			
	
		// default to the mode that is compatible with preferred caps
		if (options.preferred_caps) {
			defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode);
		}

		if (MXI_DEBUG && Env.debug.runtime) {
			Env.log("\tdefault mode: %s", defaultMode);	
		}
		
		// small extension factory here (is meant to be extended with actual extensions constructors)
		_shim = (function() {
			var objpool = {};
			return {
				exec: function(uid, comp, fn, args) {
					if (_shim[comp]) {
						if (!objpool[uid]) {
							objpool[uid] = {
								context: this,
								instance: new _shim[comp]()
							};
						}
						if (objpool[uid].instance[fn]) {
							return objpool[uid].instance[fn].apply(this, args);
						}
					}
				},

				removeInstance: function(uid) {
					delete objpool[uid];
				},

				removeAllInstances: function() {
					var self = this;
					Basic.each(objpool, function(obj, uid) {
						if (Basic.typeOf(obj.instance.destroy) === 'function') {
							obj.instance.destroy.call(obj.context);
						}
						self.removeInstance(uid);
					});
				}
			};
		}());


		// public methods
		Basic.extend(this, {
			/**
			Specifies whether runtime instance was initialized or not

			@property initialized
			@type {Boolean}
			@default false
			*/
			initialized: false, // shims require this flag to stop initialization retries

			/**
			Unique ID of the runtime

			@property uid
			@type {String}
			*/
			uid: _uid,

			/**
			Runtime type (e.g. flash, html5, etc)

			@property type
			@type {String}
			*/
			type: type,

			/**
			Runtime (not native one) may operate in browser or client mode.

			@property mode
			@private
			@type {String|Boolean} current mode or false, if none possible
			*/
			mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode),

			/**
			id of the DOM container for the runtime (if available)

			@property shimid
			@type {String}
			*/
			shimid: _uid + '_container',

			/**
			Number of connected clients. If equal to zero, runtime can be destroyed

			@property clients
			@type {Number}
			*/
			clients: 0,

			/**
			Runtime initialization options

			@property options
			@type {Object}
			*/
			options: options,

			/**
			Checks if the runtime has specific capability

			@method can
			@param {String} cap Name of capability to check
			@param {Mixed} [value] If passed, capability should somehow correlate to the value
			@param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set)
			@return {Boolean} true if runtime has such capability and false, if - not
			*/
			can: function(cap, value) {
				var refCaps = arguments[2] || caps;

				// if cap var is a comma-separated list of caps, convert it to object (key/value)
				if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') {
					cap = Runtime.parseCaps(cap);
				}

				if (Basic.typeOf(cap) === 'object') {
					for (var key in cap) {
						if (!this.can(key, cap[key], refCaps)) {
							return false;
						}
					}
					return true;
				}

				// check the individual cap
				if (Basic.typeOf(refCaps[cap]) === 'function') {
					return refCaps[cap].call(this, value);
				} else {
					return (value === refCaps[cap]);
				}
			},

			/**
			Returns container for the runtime as DOM element

			@method getShimContainer
			@return {DOMElement}
			*/
			getShimContainer: function() {
				var container, shimContainer = Dom.get(this.shimid);

				// if no container for shim, create one
				if (!shimContainer) {
					container = this.options.container ? Dom.get(this.options.container) : document.body;

					// create shim container and insert it at an absolute position into the outer container
					shimContainer = document.createElement('div');
					shimContainer.id = this.shimid;
					shimContainer.className = 'moxie-shim moxie-shim-' + this.type;

					Basic.extend(shimContainer.style, {
						position: 'absolute',
						top: '0px',
						left: '0px',
						width: '1px',
						height: '1px',
						overflow: 'hidden'
					});

					container.appendChild(shimContainer);
					container = null;
				}

				return shimContainer;
			},

			/**
			Returns runtime as DOM element (if appropriate)

			@method getShim
			@return {DOMElement}
			*/
			getShim: function() {
				return _shim;
			},

			/**
			Invokes a method within the runtime itself (might differ across the runtimes)

			@method shimExec
			@param {Mixed} []
			@protected
			@return {Mixed} Depends on the action and component
			*/
			shimExec: function(component, action) {
				var args = [].slice.call(arguments, 2);
				return self.getShim().exec.call(this, this.uid, component, action, args);
			},

			/**
			Operaional interface that is used by components to invoke specific actions on the runtime
			(is invoked in the scope of component)

			@method exec
			@param {Mixed} []*
			@protected
			@return {Mixed} Depends on the action and component
			*/
			exec: function(component, action) { // this is called in the context of component, not runtime
				var args = [].slice.call(arguments, 2);

				if (self[component] && self[component][action]) {
					return self[component][action].apply(this, args);
				}
				return self.shimExec.apply(this, arguments);
			},

			/**
			Destroys the runtime (removes all events and deletes DOM structures)

			@method destroy
			*/
			destroy: function() {
				if (!self) {
					return; // obviously already destroyed
				}

				var shimContainer = Dom.get(this.shimid);
				if (shimContainer) {
					shimContainer.parentNode.removeChild(shimContainer);
				}

				if (_shim) {
					_shim.removeAllInstances();
				}

				this.unbindAll();
				delete runtimes[this.uid];
				this.uid = null; // mark this runtime as destroyed
				_uid = self = _shim = shimContainer = null;
			}
		});

		// once we got the mode, test against all caps
		if (this.mode && options.required_caps && !this.can(options.required_caps)) {
			this.mode = false;
		}	
	}


	/**
	Default order to try different runtime types

	@property order
	@type String
	@static
	*/
	Runtime.order = 'html5,flash,silverlight,html4';


	/**
	Retrieves runtime from private hash by it's uid

	@method getRuntime
	@private
	@static
	@param {String} uid Unique identifier of the runtime
	@return {Runtime|Boolean} Returns runtime, if it exists and false, if - not
	*/
	Runtime.getRuntime = function(uid) {
		return runtimes[uid] ? runtimes[uid] : false;
	};


	/**
	Register constructor for the Runtime of new (or perhaps modified) type

	@method addConstructor
	@static
	@param {String} type Runtime type (e.g. flash, html5, etc)
	@param {Function} construct Constructor for the Runtime type
	*/
	Runtime.addConstructor = function(type, constructor) {
		constructor.prototype = EventTarget.instance;
		runtimeConstructors[type] = constructor;
	};


	/**
	Get the constructor for the specified type.

	method getConstructor
	@static
	@param {String} type Runtime type (e.g. flash, html5, etc)
	@return {Function} Constructor for the Runtime type
	*/
	Runtime.getConstructor = function(type) {
		return runtimeConstructors[type] || null;
	};


	/**
	Get info about the runtime (uid, type, capabilities)

	@method getInfo
	@static
	@param {String} uid Unique identifier of the runtime
	@return {Mixed} Info object or null if runtime doesn't exist
	*/
	Runtime.getInfo = function(uid) {
		var runtime = Runtime.getRuntime(uid);

		if (runtime) {
			return {
				uid: runtime.uid,
				type: runtime.type,
				mode: runtime.mode,
				can: function() {
					return runtime.can.apply(runtime, arguments);
				}
			};
		}
		return null;
	};


	/**
	Convert caps represented by a comma-separated string to the object representation.

	@method parseCaps
	@static
	@param {String} capStr Comma-separated list of capabilities
	@return {Object}
	*/
	Runtime.parseCaps = function(capStr) {
		var capObj = {};

		if (Basic.typeOf(capStr) !== 'string') {
			return capStr || {};
		}

		Basic.each(capStr.split(','), function(key) {
			capObj[key] = true; // we assume it to be - true
		});

		return capObj;
	};

	/**
	Test the specified runtime for specific capabilities.

	@method can
	@static
	@param {String} type Runtime type (e.g. flash, html5, etc)
	@param {String|Object} caps Set of capabilities to check
	@return {Boolean} Result of the test
	*/
	Runtime.can = function(type, caps) {
		var runtime
		, constructor = Runtime.getConstructor(type)
		, mode
		;
		if (constructor) {
			runtime = new constructor({
				required_caps: caps
			});
			mode = runtime.mode;
			runtime.destroy();
			return !!mode;
		}
		return false;
	};


	/**
	Figure out a runtime that supports specified capabilities.

	@method thatCan
	@static
	@param {String|Object} caps Set of capabilities to check
	@param {String} [runtimeOrder] Comma-separated list of runtimes to check against
	@return {String} Usable runtime identifier or null
	*/
	Runtime.thatCan = function(caps, runtimeOrder) {
		var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/);
		for (var i in types) {
			if (Runtime.can(types[i], caps)) {
				return types[i];
			}
		}
		return null;
	};


	/**
	Figure out an operational mode for the specified set of capabilities.

	@method getMode
	@static
	@param {Object} modeCaps Set of capabilities that depend on particular runtime mode
	@param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for
	@param {String|Boolean} [defaultMode='browser'] Default mode to use 
	@return {String|Boolean} Compatible operational mode
	*/
	Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) {
		var mode = null;

		if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified
			defaultMode = 'browser';
		}

		if (requiredCaps && !Basic.isEmptyObj(modeCaps)) {
			// loop over required caps and check if they do require the same mode
			Basic.each(requiredCaps, function(value, cap) {
				if (modeCaps.hasOwnProperty(cap)) {
					var capMode = modeCaps[cap](value);

					// make sure we always have an array
					if (typeof(capMode) === 'string') {
						capMode = [capMode];
					}
					
					if (!mode) {
						mode = capMode;						
					} else if (!(mode = Basic.arrayIntersect(mode, capMode))) {
						// if cap requires conflicting mode - runtime cannot fulfill required caps

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("\t\t%c: %v (conflicting mode requested: %s)", cap, value, capMode);	
						}

						return (mode = false);
					}					
				}

				if (MXI_DEBUG && Env.debug.runtime) {
					Env.log("\t\t%c: %v (compatible modes: %s)", cap, value, mode);	
				}
			});

			if (mode) {
				return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0];
			} else if (mode === false) {
				return false;
			}
		}
		return defaultMode; 
	};


	/**
	Capability check that always returns true

	@private
	@static
	@return {True}
	*/
	Runtime.capTrue = function() {
		return true;
	};

	/**
	Capability check that always returns false

	@private
	@static
	@return {False}
	*/
	Runtime.capFalse = function() {
		return false;
	};

	/**
	Evaluate the expression to boolean value and create a function that always returns it.

	@private
	@static
	@param {Mixed} expr Expression to evaluate
	@return {Function} Function returning the result of evaluation
	*/
	Runtime.capTest = function(expr) {
		return function() {
			return !!expr;
		};
	};

	return Runtime;
});

// Included from: src/javascript/runtime/RuntimeClient.js

/**
 * RuntimeClient.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/runtime/RuntimeClient', [
	'moxie/core/utils/Env',
	'moxie/core/Exceptions',
	'moxie/core/utils/Basic',
	'moxie/runtime/Runtime'
], function(Env, x, Basic, Runtime) {
	/**
	Set of methods and properties, required by a component to acquire ability to connect to a runtime

	@class RuntimeClient
	*/
	return function RuntimeClient() {
		var runtime;

		Basic.extend(this, {
			/**
			Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
			Increments number of clients connected to the specified runtime.

			@private
			@method connectRuntime
			@param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
			*/
			connectRuntime: function(options) {
				var comp = this, ruid;

				function initialize(items) {
					var type, constructor;

					// if we ran out of runtimes
					if (!items.length) {
						comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
						runtime = null;
						return;
					}

					type = items.shift().toLowerCase();
					constructor = Runtime.getConstructor(type);
					if (!constructor) {
						initialize(items);
						return;
					}

					if (MXI_DEBUG && Env.debug.runtime) {
						Env.log("Trying runtime: %s", type);
						Env.log(options);
					}

					// try initializing the runtime
					runtime = new constructor(options);

					runtime.bind('Init', function() {
						// mark runtime as initialized
						runtime.initialized = true;

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' initialized", runtime.type);
						}

						// jailbreak ...
						setTimeout(function() {
							runtime.clients++;
							// this will be triggered on component
							comp.trigger('RuntimeInit', runtime);
						}, 1);
					});

					runtime.bind('Error', function() {
						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' failed to initialize", runtime.type);
						}

						runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
						initialize(items);
					});

					/*runtime.bind('Exception', function() { });*/

					if (MXI_DEBUG && Env.debug.runtime) {
						Env.log("\tselected mode: %s", runtime.mode);	
					}

					// check if runtime managed to pick-up operational mode
					if (!runtime.mode) {
						runtime.trigger('Error');
						return;
					}

					runtime.init();
				}

				// check if a particular runtime was requested
				if (Basic.typeOf(options) === 'string') {
					ruid = options;
				} else if (Basic.typeOf(options.ruid) === 'string') {
					ruid = options.ruid;
				}

				if (ruid) {
					runtime = Runtime.getRuntime(ruid);
					if (runtime) {
						runtime.clients++;
						return runtime;
					} else {
						// there should be a runtime and there's none - weird case
						throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
					}
				}

				// initialize a fresh one, that fits runtime list and required features best
				initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
			},


			/**
			Disconnects from the runtime. Decrements number of clients connected to the specified runtime.

			@private
			@method disconnectRuntime
			*/
			disconnectRuntime: function() {
				if (runtime && --runtime.clients <= 0) {
					runtime.destroy();
				}

				// once the component is disconnected, it shouldn't have access to the runtime
				runtime = null;
			},


			/**
			Returns the runtime to which the client is currently connected.

			@method getRuntime
			@return {Runtime} Runtime or null if client is not connected
			*/
			getRuntime: function() {
				if (runtime && runtime.uid) {
					return runtime;
				}
				return runtime = null; // make sure we do not leave zombies rambling around
			},


			/**
			Handy shortcut to safely invoke runtime extension methods.
			
			@private
			@method exec
			@return {Mixed} Whatever runtime extension method returns
			*/
			exec: function() {
				if (runtime) {
					return runtime.exec.apply(this, arguments);
				}
				return null;
			}

		});
	};


});

// Included from: src/javascript/file/FileInput.js

/**
 * FileInput.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/file/FileInput', [
	'moxie/core/utils/Basic',
	'moxie/core/utils/Env',
	'moxie/core/utils/Mime',
	'moxie/core/utils/Dom',
	'moxie/core/Exceptions',
	'moxie/core/EventTarget',
	'moxie/core/I18n',
	'moxie/runtime/Runtime',
	'moxie/runtime/RuntimeClient'
], function(Basic, Env, Mime, Dom, x, EventTarget, I18n, Runtime, RuntimeClient) {
	/**
	Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click,
	converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory
	with _FileReader_ or uploaded to a server through _XMLHttpRequest_.

	@class FileInput
	@constructor
	@extends EventTarget
	@uses RuntimeClient
	@param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_.
		@param {String|DOMElement} options.browse_button DOM Element to turn into file picker.
		@param {Array} [options.accept] Array of mime types to accept. By default accepts all.
		@param {String} [options.file='file'] Name of the file field (not the filename).
		@param {Boolean} [options.multiple=false] Enable selection of multiple files.
		@param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time).
		@param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode 
		for _browse\_button_.
		@param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support.

	@example
		<div id="container">
			<a id="file-picker" href="javascript:;">Browse...</a>
		</div>

		<script>
			var fileInput = new mOxie.FileInput({
				browse_button: 'file-picker', // or document.getElementById('file-picker')
				container: 'container',
				accept: [
					{title: "Image files", extensions: "jpg,gif,png"} // accept only images
				],
				multiple: true // allow multiple file selection
			});

			fileInput.onchange = function(e) {
				// do something to files array
				console.info(e.target.files); // or this.files or fileInput.files
			};

			fileInput.init(); // initialize
		</script>
	*/
	var dispatches = [
		/**
		Dispatched when runtime is connected and file-picker is ready to be used.

		@event ready
		@param {Object} event
		*/
		'ready',

		/**
		Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked. 
		Check [corresponding documentation entry](#method_refresh) for more info.

		@event refresh
		@param {Object} event
		*/

		/**
		Dispatched when selection of files in the dialog is complete.

		@event change
		@param {Object} event
		*/
		'change',

		'cancel', // TODO: might be useful

		/**
		Dispatched when mouse cursor enters file-picker area. Can be used to style element
		accordingly.

		@event mouseenter
		@param {Object} event
		*/
		'mouseenter',

		/**
		Dispatched when mouse cursor leaves file-picker area. Can be used to style element
		accordingly.

		@event mouseleave
		@param {Object} event
		*/
		'mouseleave',

		/**
		Dispatched when functional mouse button is pressed on top of file-picker area.

		@event mousedown
		@param {Object} event
		*/
		'mousedown',

		/**
		Dispatched when functional mouse button is released on top of file-picker area.

		@event mouseup
		@param {Object} event
		*/
		'mouseup'
	];

	function FileInput(options) {
		if (MXI_DEBUG) {
			Env.log("Instantiating FileInput...");	
		}

		var self = this,
			container, browseButton, defaults;

		// if flat argument passed it should be browse_button id
		if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) {
			options = { browse_button : options };
		}

		// this will help us to find proper default container
		browseButton = Dom.get(options.browse_button);
		if (!browseButton) {
			// browse button is required
			throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
		}

		// figure out the options
		defaults = {
			accept: [{
				title: I18n.translate('All Files'),
				extensions: '*'
			}],
			name: 'file',
			multiple: false,
			required_caps: false,
			container: browseButton.parentNode || document.body
		};
		
		options = Basic.extend({}, defaults, options);

		// convert to object representation
		if (typeof(options.required_caps) === 'string') {
			options.required_caps = Runtime.parseCaps(options.required_caps);
		}
					
		// normalize accept option (could be list of mime types or array of title/extensions pairs)
		if (typeof(options.accept) === 'string') {
			options.accept = Mime.mimes2extList(options.accept);
		}

		container = Dom.get(options.container);
		// make sure we have container
		if (!container) {
			container = document.body;
		}

		// make container relative, if it's not
		if (Dom.getStyle(container, 'position') === 'static') {
			container.style.position = 'relative';
		}

		container = browseButton = null; // IE
						
		RuntimeClient.call(self);
		
		Basic.extend(self, {
			/**
			Unique id of the component

			@property uid
			@protected
			@readOnly
			@type {String}
			@default UID
			*/
			uid: Basic.guid('uid_'),
			
			/**
			Unique id of the connected runtime, if any.

			@property ruid
			@protected
			@type {String}
			*/
			ruid: null,

			/**
			Unique id of the runtime container. Useful to get hold of it for various manipulations.

			@property shimid
			@protected
			@type {String}
			*/
			shimid: null,
			
			/**
			Array of selected mOxie.File objects

			@property files
			@type {Array}
			@default null
			*/
			files: null,

			/**
			Initializes the file-picker, connects it to runtime and dispatches event ready when done.

			@method init
			*/
			init: function() {
				self.bind('RuntimeInit', function(e, runtime) {
					self.ruid = runtime.uid;
					self.shimid = runtime.shimid;

					self.bind("Ready", function() {
						self.trigger("Refresh");
					}, 999);

					// re-position and resize shim container
					self.bind('Refresh', function() {
						var pos, size, browseButton, shimContainer;
						
						browseButton = Dom.get(options.browse_button);
						shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist

						if (browseButton) {
							pos = Dom.getPos(browseButton, Dom.get(options.container));
							size = Dom.getSize(browseButton);

							if (shimContainer) {
								Basic.extend(shimContainer.style, {
									top     : pos.y + 'px',
									left    : pos.x + 'px',
									width   : size.w + 'px',
									height  : size.h + 'px'
								});
							}
						}
						shimContainer = browseButton = null;
					});
					
					runtime.exec.call(self, 'FileInput', 'init', options);
				});

				// runtime needs: options.required_features, options.runtime_order and options.container
				self.connectRuntime(Basic.extend({}, options, {
					required_caps: {
						select_file: true
					}
				}));
			},

			/**
			Disables file-picker element, so that it doesn't react to mouse clicks.

			@method disable
			@param {Boolean} [state=true] Disable component if - true, enable if - false
			*/
			disable: function(state) {
				var runtime = this.getRuntime();
				if (runtime) {
					runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state);
				}
			},


			/**
			Reposition and resize dialog trigger to match the position and size of browse_button element.

			@method refresh
			*/
			refresh: function() {
				self.trigger("Refresh");
			},


			/**
			Destroy component.

			@method destroy
			*/
			destroy: function() {
				var runtime = this.getRuntime();
				if (runtime) {
					runtime.exec.call(this, 'FileInput', 'destroy');
					this.disconnectRuntime();
				}

				if (Basic.typeOf(this.files) === 'array') {
					// no sense in leaving associated files behind
					Basic.each(this.files, function(file) {
						file.destroy();
					});
				} 
				this.files = null;

				this.unbindAll();
			}
		});

		this.handleEventProps(dispatches);
	}

	FileInput.prototype = EventTarget.instance;

	return FileInput;
});

// Included from: src/javascript/core/utils/Encode.js

/**
 * Encode.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/core/utils/Encode', [], function() {

	/**
	Encode string with UTF-8

	@method utf8_encode
	@for Utils
	@static
	@param {String} str String to encode
	@return {String} UTF-8 encoded string
	*/
	var utf8_encode = function(str) {
		return unescape(encodeURIComponent(str));
	};
	
	/**
	Decode UTF-8 encoded string

	@method utf8_decode
	@static
	@param {String} str String to decode
	@return {String} Decoded string
	*/
	var utf8_decode = function(str_data) {
		return decodeURIComponent(escape(str_data));
	};
	
	/**
	Decode Base64 encoded string (uses browser's default method if available),
	from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js

	@method atob
	@static
	@param {String} data String to decode
	@return {String} Decoded string
	*/
	var atob = function(data, utf8) {
		if (typeof(window.atob) === 'function') {
			return utf8 ? utf8_decode(window.atob(data)) : window.atob(data);
		}

		// http://kevin.vanzonneveld.net
		// +   original by: Tyler Akins (http://rumkin.com)
		// +   improved by: Thunder.m
		// +      input by: Aman Gupta
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   bugfixed by: Onno Marsman
		// +   bugfixed by: Pellentesque Malesuada
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: Brett Zamir (http://brett-zamir.me)
		// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
		// *     returns 1: 'Kevin van Zonneveld'
		// mozilla has this native
		// - but breaks in 2.0.0.12!
		//if (typeof this.window.atob == 'function') {
		//    return atob(data);
		//}
		var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
			ac = 0,
			dec = "",
			tmp_arr = [];

		if (!data) {
			return data;
		}

		data += '';

		do { // unpack four hexets into three octets using index points in b64
			h1 = b64.indexOf(data.charAt(i++));
			h2 = b64.indexOf(data.charAt(i++));
			h3 = b64.indexOf(data.charAt(i++));
			h4 = b64.indexOf(data.charAt(i++));

			bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

			o1 = bits >> 16 & 0xff;
			o2 = bits >> 8 & 0xff;
			o3 = bits & 0xff;

			if (h3 == 64) {
				tmp_arr[ac++] = String.fromCharCode(o1);
			} else if (h4 == 64) {
				tmp_arr[ac++] = String.fromCharCode(o1, o2);
			} else {
				tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
			}
		} while (i < data.length);

		dec = tmp_arr.join('');

		return utf8 ? utf8_decode(dec) : dec;
	};
	
	/**
	Base64 encode string (uses browser's default method if available),
	from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js

	@method btoa
	@static
	@param {String} data String to encode
	@return {String} Base64 encoded string
	*/
	var btoa = function(data, utf8) {
		if (utf8) {
			data = utf8_encode(data);
		}

		if (typeof(window.btoa) === 'function') {
			return window.btoa(data);
		}

		// http://kevin.vanzonneveld.net
		// +   original by: Tyler Akins (http://rumkin.com)
		// +   improved by: Bayron Guevara
		// +   improved by: Thunder.m
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   bugfixed by: Pellentesque Malesuada
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Rafał Kukawski (http://kukawski.pl)
		// *     example 1: base64_encode('Kevin van Zonneveld');
		// *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
		// mozilla has this native
		// - but breaks in 2.0.0.12!
		var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
			ac = 0,
			enc = "",
			tmp_arr = [];

		if (!data) {
			return data;
		}

		do { // pack three octets into four hexets
			o1 = data.charCodeAt(i++);
			o2 = data.charCodeAt(i++);
			o3 = data.charCodeAt(i++);

			bits = o1 << 16 | o2 << 8 | o3;

			h1 = bits >> 18 & 0x3f;
			h2 = bits >> 12 & 0x3f;
			h3 = bits >> 6 & 0x3f;
			h4 = bits & 0x3f;

			// use hexets to index into b64, and append result to encoded string
			tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
		} while (i < data.length);

		enc = tmp_arr.join('');

		var r = data.length % 3;

		return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
	};


	return {
		utf8_encode: utf8_encode,
		utf8_decode: utf8_decode,
		atob: atob,
		btoa: btoa
	};
});

// Included from: src/javascript/file/Blob.js

/**
 * Blob.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/file/Blob', [
	'moxie/core/utils/Basic',
	'moxie/core/utils/Encode',
	'moxie/runtime/RuntimeClient'
], function(Basic, Encode, RuntimeClient) {
	
	var blobpool = {};

	/**
	@class Blob
	@constructor
	@param {String} ruid Unique id of the runtime, to which this blob belongs to
	@param {Object} blob Object "Native" blob object, as it is represented in the runtime
	*/
	function Blob(ruid, blob) {

		function _sliceDetached(start, end, type) {
			var blob, data = blobpool[this.uid];

			if (Basic.typeOf(data) !== 'string' || !data.length) {
				return null; // or throw exception
			}

			blob = new Blob(null, {
				type: type,
				size: end - start
			});
			blob.detach(data.substr(start, blob.size));

			return blob;
		}

		RuntimeClient.call(this);

		if (ruid) {	
			this.connectRuntime(ruid);
		}

		if (!blob) {
			blob = {};
		} else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string
			blob = { data: blob };
		}

		Basic.extend(this, {
			
			/**
			Unique id of the component

			@property uid
			@type {String}
			*/
			uid: blob.uid || Basic.guid('uid_'),
			
			/**
			Unique id of the connected runtime, if falsy, then runtime will have to be initialized 
			before this Blob can be used, modified or sent

			@property ruid
			@type {String}
			*/
			ruid: ruid,
	
			/**
			Size of blob

			@property size
			@type {Number}
			@default 0
			*/
			size: blob.size || 0,
			
			/**
			Mime type of blob

			@property type
			@type {String}
			@default ''
			*/
			type: blob.type || '',
			
			/**
			@method slice
			@param {Number} [start=0]
			*/
			slice: function(start, end, type) {		
				if (this.isDetached()) {
					return _sliceDetached.apply(this, arguments);
				}
				return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type);
			},

			/**
			Returns "native" blob object (as it is represented in connected runtime) or null if not found

			@method getSource
			@return {Blob} Returns "native" blob object or null if not found
			*/
			getSource: function() {
				if (!blobpool[this.uid]) {
					return null;	
				}
				return blobpool[this.uid];
			},

			/** 
			Detaches blob from any runtime that it depends on and initialize with standalone value

			@method detach
			@protected
			@param {DOMString} [data=''] Standalone value
			*/
			detach: function(data) {
				if (this.ruid) {
					this.getRuntime().exec.call(this, 'Blob', 'destroy');
					this.disconnectRuntime();
					this.ruid = null;
				}

				data = data || '';

				// if dataUrl, convert to binary string
				if (data.substr(0, 5) == 'data:') {
					var base64Offset = data.indexOf(';base64,');
					this.type = data.substring(5, base64Offset);
					data = Encode.atob(data.substring(base64Offset + 8));
				}

				this.size = data.length;

				blobpool[this.uid] = data;
			},

			/**
			Checks if blob is standalone (detached of any runtime)
			
			@method isDetached
			@protected
			@return {Boolean}
			*/
			isDetached: function() {
				return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string';
			},
			
			/** 
			Destroy Blob and free any resources it was using

			@method destroy
			*/
			destroy: function() {
				this.detach();
				delete blobpool[this.uid];
			}
		});

		
		if (blob.data) {
			this.detach(blob.data); // auto-detach if payload has been passed
		} else {
			blobpool[this.uid] = blob;	
		}
	}
	
	return Blob;
});

// Included from: src/javascript/file/File.js

/**
 * File.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/file/File', [
	'moxie/core/utils/Basic',
	'moxie/core/utils/Mime',
	'moxie/file/Blob'
], function(Basic, Mime, Blob) {
	/**
	@class File
	@extends Blob
	@constructor
	@param {String} ruid Unique id of the runtime, to which this blob belongs to
	@param {Object} file Object "Native" file object, as it is represented in the runtime
	*/
	function File(ruid, file) {
		if (!file) { // avoid extra errors in case we overlooked something
			file = {};
		}

		Blob.apply(this, arguments);

		if (!this.type) {
			this.type = Mime.getFileMime(file.name);
		}

		// sanitize file name or generate new one
		var name;
		if (file.name) {
			name = file.name.replace(/\\/g, '/');
			name = name.substr(name.lastIndexOf('/') + 1);
		} else if (this.type) {
			var prefix = this.type.split('/')[0];
			name = Basic.guid((prefix !== '' ? prefix : 'file') + '_');
			
			if (Mime.extensions[this.type]) {
				name += '.' + Mime.extensions[this.type][0]; // append proper extension if possible
			}
		}
		
		
		Basic.extend(this, {
			/**
			File name

			@property name
			@type {String}
			@default UID
			*/
			name: name || Basic.guid('file_'),

			/**
			Relative path to the file inside a directory

			@property relativePath
			@type {String}
			@default ''
			*/
			relativePath: '',
			
			/**
			Date of last modification

			@property lastModifiedDate
			@type {String}
			@default now
			*/
			lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
		});
	}

	File.prototype = Blob.prototype;

	return File;
});

// Included from: src/javascript/file/FileDrop.js

/**
 * FileDrop.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/file/FileDrop', [
	'moxie/core/I18n',
	'moxie/core/utils/Dom',
	'moxie/core/Exceptions',
	'moxie/core/utils/Basic',
	'moxie/core/utils/Env',
	'moxie/file/File',
	'moxie/runtime/RuntimeClient',
	'moxie/core/EventTarget',
	'moxie/core/utils/Mime'
], function(I18n, Dom, x, Basic, Env, File, RuntimeClient, EventTarget, Mime) {
	/**
	Turn arbitrary DOM element to a drop zone accepting files. Converts selected files to _File_ objects, to be used 
	in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through 
	_XMLHttpRequest_.

	@example
		<div id="drop_zone">
			Drop files here
		</div>
		<br />
		<div id="filelist"></div>

		<script type="text/javascript">
			var fileDrop = new mOxie.FileDrop('drop_zone'), fileList = mOxie.get('filelist');

			fileDrop.ondrop = function() {
				mOxie.each(this.files, function(file) {
					fileList.innerHTML += '<div>' + file.name + '</div>';
				});
			};

			fileDrop.init();
		</script>

	@class FileDrop
	@constructor
	@extends EventTarget
	@uses RuntimeClient
	@param {Object|String} options If options has typeof string, argument is considered as options.drop_zone
		@param {String|DOMElement} options.drop_zone DOM Element to turn into a drop zone
		@param {Array} [options.accept] Array of mime types to accept. By default accepts all
		@param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support
	*/
	var dispatches = [
		/**
		Dispatched when runtime is connected and drop zone is ready to accept files.

		@event ready
		@param {Object} event
		*/
		'ready', 

		/**
		Dispatched when dragging cursor enters the drop zone.

		@event dragenter
		@param {Object} event
		*/
		'dragenter',

		/**
		Dispatched when dragging cursor leaves the drop zone.

		@event dragleave
		@param {Object} event
		*/
		'dragleave', 

		/**
		Dispatched when file is dropped onto the drop zone.

		@event drop
		@param {Object} event
		*/
		'drop', 

		/**
		Dispatched if error occurs.

		@event error
		@param {Object} event
		*/
		'error'
	];

	function FileDrop(options) {
		if (MXI_DEBUG) {
			Env.log("Instantiating FileDrop...");	
		}

		var self = this, defaults;

		// if flat argument passed it should be drop_zone id
		if (typeof(options) === 'string') {
			options = { drop_zone : options };
		}

		// figure out the options
		defaults = {
			accept: [{
				title: I18n.translate('All Files'),
				extensions: '*'
			}],
			required_caps: {
				drag_and_drop: true
			}
		};
		
		options = typeof(options) === 'object' ? Basic.extend({}, defaults, options) : defaults;

		// this will help us to find proper default container
		options.container = Dom.get(options.drop_zone) || document.body;

		// make container relative, if it is not
		if (Dom.getStyle(options.container, 'position') === 'static') {
			options.container.style.position = 'relative';
		}
					
		// normalize accept option (could be list of mime types or array of title/extensions pairs)
		if (typeof(options.accept) === 'string') {
			options.accept = Mime.mimes2extList(options.accept);
		}

		RuntimeClient.call(self);

		Basic.extend(self, {
			uid: Basic.guid('uid_'),

			ruid: null,

			files: null,

			init: function() {		
				self.bind('RuntimeInit', function(e, runtime) {
					self.ruid = runtime.uid;
					runtime.exec.call(self, 'FileDrop', 'init', options);
					self.dispatchEvent('ready');
				});
							
				// runtime needs: options.required_features, options.runtime_order and options.container
				self.connectRuntime(options); // throws RuntimeError
			},

			destroy: function() {
				var runtime = this.getRuntime();
				if (runtime) {
					runtime.exec.call(this, 'FileDrop', 'destroy');
					this.disconnectRuntime();
				}
				this.files = null;
				
				this.unbindAll();
			}
		});

		this.handleEventProps(dispatches);
	}

	FileDrop.prototype = EventTarget.instance;

	return FileDrop;
});

// Included from: src/javascript/file/FileReader.js

/**
 * FileReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/file/FileReader', [
	'moxie/core/utils/Basic',
	'moxie/core/utils/Encode',
	'moxie/core/Exceptions',
	'moxie/core/EventTarget',
	'moxie/file/Blob',
	'moxie/runtime/RuntimeClient'
], function(Basic, Encode, x, EventTarget, Blob, RuntimeClient) {
	/**
	Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader)
	interface. Where possible uses native FileReader, where - not falls back to shims.

	@class FileReader
	@constructor FileReader
	@extends EventTarget
	@uses RuntimeClient
	*/
	var dispatches = [

		/** 
		Dispatched when the read starts.

		@event loadstart
		@param {Object} event
		*/
		'loadstart', 

		/** 
		Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total).

		@event progress
		@param {Object} event
		*/
		'progress', 

		/** 
		Dispatched when the read has successfully completed.

		@event load
		@param {Object} event
		*/
		'load', 

		/** 
		Dispatched when the read has been aborted. For instance, by invoking the abort() method.

		@event abort
		@param {Object} event
		*/
		'abort', 

		/** 
		Dispatched when the read has failed.

		@event error
		@param {Object} event
		*/
		'error', 

		/** 
		Dispatched when the request has completed (either in success or failure).

		@event loadend
		@param {Object} event
		*/
		'loadend'
	];
	
	function FileReader() {

		RuntimeClient.call(this);

		Basic.extend(this, {
			/**
			UID of the component instance.

			@property uid
			@type {String}
			*/
			uid: Basic.guid('uid_'),

			/**
			Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING
			and FileReader.DONE.

			@property readyState
			@type {Number}
			@default FileReader.EMPTY
			*/
			readyState: FileReader.EMPTY,
			
			/**
			Result of the successful read operation.

			@property result
			@type {String}
			*/
			result: null,
			
			/**
			Stores the error of failed asynchronous read operation.

			@property error
			@type {DOMError}
			*/
			error: null,
			
			/**
			Initiates reading of File/Blob object contents to binary string.

			@method readAsBinaryString
			@param {Blob|File} blob Object to preload
			*/
			readAsBinaryString: function(blob) {
				_read.call(this, 'readAsBinaryString', blob);
			},
			
			/**
			Initiates reading of File/Blob object contents to dataURL string.

			@method readAsDataURL
			@param {Blob|File} blob Object to preload
			*/
			readAsDataURL: function(blob) {
				_read.call(this, 'readAsDataURL', blob);
			},
			
			/**
			Initiates reading of File/Blob object contents to string.

			@method readAsText
			@param {Blob|File} blob Object to preload
			*/
			readAsText: function(blob) {
				_read.call(this, 'readAsText', blob);
			},
			
			/**
			Aborts preloading process.

			@method abort
			*/
			abort: function() {
				this.result = null;
				
				if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) {
					return;
				} else if (this.readyState === FileReader.LOADING) {
					this.readyState = FileReader.DONE;
				}

				this.exec('FileReader', 'abort');
				
				this.trigger('abort');
				this.trigger('loadend');
			},

			/**
			Destroy component and release resources.

			@method destroy
			*/
			destroy: function() {
				this.abort();
				this.exec('FileReader', 'destroy');
				this.disconnectRuntime();
				this.unbindAll();
			}
		});

		// uid must already be assigned
		this.handleEventProps(dispatches);

		this.bind('Error', function(e, err) {
			this.readyState = FileReader.DONE;
			this.error = err;
		}, 999);
		
		this.bind('Load', function(e) {
			this.readyState = FileReader.DONE;
		}, 999);

		
		function _read(op, blob) {
			var self = this;			

			this.trigger('loadstart');

			if (this.readyState === FileReader.LOADING) {
				this.trigger('error', new x.DOMException(x.DOMException.INVALID_STATE_ERR));
				this.trigger('loadend');
				return;
			}

			// if source is not o.Blob/o.File
			if (!(blob instanceof Blob)) {
				this.trigger('error', new x.DOMException(x.DOMException.NOT_FOUND_ERR));
				this.trigger('loadend');
				return;
			}

			this.result = null;
			this.readyState = FileReader.LOADING;
			
			if (blob.isDetached()) {
				var src = blob.getSource();
				switch (op) {
					case 'readAsText':
					case 'readAsBinaryString':
						this.result = src;
						break;
					case 'readAsDataURL':
						this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src);
						break;
				}
				this.readyState = FileReader.DONE;
				this.trigger('load');
				this.trigger('loadend');
			} else {
				this.connectRuntime(blob.ruid);
				this.exec('FileReader', 'read', op, blob);
			}
		}
	}
	
	/**
	Initial FileReader state

	@property EMPTY
	@type {Number}
	@final
	@static
	@default 0
	*/
	FileReader.EMPTY = 0;

	/**
	FileReader switches to this state when it is preloading the source

	@property LOADING
	@type {Number}
	@final
	@static
	@default 1
	*/
	FileReader.LOADING = 1;

	/**
	Preloading is complete, this is a final state

	@property DONE
	@type {Number}
	@final
	@static
	@default 2
	*/
	FileReader.DONE = 2;

	FileReader.prototype = EventTarget.instance;

	return FileReader;
});

// Included from: src/javascript/core/utils/Url.js

/**
 * Url.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/core/utils/Url', [], function() {
	/**
	Parse url into separate components and fill in absent parts with parts from current url,
	based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js

	@method parseUrl
	@for Utils
	@static
	@param {String} url Url to parse (defaults to empty string if undefined)
	@return {Object} Hash containing extracted uri components
	*/
	var parseUrl = function(url, currentUrl) {
		var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment']
		, i = key.length
		, ports = {
			http: 80,
			https: 443
		}
		, uri = {}
		, regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/
		, m = regex.exec(url || '')
		;
					
		while (i--) {
			if (m[i]) {
				uri[key[i]] = m[i];
			}
		}

		// when url is relative, we set the origin and the path ourselves
		if (!uri.scheme) {
			// come up with defaults
			if (!currentUrl || typeof(currentUrl) === 'string') {
				currentUrl = parseUrl(currentUrl || document.location.href);
			}

			uri.scheme = currentUrl.scheme;
			uri.host = currentUrl.host;
			uri.port = currentUrl.port;

			var path = '';
			// for urls without trailing slash we need to figure out the path
			if (/^[^\/]/.test(uri.path)) {
				path = currentUrl.path;
				// if path ends with a filename, strip it
				if (/\/[^\/]*\.[^\/]*$/.test(path)) {
					path = path.replace(/\/[^\/]+$/, '/');
				} else {
					// avoid double slash at the end (see #127)
					path = path.replace(/\/?$/, '/');
				}
			}
			uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir
		}

		if (!uri.port) {
			uri.port = ports[uri.scheme] || 80;
		} 
		
		uri.port = parseInt(uri.port, 10);

		if (!uri.path) {
			uri.path = "/";
		}

		delete uri.source;

		return uri;
	};

	/**
	Resolve url - among other things will turn relative url to absolute

	@method resolveUrl
	@static
	@param {String|Object} url Either absolute or relative, or a result of parseUrl call
	@return {String} Resolved, absolute url
	*/
	var resolveUrl = function(url) {
		var ports = { // we ignore default ports
			http: 80,
			https: 443
		}
		, urlp = typeof(url) === 'object' ? url : parseUrl(url);
		;

		return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : '');
	};

	/**
	Check if specified url has the same origin as the current document

	@method hasSameOrigin
	@param {String|Object} url
	@return {Boolean}
	*/
	var hasSameOrigin = function(url) {
		function origin(url) {
			return [url.scheme, url.host, url.port].join('/');
		}
			
		if (typeof url === 'string') {
			url = parseUrl(url);
		}	
		
		return origin(parseUrl()) === origin(url);
	};

	return {
		parseUrl: parseUrl,
		resolveUrl: resolveUrl,
		hasSameOrigin: hasSameOrigin
	};
});

// Included from: src/javascript/runtime/RuntimeTarget.js

/**
 * RuntimeTarget.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/runtime/RuntimeTarget', [
	'moxie/core/utils/Basic',
	'moxie/runtime/RuntimeClient',
	"moxie/core/EventTarget"
], function(Basic, RuntimeClient, EventTarget) {
	/**
	Instance of this class can be used as a target for the events dispatched by shims,
	when allowing them onto components is for either reason inappropriate

	@class RuntimeTarget
	@constructor
	@protected
	@extends EventTarget
	*/
	function RuntimeTarget() {
		this.uid = Basic.guid('uid_');
		
		RuntimeClient.call(this);

		this.destroy = function() {
			this.disconnectRuntime();
			this.unbindAll();
		};
	}

	RuntimeTarget.prototype = EventTarget.instance;

	return RuntimeTarget;
});

// Included from: src/javascript/file/FileReaderSync.js

/**
 * FileReaderSync.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/file/FileReaderSync', [
	'moxie/core/utils/Basic',
	'moxie/runtime/RuntimeClient',
	'moxie/core/utils/Encode'
], function(Basic, RuntimeClient, Encode) {
	/**
	Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here
	it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be,
	but probably < 1mb). Not meant to be used directly by user.

	@class FileReaderSync
	@private
	@constructor
	*/
	return function() {
		RuntimeClient.call(this);

		Basic.extend(this, {
			uid: Basic.guid('uid_'),

			readAsBinaryString: function(blob) {
				return _read.call(this, 'readAsBinaryString', blob);
			},
			
			readAsDataURL: function(blob) {
				return _read.call(this, 'readAsDataURL', blob);
			},
			
			/*readAsArrayBuffer: function(blob) {
				return _read.call(this, 'readAsArrayBuffer', blob);
			},*/
			
			readAsText: function(blob) {
				return _read.call(this, 'readAsText', blob);
			}
		});

		function _read(op, blob) {
			if (blob.isDetached()) {
				var src = blob.getSource();
				switch (op) {
					case 'readAsBinaryString':
						return src;
					case 'readAsDataURL':
						return 'data:' + blob.type + ';base64,' + Encode.btoa(src);
					case 'readAsText':
						var txt = '';
						for (var i = 0, length = src.length; i < length; i++) {
							txt += String.fromCharCode(src[i]);
						}
						return txt;
				}
			} else {
				var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob);
				this.disconnectRuntime();
				return result;
			}
		}
	};
});

// Included from: src/javascript/xhr/FormData.js

/**
 * FormData.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define("moxie/xhr/FormData", [
	"moxie/core/Exceptions",
	"moxie/core/utils/Basic",
	"moxie/file/Blob"
], function(x, Basic, Blob) {
	/**
	FormData

	@class FormData
	@constructor
	*/
	function FormData() {
		var _blob, _fields = [];

		Basic.extend(this, {
			/**
			Append another key-value pair to the FormData object

			@method append
			@param {String} name Name for the new field
			@param {String|Blob|Array|Object} value Value for the field
			*/
			append: function(name, value) {
				var self = this, valueType = Basic.typeOf(value);

				// according to specs value might be either Blob or String
				if (value instanceof Blob) {
					_blob = {
						name: name,
						value: value // unfortunately we can only send single Blob in one FormData
					};
				} else if ('array' === valueType) {
					name += '[]';

					Basic.each(value, function(value) {
						self.append(name, value);
					});
				} else if ('object' === valueType) {
					Basic.each(value, function(value, key) {
						self.append(name + '[' + key + ']', value);
					});
				} else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) {
					self.append(name, "false");
				} else {
					_fields.push({
						name: name,
						value: value.toString()
					});
				}
			},

			/**
			Checks if FormData contains Blob.

			@method hasBlob
			@return {Boolean}
			*/
			hasBlob: function() {
				return !!this.getBlob();
			},

			/**
			Retrieves blob.

			@method getBlob
			@return {Object} Either Blob if found or null
			*/
			getBlob: function() {
				return _blob && _blob.value || null;
			},

			/**
			Retrieves blob field name.

			@method getBlobName
			@return {String} Either Blob field name or null
			*/
			getBlobName: function() {
				return _blob && _blob.name || null;
			},

			/**
			Loop over the fields in FormData and invoke the callback for each of them.

			@method each
			@param {Function} cb Callback to call for each field
			*/
			each: function(cb) {
				Basic.each(_fields, function(field) {
					cb(field.value, field.name);
				});

				if (_blob) {
					cb(_blob.value, _blob.name);
				}
			},

			destroy: function() {
				_blob = null;
				_fields = [];
			}
		});
	}

	return FormData;
});

// Included from: src/javascript/xhr/XMLHttpRequest.js

/**
 * XMLHttpRequest.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define("moxie/xhr/XMLHttpRequest", [
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/core/EventTarget",
	"moxie/core/utils/Encode",
	"moxie/core/utils/Url",
	"moxie/runtime/Runtime",
	"moxie/runtime/RuntimeTarget",
	"moxie/file/Blob",
	"moxie/file/FileReaderSync",
	"moxie/xhr/FormData",
	"moxie/core/utils/Env",
	"moxie/core/utils/Mime"
], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) {

	var httpCode = {
		100: 'Continue',
		101: 'Switching Protocols',
		102: 'Processing',

		200: 'OK',
		201: 'Created',
		202: 'Accepted',
		203: 'Non-Authoritative Information',
		204: 'No Content',
		205: 'Reset Content',
		206: 'Partial Content',
		207: 'Multi-Status',
		226: 'IM Used',

		300: 'Multiple Choices',
		301: 'Moved Permanently',
		302: 'Found',
		303: 'See Other',
		304: 'Not Modified',
		305: 'Use Proxy',
		306: 'Reserved',
		307: 'Temporary Redirect',

		400: 'Bad Request',
		401: 'Unauthorized',
		402: 'Payment Required',
		403: 'Forbidden',
		404: 'Not Found',
		405: 'Method Not Allowed',
		406: 'Not Acceptable',
		407: 'Proxy Authentication Required',
		408: 'Request Timeout',
		409: 'Conflict',
		410: 'Gone',
		411: 'Length Required',
		412: 'Precondition Failed',
		413: 'Request Entity Too Large',
		414: 'Request-URI Too Long',
		415: 'Unsupported Media Type',
		416: 'Requested Range Not Satisfiable',
		417: 'Expectation Failed',
		422: 'Unprocessable Entity',
		423: 'Locked',
		424: 'Failed Dependency',
		426: 'Upgrade Required',

		500: 'Internal Server Error',
		501: 'Not Implemented',
		502: 'Bad Gateway',
		503: 'Service Unavailable',
		504: 'Gateway Timeout',
		505: 'HTTP Version Not Supported',
		506: 'Variant Also Negotiates',
		507: 'Insufficient Storage',
		510: 'Not Extended'
	};

	function XMLHttpRequestUpload() {
		this.uid = Basic.guid('uid_');
	}
	
	XMLHttpRequestUpload.prototype = EventTarget.instance;

	/**
	Implementation of XMLHttpRequest

	@class XMLHttpRequest
	@constructor
	@uses RuntimeClient
	@extends EventTarget
	*/
	var dispatches = [
		'loadstart',

		'progress',

		'abort',

		'error',

		'load',

		'timeout',

		'loadend'

		// readystatechange (for historical reasons)
	]; 
	
	var NATIVE = 1, RUNTIME = 2;
					
	function XMLHttpRequest() {
		var self = this,
			// this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible
			props = {
				/**
				The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout.

				@property timeout
				@type Number
				@default 0
				*/
				timeout: 0,

				/**
				Current state, can take following values:
				UNSENT (numeric value 0)
				The object has been constructed.

				OPENED (numeric value 1)
				The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

				HEADERS_RECEIVED (numeric value 2)
				All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

				LOADING (numeric value 3)
				The response entity body is being received.

				DONE (numeric value 4)

				@property readyState
				@type Number
				@default 0 (UNSENT)
				*/
				readyState: XMLHttpRequest.UNSENT,

				/**
				True when user credentials are to be included in a cross-origin request. False when they are to be excluded
				in a cross-origin request and when cookies are to be ignored in its response. Initially false.

				@property withCredentials
				@type Boolean
				@default false
				*/
				withCredentials: false,

				/**
				Returns the HTTP status code.

				@property status
				@type Number
				@default 0
				*/
				status: 0,

				/**
				Returns the HTTP status text.

				@property statusText
				@type String
				*/
				statusText: "",

				/**
				Returns the response type. Can be set to change the response type. Values are:
				the empty string (default), "arraybuffer", "blob", "document", "json", and "text".
				
				@property responseType
				@type String
				*/
				responseType: "",

				/**
				Returns the document response entity body.
				
				Throws an "InvalidStateError" exception if responseType is not the empty string or "document".

				@property responseXML
				@type Document
				*/
				responseXML: null,

				/**
				Returns the text response entity body.
				
				Throws an "InvalidStateError" exception if responseType is not the empty string or "text".

				@property responseText
				@type String
				*/
				responseText: null,

				/**
				Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body).
				Can become: ArrayBuffer, Blob, Document, JSON, Text
				
				@property response
				@type Mixed
				*/
				response: null
			},

			_async = true,
			_url,
			_method,
			_headers = {},
			_user,
			_password,
			_encoding = null,
			_mimeType = null,

			// flags
			_sync_flag = false,
			_send_flag = false,
			_upload_events_flag = false,
			_upload_complete_flag = false,
			_error_flag = false,
			_same_origin_flag = false,

			// times
			_start_time,
			_timeoutset_time,

			_finalMime = null,
			_finalCharset = null,

			_options = {},
			_xhr,
			_responseHeaders = '',
			_responseHeadersBag
			;

		
		Basic.extend(this, props, {
			/**
			Unique id of the component

			@property uid
			@type String
			*/
			uid: Basic.guid('uid_'),
			
			/**
			Target for Upload events

			@property upload
			@type XMLHttpRequestUpload
			*/
			upload: new XMLHttpRequestUpload(),
			

			/**
			Sets the request method, request URL, synchronous flag, request username, and request password.

			Throws a "SyntaxError" exception if one of the following is true:

			method is not a valid HTTP method.
			url cannot be resolved.
			url contains the "user:password" format in the userinfo production.
			Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.

			Throws an "InvalidAccessError" exception if one of the following is true:

			Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin.
			There is an associated XMLHttpRequest document and either the timeout attribute is not zero,
			the withCredentials attribute is true, or the responseType attribute is not the empty string.


			@method open
			@param {String} method HTTP method to use on request
			@param {String} url URL to request
			@param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default.
			@param {String} [user] Username to use in HTTP authentication process on server-side
			@param {String} [password] Password to use in HTTP authentication process on server-side
			*/
			open: function(method, url, async, user, password) {
				var urlp;
				
				// first two arguments are required
				if (!method || !url) {
					throw new x.DOMException(x.DOMException.SYNTAX_ERR);
				}
				
				// 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method
				if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) {
					throw new x.DOMException(x.DOMException.SYNTAX_ERR);
				}

				// 3
				if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) {
					_method = method.toUpperCase();
				}
				
				
				// 4 - allowing these methods poses a security risk
				if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) {
					throw new x.DOMException(x.DOMException.SECURITY_ERR);
				}

				// 5
				url = Encode.utf8_encode(url);
				
				// 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError".
				urlp = Url.parseUrl(url);

				_same_origin_flag = Url.hasSameOrigin(urlp);
																
				// 7 - manually build up absolute url
				_url = Url.resolveUrl(url);
		
				// 9-10, 12-13
				if ((user || password) && !_same_origin_flag) {
					throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
				}

				_user = user || urlp.user;
				_password = password || urlp.pass;
				
				// 11
				_async = async || true;
				
				if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) {
					throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
				}
				
				// 14 - terminate abort()
				
				// 15 - terminate send()

				// 18
				_sync_flag = !_async;
				_send_flag = false;
				_headers = {};
				_reset.call(this);

				// 19
				_p('readyState', XMLHttpRequest.OPENED);
				
				// 20
				this.dispatchEvent('readystatechange');
			},
			
			/**
			Appends an header to the list of author request headers, or if header is already
			in the list of author request headers, combines its value with value.

			Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
			Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value
			is not a valid HTTP header field value.
			
			@method setRequestHeader
			@param {String} header
			@param {String|Number} value
			*/
			setRequestHeader: function(header, value) {
				var uaHeaders = [ // these headers are controlled by the user agent
						"accept-charset",
						"accept-encoding",
						"access-control-request-headers",
						"access-control-request-method",
						"connection",
						"content-length",
						"cookie",
						"cookie2",
						"content-transfer-encoding",
						"date",
						"expect",
						"host",
						"keep-alive",
						"origin",
						"referer",
						"te",
						"trailer",
						"transfer-encoding",
						"upgrade",
						"user-agent",
						"via"
					];
				
				// 1-2
				if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				// 3
				if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) {
					throw new x.DOMException(x.DOMException.SYNTAX_ERR);
				}

				// 4
				/* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values
				if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {
					throw new x.DOMException(x.DOMException.SYNTAX_ERR);
				}*/

				header = Basic.trim(header).toLowerCase();
				
				// setting of proxy-* and sec-* headers is prohibited by spec
				if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) {
					return false;
				}

				// camelize
				// browsers lowercase header names (at least for custom ones)
				// header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); });
				
				if (!_headers[header]) {
					_headers[header] = value;
				} else {
					// http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph)
					_headers[header] += ', ' + value;
				}
				return true;
			},

			/**
			Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.

			@method getAllResponseHeaders
			@return {String} reponse headers or empty string
			*/
			getAllResponseHeaders: function() {
				return _responseHeaders || '';
			},

			/**
			Returns the header field value from the response of which the field name matches header, 
			unless the field name is Set-Cookie or Set-Cookie2.

			@method getResponseHeader
			@param {String} header
			@return {String} value(s) for the specified header or null
			*/
			getResponseHeader: function(header) {
				header = header.toLowerCase();

				if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) {
					return null;
				}

				if (_responseHeaders && _responseHeaders !== '') {
					// if we didn't parse response headers until now, do it and keep for later
					if (!_responseHeadersBag) {
						_responseHeadersBag = {};
						Basic.each(_responseHeaders.split(/\r\n/), function(line) {
							var pair = line.split(/:\s+/);
							if (pair.length === 2) { // last line might be empty, omit
								pair[0] = Basic.trim(pair[0]); // just in case
								_responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form
									header: pair[0],
									value: Basic.trim(pair[1])
								};
							}
						});
					}
					if (_responseHeadersBag.hasOwnProperty(header)) {
						return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value;
					}
				}
				return null;
			},
			
			/**
			Sets the Content-Type header for the response to mime.
			Throws an "InvalidStateError" exception if the state is LOADING or DONE.
			Throws a "SyntaxError" exception if mime is not a valid media type.

			@method overrideMimeType
			@param String mime Mime type to set
			*/
			overrideMimeType: function(mime) {
				var matches, charset;
			
				// 1
				if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				// 2
				mime = Basic.trim(mime.toLowerCase());

				if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) {
					mime = matches[1];
					if (matches[2]) {
						charset = matches[2];
					}
				}

				if (!Mime.mimes[mime]) {
					throw new x.DOMException(x.DOMException.SYNTAX_ERR);
				}

				// 3-4
				_finalMime = mime;
				_finalCharset = charset;
			},
			
			/**
			Initiates the request. The optional argument provides the request entity body.
			The argument is ignored if request method is GET or HEAD.

			Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.

			@method send
			@param {Blob|Document|String|FormData} [data] Request entity body
			@param {Object} [options] Set of requirements and pre-requisities for runtime initialization
			*/
			send: function(data, options) {					
				if (Basic.typeOf(options) === 'string') {
					_options = { ruid: options };
				} else if (!options) {
					_options = {};
				} else {
					_options = options;
				}
															
				// 1-2
				if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}
				
				// 3					
				// sending Blob
				if (data instanceof Blob) {
					_options.ruid = data.ruid;
					_mimeType = data.type || 'application/octet-stream';
				}
				
				// FormData
				else if (data instanceof FormData) {
					if (data.hasBlob()) {
						var blob = data.getBlob();
						_options.ruid = blob.ruid;
						_mimeType = blob.type || 'application/octet-stream';
					}
				}
				
				// DOMString
				else if (typeof data === 'string') {
					_encoding = 'UTF-8';
					_mimeType = 'text/plain;charset=UTF-8';
					
					// data should be converted to Unicode and encoded as UTF-8
					data = Encode.utf8_encode(data);
				}

				// if withCredentials not set, but requested, set it automatically
				if (!this.withCredentials) {
					this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag;
				}

				// 4 - storage mutex
				// 5
				_upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP
				// 6
				_error_flag = false;
				// 7
				_upload_complete_flag = !data;
				// 8 - Asynchronous steps
				if (!_sync_flag) {
					// 8.1
					_send_flag = true;
					// 8.2
					// this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
					// 8.3
					//if (!_upload_complete_flag) {
						// this.upload.dispatchEvent('loadstart');	// will be dispatched either by native or runtime xhr
					//}
				}
				// 8.5 - Return the send() method call, but continue running the steps in this algorithm.
				_doXHR.call(this, data);
			},
			
			/**
			Cancels any network activity.
			
			@method abort
			*/
			abort: function() {
				_error_flag = true;
				_sync_flag = false;

				if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) {
					_p('readyState', XMLHttpRequest.DONE);
					_send_flag = false;

					if (_xhr) {
						_xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag);
					} else {
						throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
					}

					_upload_complete_flag = true;
				} else {
					_p('readyState', XMLHttpRequest.UNSENT);
				}
			},

			destroy: function() {
				if (_xhr) {
					if (Basic.typeOf(_xhr.destroy) === 'function') {
						_xhr.destroy();
					}
					_xhr = null;
				}

				this.unbindAll();

				if (this.upload) {
					this.upload.unbindAll();
					this.upload = null;
				}
			}
		});

		this.handleEventProps(dispatches.concat(['readystatechange'])); // for historical reasons
		this.upload.handleEventProps(dispatches);

		/* this is nice, but maybe too lengthy

		// if supported by JS version, set getters/setters for specific properties
		o.defineProperty(this, 'readyState', {
			configurable: false,

			get: function() {
				return _p('readyState');
			}
		});

		o.defineProperty(this, 'timeout', {
			configurable: false,

			get: function() {
				return _p('timeout');
			},

			set: function(value) {

				if (_sync_flag) {
					throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
				}

				// timeout still should be measured relative to the start time of request
				_timeoutset_time = (new Date).getTime();

				_p('timeout', value);
			}
		});

		// the withCredentials attribute has no effect when fetching same-origin resources
		o.defineProperty(this, 'withCredentials', {
			configurable: false,

			get: function() {
				return _p('withCredentials');
			},

			set: function(value) {
				// 1-2
				if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				// 3-4
				if (_anonymous_flag || _sync_flag) {
					throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
				}

				// 5
				_p('withCredentials', value);
			}
		});

		o.defineProperty(this, 'status', {
			configurable: false,

			get: function() {
				return _p('status');
			}
		});

		o.defineProperty(this, 'statusText', {
			configurable: false,

			get: function() {
				return _p('statusText');
			}
		});

		o.defineProperty(this, 'responseType', {
			configurable: false,

			get: function() {
				return _p('responseType');
			},

			set: function(value) {
				// 1
				if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				// 2
				if (_sync_flag) {
					throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
				}

				// 3
				_p('responseType', value.toLowerCase());
			}
		});

		o.defineProperty(this, 'responseText', {
			configurable: false,

			get: function() {
				// 1
				if (!~o.inArray(_p('responseType'), ['', 'text'])) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				// 2-3
				if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				return _p('responseText');
			}
		});

		o.defineProperty(this, 'responseXML', {
			configurable: false,

			get: function() {
				// 1
				if (!~o.inArray(_p('responseType'), ['', 'document'])) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				// 2-3
				if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}

				return _p('responseXML');
			}
		});

		o.defineProperty(this, 'response', {
			configurable: false,

			get: function() {
				if (!!~o.inArray(_p('responseType'), ['', 'text'])) {
					if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
						return '';
					}
				}

				if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
					return null;
				}

				return _p('response');
			}
		});

		*/

		function _p(prop, value) {
			if (!props.hasOwnProperty(prop)) {
				return;
			}
			if (arguments.length === 1) { // get
				return Env.can('define_property') ? props[prop] : self[prop];
			} else { // set
				if (Env.can('define_property')) {
					props[prop] = value;
				} else {
					self[prop] = value;
				}
			}
		}
		
		/*
		function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) {
			// TODO: http://tools.ietf.org/html/rfc3490#section-4.1
			return str.toLowerCase();
		}
		*/
		
		
		function _doXHR(data) {
			var self = this;
			
			_start_time = new Date().getTime();

			_xhr = new RuntimeTarget();

			function loadEnd() {
				if (_xhr) { // it could have been destroyed by now
					_xhr.destroy();
					_xhr = null;
				}
				self.dispatchEvent('loadend');
				self = null;
			}

			function exec(runtime) {
				_xhr.bind('LoadStart', function(e) {
					_p('readyState', XMLHttpRequest.LOADING);
					self.dispatchEvent('readystatechange');

					self.dispatchEvent(e);
					
					if (_upload_events_flag) {
						self.upload.dispatchEvent(e);
					}
				});
				
				_xhr.bind('Progress', function(e) {
					if (_p('readyState') !== XMLHttpRequest.LOADING) {
						_p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example)
						self.dispatchEvent('readystatechange');
					}
					self.dispatchEvent(e);
				});
				
				_xhr.bind('UploadProgress', function(e) {
					if (_upload_events_flag) {
						self.upload.dispatchEvent({
							type: 'progress',
							lengthComputable: false,
							total: e.total,
							loaded: e.loaded
						});
					}
				});
				
				_xhr.bind('Load', function(e) {
					_p('readyState', XMLHttpRequest.DONE);
					_p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0));
					_p('statusText', httpCode[_p('status')] || "");
					
					_p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType')));

					if (!!~Basic.inArray(_p('responseType'), ['text', ''])) {
						_p('responseText', _p('response'));
					} else if (_p('responseType') === 'document') {
						_p('responseXML', _p('response'));
					}

					_responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders');

					self.dispatchEvent('readystatechange');
					
					if (_p('status') > 0) { // status 0 usually means that server is unreachable
						if (_upload_events_flag) {
							self.upload.dispatchEvent(e);
						}
						self.dispatchEvent(e);
					} else {
						_error_flag = true;
						self.dispatchEvent('error');
					}
					loadEnd();
				});

				_xhr.bind('Abort', function(e) {
					self.dispatchEvent(e);
					loadEnd();
				});
				
				_xhr.bind('Error', function(e) {
					_error_flag = true;
					_p('readyState', XMLHttpRequest.DONE);
					self.dispatchEvent('readystatechange');
					_upload_complete_flag = true;
					self.dispatchEvent(e);
					loadEnd();
				});

				runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', {
					url: _url,
					method: _method,
					async: _async,
					user: _user,
					password: _password,
					headers: _headers,
					mimeType: _mimeType,
					encoding: _encoding,
					responseType: self.responseType,
					withCredentials: self.withCredentials,
					options: _options
				}, data);
			}

			// clarify our requirements
			if (typeof(_options.required_caps) === 'string') {
				_options.required_caps = Runtime.parseCaps(_options.required_caps);
			}

			_options.required_caps = Basic.extend({}, _options.required_caps, {
				return_response_type: self.responseType
			});

			if (data instanceof FormData) {
				_options.required_caps.send_multipart = true;
			}

			if (!Basic.isEmptyObj(_headers)) {
				_options.required_caps.send_custom_headers = true;
			}

			if (!_same_origin_flag) {
				_options.required_caps.do_cors = true;
			}
			

			if (_options.ruid) { // we do not need to wait if we can connect directly
				exec(_xhr.connectRuntime(_options));
			} else {
				_xhr.bind('RuntimeInit', function(e, runtime) {
					exec(runtime);
				});
				_xhr.bind('RuntimeError', function(e, err) {
					self.dispatchEvent('RuntimeError', err);
				});
				_xhr.connectRuntime(_options);
			}
		}
	
		
		function _reset() {
			_p('responseText', "");
			_p('responseXML', null);
			_p('response', null);
			_p('status', 0);
			_p('statusText', "");
			_start_time = _timeoutset_time = null;
		}
	}

	XMLHttpRequest.UNSENT = 0;
	XMLHttpRequest.OPENED = 1;
	XMLHttpRequest.HEADERS_RECEIVED = 2;
	XMLHttpRequest.LOADING = 3;
	XMLHttpRequest.DONE = 4;
	
	XMLHttpRequest.prototype = EventTarget.instance;

	return XMLHttpRequest;
});

// Included from: src/javascript/runtime/Transporter.js

/**
 * Transporter.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define("moxie/runtime/Transporter", [
	"moxie/core/utils/Basic",
	"moxie/core/utils/Encode",
	"moxie/runtime/RuntimeClient",
	"moxie/core/EventTarget"
], function(Basic, Encode, RuntimeClient, EventTarget) {
	function Transporter() {
		var mod, _runtime, _data, _size, _pos, _chunk_size;

		RuntimeClient.call(this);

		Basic.extend(this, {
			uid: Basic.guid('uid_'),

			state: Transporter.IDLE,

			result: null,

			transport: function(data, type, options) {
				var self = this;

				options = Basic.extend({
					chunk_size: 204798
				}, options);

				// should divide by three, base64 requires this
				if ((mod = options.chunk_size % 3)) {
					options.chunk_size += 3 - mod;
				}

				_chunk_size = options.chunk_size;

				_reset.call(this);
				_data = data;
				_size = data.length;

				if (Basic.typeOf(options) === 'string' || options.ruid) {
					_run.call(self, type, this.connectRuntime(options));
				} else {
					// we require this to run only once
					var cb = function(e, runtime) {
						self.unbind("RuntimeInit", cb);
						_run.call(self, type, runtime);
					};
					this.bind("RuntimeInit", cb);
					this.connectRuntime(options);
				}
			},

			abort: function() {
				var self = this;

				self.state = Transporter.IDLE;
				if (_runtime) {
					_runtime.exec.call(self, 'Transporter', 'clear');
					self.trigger("TransportingAborted");
				}

				_reset.call(self);
			},


			destroy: function() {
				this.unbindAll();
				_runtime = null;
				this.disconnectRuntime();
				_reset.call(this);
			}
		});

		function _reset() {
			_size = _pos = 0;
			_data = this.result = null;
		}

		function _run(type, runtime) {
			var self = this;

			_runtime = runtime;

			//self.unbind("RuntimeInit");

			self.bind("TransportingProgress", function(e) {
				_pos = e.loaded;

				if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) {
					_transport.call(self);
				}
			}, 999);

			self.bind("TransportingComplete", function() {
				_pos = _size;
				self.state = Transporter.DONE;
				_data = null; // clean a bit
				self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || '');
			}, 999);

			self.state = Transporter.BUSY;
			self.trigger("TransportingStarted");
			_transport.call(self);
		}

		function _transport() {
			var self = this,
				chunk,
				bytesLeft = _size - _pos;

			if (_chunk_size > bytesLeft) {
				_chunk_size = bytesLeft;
			}

			chunk = Encode.btoa(_data.substr(_pos, _chunk_size));
			_runtime.exec.call(self, 'Transporter', 'receive', chunk, _size);
		}
	}

	Transporter.IDLE = 0;
	Transporter.BUSY = 1;
	Transporter.DONE = 2;

	Transporter.prototype = EventTarget.instance;

	return Transporter;
});

// Included from: src/javascript/image/Image.js

/**
 * Image.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define("moxie/image/Image", [
	"moxie/core/utils/Basic",
	"moxie/core/utils/Dom",
	"moxie/core/Exceptions",
	"moxie/file/FileReaderSync",
	"moxie/xhr/XMLHttpRequest",
	"moxie/runtime/Runtime",
	"moxie/runtime/RuntimeClient",
	"moxie/runtime/Transporter",
	"moxie/core/utils/Env",
	"moxie/core/EventTarget",
	"moxie/file/Blob",
	"moxie/file/File",
	"moxie/core/utils/Encode"
], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode) {
	/**
	Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data.

	@class Image
	@constructor
	@extends EventTarget
	*/
	var dispatches = [
		'progress',

		/**
		Dispatched when loading is complete.

		@event load
		@param {Object} event
		*/
		'load',

		'error',

		/**
		Dispatched when resize operation is complete.
		
		@event resize
		@param {Object} event
		*/
		'resize',

		/**
		Dispatched when visual representation of the image is successfully embedded
		into the corresponsing container.

		@event embedded
		@param {Object} event
		*/
		'embedded'
	];

	function Image() {

		RuntimeClient.call(this);

		Basic.extend(this, {
			/**
			Unique id of the component

			@property uid
			@type {String}
			*/
			uid: Basic.guid('uid_'),

			/**
			Unique id of the connected runtime, if any.

			@property ruid
			@type {String}
			*/
			ruid: null,

			/**
			Name of the file, that was used to create an image, if available. If not equals to empty string.

			@property name
			@type {String}
			@default ""
			*/
			name: "",

			/**
			Size of the image in bytes. Actual value is set only after image is preloaded.

			@property size
			@type {Number}
			@default 0
			*/
			size: 0,

			/**
			Width of the image. Actual value is set only after image is preloaded.

			@property width
			@type {Number}
			@default 0
			*/
			width: 0,

			/**
			Height of the image. Actual value is set only after image is preloaded.

			@property height
			@type {Number}
			@default 0
			*/
			height: 0,

			/**
			Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded.

			@property type
			@type {String}
			@default ""
			*/
			type: "",

			/**
			Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded.

			@property meta
			@type {Object}
			@default {}
			*/
			meta: {},

			/**
			Alias for load method, that takes another mOxie.Image object as a source (see load).

			@method clone
			@param {Image} src Source for the image
			@param {Boolean} [exact=false] Whether to activate in-depth clone mode
			*/
			clone: function() {
				this.load.apply(this, arguments);
			},

			/**
			Loads image from various sources. Currently the source for new image can be: mOxie.Image, mOxie.Blob/mOxie.File, 
			native Blob/File, dataUrl or URL. Depending on the type of the source, arguments - differ. When source is URL, 
			Image will be downloaded from remote destination and loaded in memory.

			@example
				var img = new mOxie.Image();
				img.onload = function() {
					var blob = img.getAsBlob();
					
					var formData = new mOxie.FormData();
					formData.append('file', blob);

					var xhr = new mOxie.XMLHttpRequest();
					xhr.onload = function() {
						// upload complete
					};
					xhr.open('post', 'upload.php');
					xhr.send(formData);
				};
				img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg)
			

			@method load
			@param {Image|Blob|File|String} src Source for the image
			@param {Boolean|Object} [mixed]
			*/
			load: function() {
				_load.apply(this, arguments);
			},

			/**
			Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions.

			@method downsize
			@param {Object} opts
				@param {Number} opts.width Resulting width
				@param {Number} [opts.height=width] Resulting height (optional, if not supplied will default to width)
				@param {Boolean} [opts.crop=false] Whether to crop the image to exact dimensions
				@param {Boolean} [opts.preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
				@param {String} [opts.resample=false] Resampling algorithm to use for resizing
			*/
			downsize: function(opts) {
				var defaults = {
					width: this.width,
					height: this.height,
					type: this.type || 'image/jpeg',
					quality: 90,
					crop: false,
					preserveHeaders: true,
					resample: false
				};

				if (typeof(opts) === 'object') {
					opts = Basic.extend(defaults, opts);
				} else {
					// for backward compatibility
					opts = Basic.extend(defaults, {
						width: arguments[0],
						height: arguments[1],
						crop: arguments[2],
						preserveHeaders: arguments[3]
					});
				}

				try {
					if (!this.size) { // only preloaded image objects can be used as source
						throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
					}

					// no way to reliably intercept the crash due to high resolution, so we simply avoid it
					if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) {
						throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
					}

					this.exec('Image', 'downsize', opts.width, opts.height, opts.crop, opts.preserveHeaders);
				} catch(ex) {
					// for now simply trigger error event
					this.trigger('error', ex.code);
				}
			},

			/**
			Alias for downsize(width, height, true). (see downsize)
			
			@method crop
			@param {Number} width Resulting width
			@param {Number} [height=width] Resulting height (optional, if not supplied will default to width)
			@param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
			*/
			crop: function(width, height, preserveHeaders) {
				this.downsize(width, height, true, preserveHeaders);
			},

			getAsCanvas: function() {
				if (!Env.can('create_canvas')) {
					throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
				}

				var runtime = this.connectRuntime(this.ruid);
				return runtime.exec.call(this, 'Image', 'getAsCanvas');
			},

			/**
			Retrieves image in it's current state as mOxie.Blob object. Cannot be run on empty or image in progress (throws
			DOMException.INVALID_STATE_ERR).

			@method getAsBlob
			@param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
			@param {Number} [quality=90] Applicable only together with mime type image/jpeg
			@return {Blob} Image as Blob
			*/
			getAsBlob: function(type, quality) {
				if (!this.size) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}
				return this.exec('Image', 'getAsBlob', type || 'image/jpeg', quality || 90);
			},

			/**
			Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws
			DOMException.INVALID_STATE_ERR).

			@method getAsDataURL
			@param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
			@param {Number} [quality=90] Applicable only together with mime type image/jpeg
			@return {String} Image as dataURL string
			*/
			getAsDataURL: function(type, quality) {
				if (!this.size) {
					throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
				}
				return this.exec('Image', 'getAsDataURL', type || 'image/jpeg', quality || 90);
			},

			/**
			Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws
			DOMException.INVALID_STATE_ERR).

			@method getAsBinaryString
			@param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
			@param {Number} [quality=90] Applicable only together with mime type image/jpeg
			@return {String} Image as binary string
			*/
			getAsBinaryString: function(type, quality) {
				var dataUrl = this.getAsDataURL(type, quality);
				return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7));
			},

			/**
			Embeds a visual representation of the image into the specified node. Depending on the runtime, 
			it might be a canvas, an img node or a thrid party shim object (Flash or SilverLight - very rare, 
			can be used in legacy browsers that do not have canvas or proper dataURI support).

			@method embed
			@param {DOMElement} el DOM element to insert the image object into
			@param {Object} [opts]
				@param {Number} [opts.width] The width of an embed (defaults to the image width)
				@param {Number} [opts.height] The height of an embed (defaults to the image height)
				@param {String} [type="image/jpeg"] Mime type
				@param {Number} [quality=90] Quality of an embed, if mime type is image/jpeg
				@param {Boolean} [crop=false] Whether to crop an embed to the specified dimensions
			*/
			embed: function(el, opts) {
				var self = this
				, runtime // this has to be outside of all the closures to contain proper runtime
				;

				opts = Basic.extend({
					width: this.width,
					height: this.height,
					type: this.type || 'image/jpeg',
					quality: 90
				}, opts || {});
				

				function render(type, quality) {
					var img = this;

					// if possible, embed a canvas element directly
					if (Env.can('create_canvas')) {
						var canvas = img.getAsCanvas();
						if (canvas) {
							el.appendChild(canvas);
							canvas = null;
							img.destroy();
							self.trigger('embedded');
							return;
						}
					}

					var dataUrl = img.getAsDataURL(type, quality);
					if (!dataUrl) {
						throw new x.ImageError(x.ImageError.WRONG_FORMAT);
					}

					if (Env.can('use_data_uri_of', dataUrl.length)) {
						el.innerHTML = '<img src="' + dataUrl + '" width="' + img.width + '" height="' + img.height + '" />';
						img.destroy();
						self.trigger('embedded');
					} else {
						var tr = new Transporter();

						tr.bind("TransportingComplete", function() {
							runtime = self.connectRuntime(this.result.ruid);

							self.bind("Embedded", function() {
								// position and size properly
								Basic.extend(runtime.getShimContainer().style, {
									//position: 'relative',
									top: '0px',
									left: '0px',
									width: img.width + 'px',
									height: img.height + 'px'
								});

								// some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's
								// position type changes (in Gecko), but since we basically need this only in IEs 6/7 and
								// sometimes 8 and they do not have this problem, we can comment this for now
								/*tr.bind("RuntimeInit", function(e, runtime) {
									tr.destroy();
									runtime.destroy();
									onResize.call(self); // re-feed our image data
								});*/

								runtime = null; // release
							}, 999);

							runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height);
							img.destroy();
						});

						tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, {
							required_caps: {
								display_media: true
							},
							runtime_order: 'flash,silverlight',
							container: el
						});
					}
				}

				try {
					if (!(el = Dom.get(el))) {
						throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR);
					}

					if (!this.size) { // only preloaded image objects can be used as source
						throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
					}
					
					// high-resolution images cannot be consistently handled across the runtimes
					if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) {
						//throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
					}

					var imgCopy = new Image();

					imgCopy.bind("Resize", function() {
						render.call(this, opts.type, opts.quality);
					});

					imgCopy.bind("Load", function() {
						imgCopy.downsize(opts);
					});

					// if embedded thumb data is available and dimensions are big enough, use it
					if (this.meta.thumb && this.meta.thumb.width >= opts.width && this.meta.thumb.height >= opts.height) {
						imgCopy.load(this.meta.thumb.data);
					} else {
						imgCopy.clone(this, false);
					}

					return imgCopy;
				} catch(ex) {
					// for now simply trigger error event
					this.trigger('error', ex.code);
				}
			},

			/**
			Properly destroys the image and frees resources in use. If any. Recommended way to dispose mOxie.Image object.

			@method destroy
			*/
			destroy: function() {
				if (this.ruid) {
					this.getRuntime().exec.call(this, 'Image', 'destroy');
					this.disconnectRuntime();
				}
				this.unbindAll();
			}
		});


		// this is here, because in order to bind properly, we need uid, which is created above
		this.handleEventProps(dispatches);

		this.bind('Load Resize', function() {
			_updateInfo.call(this);
		}, 999);


		function _updateInfo(info) {
			if (!info) {
				info = this.exec('Image', 'getInfo');
			}

			this.size = info.size;
			this.width = info.width;
			this.height = info.height;
			this.type = info.type;
			this.meta = info.meta;

			// update file name, only if empty
			if (this.name === '') {
				this.name = info.name;
			}
		}
		

		function _load(src) {
			var srcType = Basic.typeOf(src);

			try {
				// if source is Image
				if (src instanceof Image) {
					if (!src.size) { // only preloaded image objects can be used as source
						throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
					}
					_loadFromImage.apply(this, arguments);
				}
				// if source is o.Blob/o.File
				else if (src instanceof Blob) {
					if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) {
						throw new x.ImageError(x.ImageError.WRONG_FORMAT);
					}
					_loadFromBlob.apply(this, arguments);
				}
				// if native blob/file
				else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) {
					_load.call(this, new File(null, src), arguments[1]);
				}
				// if String
				else if (srcType === 'string') {
					// if dataUrl String
					if (src.substr(0, 5) === 'data:') {
						_load.call(this, new Blob(null, { data: src }), arguments[1]);
					}
					// else assume Url, either relative or absolute
					else {
						_loadFromUrl.apply(this, arguments);
					}
				}
				// if source seems to be an img node
				else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') {
					_load.call(this, src.src, arguments[1]);
				}
				else {
					throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR);
				}
			} catch(ex) {
				// for now simply trigger error event
				this.trigger('error', ex.code);
			}
		}


		function _loadFromImage(img, exact) {
			var runtime = this.connectRuntime(img.ruid);
			this.ruid = runtime.uid;
			runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact));
		}


		function _loadFromBlob(blob, options) {
			var self = this;

			self.name = blob.name || '';

			function exec(runtime) {
				self.ruid = runtime.uid;
				runtime.exec.call(self, 'Image', 'loadFromBlob', blob);
			}

			if (blob.isDetached()) {
				this.bind('RuntimeInit', function(e, runtime) {
					exec(runtime);
				});

				// convert to object representation
				if (options && typeof(options.required_caps) === 'string') {
					options.required_caps = Runtime.parseCaps(options.required_caps);
				}

				this.connectRuntime(Basic.extend({
					required_caps: {
						access_image_binary: true,
						resize_image: true
					}
				}, options));
			} else {
				exec(this.connectRuntime(blob.ruid));
			}
		}


		function _loadFromUrl(url, options) {
			var self = this, xhr;

			xhr = new XMLHttpRequest();

			xhr.open('get', url);
			xhr.responseType = 'blob';

			xhr.onprogress = function(e) {
				self.trigger(e);
			};

			xhr.onload = function() {
				_loadFromBlob.call(self, xhr.response, true);
			};

			xhr.onerror = function(e) {
				self.trigger(e);
			};

			xhr.onloadend = function() {
				xhr.destroy();
			};

			xhr.bind('RuntimeError', function(e, err) {
				self.trigger('RuntimeError', err);
			});

			xhr.send(null, options);
		}
	}

	// virtual world will crash on you if image has a resolution higher than this:
	Image.MAX_RESIZE_WIDTH = 8192;
	Image.MAX_RESIZE_HEIGHT = 8192; 

	Image.prototype = EventTarget.instance;

	return Image;
});

// Included from: src/javascript/runtime/html5/Runtime.js

/**
 * Runtime.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*global File:true */

/**
Defines constructor for HTML5 runtime.

@class moxie/runtime/html5/Runtime
@private
*/
define("moxie/runtime/html5/Runtime", [
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/runtime/Runtime",
	"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
	
	var type = "html5", extensions = {};
	
	function Html5Runtime(options) {
		var I = this
		, Test = Runtime.capTest
		, True = Runtime.capTrue
		;

		var caps = Basic.extend({
				access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL),
				access_image_binary: function() {
					return I.can('access_binary') && !!extensions.Image;
				},
				display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')),
				do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()),
				drag_and_drop: Test(function() {
					// this comes directly from Modernizr: http://www.modernizr.com/
					var div = document.createElement('div');
					// IE has support for drag and drop since version 5, but doesn't support dropping files from desktop
					return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 
						(Env.browser !== 'IE' || Env.verComp(Env.version, 9, '>'));
				}()),
				filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
					return !(
						(Env.browser === 'Chrome' && Env.verComp(Env.version, 28, '<')) || 
						(Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) || 
						(Env.browser === 'Safari' && Env.verComp(Env.version, 7, '<')) ||
						(Env.browser === 'Firefox' && Env.verComp(Env.version, 37, '<'))
					);
				}()),
				return_response_headers: True,
				return_response_type: function(responseType) {
					if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported
						return true;
					} 
					return Env.can('return_response_type', responseType);
				},
				return_status_code: True,
				report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload),
				resize_image: function() {
					return I.can('access_binary') && Env.can('create_canvas');
				},
				select_file: function() {
					return Env.can('use_fileinput') && window.File;
				},
				select_folder: function() {
					return I.can('select_file') && Env.browser === 'Chrome' && Env.verComp(Env.version, 21, '>=');
				},
				select_multiple: function() {
					// it is buggy on Safari Windows and iOS
					return I.can('select_file') &&
						!(Env.browser === 'Safari' && Env.os === 'Windows') &&
						!(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.0", '>') && Env.verComp(Env.osVersion, "8.0.0", '<'));
				},
				send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))),
				send_custom_headers: Test(window.XMLHttpRequest),
				send_multipart: function() {
					return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string');
				},
				slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)),
				stream_upload: function(){
					return I.can('slice_blob') && I.can('send_multipart');
				},
				summon_file_dialog: function() { // yeah... some dirty sniffing here...
					return I.can('select_file') && (
						(Env.browser === 'Firefox' && Env.verComp(Env.version, 4, '>=')) ||
						(Env.browser === 'Opera' && Env.verComp(Env.version, 12, '>=')) ||
						(Env.browser === 'IE' && Env.verComp(Env.version, 10, '>=')) ||
						!!~Basic.inArray(Env.browser, ['Chrome', 'Safari'])
					);
				},
				upload_filesize: True
			}, 
			arguments[2]
		);

		Runtime.call(this, options, (arguments[1] || type), caps);


		Basic.extend(this, {

			init : function() {
				this.trigger("Init");
			},

			destroy: (function(destroy) { // extend default destroy method
				return function() {
					destroy.call(I);
					destroy = I = null;
				};
			}(this.destroy))
		});

		Basic.extend(this.getShim(), extensions);
	}

	Runtime.addConstructor(type, Html5Runtime);

	return extensions;
});

// Included from: src/javascript/core/utils/Events.js

/**
 * Events.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/core/utils/Events', [
	'moxie/core/utils/Basic'
], function(Basic) {
	var eventhash = {}, uid = 'moxie_' + Basic.guid();
	
	// IE W3C like event funcs
	function preventDefault() {
		this.returnValue = false;
	}

	function stopPropagation() {
		this.cancelBubble = true;
	}

	/**
	Adds an event handler to the specified object and store reference to the handler
	in objects internal Plupload registry (@see removeEvent).
	
	@method addEvent
	@for Utils
	@static
	@param {Object} obj DOM element like object to add handler to.
	@param {String} name Name to add event listener to.
	@param {Function} callback Function to call when event occurs.
	@param {String} [key] that might be used to add specifity to the event record.
	*/
	var addEvent = function(obj, name, callback, key) {
		var func, events;
					
		name = name.toLowerCase();

		// Add event listener
		if (obj.addEventListener) {
			func = callback;
			
			obj.addEventListener(name, func, false);
		} else if (obj.attachEvent) {
			func = function() {
				var evt = window.event;

				if (!evt.target) {
					evt.target = evt.srcElement;
				}

				evt.preventDefault = preventDefault;
				evt.stopPropagation = stopPropagation;

				callback(evt);
			};

			obj.attachEvent('on' + name, func);
		}
		
		// Log event handler to objects internal mOxie registry
		if (!obj[uid]) {
			obj[uid] = Basic.guid();
		}
		
		if (!eventhash.hasOwnProperty(obj[uid])) {
			eventhash[obj[uid]] = {};
		}
		
		events = eventhash[obj[uid]];
		
		if (!events.hasOwnProperty(name)) {
			events[name] = [];
		}
				
		events[name].push({
			func: func,
			orig: callback, // store original callback for IE
			key: key
		});
	};
	
	
	/**
	Remove event handler from the specified object. If third argument (callback)
	is not specified remove all events with the specified name.
	
	@method removeEvent
	@static
	@param {Object} obj DOM element to remove event listener(s) from.
	@param {String} name Name of event listener to remove.
	@param {Function|String} [callback] might be a callback or unique key to match.
	*/
	var removeEvent = function(obj, name, callback) {
		var type, undef;
		
		name = name.toLowerCase();
		
		if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) {
			type = eventhash[obj[uid]][name];
		} else {
			return;
		}
			
		for (var i = type.length - 1; i >= 0; i--) {
			// undefined or not, key should match
			if (type[i].orig === callback || type[i].key === callback) {
				if (obj.removeEventListener) {
					obj.removeEventListener(name, type[i].func, false);
				} else if (obj.detachEvent) {
					obj.detachEvent('on'+name, type[i].func);
				}
				
				type[i].orig = null;
				type[i].func = null;
				type.splice(i, 1);
				
				// If callback was passed we are done here, otherwise proceed
				if (callback !== undef) {
					break;
				}
			}
		}
		
		// If event array got empty, remove it
		if (!type.length) {
			delete eventhash[obj[uid]][name];
		}
		
		// If mOxie registry has become empty, remove it
		if (Basic.isEmptyObj(eventhash[obj[uid]])) {
			delete eventhash[obj[uid]];
			
			// IE doesn't let you remove DOM object property with - delete
			try {
				delete obj[uid];
			} catch(e) {
				obj[uid] = undef;
			}
		}
	};
	
	
	/**
	Remove all kind of events from the specified object
	
	@method removeAllEvents
	@static
	@param {Object} obj DOM element to remove event listeners from.
	@param {String} [key] unique key to match, when removing events.
	*/
	var removeAllEvents = function(obj, key) {		
		if (!obj || !obj[uid]) {
			return;
		}
		
		Basic.each(eventhash[obj[uid]], function(events, name) {
			removeEvent(obj, name, key);
		});
	};

	return {
		addEvent: addEvent,
		removeEvent: removeEvent,
		removeAllEvents: removeAllEvents
	};
});

// Included from: src/javascript/runtime/html5/file/FileInput.js

/**
 * FileInput.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/file/FileInput
@private
*/
define("moxie/runtime/html5/file/FileInput", [
	"moxie/runtime/html5/Runtime",
	"moxie/file/File",
	"moxie/core/utils/Basic",
	"moxie/core/utils/Dom",
	"moxie/core/utils/Events",
	"moxie/core/utils/Mime",
	"moxie/core/utils/Env"
], function(extensions, File, Basic, Dom, Events, Mime, Env) {
	
	function FileInput() {
		var _options;

		Basic.extend(this, {
			init: function(options) {
				var comp = this, I = comp.getRuntime(), input, shimContainer, mimes, browseButton, zIndex, top;

				_options = options;

				// figure out accept string
				mimes = _options.accept.mimes || Mime.extList2mimes(_options.accept, I.can('filter_by_extension'));

				shimContainer = I.getShimContainer();

				shimContainer.innerHTML = '<input id="' + I.uid +'" type="file" style="font-size:999px;opacity:0;"' +
					(_options.multiple && I.can('select_multiple') ? 'multiple' : '') + 
					(_options.directory && I.can('select_folder') ? 'webkitdirectory directory' : '') + // Chrome 11+
					(mimes ? ' accept="' + mimes.join(',') + '"' : '') + ' />';

				input = Dom.get(I.uid);

				// prepare file input to be placed underneath the browse_button element
				Basic.extend(input.style, {
					position: 'absolute',
					top: 0,
					left: 0,
					width: '100%',
					height: '100%'
				});


				browseButton = Dom.get(_options.browse_button);

				// Route click event to the input[type=file] element for browsers that support such behavior
				if (I.can('summon_file_dialog')) {
					if (Dom.getStyle(browseButton, 'position') === 'static') {
						browseButton.style.position = 'relative';
					}

					zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1;

					browseButton.style.zIndex = zIndex;
					shimContainer.style.zIndex = zIndex - 1;

					Events.addEvent(browseButton, 'click', function(e) {
						var input = Dom.get(I.uid);
						if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
							input.click();
						}
						e.preventDefault();
					}, comp.uid);
				}

				/* Since we have to place input[type=file] on top of the browse_button for some browsers,
				browse_button loses interactivity, so we restore it here */
				top = I.can('summon_file_dialog') ? browseButton : shimContainer;

				Events.addEvent(top, 'mouseover', function() {
					comp.trigger('mouseenter');
				}, comp.uid);

				Events.addEvent(top, 'mouseout', function() {
					comp.trigger('mouseleave');
				}, comp.uid);

				Events.addEvent(top, 'mousedown', function() {
					comp.trigger('mousedown');
				}, comp.uid);

				Events.addEvent(Dom.get(_options.container), 'mouseup', function() {
					comp.trigger('mouseup');
				}, comp.uid);


				input.onchange = function onChange(e) { // there should be only one handler for this
					comp.files = [];

					Basic.each(this.files, function(file) {
						var relativePath = '';

						if (_options.directory) {
							// folders are represented by dots, filter them out (Chrome 11+)
							if (file.name == ".") {
								// if it looks like a folder...
								return true;
							}
						}

						if (file.webkitRelativePath) {
							relativePath = '/' + file.webkitRelativePath.replace(/^\//, '');
						}
						
						file = new File(I.uid, file);
						file.relativePath = relativePath;

						comp.files.push(file);
					});

					// clearing the value enables the user to select the same file again if they want to
					if (Env.browser !== 'IE' && Env.browser !== 'IEMobile') {
						this.value = '';
					} else {
						// in IE input[type="file"] is read-only so the only way to reset it is to re-insert it
						var clone = this.cloneNode(true);
						this.parentNode.replaceChild(clone, this);
						clone.onchange = onChange;
					}

					if (comp.files.length) {
						comp.trigger('change');
					}
				};

				// ready event is perfectly asynchronous
				comp.trigger({
					type: 'ready',
					async: true
				});

				shimContainer = null;
			},


			disable: function(state) {
				var I = this.getRuntime(), input;

				if ((input = Dom.get(I.uid))) {
					input.disabled = !!state;
				}
			},

			destroy: function() {
				var I = this.getRuntime()
				, shim = I.getShim()
				, shimContainer = I.getShimContainer()
				;
				
				Events.removeAllEvents(shimContainer, this.uid);
				Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
				Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid);
				
				if (shimContainer) {
					shimContainer.innerHTML = '';
				}

				shim.removeInstance(this.uid);

				_options = shimContainer = shim = null;
			}
		});
	}

	return (extensions.FileInput = FileInput);
});

// Included from: src/javascript/runtime/html5/file/Blob.js

/**
 * Blob.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/file/Blob
@private
*/
define("moxie/runtime/html5/file/Blob", [
	"moxie/runtime/html5/Runtime",
	"moxie/file/Blob"
], function(extensions, Blob) {

	function HTML5Blob() {
		function w3cBlobSlice(blob, start, end) {
			var blobSlice;

			if (window.File.prototype.slice) {
				try {
					blob.slice();	// depricated version will throw WRONG_ARGUMENTS_ERR exception
					return blob.slice(start, end);
				} catch (e) {
					// depricated slice method
					return blob.slice(start, end - start);
				}
			// slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672
			} else if ((blobSlice = window.File.prototype.webkitSlice || window.File.prototype.mozSlice)) {
				return blobSlice.call(blob, start, end);
			} else {
				return null; // or throw some exception
			}
		}

		this.slice = function() {
			return new Blob(this.getRuntime().uid, w3cBlobSlice.apply(this, arguments));
		};
	}

	return (extensions.Blob = HTML5Blob);
});

// Included from: src/javascript/runtime/html5/file/FileDrop.js

/**
 * FileDrop.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/file/FileDrop
@private
*/
define("moxie/runtime/html5/file/FileDrop", [
	"moxie/runtime/html5/Runtime",
	'moxie/file/File',
	"moxie/core/utils/Basic",
	"moxie/core/utils/Dom",
	"moxie/core/utils/Events",
	"moxie/core/utils/Mime"
], function(extensions, File, Basic, Dom, Events, Mime) {
	
	function FileDrop() {
		var _files = [], _allowedExts = [], _options, _ruid;

		Basic.extend(this, {
			init: function(options) {
				var comp = this, dropZone;

				_options = options;
				_ruid = comp.ruid; // every dropped-in file should have a reference to the runtime
				_allowedExts = _extractExts(_options.accept);
				dropZone = _options.container;

				Events.addEvent(dropZone, 'dragover', function(e) {
					if (!_hasFiles(e)) {
						return;
					}
					e.preventDefault();
					e.dataTransfer.dropEffect = 'copy';
				}, comp.uid);

				Events.addEvent(dropZone, 'drop', function(e) {
					if (!_hasFiles(e)) {
						return;
					}
					e.preventDefault();

					_files = [];

					// Chrome 21+ accepts folders via Drag'n'Drop
					if (e.dataTransfer.items && e.dataTransfer.items[0].webkitGetAsEntry) {
						_readItems(e.dataTransfer.items, function() {
							comp.files = _files;
							comp.trigger("drop");
						});
					} else {
						Basic.each(e.dataTransfer.files, function(file) {
							_addFile(file);
						});
						comp.files = _files;
						comp.trigger("drop");
					}
				}, comp.uid);

				Events.addEvent(dropZone, 'dragenter', function(e) {
					comp.trigger("dragenter");
				}, comp.uid);

				Events.addEvent(dropZone, 'dragleave', function(e) {
					comp.trigger("dragleave");
				}, comp.uid);
			},

			destroy: function() {
				Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
				_ruid = _files = _allowedExts = _options = null;
			}
		});


		function _hasFiles(e) {
			if (!e.dataTransfer || !e.dataTransfer.types) { // e.dataTransfer.files is not available in Gecko during dragover
				return false;
			}

			var types = Basic.toArray(e.dataTransfer.types || []);

			return Basic.inArray("Files", types) !== -1 ||
				Basic.inArray("public.file-url", types) !== -1 || // Safari < 5
				Basic.inArray("application/x-moz-file", types) !== -1 // Gecko < 1.9.2 (< Firefox 3.6)
				;
		}


		function _addFile(file, relativePath) {
			if (_isAcceptable(file)) {
				var fileObj = new File(_ruid, file);
				fileObj.relativePath = relativePath || '';
				_files.push(fileObj);
			}
		}

		
		function _extractExts(accept) {
			var exts = [];
			for (var i = 0; i < accept.length; i++) {
				[].push.apply(exts, accept[i].extensions.split(/\s*,\s*/));
			}
			return Basic.inArray('*', exts) === -1 ? exts : [];
		}


		function _isAcceptable(file) {
			if (!_allowedExts.length) {
				return true;
			}
			var ext = Mime.getFileExtension(file.name);
			return !ext || Basic.inArray(ext, _allowedExts) !== -1;
		}


		function _readItems(items, cb) {
			var entries = [];
			Basic.each(items, function(item) {
				var entry = item.webkitGetAsEntry();
				// Address #998 (https://code.google.com/p/chromium/issues/detail?id=332579)
				if (entry) {
					// file() fails on OSX when the filename contains a special character (e.g. umlaut): see #61
					if (entry.isFile) {
						_addFile(item.getAsFile(), entry.fullPath);
					} else {
						entries.push(entry);
					}
				}
			});

			if (entries.length) {
				_readEntries(entries, cb);
			} else {
				cb();
			}
		}


		function _readEntries(entries, cb) {
			var queue = [];
			Basic.each(entries, function(entry) {
				queue.push(function(cbcb) {
					_readEntry(entry, cbcb);
				});
			});
			Basic.inSeries(queue, function() {
				cb();
			});
		}


		function _readEntry(entry, cb) {
			if (entry.isFile) {
				entry.file(function(file) {
					_addFile(file, entry.fullPath);
					cb();
				}, function() {
					// fire an error event maybe
					cb();
				});
			} else if (entry.isDirectory) {
				_readDirEntry(entry, cb);
			} else {
				cb(); // not file, not directory? what then?..
			}
		}


		function _readDirEntry(dirEntry, cb) {
			var entries = [], dirReader = dirEntry.createReader();

			// keep quering recursively till no more entries
			function getEntries(cbcb) {
				dirReader.readEntries(function(moreEntries) {
					if (moreEntries.length) {
						[].push.apply(entries, moreEntries);
						getEntries(cbcb);
					} else {
						cbcb();
					}
				}, cbcb);
			}

			// ...and you thought FileReader was crazy...
			getEntries(function() {
				_readEntries(entries, cb);
			}); 
		}
	}

	return (extensions.FileDrop = FileDrop);
});

// Included from: src/javascript/runtime/html5/file/FileReader.js

/**
 * FileReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/file/FileReader
@private
*/
define("moxie/runtime/html5/file/FileReader", [
	"moxie/runtime/html5/Runtime",
	"moxie/core/utils/Encode",
	"moxie/core/utils/Basic"
], function(extensions, Encode, Basic) {
	
	function FileReader() {
		var _fr, _convertToBinary = false;

		Basic.extend(this, {

			read: function(op, blob) {
				var comp = this;

				comp.result = '';

				_fr = new window.FileReader();

				_fr.addEventListener('progress', function(e) {
					comp.trigger(e);
				});

				_fr.addEventListener('load', function(e) {
					comp.result = _convertToBinary ? _toBinary(_fr.result) : _fr.result;
					comp.trigger(e);
				});

				_fr.addEventListener('error', function(e) {
					comp.trigger(e, _fr.error);
				});

				_fr.addEventListener('loadend', function(e) {
					_fr = null;
					comp.trigger(e);
				});

				if (Basic.typeOf(_fr[op]) === 'function') {
					_convertToBinary = false;
					_fr[op](blob.getSource());
				} else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
					_convertToBinary = true;
					_fr.readAsDataURL(blob.getSource());
				}
			},

			abort: function() {
				if (_fr) {
					_fr.abort();
				}
			},

			destroy: function() {
				_fr = null;
			}
		});

		function _toBinary(str) {
			return Encode.atob(str.substring(str.indexOf('base64,') + 7));
		}
	}

	return (extensions.FileReader = FileReader);
});

// Included from: src/javascript/runtime/html5/xhr/XMLHttpRequest.js

/**
 * XMLHttpRequest.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*global ActiveXObject:true */

/**
@class moxie/runtime/html5/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/html5/xhr/XMLHttpRequest", [
	"moxie/runtime/html5/Runtime",
	"moxie/core/utils/Basic",
	"moxie/core/utils/Mime",
	"moxie/core/utils/Url",
	"moxie/file/File",
	"moxie/file/Blob",
	"moxie/xhr/FormData",
	"moxie/core/Exceptions",
	"moxie/core/utils/Env"
], function(extensions, Basic, Mime, Url, File, Blob, FormData, x, Env) {
	
	function XMLHttpRequest() {
		var self = this
		, _xhr
		, _filename
		;

		Basic.extend(this, {
			send: function(meta, data) {
				var target = this
				, isGecko2_5_6 = (Env.browser === 'Mozilla' && Env.verComp(Env.version, 4, '>=') && Env.verComp(Env.version, 7, '<'))
				, isAndroidBrowser = Env.browser === 'Android Browser'
				, mustSendAsBinary = false
				;

				// extract file name
				_filename = meta.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase();

				_xhr = _getNativeXHR();
				_xhr.open(meta.method, meta.url, meta.async, meta.user, meta.password);


				// prepare data to be sent
				if (data instanceof Blob) {
					if (data.isDetached()) {
						mustSendAsBinary = true;
					}
					data = data.getSource();
				} else if (data instanceof FormData) {

					if (data.hasBlob()) {
						if (data.getBlob().isDetached()) {
							data = _prepareMultipart.call(target, data); // _xhr must be instantiated and be in OPENED state
							mustSendAsBinary = true;
						} else if ((isGecko2_5_6 || isAndroidBrowser) && Basic.typeOf(data.getBlob().getSource()) === 'blob' && window.FileReader) {
							// Gecko 2/5/6 can't send blob in FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150
							// Android browsers (default one and Dolphin) seem to have the same issue, see: #613
							_preloadAndSend.call(target, meta, data);
							return; // _preloadAndSend will reinvoke send() with transmutated FormData =%D
						}	
					}

					// transfer fields to real FormData
					if (data instanceof FormData) { // if still a FormData, e.g. not mangled by _prepareMultipart()
						var fd = new window.FormData();
						data.each(function(value, name) {
							if (value instanceof Blob) {
								fd.append(name, value.getSource());
							} else {
								fd.append(name, value);
							}
						});
						data = fd;
					}
				}


				// if XHR L2
				if (_xhr.upload) {
					if (meta.withCredentials) {
						_xhr.withCredentials = true;
					}

					_xhr.addEventListener('load', function(e) {
						target.trigger(e);
					});

					_xhr.addEventListener('error', function(e) {
						target.trigger(e);
					});

					// additionally listen to progress events
					_xhr.addEventListener('progress', function(e) {
						target.trigger(e);
					});

					_xhr.upload.addEventListener('progress', function(e) {
						target.trigger({
							type: 'UploadProgress',
							loaded: e.loaded,
							total: e.total
						});
					});
				// ... otherwise simulate XHR L2
				} else {
					_xhr.onreadystatechange = function onReadyStateChange() {
						
						// fake Level 2 events
						switch (_xhr.readyState) {
							
							case 1: // XMLHttpRequest.OPENED
								// readystatechanged is fired twice for OPENED state (in IE and Mozilla) - neu
								break;
							
							// looks like HEADERS_RECEIVED (state 2) is not reported in Opera (or it's old versions) - neu
							case 2: // XMLHttpRequest.HEADERS_RECEIVED
								break;
								
							case 3: // XMLHttpRequest.LOADING 
								// try to fire progress event for not XHR L2
								var total, loaded;
								
								try {
									if (Url.hasSameOrigin(meta.url)) { // Content-Length not accessible for cross-domain on some browsers
										total = _xhr.getResponseHeader('Content-Length') || 0; // old Safari throws an exception here
									}

									if (_xhr.responseText) { // responseText was introduced in IE7
										loaded = _xhr.responseText.length;
									}
								} catch(ex) {
									total = loaded = 0;
								}

								target.trigger({
									type: 'progress',
									lengthComputable: !!total,
									total: parseInt(total, 10),
									loaded: loaded
								});
								break;
								
							case 4: // XMLHttpRequest.DONE
								// release readystatechange handler (mostly for IE)
								_xhr.onreadystatechange = function() {};

								// usually status 0 is returned when server is unreachable, but FF also fails to status 0 for 408 timeout
								if (_xhr.status === 0) {
									target.trigger('error');
								} else {
									target.trigger('load');
								}							
								break;
						}
					};
				}
				

				// set request headers
				if (!Basic.isEmptyObj(meta.headers)) {
					Basic.each(meta.headers, function(value, header) {
						_xhr.setRequestHeader(header, value);
					});
				}

				// request response type
				if ("" !== meta.responseType && 'responseType' in _xhr) {
					if ('json' === meta.responseType && !Env.can('return_response_type', 'json')) { // we can fake this one
						_xhr.responseType = 'text';
					} else {
						_xhr.responseType = meta.responseType;
					}
				}

				// send ...
				if (!mustSendAsBinary) {
					_xhr.send(data);
				} else {
					if (_xhr.sendAsBinary) { // Gecko
						_xhr.sendAsBinary(data);
					} else { // other browsers having support for typed arrays
						(function() {
							// mimic Gecko's sendAsBinary
							var ui8a = new Uint8Array(data.length);
							for (var i = 0; i < data.length; i++) {
								ui8a[i] = (data.charCodeAt(i) & 0xff);
							}
							_xhr.send(ui8a.buffer);
						}());
					}
				}

				target.trigger('loadstart');
			},

			getStatus: function() {
				// according to W3C spec it should return 0 for readyState < 3, but instead it throws an exception
				try {
					if (_xhr) {
						return _xhr.status;
					}
				} catch(ex) {}
				return 0;
			},

			getResponse: function(responseType) {
				var I = this.getRuntime();

				try {
					switch (responseType) {
						case 'blob':
							var file = new File(I.uid, _xhr.response);
							
							// try to extract file name from content-disposition if possible (might be - not, if CORS for example)	
							var disposition = _xhr.getResponseHeader('Content-Disposition');
							if (disposition) {
								// extract filename from response header if available
								var match = disposition.match(/filename=([\'\"'])([^\1]+)\1/);
								if (match) {
									_filename = match[2];
								}
							}
							file.name = _filename;

							// pre-webkit Opera doesn't set type property on the blob response
							if (!file.type) {
								file.type = Mime.getFileMime(_filename);
							}
							return file;

						case 'json':
							if (!Env.can('return_response_type', 'json')) {
								return _xhr.status === 200 && !!window.JSON ? JSON.parse(_xhr.responseText) : null;
							}
							return _xhr.response;

						case 'document':
							return _getDocument(_xhr);

						default:
							return _xhr.responseText !== '' ? _xhr.responseText : null; // against the specs, but for consistency across the runtimes
					}
				} catch(ex) {
					return null;
				}				
			},

			getAllResponseHeaders: function() {
				try {
					return _xhr.getAllResponseHeaders();
				} catch(ex) {}
				return '';
			},

			abort: function() {
				if (_xhr) {
					_xhr.abort();
				}
			},

			destroy: function() {
				self = _filename = null;
			}
		});


		// here we go... ugly fix for ugly bug
		function _preloadAndSend(meta, data) {
			var target = this, blob, fr;
				
			// get original blob
			blob = data.getBlob().getSource();
			
			// preload blob in memory to be sent as binary string
			fr = new window.FileReader();
			fr.onload = function() {
				// overwrite original blob
				data.append(data.getBlobName(), new Blob(null, {
					type: blob.type,
					data: fr.result
				}));
				// invoke send operation again
				self.send.call(target, meta, data);
			};
			fr.readAsBinaryString(blob);
		}

		
		function _getNativeXHR() {
			if (window.XMLHttpRequest && !(Env.browser === 'IE' && Env.verComp(Env.version, 8, '<'))) { // IE7 has native XHR but it's buggy
				return new window.XMLHttpRequest();
			} else {
				return (function() {
					var progIDs = ['Msxml2.XMLHTTP.6.0', 'Microsoft.XMLHTTP']; // if 6.0 available, use it, otherwise failback to default 3.0
					for (var i = 0; i < progIDs.length; i++) {
						try {
							return new ActiveXObject(progIDs[i]);
						} catch (ex) {}
					}
				})();
			}
		}
		
		// @credits Sergey Ilinsky	(http://www.ilinsky.com/)
		function _getDocument(xhr) {
			var rXML = xhr.responseXML;
			var rText = xhr.responseText;
			
			// Try parsing responseText (@see: http://www.ilinsky.com/articles/XMLHttpRequest/#bugs-ie-responseXML-content-type)
			if (Env.browser === 'IE' && rText && rXML && !rXML.documentElement && /[^\/]+\/[^\+]+\+xml/.test(xhr.getResponseHeader("Content-Type"))) {
				rXML = new window.ActiveXObject("Microsoft.XMLDOM");
				rXML.async = false;
				rXML.validateOnParse = false;
				rXML.loadXML(rText);
			}
	
			// Check if there is no error in document
			if (rXML) {
				if ((Env.browser === 'IE' && rXML.parseError !== 0) || !rXML.documentElement || rXML.documentElement.tagName === "parsererror") {
					return null;
				}
			}
			return rXML;
		}


		function _prepareMultipart(fd) {
			var boundary = '----moxieboundary' + new Date().getTime()
			, dashdash = '--'
			, crlf = '\r\n'
			, multipart = ''
			, I = this.getRuntime()
			;

			if (!I.can('send_binary_string')) {
				throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
			}

			_xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

			// append multipart parameters
			fd.each(function(value, name) {
				// Firefox 3.6 failed to convert multibyte characters to UTF-8 in sendAsBinary(), 
				// so we try it here ourselves with: unescape(encodeURIComponent(value))
				if (value instanceof Blob) {
					// Build RFC2388 blob
					multipart += dashdash + boundary + crlf +
						'Content-Disposition: form-data; name="' + name + '"; filename="' + unescape(encodeURIComponent(value.name || 'blob')) + '"' + crlf +
						'Content-Type: ' + (value.type || 'application/octet-stream') + crlf + crlf +
						value.getSource() + crlf;
				} else {
					multipart += dashdash + boundary + crlf +
						'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf +
						unescape(encodeURIComponent(value)) + crlf;
				}
			});

			multipart += dashdash + boundary + dashdash + crlf;

			return multipart;
		}
	}

	return (extensions.XMLHttpRequest = XMLHttpRequest);
});

// Included from: src/javascript/runtime/html5/utils/BinaryReader.js

/**
 * BinaryReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/utils/BinaryReader
@private
*/
define("moxie/runtime/html5/utils/BinaryReader", [
	"moxie/core/utils/Basic"
], function(Basic) {

	
	function BinaryReader(data) {
		if (data instanceof ArrayBuffer) {
			ArrayBufferReader.apply(this, arguments);
		} else {
			UTF16StringReader.apply(this, arguments);
		}
	}
	 

	Basic.extend(BinaryReader.prototype, {
		
		littleEndian: false,


		read: function(idx, size) {
			var sum, mv, i;

			if (idx + size > this.length()) {
				throw new Error("You are trying to read outside the source boundaries.");
			}
			
			mv = this.littleEndian 
				? 0 
				: -8 * (size - 1)
			;

			for (i = 0, sum = 0; i < size; i++) {
				sum |= (this.readByteAt(idx + i) << Math.abs(mv + i*8));
			}
			return sum;
		},


		write: function(idx, num, size) {
			var mv, i, str = '';

			if (idx > this.length()) {
				throw new Error("You are trying to write outside the source boundaries.");
			}

			mv = this.littleEndian 
				? 0 
				: -8 * (size - 1)
			;

			for (i = 0; i < size; i++) {
				this.writeByteAt(idx + i, (num >> Math.abs(mv + i*8)) & 255);
			}
		},


		BYTE: function(idx) {
			return this.read(idx, 1);
		},


		SHORT: function(idx) {
			return this.read(idx, 2);
		},


		LONG: function(idx) {
			return this.read(idx, 4);
		},


		SLONG: function(idx) { // 2's complement notation
			var num = this.read(idx, 4);
			return (num > 2147483647 ? num - 4294967296 : num);
		},


		CHAR: function(idx) {
			return String.fromCharCode(this.read(idx, 1));
		},


		STRING: function(idx, count) {
			return this.asArray('CHAR', idx, count).join('');
		},


		asArray: function(type, idx, count) {
			var values = [];

			for (var i = 0; i < count; i++) {
				values[i] = this[type](idx + i);
			}
			return values;
		}
	});


	function ArrayBufferReader(data) {
		var _dv = new DataView(data);

		Basic.extend(this, {
			
			readByteAt: function(idx) {
				return _dv.getUint8(idx);
			},


			writeByteAt: function(idx, value) {
				_dv.setUint8(idx, value);
			},
			

			SEGMENT: function(idx, size, value) {
				switch (arguments.length) {
					case 2:
						return data.slice(idx, idx + size);

					case 1:
						return data.slice(idx);

					case 3:
						if (value === null) {
							value = new ArrayBuffer();
						}

						if (value instanceof ArrayBuffer) {					
							var arr = new Uint8Array(this.length() - size + value.byteLength);
							if (idx > 0) {
								arr.set(new Uint8Array(data.slice(0, idx)), 0);
							}
							arr.set(new Uint8Array(value), idx);
							arr.set(new Uint8Array(data.slice(idx + size)), idx + value.byteLength);

							this.clear();
							data = arr.buffer;
							_dv = new DataView(data);
							break;
						}

					default: return data;
				}
			},


			length: function() {
				return data ? data.byteLength : 0;
			},


			clear: function() {
				_dv = data = null;
			}
		});
	}


	function UTF16StringReader(data) {
		Basic.extend(this, {
			
			readByteAt: function(idx) {
				return data.charCodeAt(idx);
			},


			writeByteAt: function(idx, value) {
				putstr(String.fromCharCode(value), idx, 1);
			},


			SEGMENT: function(idx, length, segment) {
				switch (arguments.length) {
					case 1:
						return data.substr(idx);
					case 2:
						return data.substr(idx, length);
					case 3:
						putstr(segment !== null ? segment : '', idx, length);
						break;
					default: return data;
				}
			},


			length: function() {
				return data ? data.length : 0;
			}, 

			clear: function() {
				data = null;
			}
		});


		function putstr(segment, idx, length) {
			length = arguments.length === 3 ? length : data.length - idx - 1;
			data = data.substr(0, idx) + segment + data.substr(length + idx);
		}
	}


	return BinaryReader;
});

// Included from: src/javascript/runtime/html5/image/JPEGHeaders.js

/**
 * JPEGHeaders.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */
 
/**
@class moxie/runtime/html5/image/JPEGHeaders
@private
*/
define("moxie/runtime/html5/image/JPEGHeaders", [
	"moxie/runtime/html5/utils/BinaryReader",
	"moxie/core/Exceptions"
], function(BinaryReader, x) {
	
	return function JPEGHeaders(data) {
		var headers = [], _br, idx, marker, length = 0;

		_br = new BinaryReader(data);

		// Check if data is jpeg
		if (_br.SHORT(0) !== 0xFFD8) {
			_br.clear();
			throw new x.ImageError(x.ImageError.WRONG_FORMAT);
		}

		idx = 2;

		while (idx <= _br.length()) {
			marker = _br.SHORT(idx);

			// omit RST (restart) markers
			if (marker >= 0xFFD0 && marker <= 0xFFD7) {
				idx += 2;
				continue;
			}

			// no headers allowed after SOS marker
			if (marker === 0xFFDA || marker === 0xFFD9) {
				break;
			}

			length = _br.SHORT(idx + 2) + 2;

			// APPn marker detected
			if (marker >= 0xFFE1 && marker <= 0xFFEF) {
				headers.push({
					hex: marker,
					name: 'APP' + (marker & 0x000F),
					start: idx,
					length: length,
					segment: _br.SEGMENT(idx, length)
				});
			}

			idx += length;
		}

		_br.clear();

		return {
			headers: headers,

			restore: function(data) {
				var max, i, br;

				br = new BinaryReader(data);

				idx = br.SHORT(2) == 0xFFE0 ? 4 + br.SHORT(4) : 2;

				for (i = 0, max = headers.length; i < max; i++) {
					br.SEGMENT(idx, 0, headers[i].segment);
					idx += headers[i].length;
				}

				data = br.SEGMENT();
				br.clear();
				return data;
			},

			strip: function(data) {
				var br, headers, jpegHeaders, i;

				jpegHeaders = new JPEGHeaders(data);
				headers = jpegHeaders.headers;
				jpegHeaders.purge();

				br = new BinaryReader(data);

				i = headers.length;
				while (i--) {
					br.SEGMENT(headers[i].start, headers[i].length, '');
				}
				
				data = br.SEGMENT();
				br.clear();
				return data;
			},

			get: function(name) {
				var array = [];

				for (var i = 0, max = headers.length; i < max; i++) {
					if (headers[i].name === name.toUpperCase()) {
						array.push(headers[i].segment);
					}
				}
				return array;
			},

			set: function(name, segment) {
				var array = [], i, ii, max;

				if (typeof(segment) === 'string') {
					array.push(segment);
				} else {
					array = segment;
				}

				for (i = ii = 0, max = headers.length; i < max; i++) {
					if (headers[i].name === name.toUpperCase()) {
						headers[i].segment = array[ii];
						headers[i].length = array[ii].length;
						ii++;
					}
					if (ii >= array.length) {
						break;
					}
				}
			},

			purge: function() {
				this.headers = headers = [];
			}
		};
	};
});

// Included from: src/javascript/runtime/html5/image/ExifParser.js

/**
 * ExifParser.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/image/ExifParser
@private
*/
define("moxie/runtime/html5/image/ExifParser", [
	"moxie/core/utils/Basic",
	"moxie/runtime/html5/utils/BinaryReader",
	"moxie/core/Exceptions"
], function(Basic, BinaryReader, x) {
	
	function ExifParser(data) {
		var __super__, tags, tagDescs, offsets, idx, Tiff;
		
		BinaryReader.call(this, data);

		tags = {
			tiff: {
				/*
				The image orientation viewed in terms of rows and columns.

				1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
				2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
				3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
				4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
				5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
				6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
				7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
				8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
				*/
				0x0112: 'Orientation',
				0x010E: 'ImageDescription',
				0x010F: 'Make',
				0x0110: 'Model',
				0x0131: 'Software',
				0x8769: 'ExifIFDPointer',
				0x8825:	'GPSInfoIFDPointer'
			},
			exif: {
				0x9000: 'ExifVersion',
				0xA001: 'ColorSpace',
				0xA002: 'PixelXDimension',
				0xA003: 'PixelYDimension',
				0x9003: 'DateTimeOriginal',
				0x829A: 'ExposureTime',
				0x829D: 'FNumber',
				0x8827: 'ISOSpeedRatings',
				0x9201: 'ShutterSpeedValue',
				0x9202: 'ApertureValue'	,
				0x9207: 'MeteringMode',
				0x9208: 'LightSource',
				0x9209: 'Flash',
				0x920A: 'FocalLength',
				0xA402: 'ExposureMode',
				0xA403: 'WhiteBalance',
				0xA406: 'SceneCaptureType',
				0xA404: 'DigitalZoomRatio',
				0xA408: 'Contrast',
				0xA409: 'Saturation',
				0xA40A: 'Sharpness'
			},
			gps: {
				0x0000: 'GPSVersionID',
				0x0001: 'GPSLatitudeRef',
				0x0002: 'GPSLatitude',
				0x0003: 'GPSLongitudeRef',
				0x0004: 'GPSLongitude'
			},

			thumb: {
				0x0201: 'JPEGInterchangeFormat',
				0x0202: 'JPEGInterchangeFormatLength'
			}
		};

		tagDescs = {
			'ColorSpace': {
				1: 'sRGB',
				0: 'Uncalibrated'
			},

			'MeteringMode': {
				0: 'Unknown',
				1: 'Average',
				2: 'CenterWeightedAverage',
				3: 'Spot',
				4: 'MultiSpot',
				5: 'Pattern',
				6: 'Partial',
				255: 'Other'
			},

			'LightSource': {
				1: 'Daylight',
				2: 'Fliorescent',
				3: 'Tungsten',
				4: 'Flash',
				9: 'Fine weather',
				10: 'Cloudy weather',
				11: 'Shade',
				12: 'Daylight fluorescent (D 5700 - 7100K)',
				13: 'Day white fluorescent (N 4600 -5400K)',
				14: 'Cool white fluorescent (W 3900 - 4500K)',
				15: 'White fluorescent (WW 3200 - 3700K)',
				17: 'Standard light A',
				18: 'Standard light B',
				19: 'Standard light C',
				20: 'D55',
				21: 'D65',
				22: 'D75',
				23: 'D50',
				24: 'ISO studio tungsten',
				255: 'Other'
			},

			'Flash': {
				0x0000: 'Flash did not fire',
				0x0001: 'Flash fired',
				0x0005: 'Strobe return light not detected',
				0x0007: 'Strobe return light detected',
				0x0009: 'Flash fired, compulsory flash mode',
				0x000D: 'Flash fired, compulsory flash mode, return light not detected',
				0x000F: 'Flash fired, compulsory flash mode, return light detected',
				0x0010: 'Flash did not fire, compulsory flash mode',
				0x0018: 'Flash did not fire, auto mode',
				0x0019: 'Flash fired, auto mode',
				0x001D: 'Flash fired, auto mode, return light not detected',
				0x001F: 'Flash fired, auto mode, return light detected',
				0x0020: 'No flash function',
				0x0041: 'Flash fired, red-eye reduction mode',
				0x0045: 'Flash fired, red-eye reduction mode, return light not detected',
				0x0047: 'Flash fired, red-eye reduction mode, return light detected',
				0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode',
				0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
				0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
				0x0059: 'Flash fired, auto mode, red-eye reduction mode',
				0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
				0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode'
			},

			'ExposureMode': {
				0: 'Auto exposure',
				1: 'Manual exposure',
				2: 'Auto bracket'
			},

			'WhiteBalance': {
				0: 'Auto white balance',
				1: 'Manual white balance'
			},

			'SceneCaptureType': {
				0: 'Standard',
				1: 'Landscape',
				2: 'Portrait',
				3: 'Night scene'
			},

			'Contrast': {
				0: 'Normal',
				1: 'Soft',
				2: 'Hard'
			},

			'Saturation': {
				0: 'Normal',
				1: 'Low saturation',
				2: 'High saturation'
			},

			'Sharpness': {
				0: 'Normal',
				1: 'Soft',
				2: 'Hard'
			},

			// GPS related
			'GPSLatitudeRef': {
				N: 'North latitude',
				S: 'South latitude'
			},

			'GPSLongitudeRef': {
				E: 'East longitude',
				W: 'West longitude'
			}
		};

		offsets = {
			tiffHeader: 10
		};
		
		idx = offsets.tiffHeader;

		__super__ = {
			clear: this.clear
		};

		// Public functions
		Basic.extend(this, {
			
			read: function() {
				try {
					return ExifParser.prototype.read.apply(this, arguments);
				} catch (ex) {
					throw new x.ImageError(x.ImageError.INVALID_META_ERR);
				}
			},


			write: function() {
				try {
					return ExifParser.prototype.write.apply(this, arguments);
				} catch (ex) {
					throw new x.ImageError(x.ImageError.INVALID_META_ERR);
				}
			},


			UNDEFINED: function() {
				return this.BYTE.apply(this, arguments);
			},


			RATIONAL: function(idx) {
				return this.LONG(idx) / this.LONG(idx + 4)
			},


			SRATIONAL: function(idx) {
				return this.SLONG(idx) / this.SLONG(idx + 4)
			},

			ASCII: function(idx) {
				return this.CHAR(idx);
			},

			TIFF: function() {
				return Tiff || null;
			},


			EXIF: function() {
				var Exif = null;

				if (offsets.exifIFD) {
					try {
						Exif = extractTags.call(this, offsets.exifIFD, tags.exif);
					} catch(ex) {
						return null;
					}

					// Fix formatting of some tags
					if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') {
						for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) {
							exifVersion += String.fromCharCode(Exif.ExifVersion[i]);
						}
						Exif.ExifVersion = exifVersion;
					}
				}

				return Exif;
			},


			GPS: function() {
				var GPS = null;

				if (offsets.gpsIFD) {
					try {
						GPS = extractTags.call(this, offsets.gpsIFD, tags.gps);
					} catch (ex) {
						return null;
					}

					// iOS devices (and probably some others) do not put in GPSVersionID tag (why?..)
					if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') {
						GPS.GPSVersionID = GPS.GPSVersionID.join('.');
					}
				}

				return GPS;
			},


			thumb: function() {
				if (offsets.IFD1) {
					try {
						var IFD1Tags = extractTags.call(this, offsets.IFD1, tags.thumb);
						
						if ('JPEGInterchangeFormat' in IFD1Tags) {
							return this.SEGMENT(offsets.tiffHeader + IFD1Tags.JPEGInterchangeFormat, IFD1Tags.JPEGInterchangeFormatLength);
						}
					} catch (ex) {}
				}
				return null;
			},


			setExif: function(tag, value) {
				// Right now only setting of width/height is possible
				if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') { return false; }

				return setTag.call(this, 'exif', tag, value);
			},


			clear: function() {
				__super__.clear();
				data = tags = tagDescs = Tiff = offsets = __super__ = null;
			}
		});


		// Check if that's APP1 and that it has EXIF
		if (this.SHORT(0) !== 0xFFE1 || this.STRING(4, 5).toUpperCase() !== "EXIF\0") {
			throw new x.ImageError(x.ImageError.INVALID_META_ERR);
		}

		// Set read order of multi-byte data
		this.littleEndian = (this.SHORT(idx) == 0x4949);

		// Check if always present bytes are indeed present
		if (this.SHORT(idx+=2) !== 0x002A) {
			throw new x.ImageError(x.ImageError.INVALID_META_ERR);
		}

		offsets.IFD0 = offsets.tiffHeader + this.LONG(idx += 2);
		Tiff = extractTags.call(this, offsets.IFD0, tags.tiff);

		if ('ExifIFDPointer' in Tiff) {
			offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer;
			delete Tiff.ExifIFDPointer;
		}

		if ('GPSInfoIFDPointer' in Tiff) {
			offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer;
			delete Tiff.GPSInfoIFDPointer;
		}

		if (Basic.isEmptyObj(Tiff)) {
			Tiff = null;
		}

		// check if we have a thumb as well
		var IFD1Offset = this.LONG(offsets.IFD0 + this.SHORT(offsets.IFD0) * 12 + 2);
		if (IFD1Offset) {
			offsets.IFD1 = offsets.tiffHeader + IFD1Offset;
		}


		function extractTags(IFD_offset, tags2extract) {
			var data = this;
			var length, i, tag, type, count, size, offset, value, values = [], hash = {};
			
			var types = {
				1 : 'BYTE',
				7 : 'UNDEFINED',
				2 : 'ASCII',
				3 : 'SHORT',
				4 : 'LONG',
				5 : 'RATIONAL',
				9 : 'SLONG',
				10: 'SRATIONAL'
			};

			var sizes = {
				'BYTE' 		: 1,
				'UNDEFINED'	: 1,
				'ASCII'		: 1,
				'SHORT'		: 2,
				'LONG' 		: 4,
				'RATIONAL' 	: 8,
				'SLONG'		: 4,
				'SRATIONAL'	: 8
			};

			length = data.SHORT(IFD_offset);

			// The size of APP1 including all these elements shall not exceed the 64 Kbytes specified in the JPEG standard.

			for (i = 0; i < length; i++) {
				values = [];

				// Set binary reader pointer to beginning of the next tag
				offset = IFD_offset + 2 + i*12;

				tag = tags2extract[data.SHORT(offset)];

				if (tag === undefined) {
					continue; // Not the tag we requested
				}

				type = types[data.SHORT(offset+=2)];
				count = data.LONG(offset+=2);
				size = sizes[type];

				if (!size) {
					throw new x.ImageError(x.ImageError.INVALID_META_ERR);
				}

				offset += 4;

				// tag can only fit 4 bytes of data, if data is larger we should look outside
				if (size * count > 4) {
					// instead of data tag contains an offset of the data
					offset = data.LONG(offset) + offsets.tiffHeader;
				}

				// in case we left the boundaries of data throw an early exception
				if (offset + size * count >= this.length()) {
					throw new x.ImageError(x.ImageError.INVALID_META_ERR);
				} 

				// special care for the string
				if (type === 'ASCII') {
					hash[tag] = Basic.trim(data.STRING(offset, count).replace(/\0$/, '')); // strip trailing NULL
					continue;
				} else {
					values = data.asArray(type, offset, count);
					value = (count == 1 ? values[0] : values);

					if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') {
						hash[tag] = tagDescs[tag][value];
					} else {
						hash[tag] = value;
					}
				}
			}

			return hash;
		}

		// At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported
		function setTag(ifd, tag, value) {
			var offset, length, tagOffset, valueOffset = 0;

			// If tag name passed translate into hex key
			if (typeof(tag) === 'string') {
				var tmpTags = tags[ifd.toLowerCase()];
				for (var hex in tmpTags) {
					if (tmpTags[hex] === tag) {
						tag = hex;
						break;
					}
				}
			}
			offset = offsets[ifd.toLowerCase() + 'IFD'];
			length = this.SHORT(offset);

			for (var i = 0; i < length; i++) {
				tagOffset = offset + 12 * i + 2;

				if (this.SHORT(tagOffset) == tag) {
					valueOffset = tagOffset + 8;
					break;
				}
			}

			if (!valueOffset) {
				return false;
			}

			try {
				this.write(valueOffset, value, 4);
			} catch(ex) {
				return false;
			}

			return true;
		}
	}

	ExifParser.prototype = BinaryReader.prototype;

	return ExifParser;
});

// Included from: src/javascript/runtime/html5/image/JPEG.js

/**
 * JPEG.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/image/JPEG
@private
*/
define("moxie/runtime/html5/image/JPEG", [
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/runtime/html5/image/JPEGHeaders",
	"moxie/runtime/html5/utils/BinaryReader",
	"moxie/runtime/html5/image/ExifParser"
], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) {
	
	function JPEG(data) {
		var _br, _hm, _ep, _info;

		_br = new BinaryReader(data);

		// check if it is jpeg
		if (_br.SHORT(0) !== 0xFFD8) {
			throw new x.ImageError(x.ImageError.WRONG_FORMAT);
		}

		// backup headers
		_hm = new JPEGHeaders(data);

		// extract exif info
		try {
			_ep = new ExifParser(_hm.get('app1')[0]);
		} catch(ex) {}

		// get dimensions
		_info = _getDimensions.call(this);

		Basic.extend(this, {
			type: 'image/jpeg',

			size: _br.length(),

			width: _info && _info.width || 0,

			height: _info && _info.height || 0,

			setExif: function(tag, value) {
				if (!_ep) {
					return false; // or throw an exception
				}

				if (Basic.typeOf(tag) === 'object') {
					Basic.each(tag, function(value, tag) {
						_ep.setExif(tag, value);
					});
				} else {
					_ep.setExif(tag, value);
				}

				// update internal headers
				_hm.set('app1', _ep.SEGMENT());
			},

			writeHeaders: function() {
				if (!arguments.length) {
					// if no arguments passed, update headers internally
					return _hm.restore(data);
				}
				return _hm.restore(arguments[0]);
			},

			stripHeaders: function(data) {
				return _hm.strip(data);
			},

			purge: function() {
				_purge.call(this);
			}
		});

		if (_ep) {
			this.meta = {
				tiff: _ep.TIFF(),
				exif: _ep.EXIF(),
				gps: _ep.GPS(),
				thumb: _getThumb()
			};
		}


		function _getDimensions(br) {
			var idx = 0
			, marker
			, length
			;

			if (!br) {
				br = _br;
			}

			// examine all through the end, since some images might have very large APP segments
			while (idx <= br.length()) {
				marker = br.SHORT(idx += 2);

				if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn
					idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte)
					return {
						height: br.SHORT(idx),
						width: br.SHORT(idx += 2)
					};
				}
				length = br.SHORT(idx += 2);
				idx += length - 2;
			}
			return null;
		}


		function _getThumb() {
			var data =  _ep.thumb()
			, br
			, info
			;

			if (data) {
				br = new BinaryReader(data);
				info = _getDimensions(br);
				br.clear();

				if (info) {
					info.data = data;
					return info;
				}
			}
			return null;
		}


		function _purge() {
			if (!_ep || !_hm || !_br) { 
				return; // ignore any repeating purge requests
			}
			_ep.clear();
			_hm.purge();
			_br.clear();
			_info = _hm = _ep = _br = null;
		}
	}

	return JPEG;
});

// Included from: src/javascript/runtime/html5/image/PNG.js

/**
 * PNG.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/image/PNG
@private
*/
define("moxie/runtime/html5/image/PNG", [
	"moxie/core/Exceptions",
	"moxie/core/utils/Basic",
	"moxie/runtime/html5/utils/BinaryReader"
], function(x, Basic, BinaryReader) {
	
	function PNG(data) {
		var _br, _hm, _ep, _info;

		_br = new BinaryReader(data);

		// check if it's png
		(function() {
			var idx = 0, i = 0
			, signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A]
			;

			for (i = 0; i < signature.length; i++, idx += 2) {
				if (signature[i] != _br.SHORT(idx)) {
					throw new x.ImageError(x.ImageError.WRONG_FORMAT);
				}
			}
		}());

		function _getDimensions() {
			var chunk, idx;

			chunk = _getChunkAt.call(this, 8);

			if (chunk.type == 'IHDR') {
				idx = chunk.start;
				return {
					width: _br.LONG(idx),
					height: _br.LONG(idx += 4)
				};
			}
			return null;
		}

		function _purge() {
			if (!_br) {
				return; // ignore any repeating purge requests
			}
			_br.clear();
			data = _info = _hm = _ep = _br = null;
		}

		_info = _getDimensions.call(this);

		Basic.extend(this, {
			type: 'image/png',

			size: _br.length(),

			width: _info.width,

			height: _info.height,

			purge: function() {
				_purge.call(this);
			}
		});

		// for PNG we can safely trigger purge automatically, as we do not keep any data for later
		_purge.call(this);

		function _getChunkAt(idx) {
			var length, type, start, CRC;

			length = _br.LONG(idx);
			type = _br.STRING(idx += 4, 4);
			start = idx += 4;
			CRC = _br.LONG(idx + length);

			return {
				length: length,
				type: type,
				start: start,
				CRC: CRC
			};
		}
	}

	return PNG;
});

// Included from: src/javascript/runtime/html5/image/ImageInfo.js

/**
 * ImageInfo.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/image/ImageInfo
@private
*/
define("moxie/runtime/html5/image/ImageInfo", [
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/runtime/html5/image/JPEG",
	"moxie/runtime/html5/image/PNG"
], function(Basic, x, JPEG, PNG) {
	/**
	Optional image investigation tool for HTML5 runtime. Provides the following features:
	- ability to distinguish image type (JPEG or PNG) by signature
	- ability to extract image width/height directly from it's internals, without preloading in memory (fast)
	- ability to extract APP headers from JPEGs (Exif, GPS, etc)
	- ability to replace width/height tags in extracted JPEG headers
	- ability to restore APP headers, that were for example stripped during image manipulation

	@class ImageInfo
	@constructor
	@param {String} data Image source as binary string
	*/
	return function(data) {
		var _cs = [JPEG, PNG], _img;

		// figure out the format, throw: ImageError.WRONG_FORMAT if not supported
		_img = (function() {
			for (var i = 0; i < _cs.length; i++) {
				try {
					return new _cs[i](data);
				} catch (ex) {
					// console.info(ex);
				}
			}
			throw new x.ImageError(x.ImageError.WRONG_FORMAT);
		}());

		Basic.extend(this, {
			/**
			Image Mime Type extracted from it's depths

			@property type
			@type {String}
			@default ''
			*/
			type: '',

			/**
			Image size in bytes

			@property size
			@type {Number}
			@default 0
			*/
			size: 0,

			/**
			Image width extracted from image source

			@property width
			@type {Number}
			@default 0
			*/
			width: 0,

			/**
			Image height extracted from image source

			@property height
			@type {Number}
			@default 0
			*/
			height: 0,

			/**
			Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs.

			@method setExif
			@param {String} tag Tag to set
			@param {Mixed} value Value to assign to the tag
			*/
			setExif: function() {},

			/**
			Restores headers to the source.

			@method writeHeaders
			@param {String} data Image source as binary string
			@return {String} Updated binary string
			*/
			writeHeaders: function(data) {
				return data;
			},

			/**
			Strip all headers from the source.

			@method stripHeaders
			@param {String} data Image source as binary string
			@return {String} Updated binary string
			*/
			stripHeaders: function(data) {
				return data;
			},

			/**
			Dispose resources.

			@method purge
			*/
			purge: function() {
				data = null;
			}
		});

		Basic.extend(this, _img);

		this.purge = function() {
			_img.purge();
			_img = null;
		};
	};
});

// Included from: src/javascript/runtime/html5/image/MegaPixel.js

/**
(The MIT License)

Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>;

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/**
 * Mega pixel image rendering library for iOS6 Safari
 *
 * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel),
 * which causes unexpected subsampling when drawing it in canvas.
 * By using this library, you can safely render the image with proper stretching.
 *
 * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>
 * Released under the MIT license
 */

/**
@class moxie/runtime/html5/image/MegaPixel
@private
*/
define("moxie/runtime/html5/image/MegaPixel", [], function() {

	/**
	 * Rendering image element (with resizing) into the canvas element
	 */
	function renderImageToCanvas(img, canvas, options) {
		var iw = img.naturalWidth, ih = img.naturalHeight;
		var width = options.width, height = options.height;
		var x = options.x || 0, y = options.y || 0;
		var ctx = canvas.getContext('2d');
		if (detectSubsampling(img)) {
			iw /= 2;
			ih /= 2;
		}
		var d = 1024; // size of tiling canvas
		var tmpCanvas = document.createElement('canvas');
		tmpCanvas.width = tmpCanvas.height = d;
		var tmpCtx = tmpCanvas.getContext('2d');
		var vertSquashRatio = detectVerticalSquash(img, iw, ih);
		var sy = 0;
		while (sy < ih) {
			var sh = sy + d > ih ? ih - sy : d;
			var sx = 0;
			while (sx < iw) {
				var sw = sx + d > iw ? iw - sx : d;
				tmpCtx.clearRect(0, 0, d, d);
				tmpCtx.drawImage(img, -sx, -sy);
				var dx = (sx * width / iw + x) << 0;
				var dw = Math.ceil(sw * width / iw);
				var dy = (sy * height / ih / vertSquashRatio + y) << 0;
				var dh = Math.ceil(sh * height / ih / vertSquashRatio);
				ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh);
				sx += d;
			}
			sy += d;
		}
		tmpCanvas = tmpCtx = null;
	}

	/**
	 * Detect subsampling in loaded image.
	 * In iOS, larger images than 2M pixels may be subsampled in rendering.
	 */
	function detectSubsampling(img) {
		var iw = img.naturalWidth, ih = img.naturalHeight;
		if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image
			var canvas = document.createElement('canvas');
			canvas.width = canvas.height = 1;
			var ctx = canvas.getContext('2d');
			ctx.drawImage(img, -iw + 1, 0);
			// subsampled image becomes half smaller in rendering size.
			// check alpha channel value to confirm image is covering edge pixel or not.
			// if alpha value is 0 image is not covering, hence subsampled.
			return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
		} else {
			return false;
		}
	}


	/**
	 * Detecting vertical squash in loaded image.
	 * Fixes a bug which squash image vertically while drawing into canvas for some images.
	 */
	function detectVerticalSquash(img, iw, ih) {
		var canvas = document.createElement('canvas');
		canvas.width = 1;
		canvas.height = ih;
		var ctx = canvas.getContext('2d');
		ctx.drawImage(img, 0, 0);
		var data = ctx.getImageData(0, 0, 1, ih).data;
		// search image edge pixel position in case it is squashed vertically.
		var sy = 0;
		var ey = ih;
		var py = ih;
		while (py > sy) {
			var alpha = data[(py - 1) * 4 + 3];
			if (alpha === 0) {
				ey = py;
			} else {
			sy = py;
			}
			py = (ey + sy) >> 1;
		}
		canvas = null;
		var ratio = (py / ih);
		return (ratio === 0) ? 1 : ratio;
	}

	return {
		isSubsampled: detectSubsampling,
		renderTo: renderImageToCanvas
	};
});

// Included from: src/javascript/runtime/html5/image/Image.js

/**
 * Image.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/image/Image
@private
*/
define("moxie/runtime/html5/image/Image", [
	"moxie/runtime/html5/Runtime",
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/core/utils/Encode",
	"moxie/file/Blob",
	"moxie/file/File",
	"moxie/runtime/html5/image/ImageInfo",
	"moxie/runtime/html5/image/MegaPixel",
	"moxie/core/utils/Mime",
	"moxie/core/utils/Env"
], function(extensions, Basic, x, Encode, Blob, File, ImageInfo, MegaPixel, Mime, Env) {
	
	function HTML5Image() {
		var me = this
		, _img, _imgInfo, _canvas, _binStr, _blob
		, _modified = false // is set true whenever image is modified
		, _preserveHeaders = true
		;

		Basic.extend(this, {
			loadFromBlob: function(blob) {
				var comp = this, I = comp.getRuntime()
				, asBinary = arguments.length > 1 ? arguments[1] : true
				;

				if (!I.can('access_binary')) {
					throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
				}

				_blob = blob;

				if (blob.isDetached()) {
					_binStr = blob.getSource();
					_preload.call(this, _binStr);
					return;
				} else {
					_readAsDataUrl.call(this, blob.getSource(), function(dataUrl) {
						if (asBinary) {
							_binStr = _toBinary(dataUrl);
						}
						_preload.call(comp, dataUrl);
					});
				}
			},

			loadFromImage: function(img, exact) {
				this.meta = img.meta;

				_blob = new File(null, {
					name: img.name,
					size: img.size,
					type: img.type
				});

				_preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL());
			},

			getInfo: function() {
				var I = this.getRuntime(), info;

				if (!_imgInfo && _binStr && I.can('access_image_binary')) {
					_imgInfo = new ImageInfo(_binStr);
				}

				info = {
					width: _getImg().width || 0,
					height: _getImg().height || 0,
					type: _blob.type || Mime.getFileMime(_blob.name),
					size: _binStr && _binStr.length || _blob.size || 0,
					name: _blob.name || '',
					meta: _imgInfo && _imgInfo.meta || this.meta || {}
				};

				// store thumbnail data as blob
				if (info.meta && info.meta.thumb && !(info.meta.thumb.data instanceof Blob)) {
					info.meta.thumb.data = new Blob(null, {
						type: 'image/jpeg',
						data: info.meta.thumb.data
					});
				}

				return info;
			},

			downsize: function() {
				_downsize.apply(this, arguments);
			},

			getAsCanvas: function() {
				if (_canvas) {
					_canvas.id = this.uid + '_canvas';
				}
				return _canvas;
			},

			getAsBlob: function(type, quality) {
				if (type !== this.type) {
					// if different mime type requested prepare image for conversion
					_downsize.call(this, this.width, this.height, false);
				}
				return new File(null, {
					name: _blob.name || '',
					type: type,
					data: me.getAsBinaryString.call(this, type, quality)
				});
			},

			getAsDataURL: function(type) {
				var quality = arguments[1] || 90;

				// if image has not been modified, return the source right away
				if (!_modified) {
					return _img.src;
				}

				if ('image/jpeg' !== type) {
					return _canvas.toDataURL('image/png');
				} else {
					try {
						// older Geckos used to result in an exception on quality argument
						return _canvas.toDataURL('image/jpeg', quality/100);
					} catch (ex) {
						return _canvas.toDataURL('image/jpeg');
					}
				}
			},

			getAsBinaryString: function(type, quality) {
				// if image has not been modified, return the source right away
				if (!_modified) {
					// if image was not loaded from binary string
					if (!_binStr) {
						_binStr = _toBinary(me.getAsDataURL(type, quality));
					}
					return _binStr;
				}

				if ('image/jpeg' !== type) {
					_binStr = _toBinary(me.getAsDataURL(type, quality));
				} else {
					var dataUrl;

					// if jpeg
					if (!quality) {
						quality = 90;
					}

					try {
						// older Geckos used to result in an exception on quality argument
						dataUrl = _canvas.toDataURL('image/jpeg', quality/100);
					} catch (ex) {
						dataUrl = _canvas.toDataURL('image/jpeg');
					}

					_binStr = _toBinary(dataUrl);

					if (_imgInfo) {
						_binStr = _imgInfo.stripHeaders(_binStr);

						if (_preserveHeaders) {
							// update dimensions info in exif
							if (_imgInfo.meta && _imgInfo.meta.exif) {
								_imgInfo.setExif({
									PixelXDimension: this.width,
									PixelYDimension: this.height
								});
							}

							// re-inject the headers
							_binStr = _imgInfo.writeHeaders(_binStr);
						}

						// will be re-created from fresh on next getInfo call
						_imgInfo.purge();
						_imgInfo = null;
					}
				}

				_modified = false;

				return _binStr;
			},

			destroy: function() {
				me = null;
				_purge.call(this);
				this.getRuntime().getShim().removeInstance(this.uid);
			}
		});


		function _getImg() {
			if (!_canvas && !_img) {
				throw new x.ImageError(x.DOMException.INVALID_STATE_ERR);
			}
			return _canvas || _img;
		}


		function _toBinary(str) {
			return Encode.atob(str.substring(str.indexOf('base64,') + 7));
		}


		function _toDataUrl(str, type) {
			return 'data:' + (type || '') + ';base64,' + Encode.btoa(str);
		}


		function _preload(str) {
			var comp = this;

			_img = new Image();
			_img.onerror = function() {
				_purge.call(this);
				comp.trigger('error', x.ImageError.WRONG_FORMAT);
			};
			_img.onload = function() {
				comp.trigger('load');
			};

			_img.src = str.substr(0, 5) == 'data:' ? str : _toDataUrl(str, _blob.type);
		}


		function _readAsDataUrl(file, callback) {
			var comp = this, fr;

			// use FileReader if it's available
			if (window.FileReader) {
				fr = new FileReader();
				fr.onload = function() {
					callback(this.result);
				};
				fr.onerror = function() {
					comp.trigger('error', x.ImageError.WRONG_FORMAT);
				};
				fr.readAsDataURL(file);
			} else {
				return callback(file.getAsDataURL());
			}
		}

		function _downsize(width, height, crop, preserveHeaders) {
			var self = this
			, scale
			, mathFn
			, x = 0
			, y = 0
			, img
			, destWidth
			, destHeight
			, orientation
			;

			_preserveHeaders = preserveHeaders; // we will need to check this on export (see getAsBinaryString())

			// take into account orientation tag
			orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1;

			if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation
				// swap dimensions
				var tmp = width;
				width = height;
				height = tmp;
			}

			img = _getImg();

			// unify dimensions
			if (!crop) {
				scale = Math.min(width/img.width, height/img.height);
			} else {
				// one of the dimensions may exceed the actual image dimensions - we need to take the smallest value
				width = Math.min(width, img.width);
				height = Math.min(height, img.height);

				scale = Math.max(width/img.width, height/img.height);
			}
		
			// we only downsize here
			if (scale > 1 && !crop && preserveHeaders) {
				this.trigger('Resize');
				return;
			}

			// prepare canvas if necessary
			if (!_canvas) {
				_canvas = document.createElement("canvas");
			}

			// calculate dimensions of proportionally resized image
			destWidth = Math.round(img.width * scale);	
			destHeight = Math.round(img.height * scale);

			// scale image and canvas
			if (crop) {
				_canvas.width = width;
				_canvas.height = height;

				// if dimensions of the resulting image still larger than canvas, center it
				if (destWidth > width) {
					x = Math.round((destWidth - width) / 2);
				}

				if (destHeight > height) {
					y = Math.round((destHeight - height) / 2);
				}
			} else {
				_canvas.width = destWidth;
				_canvas.height = destHeight;
			}

			// rotate if required, according to orientation tag
			if (!_preserveHeaders) {
				_rotateToOrientaion(_canvas.width, _canvas.height, orientation);
			}

			_drawToCanvas.call(this, img, _canvas, -x, -y, destWidth, destHeight);

			this.width = _canvas.width;
			this.height = _canvas.height;

			_modified = true;
			self.trigger('Resize');
		}


		function _drawToCanvas(img, canvas, x, y, w, h) {
			if (Env.OS === 'iOS') { 
				// avoid squish bug in iOS6
				MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y });
			} else {
				var ctx = canvas.getContext('2d');
				ctx.drawImage(img, x, y, w, h);
			}
		}


		/**
		* Transform canvas coordination according to specified frame size and orientation
		* Orientation value is from EXIF tag
		* @author Shinichi Tomita <shinichi.tomita@gmail.com>
		*/
		function _rotateToOrientaion(width, height, orientation) {
			switch (orientation) {
				case 5:
				case 6:
				case 7:
				case 8:
					_canvas.width = height;
					_canvas.height = width;
					break;
				default:
					_canvas.width = width;
					_canvas.height = height;
			}

			/**
			1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
			2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
			3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
			4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
			5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
			6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
			7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
			8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
			*/

			var ctx = _canvas.getContext('2d');
			switch (orientation) {
				case 2:
					// horizontal flip
					ctx.translate(width, 0);
					ctx.scale(-1, 1);
					break;
				case 3:
					// 180 rotate left
					ctx.translate(width, height);
					ctx.rotate(Math.PI);
					break;
				case 4:
					// vertical flip
					ctx.translate(0, height);
					ctx.scale(1, -1);
					break;
				case 5:
					// vertical flip + 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.scale(1, -1);
					break;
				case 6:
					// 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.translate(0, -height);
					break;
				case 7:
					// horizontal flip + 90 rotate right
					ctx.rotate(0.5 * Math.PI);
					ctx.translate(width, -height);
					ctx.scale(-1, 1);
					break;
				case 8:
					// 90 rotate left
					ctx.rotate(-0.5 * Math.PI);
					ctx.translate(-width, 0);
					break;
			}
		}


		function _purge() {
			if (_imgInfo) {
				_imgInfo.purge();
				_imgInfo = null;
			}
			_binStr = _img = _canvas = _blob = null;
			_modified = false;
		}
	}

	return (extensions.Image = HTML5Image);
});

// Included from: src/javascript/runtime/flash/Runtime.js

/**
 * Runtime.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*global ActiveXObject:true */

/**
Defines constructor for Flash runtime.

@class moxie/runtime/flash/Runtime
@private
*/
define("moxie/runtime/flash/Runtime", [
	"moxie/core/utils/Basic",
	"moxie/core/utils/Env",
	"moxie/core/utils/Dom",
	"moxie/core/Exceptions",
	"moxie/runtime/Runtime"
], function(Basic, Env, Dom, x, Runtime) {
	
	var type = 'flash', extensions = {};

	/**
	Get the version of the Flash Player

	@method getShimVersion
	@private
	@return {Number} Flash Player version
	*/
	function getShimVersion() {
		var version;

		try {
			version = navigator.plugins['Shockwave Flash'];
			version = version.description;
		} catch (e1) {
			try {
				version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
			} catch (e2) {
				version = '0.0';
			}
		}
		version = version.match(/\d+/g);
		return parseFloat(version[0] + '.' + version[1]);
	}


	/**
	Cross-browser SWF removal
    	- Especially needed to safely and completely remove a SWF in Internet Explorer

   	Originated from SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	*/
	function removeSWF(id) {
        var obj = Dom.get(id);
        if (obj && obj.nodeName == "OBJECT") {
            if (Env.browser === 'IE') {
                obj.style.display = "none";
                (function onInit(){
                	// http://msdn.microsoft.com/en-us/library/ie/ms534360(v=vs.85).aspx
                    if (obj.readyState == 4) {
                        removeObjectInIE(id);
                    }
                    else {
                        setTimeout(onInit, 10);
                    }
                })();
            }
            else {
                obj.parentNode.removeChild(obj);
            }
        }
    }


	function removeObjectInIE(id) {
        var obj = Dom.get(id);
        if (obj) {
            for (var i in obj) {
                if (typeof obj[i] == "function") {
                    obj[i] = null;
                }
            }
            obj.parentNode.removeChild(obj);
        }
    }

	/**
	Constructor for the Flash Runtime

	@class FlashRuntime
	@extends Runtime
	*/
	function FlashRuntime(options) {
		var I = this, initTimer;

		options = Basic.extend({ swf_url: Env.swf_url }, options);

		Runtime.call(this, options, type, {
			access_binary: function(value) {
				return value && I.mode === 'browser';
			},
			access_image_binary: function(value) {
				return value && I.mode === 'browser';
			},
			display_media: Runtime.capTrue,
			do_cors: Runtime.capTrue,
			drag_and_drop: false,
			report_upload_progress: function() {
				return I.mode === 'client';
			},
			resize_image: Runtime.capTrue,
			return_response_headers: false,
			return_response_type: function(responseType) {
				if (responseType === 'json' && !!window.JSON) {
					return true;
				} 
				return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser';
			},
			return_status_code: function(code) {
				return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]);
			},
			select_file: Runtime.capTrue,
			select_multiple: Runtime.capTrue,
			send_binary_string: function(value) {
				return value && I.mode === 'browser';
			},
			send_browser_cookies: function(value) {
				return value && I.mode === 'browser';
			},
			send_custom_headers: function(value) {
				return value && I.mode === 'browser';
			},
			send_multipart: Runtime.capTrue,
			slice_blob: function(value) {
				return value && I.mode === 'browser';
			},
			stream_upload: function(value) {
				return value && I.mode === 'browser';
			},
			summon_file_dialog: false,
			upload_filesize: function(size) {
				return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client';
			},
			use_http_method: function(methods) {
				return !Basic.arrayDiff(methods, ['GET', 'POST']);
			}
		}, { 
			// capabilities that require specific mode
			access_binary: function(value) {
				return value ? 'browser' : 'client';
			},
			access_image_binary: function(value) {
				return value ? 'browser' : 'client';
			},
			report_upload_progress: function(value) {
				return value ? 'browser' : 'client';
			},
			return_response_type: function(responseType) {
				return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser'];
			},
			return_status_code: function(code) {
				return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser'];
			},
			send_binary_string: function(value) {
				return value ? 'browser' : 'client';
			},
			send_browser_cookies: function(value) {
				return value ? 'browser' : 'client';
			},
			send_custom_headers: function(value) {
				return value ? 'browser' : 'client';
			},
			stream_upload: function(value) {
				return value ? 'client' : 'browser';
			},
			upload_filesize: function(size) {
				return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser';
			}
		}, 'client');


		// minimal requirement for Flash Player version
		if (getShimVersion() < 11.3) {
			if (MXI_DEBUG && Env.debug.runtime) {
				Env.log("\tFlash didn't meet minimal version requirement (11.3).");	
			}

			this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before
		}


		Basic.extend(this, {

			getShim: function() {
				return Dom.get(this.uid);
			},

			shimExec: function(component, action) {
				var args = [].slice.call(arguments, 2);
				return I.getShim().exec(this.uid, component, action, args);
			},

			init: function() {
				var html, el, container;

				container = this.getShimContainer();

				// if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
				Basic.extend(container.style, {
					position: 'absolute',
					top: '-8px',
					left: '-8px',
					width: '9px',
					height: '9px',
					overflow: 'hidden'
				});

				// insert flash object
				html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' +  options.swf_url + '" ';

				if (Env.browser === 'IE') {
					html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
				}

				html += 'width="100%" height="100%" style="outline:0">'  +
					'<param name="movie" value="' + options.swf_url + '" />' +
					'<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' +
					'<param name="wmode" value="transparent" />' +
					'<param name="allowscriptaccess" value="always" />' +
				'</object>';

				if (Env.browser === 'IE') {
					el = document.createElement('div');
					container.appendChild(el);
					el.outerHTML = html;
					el = container = null; // just in case
				} else {
					container.innerHTML = html;
				}

				// Init is dispatched by the shim
				initTimer = setTimeout(function() {
					if (I && !I.initialized) { // runtime might be already destroyed by this moment
						I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("\tFlash failed to initialize within a specified period of time (typically 5s).");	
						}
					}
				}, 5000);
			},

			destroy: (function(destroy) { // extend default destroy method
				return function() {
					removeSWF(I.uid); // SWF removal requires special care in IE

					destroy.call(I);
					clearTimeout(initTimer); // initialization check might be still onwait
					options = initTimer = destroy = I = null;
				};
			}(this.destroy))

		}, extensions);
	}

	Runtime.addConstructor(type, FlashRuntime);

	return extensions;
});

// Included from: src/javascript/runtime/flash/file/FileInput.js

/**
 * FileInput.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/flash/file/FileInput
@private
*/
define("moxie/runtime/flash/file/FileInput", [
	"moxie/runtime/flash/Runtime",
	"moxie/file/File",
	"moxie/core/utils/Basic"
], function(extensions, File, Basic) {
	
	var FileInput = {		
		init: function(options) {
			var comp = this, I = this.getRuntime();

			this.bind("Change", function() {
				var files = I.shimExec.call(comp, 'FileInput', 'getFiles');
				comp.files = [];
				Basic.each(files, function(file) {
					comp.files.push(new File(I.uid, file));
				});
			}, 999);

			this.getRuntime().shimExec.call(this, 'FileInput', 'init', {
				name: options.name,
				accept: options.accept,
				multiple: options.multiple
			});

			this.trigger('ready');
		}
	};

	return (extensions.FileInput = FileInput);
});

// Included from: src/javascript/runtime/flash/file/Blob.js

/**
 * Blob.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/flash/file/Blob
@private
*/
define("moxie/runtime/flash/file/Blob", [
	"moxie/runtime/flash/Runtime",
	"moxie/file/Blob"
], function(extensions, Blob) {

	var FlashBlob = {
		slice: function(blob, start, end, type) {
			var self = this.getRuntime();

			if (start < 0) {
				start = Math.max(blob.size + start, 0);
			} else if (start > 0) {
				start = Math.min(start, blob.size);
			}

			if (end < 0) {
				end = Math.max(blob.size + end, 0);
			} else if (end > 0) {
				end = Math.min(end, blob.size);
			}

			blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || '');

			if (blob) {
				blob = new Blob(self.uid, blob);
			}
			return blob;
		}
	};

	return (extensions.Blob = FlashBlob);
});

// Included from: src/javascript/runtime/flash/file/FileReader.js

/**
 * FileReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/flash/file/FileReader
@private
*/
define("moxie/runtime/flash/file/FileReader", [
	"moxie/runtime/flash/Runtime",
	"moxie/core/utils/Encode"
], function(extensions, Encode) {

	function _formatData(data, op) {
		switch (op) {
			case 'readAsText':
				return Encode.atob(data, 'utf8');
			case 'readAsBinaryString':
				return Encode.atob(data);
			case 'readAsDataURL':
				return data;
		}
		return null;
	}

	var FileReader = {
		read: function(op, blob) {
			var comp = this;

			comp.result = '';

			// special prefix for DataURL read mode
			if (op === 'readAsDataURL') {
				comp.result = 'data:' + (blob.type || '') + ';base64,';
			}

			comp.bind('Progress', function(e, data) {
				if (data) {
					comp.result += _formatData(data, op);
				}
			}, 999);

			return comp.getRuntime().shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid);
		}
	};

	return (extensions.FileReader = FileReader);
});

// Included from: src/javascript/runtime/flash/file/FileReaderSync.js

/**
 * FileReaderSync.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/flash/file/FileReaderSync
@private
*/
define("moxie/runtime/flash/file/FileReaderSync", [
	"moxie/runtime/flash/Runtime",
	"moxie/core/utils/Encode"
], function(extensions, Encode) {
	
	function _formatData(data, op) {
		switch (op) {
			case 'readAsText':
				return Encode.atob(data, 'utf8');
			case 'readAsBinaryString':
				return Encode.atob(data);
			case 'readAsDataURL':
				return data;
		}
		return null;
	}

	var FileReaderSync = {
		read: function(op, blob) {
			var result, self = this.getRuntime();

			result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid);
			if (!result) {
				return null; // or throw ex
			}

			// special prefix for DataURL read mode
			if (op === 'readAsDataURL') {
				result = 'data:' + (blob.type || '') + ';base64,' + result;
			}

			return _formatData(result, op, blob.type);
		}
	};

	return (extensions.FileReaderSync = FileReaderSync);
});

// Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js

/**
 * XMLHttpRequest.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/flash/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/flash/xhr/XMLHttpRequest", [
	"moxie/runtime/flash/Runtime",
	"moxie/core/utils/Basic",
	"moxie/file/Blob",
	"moxie/file/File",
	"moxie/file/FileReaderSync",
	"moxie/xhr/FormData",
	"moxie/runtime/Transporter"
], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter) {
	
	var XMLHttpRequest = {

		send: function(meta, data) {
			var target = this, self = target.getRuntime();

			function send() {
				meta.transport = self.mode;
				self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data);
			}


			function appendBlob(name, blob) {
				self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid);
				data = null;
				send();
			}


			function attachBlob(blob, cb) {
				var tr = new Transporter();

				tr.bind("TransportingComplete", function() {
					cb(this.result);
				});

				tr.transport(blob.getSource(), blob.type, {
					ruid: self.uid
				});
			}

			// copy over the headers if any
			if (!Basic.isEmptyObj(meta.headers)) {
				Basic.each(meta.headers, function(value, header) {
					self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object
				});
			}

			// transfer over multipart params and blob itself
			if (data instanceof FormData) {
				var blobField;
				data.each(function(value, name) {
					if (value instanceof Blob) {
						blobField = name;
					} else {
						self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value);
					}
				});

				if (!data.hasBlob()) {
					data = null;
					send();
				} else {
					var blob = data.getBlob();
					if (blob.isDetached()) {
						attachBlob(blob, function(attachedBlob) {
							blob.destroy();
							appendBlob(blobField, attachedBlob);		
						});
					} else {
						appendBlob(blobField, blob);
					}
				}
			} else if (data instanceof Blob) {
				if (data.isDetached()) {
					attachBlob(data, function(attachedBlob) {
						data.destroy();
						data = attachedBlob.uid;
						send();
					});
				} else {
					data = data.uid;
					send();
				}
			} else {
				send();
			}
		},

		getResponse: function(responseType) {
			var frs, blob, self = this.getRuntime();

			blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob');

			if (blob) {
				blob = new File(self.uid, blob);

				if ('blob' === responseType) {
					return blob;
				}

				try { 
					frs = new FileReaderSync();

					if (!!~Basic.inArray(responseType, ["", "text"])) {
						return frs.readAsText(blob);
					} else if ('json' === responseType && !!window.JSON) {
						return JSON.parse(frs.readAsText(blob));
					}
				} finally {
					blob.destroy();
				}
			}
			return null;
		},

		abort: function(upload_complete_flag) {
			var self = this.getRuntime();

			self.shimExec.call(this, 'XMLHttpRequest', 'abort');

			this.dispatchEvent('readystatechange');
			// this.dispatchEvent('progress');
			this.dispatchEvent('abort');

			//if (!upload_complete_flag) {
				// this.dispatchEvent('uploadprogress');
			//}
		}
	};

	return (extensions.XMLHttpRequest = XMLHttpRequest);
});

// Included from: src/javascript/runtime/flash/runtime/Transporter.js

/**
 * Transporter.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/flash/runtime/Transporter
@private
*/
define("moxie/runtime/flash/runtime/Transporter", [
	"moxie/runtime/flash/Runtime",
	"moxie/file/Blob"
], function(extensions, Blob) {

	var Transporter = {
		getAsBlob: function(type) {
			var self = this.getRuntime()
			, blob = self.shimExec.call(this, 'Transporter', 'getAsBlob', type)
			;
			if (blob) {
				return new Blob(self.uid, blob);
			}
			return null;
		}
	};

	return (extensions.Transporter = Transporter);
});

// Included from: src/javascript/runtime/flash/image/Image.js

/**
 * Image.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/flash/image/Image
@private
*/
define("moxie/runtime/flash/image/Image", [
	"moxie/runtime/flash/Runtime",
	"moxie/core/utils/Basic",
	"moxie/runtime/Transporter",
	"moxie/file/Blob",
	"moxie/file/FileReaderSync"
], function(extensions, Basic, Transporter, Blob, FileReaderSync) {
	
	var Image = {
		loadFromBlob: function(blob) {
			var comp = this, self = comp.getRuntime();

			function exec(srcBlob) {
				self.shimExec.call(comp, 'Image', 'loadFromBlob', srcBlob.uid);
				comp = self = null;
			}

			if (blob.isDetached()) { // binary string
				var tr = new Transporter();
				tr.bind("TransportingComplete", function() {
					exec(tr.result.getSource());
				});
				tr.transport(blob.getSource(), blob.type, { ruid: self.uid });
			} else {
				exec(blob.getSource());
			}
		},

		loadFromImage: function(img) {
			var self = this.getRuntime();
			return self.shimExec.call(this, 'Image', 'loadFromImage', img.uid);
		},

		getInfo: function() {
			var self = this.getRuntime()
			, info = self.shimExec.call(this, 'Image', 'getInfo')
			;

			if (info.meta && info.meta.thumb && !(info.meta.thumb.data instanceof Blob)) {
				info.meta.thumb.data = new Blob(self.uid, info.meta.thumb.data);
			}
			return info;
		},

		getAsBlob: function(type, quality) {
			var self = this.getRuntime()
			, blob = self.shimExec.call(this, 'Image', 'getAsBlob', type, quality)
			;
			if (blob) {
				return new Blob(self.uid, blob);
			}
			return null;
		},

		getAsDataURL: function() {
			var self = this.getRuntime()
			, blob = self.Image.getAsBlob.apply(this, arguments)
			, frs
			;
			if (!blob) {
				return null;
			}
			frs = new FileReaderSync();
			return frs.readAsDataURL(blob);
		}
	};

	return (extensions.Image = Image);
});

// Included from: src/javascript/runtime/silverlight/Runtime.js

/**
 * RunTime.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*global ActiveXObject:true */

/**
Defines constructor for Silverlight runtime.

@class moxie/runtime/silverlight/Runtime
@private
*/
define("moxie/runtime/silverlight/Runtime", [
	"moxie/core/utils/Basic",
	"moxie/core/utils/Env",
	"moxie/core/utils/Dom",
	"moxie/core/Exceptions",
	"moxie/runtime/Runtime"
], function(Basic, Env, Dom, x, Runtime) {
	
	var type = "silverlight", extensions = {};

	function isInstalled(version) {
		var isVersionSupported = false, control = null, actualVer,
			actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0;

		try {
			try {
				control = new ActiveXObject('AgControl.AgControl');

				if (control.IsVersionSupported(version)) {
					isVersionSupported = true;
				}

				control = null;
			} catch (e) {
				var plugin = navigator.plugins["Silverlight Plug-In"];

				if (plugin) {
					actualVer = plugin.description;

					if (actualVer === "1.0.30226.2") {
						actualVer = "2.0.30226.2";
					}

					actualVerArray = actualVer.split(".");

					while (actualVerArray.length > 3) {
						actualVerArray.pop();
					}

					while ( actualVerArray.length < 4) {
						actualVerArray.push(0);
					}

					reqVerArray = version.split(".");

					while (reqVerArray.length > 4) {
						reqVerArray.pop();
					}

					do {
						requiredVersionPart = parseInt(reqVerArray[index], 10);
						actualVersionPart = parseInt(actualVerArray[index], 10);
						index++;
					} while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);

					if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) {
						isVersionSupported = true;
					}
				}
			}
		} catch (e2) {
			isVersionSupported = false;
		}

		return isVersionSupported;
	}

	/**
	Constructor for the Silverlight Runtime

	@class SilverlightRuntime
	@extends Runtime
	*/
	function SilverlightRuntime(options) {
		var I = this, initTimer;

		options = Basic.extend({ xap_url: Env.xap_url }, options);

		Runtime.call(this, options, type, {
			access_binary: Runtime.capTrue,
			access_image_binary: Runtime.capTrue,
			display_media: Runtime.capTrue,
			do_cors: Runtime.capTrue,
			drag_and_drop: false,
			report_upload_progress: Runtime.capTrue,
			resize_image: Runtime.capTrue,
			return_response_headers: function(value) {
				return value && I.mode === 'client';
			},
			return_response_type: function(responseType) {
				if (responseType !== 'json') {
					return true;
				} else {
					return !!window.JSON;
				}
			},
			return_status_code: function(code) {
				return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]);
			},
			select_file: Runtime.capTrue,
			select_multiple: Runtime.capTrue,
			send_binary_string: Runtime.capTrue,
			send_browser_cookies: function(value) {
				return value && I.mode === 'browser';
			},
			send_custom_headers: function(value) {
				return value && I.mode === 'client';
			},
			send_multipart: Runtime.capTrue,
			slice_blob: Runtime.capTrue,
			stream_upload: true,
			summon_file_dialog: false,
			upload_filesize: Runtime.capTrue,
			use_http_method: function(methods) {
				return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']);
			}
		}, { 
			// capabilities that require specific mode
			return_response_headers: function(value) {
				return value ? 'client' : 'browser';
			},
			return_status_code: function(code) {
				return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser'];
			},
			send_browser_cookies: function(value) {
				return value ? 'browser' : 'client';
			},
			send_custom_headers: function(value) {
				return value ? 'client' : 'browser';
			},
			use_http_method: function(methods) {
				return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser'];
			}
		});


		// minimal requirement
		if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') {
			if (MXI_DEBUG && Env.debug.runtime) {
				Env.log("\tSilverlight is not installed or minimal version (2.0.31005.0) requirement not met (not likely).");	
			}

			this.mode = false;
		}


		Basic.extend(this, {
			getShim: function() {
				return Dom.get(this.uid).content.Moxie;
			},

			shimExec: function(component, action) {
				var args = [].slice.call(arguments, 2);
				return I.getShim().exec(this.uid, component, action, args);
			},

			init : function() {
				var container;

				container = this.getShimContainer();

				container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' +
					'<param name="source" value="' + options.xap_url + '"/>' +
					'<param name="background" value="Transparent"/>' +
					'<param name="windowless" value="true"/>' +
					'<param name="enablehtmlaccess" value="true"/>' +
					'<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' +
				'</object>';

				// Init is dispatched by the shim
				initTimer = setTimeout(function() {
					if (I && !I.initialized) { // runtime might be already destroyed by this moment
						I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("\Silverlight failed to initialize within a specified period of time (5-10s).");	
						}
					}
				}, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac)
			},

			destroy: (function(destroy) { // extend default destroy method
				return function() {
					destroy.call(I);
					clearTimeout(initTimer); // initialization check might be still onwait
					options = initTimer = destroy = I = null;
				};
			}(this.destroy))

		}, extensions);
	}

	Runtime.addConstructor(type, SilverlightRuntime); 

	return extensions;
});

// Included from: src/javascript/runtime/silverlight/file/FileInput.js

/**
 * FileInput.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/silverlight/file/FileInput
@private
*/
define("moxie/runtime/silverlight/file/FileInput", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/file/File",
	"moxie/core/utils/Basic"
], function(extensions, File, Basic) {
	
	var FileInput = {
		init: function(options) {
			var comp = this, I = this.getRuntime();

			function toFilters(accept) {
				var filter = '';
				for (var i = 0; i < accept.length; i++) {
					filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.');
				}
				return filter;
			}

			this.bind("Change", function() {
				var files = I.shimExec.call(comp, 'FileInput', 'getFiles');
				comp.files = [];
				Basic.each(files, function(file) {
					comp.files.push(new File(I.uid, file));
				});
			}, 999);
			
			this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple);
			this.trigger('ready');
		}
	};

	return (extensions.FileInput = FileInput);
});

// Included from: src/javascript/runtime/silverlight/file/Blob.js

/**
 * Blob.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/silverlight/file/Blob
@private
*/
define("moxie/runtime/silverlight/file/Blob", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/core/utils/Basic",
	"moxie/runtime/flash/file/Blob"
], function(extensions, Basic, Blob) {
	return (extensions.Blob = Basic.extend({}, Blob));
});

// Included from: src/javascript/runtime/silverlight/file/FileDrop.js

/**
 * FileDrop.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/silverlight/file/FileDrop
@private
*/
define("moxie/runtime/silverlight/file/FileDrop", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/core/utils/Dom", 
	"moxie/core/utils/Events"
], function(extensions, Dom, Events) {

	// not exactly useful, since works only in safari (...crickets...)
	var FileDrop = {
		init: function() {
			var comp = this, self = comp.getRuntime(), dropZone;

			dropZone = self.getShimContainer();

			Events.addEvent(dropZone, 'dragover', function(e) {
				e.preventDefault();
				e.stopPropagation();
				e.dataTransfer.dropEffect = 'copy';
			}, comp.uid);

			Events.addEvent(dropZone, 'dragenter', function(e) {
				e.preventDefault();
				var flag = Dom.get(self.uid).dragEnter(e);
				// If handled, then stop propagation of event in DOM
				if (flag) {
					e.stopPropagation();
				}
			}, comp.uid);

			Events.addEvent(dropZone, 'drop', function(e) {
				e.preventDefault();
				var flag = Dom.get(self.uid).dragDrop(e);
				// If handled, then stop propagation of event in DOM
				if (flag) {
					e.stopPropagation();
				}
			}, comp.uid);

			return self.shimExec.call(this, 'FileDrop', 'init');
		}
	};

	return (extensions.FileDrop = FileDrop);
});

// Included from: src/javascript/runtime/silverlight/file/FileReader.js

/**
 * FileReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/silverlight/file/FileReader
@private
*/
define("moxie/runtime/silverlight/file/FileReader", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/core/utils/Basic",
	"moxie/runtime/flash/file/FileReader"
], function(extensions, Basic, FileReader) {
	return (extensions.FileReader = Basic.extend({}, FileReader));
});

// Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js

/**
 * FileReaderSync.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/silverlight/file/FileReaderSync
@private
*/
define("moxie/runtime/silverlight/file/FileReaderSync", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/core/utils/Basic",
	"moxie/runtime/flash/file/FileReaderSync"
], function(extensions, Basic, FileReaderSync) {
	return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync));
});

// Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js

/**
 * XMLHttpRequest.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/silverlight/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/core/utils/Basic",
	"moxie/runtime/flash/xhr/XMLHttpRequest"
], function(extensions, Basic, XMLHttpRequest) {
	return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest));
});

// Included from: src/javascript/runtime/silverlight/runtime/Transporter.js

/**
 * Transporter.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/silverlight/runtime/Transporter
@private
*/
define("moxie/runtime/silverlight/runtime/Transporter", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/core/utils/Basic",
	"moxie/runtime/flash/runtime/Transporter"
], function(extensions, Basic, Transporter) {
	return (extensions.Transporter = Basic.extend({}, Transporter));
});

// Included from: src/javascript/runtime/silverlight/image/Image.js

/**
 * Image.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */
 
/**
@class moxie/runtime/silverlight/image/Image
@private
*/
define("moxie/runtime/silverlight/image/Image", [
	"moxie/runtime/silverlight/Runtime",
	"moxie/core/utils/Basic",
	"moxie/file/Blob",
	"moxie/runtime/flash/image/Image"
], function(extensions, Basic, Blob, Image) {
	return (extensions.Image = Basic.extend({}, Image, {

		getInfo: function() {
			var self = this.getRuntime()
			, grps = ['tiff', 'exif', 'gps', 'thumb']
			, info = { meta: {} }
			, rawInfo = self.shimExec.call(this, 'Image', 'getInfo')
			;

			if (rawInfo.meta) {
				Basic.each(grps, function(grp) {
					var meta = rawInfo.meta[grp]
					, tag
					, i
					, length
					, value
					;
					if (meta && meta.keys) {
						info.meta[grp] = {};
						for (i = 0, length = meta.keys.length; i < length; i++) {
							tag = meta.keys[i];
							value = meta[tag];
							if (value) {
								// convert numbers
								if (/^(\d|[1-9]\d+)$/.test(value)) { // integer (make sure doesn't start with zero)
									value = parseInt(value, 10);
								} else if (/^\d*\.\d+$/.test(value)) { // double
									value = parseFloat(value);
								}
								info.meta[grp][tag] = value;
							}
						}
					}
				});

				// save thumb data as blob
				if (info.meta && info.meta.thumb && !(info.meta.thumb.data instanceof Blob)) {
					info.meta.thumb.data = new Blob(self.uid, info.meta.thumb.data);
				}
			}

			info.width = parseInt(rawInfo.width, 10);
			info.height = parseInt(rawInfo.height, 10);
			info.size = parseInt(rawInfo.size, 10);
			info.type = rawInfo.type;
			info.name = rawInfo.name;

			return info;
		}
	}));
});

// Included from: src/javascript/runtime/html4/Runtime.js

/**
 * Runtime.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*global File:true */

/**
Defines constructor for HTML4 runtime.

@class moxie/runtime/html4/Runtime
@private
*/
define("moxie/runtime/html4/Runtime", [
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/runtime/Runtime",
	"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
	
	var type = 'html4', extensions = {};

	function Html4Runtime(options) {
		var I = this
		, Test = Runtime.capTest
		, True = Runtime.capTrue
		;

		Runtime.call(this, options, type, {
			access_binary: Test(window.FileReader || window.File && File.getAsDataURL),
			access_image_binary: false,
			display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))),
			do_cors: false,
			drag_and_drop: false,
			filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
				return !(
					(Env.browser === 'Chrome' && Env.verComp(Env.version, 28, '<')) || 
					(Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) || 
					(Env.browser === 'Safari' && Env.verComp(Env.version, 7, '<')) ||
					(Env.browser === 'Firefox' && Env.verComp(Env.version, 37, '<'))
				);
			}()),
			resize_image: function() {
				return extensions.Image && I.can('access_binary') && Env.can('create_canvas');
			},
			report_upload_progress: false,
			return_response_headers: false,
			return_response_type: function(responseType) {
				if (responseType === 'json' && !!window.JSON) {
					return true;
				} 
				return !!~Basic.inArray(responseType, ['text', 'document', '']);
			},
			return_status_code: function(code) {
				return !Basic.arrayDiff(code, [200, 404]);
			},
			select_file: function() {
				return Env.can('use_fileinput');
			},
			select_multiple: false,
			send_binary_string: false,
			send_custom_headers: false,
			send_multipart: true,
			slice_blob: false,
			stream_upload: function() {
				return I.can('select_file');
			},
			summon_file_dialog: function() { // yeah... some dirty sniffing here...
				return I.can('select_file') && (
					(Env.browser === 'Firefox' && Env.verComp(Env.version, 4, '>=')) ||
					(Env.browser === 'Opera' && Env.verComp(Env.version, 12, '>=')) ||
					(Env.browser === 'IE' && Env.verComp(Env.version, 10, '>=')) ||
					!!~Basic.inArray(Env.browser, ['Chrome', 'Safari'])
				);
			},
			upload_filesize: True,
			use_http_method: function(methods) {
				return !Basic.arrayDiff(methods, ['GET', 'POST']);
			}
		});


		Basic.extend(this, {
			init : function() {
				this.trigger("Init");
			},

			destroy: (function(destroy) { // extend default destroy method
				return function() {
					destroy.call(I);
					destroy = I = null;
				};
			}(this.destroy))
		});

		Basic.extend(this.getShim(), extensions);
	}

	Runtime.addConstructor(type, Html4Runtime);

	return extensions;
});

// Included from: src/javascript/runtime/html4/file/FileInput.js

/**
 * FileInput.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html4/file/FileInput
@private
*/
define("moxie/runtime/html4/file/FileInput", [
	"moxie/runtime/html4/Runtime",
	"moxie/file/File",
	"moxie/core/utils/Basic",
	"moxie/core/utils/Dom",
	"moxie/core/utils/Events",
	"moxie/core/utils/Mime",
	"moxie/core/utils/Env"
], function(extensions, File, Basic, Dom, Events, Mime, Env) {
	
	function FileInput() {
		var _uid, _mimes = [], _options;

		function addInput() {
			var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid;

			uid = Basic.guid('uid_');

			shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE

			if (_uid) { // move previous form out of the view
				currForm = Dom.get(_uid + '_form');
				if (currForm) {
					Basic.extend(currForm.style, { top: '100%' });
				}
			}

			// build form in DOM, since innerHTML version not able to submit file for some reason
			form = document.createElement('form');
			form.setAttribute('id', uid + '_form');
			form.setAttribute('method', 'post');
			form.setAttribute('enctype', 'multipart/form-data');
			form.setAttribute('encoding', 'multipart/form-data');

			Basic.extend(form.style, {
				overflow: 'hidden',
				position: 'absolute',
				top: 0,
				left: 0,
				width: '100%',
				height: '100%'
			});

			input = document.createElement('input');
			input.setAttribute('id', uid);
			input.setAttribute('type', 'file');
			input.setAttribute('name', _options.name || 'Filedata');
			input.setAttribute('accept', _mimes.join(','));

			Basic.extend(input.style, {
				fontSize: '999px',
				opacity: 0
			});

			form.appendChild(input);
			shimContainer.appendChild(form);

			// prepare file input to be placed underneath the browse_button element
			Basic.extend(input.style, {
				position: 'absolute',
				top: 0,
				left: 0,
				width: '100%',
				height: '100%'
			});

			if (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) {
				Basic.extend(input.style, {
					filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"
				});
			}

			input.onchange = function() { // there should be only one handler for this
				var file;

				if (!this.value) {
					return;
				}

				if (this.files) { // check if browser is fresh enough
					file = this.files[0];

					// ignore empty files (IE10 for example hangs if you try to send them via XHR)
					if (file.size === 0) {
						form.parentNode.removeChild(form);
						return;
					}
				} else {
					file = {
						name: this.value
					};
				}

				file = new File(I.uid, file);

				// clear event handler
				this.onchange = function() {}; 
				addInput.call(comp); 

				comp.files = [file];

				// substitute all ids with file uids (consider file.uid read-only - we cannot do it the other way around)
				input.setAttribute('id', file.uid);
				form.setAttribute('id', file.uid + '_form');
				
				comp.trigger('change');

				input = form = null;
			};


			// route click event to the input
			if (I.can('summon_file_dialog')) {
				browseButton = Dom.get(_options.browse_button);
				Events.removeEvent(browseButton, 'click', comp.uid);
				Events.addEvent(browseButton, 'click', function(e) {
					if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
						input.click();
					}
					e.preventDefault();
				}, comp.uid);
			}

			_uid = uid;

			shimContainer = currForm = browseButton = null;
		}

		Basic.extend(this, {
			init: function(options) {
				var comp = this, I = comp.getRuntime(), shimContainer;

				// figure out accept string
				_options = options;
				_mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension'));

				shimContainer = I.getShimContainer();

				(function() {
					var browseButton, zIndex, top;

					browseButton = Dom.get(options.browse_button);

					// Route click event to the input[type=file] element for browsers that support such behavior
					if (I.can('summon_file_dialog')) {
						if (Dom.getStyle(browseButton, 'position') === 'static') {
							browseButton.style.position = 'relative';
						}

						zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1;

						browseButton.style.zIndex = zIndex;
						shimContainer.style.zIndex = zIndex - 1;
					}

					/* Since we have to place input[type=file] on top of the browse_button for some browsers,
					browse_button loses interactivity, so we restore it here */
					top = I.can('summon_file_dialog') ? browseButton : shimContainer;

					Events.addEvent(top, 'mouseover', function() {
						comp.trigger('mouseenter');
					}, comp.uid);

					Events.addEvent(top, 'mouseout', function() {
						comp.trigger('mouseleave');
					}, comp.uid);

					Events.addEvent(top, 'mousedown', function() {
						comp.trigger('mousedown');
					}, comp.uid);

					Events.addEvent(Dom.get(options.container), 'mouseup', function() {
						comp.trigger('mouseup');
					}, comp.uid);

					browseButton = null;
				}());

				addInput.call(this);

				shimContainer = null;

				// trigger ready event asynchronously
				comp.trigger({
					type: 'ready',
					async: true
				});
			},


			disable: function(state) {
				var input;

				if ((input = Dom.get(_uid))) {
					input.disabled = !!state;
				}
			},

			destroy: function() {
				var I = this.getRuntime()
				, shim = I.getShim()
				, shimContainer = I.getShimContainer()
				;
				
				Events.removeAllEvents(shimContainer, this.uid);
				Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
				Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid);
				
				if (shimContainer) {
					shimContainer.innerHTML = '';
				}

				shim.removeInstance(this.uid);

				_uid = _mimes = _options = shimContainer = shim = null;
			}
		});
	}

	return (extensions.FileInput = FileInput);
});

// Included from: src/javascript/runtime/html4/file/FileReader.js

/**
 * FileReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html4/file/FileReader
@private
*/
define("moxie/runtime/html4/file/FileReader", [
	"moxie/runtime/html4/Runtime",
	"moxie/runtime/html5/file/FileReader"
], function(extensions, FileReader) {
	return (extensions.FileReader = FileReader);
});

// Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js

/**
 * XMLHttpRequest.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html4/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/html4/xhr/XMLHttpRequest", [
	"moxie/runtime/html4/Runtime",
	"moxie/core/utils/Basic",
	"moxie/core/utils/Dom",
	"moxie/core/utils/Url",
	"moxie/core/Exceptions",
	"moxie/core/utils/Events",
	"moxie/file/Blob",
	"moxie/xhr/FormData"
], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) {
	
	function XMLHttpRequest() {
		var _status, _response, _iframe;

		function cleanup(cb) {
			var target = this, uid, form, inputs, i, hasFile = false;

			if (!_iframe) {
				return;
			}

			uid = _iframe.id.replace(/_iframe$/, '');

			form = Dom.get(uid + '_form');
			if (form) {
				inputs = form.getElementsByTagName('input');
				i = inputs.length;

				while (i--) {
					switch (inputs[i].getAttribute('type')) {
						case 'hidden':
							inputs[i].parentNode.removeChild(inputs[i]);
							break;
						case 'file':
							hasFile = true; // flag the case for later
							break;
					}
				}
				inputs = [];

				if (!hasFile) { // we need to keep the form for sake of possible retries
					form.parentNode.removeChild(form);
				}
				form = null;
			}

			// without timeout, request is marked as canceled (in console)
			setTimeout(function() {
				Events.removeEvent(_iframe, 'load', target.uid);
				if (_iframe.parentNode) { // #382
					_iframe.parentNode.removeChild(_iframe);
				}

				// check if shim container has any other children, if - not, remove it as well
				var shimContainer = target.getRuntime().getShimContainer();
				if (!shimContainer.children.length) {
					shimContainer.parentNode.removeChild(shimContainer);
				}

				shimContainer = _iframe = null;
				cb();
			}, 1);
		}

		Basic.extend(this, {
			send: function(meta, data) {
				var target = this, I = target.getRuntime(), uid, form, input, blob;

				_status = _response = null;

				function createIframe() {
					var container = I.getShimContainer() || document.body
					, temp = document.createElement('div')
					;

					// IE 6 won't be able to set the name using setAttribute or iframe.name
					temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>';
					_iframe = temp.firstChild;
					container.appendChild(_iframe);

					/* _iframe.onreadystatechange = function() {
						console.info(_iframe.readyState);
					};*/

					Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8
						var el;

						try {
							el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document;

							// try to detect some standard error pages
							if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error
								_status = el.title.replace(/^(\d+).*$/, '$1');
							} else {
								_status = 200;
								// get result
								_response = Basic.trim(el.body.innerHTML);

								// we need to fire these at least once
								target.trigger({
									type: 'progress',
									loaded: _response.length,
									total: _response.length
								});

								if (blob) { // if we were uploading a file
									target.trigger({
										type: 'uploadprogress',
										loaded: blob.size || 1025,
										total: blob.size || 1025
									});
								}
							}
						} catch (ex) {
							if (Url.hasSameOrigin(meta.url)) {
								// if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm
								// which obviously results to cross domain error (wtf?)
								_status = 404;
							} else {
								cleanup.call(target, function() {
									target.trigger('error');
								});
								return;
							}
						}	
					
						cleanup.call(target, function() {
							target.trigger('load');
						});
					}, target.uid);
				} // end createIframe

				// prepare data to be sent and convert if required
				if (data instanceof FormData && data.hasBlob()) {
					blob = data.getBlob();
					uid = blob.uid;
					input = Dom.get(uid);
					form = Dom.get(uid + '_form');
					if (!form) {
						throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
					}
				} else {
					uid = Basic.guid('uid_');

					form = document.createElement('form');
					form.setAttribute('id', uid + '_form');
					form.setAttribute('method', meta.method);
					form.setAttribute('enctype', 'multipart/form-data');
					form.setAttribute('encoding', 'multipart/form-data');

					I.getShimContainer().appendChild(form);
				}

				// set upload target
				form.setAttribute('target', uid + '_iframe');

				if (data instanceof FormData) {
					data.each(function(value, name) {
						if (value instanceof Blob) {
							if (input) {
								input.setAttribute('name', name);
							}
						} else {
							var hidden = document.createElement('input');

							Basic.extend(hidden, {
								type : 'hidden',
								name : name,
								value : value
							});

							// make sure that input[type="file"], if it's there, comes last
							if (input) {
								form.insertBefore(hidden, input);
							} else {
								form.appendChild(hidden);
							}
						}
					});
				}

				// set destination url
				form.setAttribute("action", meta.url);

				createIframe();
				form.submit();
				target.trigger('loadstart');
			},

			getStatus: function() {
				return _status;
			},

			getResponse: function(responseType) {
				if ('json' === responseType) {
					// strip off <pre>..</pre> tags that might be enclosing the response
					if (Basic.typeOf(_response) === 'string' && !!window.JSON) {
						try {
							return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, ''));
						} catch (ex) {
							return null;
						}
					} 
				} else if ('document' === responseType) {

				}
				return _response;
			},

			abort: function() {
				var target = this;

				if (_iframe && _iframe.contentWindow) {
					if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome
						_iframe.contentWindow.stop();
					} else if (_iframe.contentWindow.document.execCommand) { // IE
						_iframe.contentWindow.document.execCommand('Stop');
					} else {
						_iframe.src = "about:blank";
					}
				}

				cleanup.call(this, function() {
					// target.dispatchEvent('readystatechange');
					target.dispatchEvent('abort');
				});
			}
		});
	}

	return (extensions.XMLHttpRequest = XMLHttpRequest);
});

// Included from: src/javascript/runtime/html4/image/Image.js

/**
 * Image.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html4/image/Image
@private
*/
define("moxie/runtime/html4/image/Image", [
	"moxie/runtime/html4/Runtime",
	"moxie/runtime/html5/image/Image"
], function(extensions, Image) {
	return (extensions.Image = Image);
});

expose(["moxie/core/utils/Basic","moxie/core/utils/Env","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/FileInput","moxie/core/utils/Encode","moxie/file/Blob","moxie/file/File","moxie/file/FileDrop","moxie/file/FileReader","moxie/core/utils/Url","moxie/runtime/RuntimeTarget","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/image/Image","moxie/core/utils/Events"]);
})(this);
/**
 * o.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/*global moxie:true */

/**
Globally exposed namespace with the most frequently used public classes and handy methods.

@class o
@static
@private
*/
(function(exports) {
	"use strict";

	var o = {}, inArray = exports.moxie.core.utils.Basic.inArray;

	// directly add some public classes
	// (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included)
	(function addAlias(ns) {
		var name, itemType;
		for (name in ns) {
			itemType = typeof(ns[name]);
			if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) {
				addAlias(ns[name]);
			} else if (itemType === 'function') {
				o[name] = ns[name];
			}
		}
	})(exports.moxie);

	// add some manually
	o.Env = exports.moxie.core.utils.Env;
	o.Mime = exports.moxie.core.utils.Mime;
	o.Exceptions = exports.moxie.core.Exceptions;

	// expose globally
	exports.mOxie = o;
	if (!exports.o) {
		exports.o = o;
	}
	return o;
})(this);

define("castle-url/libs/moxie/bin/js/moxie", function(){});

/* global define, alert, mOxie */
/*jshint quotmark: false */

define('castle-url/components/upload',[
  'jquery',
  'castle-url/libs/react/react.min',
  'castle-url/components/utils',
  'mockup-utils',
  'castle-url/components/image-editor',
  'castle-url/components/image-focal-point-selector',
  'underscore',
  'mockup-patterns-select2',
  'castle-url/components/content-browser',
  'castle-url/libs/moxie/bin/js/moxie'
], function($, R, cutils, utils, ImageEditor, FocalPointSelector, _,
            Select2, ContentBrowserComponent) {
  'use strict';
  var D = R.DOM;

  var FileListing = R.createClass({
    getInitialState: function(){
      return {
        // image props
        previewUrl: null,
        imageWidth: 0,
        imageHeight: 0,
        previewWidth: 0,
        previewHeight: 0,
        imageFocal: [0, 0],

        title: '',
        description: '',
        youtube_url: '',
        tags: '',
        state: 'review', // possible: (review, uploading, finished, error, crop)
        progress: 0,
        url: '',
        workflow_state: null,
        blob: null,  // customized file
        duplicate: false,
        readonlyFields: [],
        youtubeEnabled: $('body').attr('data-youtube-enabled') === 'true'
      };
    },
    componentDidMount: function(){
      if(!this.state.previewUrl && this.isImage()){
        this.loadImage();
      }
      this.setupTagsWidget();
    },

    componentDidUpdate: function(){
      this.setupTagsWidget();
    },

    setupTagsWidget: function(){
      var that = this;

      if(!that.refs.select2){
        return;
      }

      var options = {
        vocabularyUrl:
          $('body').attr('data-portal-url') +
          "/@@getVocabulary?name=plone.app.vocabularies.Keywords&field=subjects",
        orderable: true,
        allowNewItems: true,
        separator: ";",
        width: '100%'
      };
      var $el = $(that.refs.select2.getDOMNode());
      var select2 = new Select2($el, options);
      $el.off('change').on('change', function(e){
        that.setState({
          tags: e.target.value
        });
      });
    },

    loadImage: function(){
      var that = this;
      var file = that.state.blob || that.props.file;
      var width, height;
      var img = new mOxie.Image();
      img.onload = function() {
        width = img.width;
        height = img.height;
        img.downsize({width: 300});
      };
      img.load(file);
      img.onresize = function(){
        that.setState({
          previewUrl: img.getAsDataURL('image/png'),
          imageWidth: width,
          imageHeight: height,
          imageFocal: [width / 2, height / 2],
          previewWidth: img.width,
          previewHeight: img.height
        });
      };
    },

    valueChanged: function(attr, widget, e){
      if(widget == 'checkbox'){
        this.state[attr] = e.target.checked;
        if (attr === 'upload_to_youtube') {
          if (e.target.checked) {
            this.state.youtube_url = '';
            if (this.state.readonlyFields.indexOf('youtube_url') === -1) {
              this.state.readonlyFields.push('youtube_url')
            }
          } else {
            var idx = this.state.readonlyFields.indexOf('youtube_url');
            if (idx !== -1) {
              this.state.readonlyFields.splice(idx);
            }
          }
        }
      }else{
        this.state[attr] = e.target.value;
      }
      this.forceUpdate();
    },

    render: function(){
      var that = this;
      var file = this.props.file;
      var className = 'file-container';
      var fileName = D.h5({}, file.name + ' (' + this.bytesToSize() + ')');
      var preview = D.span({ className: 'glyphicon glyphicon-file' });
      var content;
      var previewCol = 'col-md-2';
      var fieldsCol = 'col-md-10';

      if(this.state.previewUrl){
        var selector = R.createElement(FocalPointSelector, {
          enabled: this.state.state === 'review',
          url: this.state.previewUrl,
          key: this.props.file.uid + '-image',
          width: this.state.previewWidth,
          fullWidth: this.state.imageWidth,
          height: this.state.previewHeight,
          fullHeight: this.state.imageHeight,
          focalPoint: this.state.imageFocal,
          onFocalSet: function(focal){
            that.setState({
              imageFocal: focal
            });
          }
        });
        preview = selector;
        previewCol = 'col-md-6';
        fieldsCol = 'col-md-6';
      }
      var additional = [];
      if(this.state.state === 'uploading'){
        additional.push(this.renderProgress());
      }else if(this.state.state === 'review'){
        additional.push(this.renderButtons());
        className += ' active';
        if (!this.props.parent.state.update) {
          content = D.div({}, [
            this.renderForm()
          ]);
        }else{
          content = D.div({}, []);
        }
      }else if(this.state.state === 'finished'){
        additional.push(this.renderFinished());
      }else if(this.state.state === 'error'){
        additional.push(D.p({ className: 'error-msg'}, 'There was an error uploading'));
      }else if(this.state.state === 'editimage'){
        content = R.createElement(ImageEditor, {
          file: this.props.file,
          onSave: function(blob){
            that.setState({
              state: 'review',
              blob: blob
            });
            that.loadImage();
          },
          onCancel: function(){
            that.setState({
              state: 'review'
            });
          }});
      }

      return D.li({ id: file.uid, className: className,
                    key: file.uid + '-li' }, [
         D.div({ className: 'row'}, [
          D.div({ className: 'col-xs-12' }, fileName)
        ]),
        D.div({ className: 'row'}, [
          D.div({ className: 'preview-container ' + previewCol }, preview),
          D.div({ className: fieldsCol }, content)
        ]),
        D.div({ className: 'bottom-container'}, additional)
      ]);
    },

    publishClicked: function(e){
      e.preventDefault();
      var that = this;
      utils.loading.show();
      $.ajax({
        url: this.state.base_url + '/@@publish-content',
        data: {
          _authenticator: utils.getAuthenticator()
        }
      }).done(function(){
        that.setState({
          workflow_state: 'published'
        });
      }).fail(function(){
        alert('There was an error publishing content');
      }).always(function(){
        utils.loading.hide();
      });
    },

    renderFinished: function(){
      // should render info on the content, link to it, etc
      var stateAction = [];
      if(this.state.workflow_state !== 'published'){
        stateAction = [
          'This file is currently not published. ',
          D.a({ className: 'content-publish',
                href: '#', onClick: this.publishClicked }, 'Publish immediately')
        ];
      }
      var label = 'Finished uploading ';
      if(this.state.duplicate){
        label = D.span({}, [
          D.b({}, 'Duplicate detected'),
          D.span({}, ': Using file already uploaded: ')
        ]);
      }
      return D.div({className: 'finished-container'}, [
        D.p({}, [
          label,
          D.a({ className: 'content-link',
                href: this.state.base_url + '/view',
                target: '_blank'}, this.state.title),
          '. '
        ].concat(stateAction)),
      ]);
    },

    renderProgress: function(){
      var that = this;
      return D.div({ className: 'castle-progress-container'}, [
        D.div({ className: 'castle-progress'},
          D.span({ className: 'castle-progress-inner', style: { width: that.state.progress + '%'}})),
        D.p({}, 'Uploading ' + that.state.progress + '%')
      ]);
    },

    createField: function(field){
      var name = field['name'];
      var readonly = undefined;
      if (this.state.readonlyFields.indexOf(name) !== -1) {
        readonly = true;
      }

      var input;
      if(field['widget'] == 'checkbox'){
        input = D.input({
          id: id, type: 'checkbox', checked: this.state[name], readOnly: readonly,
          onChange: this.valueChanged.bind(this, name, 'checkbox') })
      }else{
        var nodeType = D.input;
        if(field['widget'] === 'textarea'){
          nodeType = D.textarea;
        }
        input = nodeType({
          className: 'form-control', value: this.state[name], id: id, readOnly: readonly,
          onChange: this.valueChanged.bind(this, name, 'text')});
      }

      var labelClass = 'col-sm-4 control-label';
      if(field['required']){
        labelClass += ' required';
      }

      var id = 'castle-upload-field-' + name;
      return D.div({ className: 'form-group upload-field-' + name }, [
        D.label({ className: labelClass, for_: id}, field['label']),
        D.div({className: 'col-sm-8' }, input)
      ]);
    },

    createTagsField: function(field){
      var labelClass = 'col-sm-4 control-label';
      if(field['required']){
        labelClass += ' required';
      }
      return D.div({ className: "field" }, [
        D.label({className: labelClass}, field['label'] || 'Tags'),
        D.div({ className: 'col-sm-8' },
          D.input({ className: "pat-select2", type: "text", ref: 'select2', value: this.state.tags}))
      ]);
    },

    renderForm: function(){
      var fields = [];
      var self = this;
      this.props.uploadFields.forEach(function(field){
        if(field['for-file-types'] && field['for-file-types'] !== '*'){
          var fileTypes = field['for-file-types'].split(',');
          if(fileTypes.indexOf(self.getType()) === -1){
            return
          }
        }
        if (field['name'] === 'upload_to_youtube' && !self.state.youtubeEnabled) {
          return;
        }

        if(field.widget === 'tags'){
          fields.push(self.createTagsField(field));
        }else{
          fields.push(self.createField(field));
        }
      });
      return D.form({ className: 'form-horizontal', key: this.props.file.uid + '-form' }, fields);
    },

    editImageClicked: function(e){
      e.preventDefault();
      this.setState({
        'state': 'editimage'
      });
    },

    renderButtons: function(){
      var that = this;
      var buttons = [];

      var canApprove = true;
      if (!that.props.parent.state.update) {
        _.each(this.props.requiredFields, function(fieldName){
          if(!that.state[fieldName]){
            canApprove = false;
          }
        });
      }

      if(this.isImage()){
        buttons.push(
          D.button({ className: 'btn btn-default castle-btn-edit', onClick: that.editImageClicked }, 'Edit Image'));
      }
      buttons.push(
        D.button({ className: 'plone-btn plone-btn-default castle-btn-remove', onClick: that.removeClicked },
          D.span({ className: 'icon-remove' }))
      );
      buttons.push(
        D.button({ className: 'plone-btn plone-btn-default castle-btn-upload',
                   onClick: that.approveClicked, disabled: !canApprove },
          D.span({ className: 'icon-ok' }))
      );

      return D.div({ className: 'row' }, D.div({ className: 'col-md-4 col-md-offset-8'}, buttons));
    },

    uploadChunk: function(chunk, id){
      var that = this;
      var chunkSize = 1024 * 1024 * 2;  // 2mb
      var start = (chunk - 1) * chunkSize;
      var end = start + chunkSize;
      var file = that.state.blob || that.props.file;
      var blob = file.slice(start, end);
      if(blob.size === 0){
        utils.loading.hide();
        return;
      }
      utils.loading.show();
      var xhr = new mOxie.XMLHttpRequest();
      var fd = new mOxie.FormData();
      xhr.open('post', $('body').attr('data-portal-url') + '/@@content-creator');
      xhr.responseType = 'json';

      fd.append('chunk', chunk);
      fd.append('action', 'chunk-upload');
      fd.append('file', blob);
      fd.append('name', that.props.file.name);

      if(that.props.parent.props.location){
        fd.append('location', that.props.parent.props.location);
      }
      if(that.state.imageFocal){
        fd.append('focalX', that.state.imageFocal[0]);
        fd.append('focalY', that.state.imageFocal[1]);
      }

      that.props.uploadFields.forEach(function(field){
        if(that.state[field['name']]){
          fd.append(field['name'], that.state[field['name']]);
        }
      });

      fd.append('totalSize', file.size);
      fd.append('chunkSize', chunkSize);
      fd.append('_authenticator', utils.getAuthenticator());

      if(id !== undefined){
        fd.append('id', id);
      }

      if (that.props.parent.state.update) {
        fd.append('content',that.props.parent.state.content);
        fd.append('field', that.props.parent.state.field);
      }

      var sent = Math.round(((start - 1) / file.size) * 100);
      that.setState({
        state: 'uploading',
        progress: sent
      });

      xhr.onload = function() {
        if (xhr.response) {
          if(xhr.response.success){
            if(end < file.size){
              that.uploadChunk(chunk + 1, xhr.response.id);
            }else{
              utils.loading.hide();
              var data = $.extend({}, true, {
                state: 'finished',
                progress: 100
              }, xhr.response);
              that.setState(data);
              that.props.parent.removeUpload(that.props.file.uid);
            }
            return;
          }
        }
        that.setState({
          state: 'error'
        });
        that.props.parent.removeUpload(that.props.file.uid);
        utils.loading.hide();
      };
      xhr.bind('error runtimeerror', function() {
        utils.loading.hide();
        that.setState({
          state: 'error'
        });
        that.props.parent.removeUpload(that.props.file.uid);
        utils.loading.hide();
      });

      xhr.send(fd, {
        runtime_order: 'html5,flash,html4',
        required_caps: {
          send_multipart: true
        }
      });
    },

    approveClicked: function(e){
      e.preventDefault();
      var that = this;
      that.setState({
        state: 'uploading',
        progress: 0
      });
      that.props.parent.addUpload(that.props.file.uid);
    },

    removeClicked: function(e){
      e.preventDefault();
      this.props.parent.removeFile(this.props.idx);
    },

    isImage: function(){
      return this.props.file.type.substring(0, 5) == 'image';
    },

    getType: function(){
      var type = this.props.file.type;
      return type.substring(0, type.indexOf('/'));
    },

    bytesToSize: function() {
      var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      var file = this.state.blob || this.props.file;
      if (file.size === 0) return '0 Byte';
      var i = parseInt(Math.floor(Math.log(file.size) / Math.log(1024)));
      return Math.round(file.size / Math.pow(1024, i), 2) + ' ' + sizes[i];
    },

    getDefaultProps: function(){
      return {
        _id: null,
        parent: null,
        file: null,
        idx: null
      };
    }

  });


  var UploadComponent = {
    getInitialState: function(){
      return {
        files: [],
        dragging: false,
        uploadQueue: [],
        zIndex: 3000,
        shown: false,
        preventClose: false,
        autoUpload: false
      };
    },

    addUpload: function(uid){
      this.state.uploadQueue.push(uid);
      if(this.state.uploadQueue.length === 1){
        this.refs[uid].uploadChunk(1);
      }
      this.state.preventClose = true;
    },

    removeUpload: function(uid){
      // means we can start next one if there is one
      var queue = this.state.uploadQueue;
      var index = queue.indexOf(uid);
      var item = queue[index];
      this.props.onUploadFinished(item, this);
      queue.splice(index, 1);
      this.state.uploadQueue = queue;
      if(queue.length > 0){
        var ref = this.refs[queue[0]];
        if(ref){
          ref.uploadChunk(1);
        }else{
          this.removeUpload(queue[0]);
        }
      }else{
        this.state.preventClose = false;
      }
    },

    afterFilesAdded: function(files){
      var that = this;
      if(that.state.autoUpload){
        files.forEach(function(file){
          that.addUpload(file.uid);
        });
      }
    },

    componentDidMount: function(){
      var that = this;
      if (that.props.update) {
        that.setState({
          update: that.props.update,
          content: that.props.content,
          field: that.props.field,
          autoUpload: that.props.autoUpload
        });
      }else{
        that.setState({
          update: false
        });
      }

      var portalUrl = $('body').attr('data-portal-url');
      mOxie.Env.swf_url = portalUrl + '/++plone++castle/libs/moxie/bin/flash/Moxie.min.swf';
      mOxie.Env.xap_url = portalUrl + '/++plone++castle/libs/moxie/bin/silverlight/Moxie.min.xap';

      var fileInput = new mOxie.FileInput({
        browse_button: that.refs.upload_btn.getDOMNode(),
        runtime_order: 'html5,flash,html4',
        multiple: true,
        // accept: accept
      });

      fileInput.onchange = function(e) {
        that.setState({
          files: that.state.files.concat(e.target.files)
        }, function(){
          that.afterFilesAdded(e.target.files);
        });
      };

      fileInput.init(); // initialize

      var dropEl = this.refs.droparea.getDOMNode();
      var fileDrop = new mOxie.FileDrop({
        drop_zone: dropEl,
        // accept: accept
      });

      fileDrop.ondrop = function() {
        var files = this.files;
        that.setState({
          files: that.state.files.concat(files)
        }, function(){
          that.afterFilesAdded(files);
        });
        dropEl.style.background = '';
      };
      fileDrop.ondragenter = function(){
        that.setState({
          dragging: true
        });
      };
      fileDrop.ondragleave = function(){
        that.setState({
          dragging: false
        });
      };

      fileDrop.init();
    },

    renderAutoApprove: function(){
      var that = this;
      if(this.getRequiredFields().length > 0){
        return '';
      }
      return D.label({ className: 'checkbox pull-right'}, [
        D.input({ type: 'checkbox', checked: this.state.autoUpload,
                  onClick: function(e){
                    that.setState({
                      autoUpload: e.target.checked
                    });
                  }}),
        'Auto upload'
      ]);
    },

    renderContent: function(){
      var that = this;
      var className = 'castle-upload-container';
      if(that.state.dragging){
        className += ' dragging';
      }
      var dropTxt = '';
      if(that.hasDnd()){
        className += ' dnd-enabled';
        dropTxt = D.div({ className: 'droptext-container'}, [
          D.p({ className: 'upload-text'}, 'Drop files here'),
          D.p({ className: 'upload-text'}, 'or')
        ]);
      }
      if(that.state.files.length > 0){
        className += ' has-files';
      }
      var children = [
        D.div({ ref: 'droparea', className: 'droparea' }, [
          dropTxt,
          D.button({
            ref: 'upload_btn',
            className: 'btn btn-default castle-btn-select-files' }, 'Select files'),
          D.p({className: 'upload-text drop-msg'},
              'Files will be uploaded to central repositories unless you choose folder'),
        ]),
        that.renderAutoApprove(),
        that.renderFileList()
      ]
      var tabs = [
        this.props.parent.renderTabItem('upload')
      ]
      if (!that.state.update) {
        children.splice(1, 0, that.renderUploadLocation());
        tabs.splice(0, 0, this.props.parent.renderTabItem('add'));
      }
      var content = D.div({ className: className }, children);

      return D.div({ className: 'pat-autotoc autotabs fullsize'}, [
        D.nav({ className: 'autotoc-nav'}, tabs),
        content
      ]);
    },

    browsing: true,
    selectFolderClicked: function(){
      var that = this;

      var query = new utils.QueryHelper({
        vocabularyUrl: $('body').attr('data-portal-url') + '/@@getVocabulary?name=plone.app.vocabularies.Catalog',
        batchSize: 18,
        pattern: this,
        sort_on: 'getObjPositionInParent',
        sort_order: 'ascending',
        attributes: ['UID', 'Title', 'portal_type', 'path', 'review_state', 'is_folderish'],
        baseCriteria: [{
          i: 'portal_type',
          o: 'plone.app.querystring.operation.list.contains',
          v: ['Folder']
        }]
      });
      query.currentPath = that.props.location;

      var ContentBrowserBinder = cutils.BindComponentFactoryRoot(
          ContentBrowserComponent, function(){
            return {
              onSelectItem: function(item){
                that.props.location = item.path;
                that.forceUpdate();
              },
              query: query
            };
          }, 'content-browser-react-container');
      ContentBrowserBinder({});
    },

    renderUploadLocation: function(){
      var that = this;
      if(that.props.location){
        return D.div({ className: 'pick-location'}, [
          D.div({ className: 'pick-location-folder'}, D.a({
            className: 'contenttype-folder', href: '#',
            onClick: function(e){
              e.preventDefault();
              that.selectFolderClicked();
            }
          }, ' ')),
          D.div({ className: 'pick-location-location'}, [
            'Upload to: ',
            that.props.location
          ]),
          D.div({ className: 'pick-location-remove'}, D.button({
            className: 'remove',
            onClick: function(e){
              e.preventDefault();
              that.props.location = null;
              that.forceUpdate();
            }
          }, 'x'))
        ]);
      }else{
        return D.div({ className: 'no-location'}, [
          D.a({ className: 'btn btn-default castle-btn-select-files drop-link', href: '#', onClick: function(e){
            e.preventDefault();
            var portalUrl = $('body').attr('data-portal-url');
            var folderUrl = $('body').attr('data-folder-url');
            that.props.location = folderUrl.replace(portalUrl, '') || '/';
            that.forceUpdate();
            that.selectFolderClicked();
          }}, 'Choose Folder')
        ]);
      }
    },

    renderHeader: function(){
      return [
        D.button({ type: 'button', className: 'close', 'data-dismiss': 'modal'}, [
          D.div({ className: 'close-button' }),
          D.span({ 'aria-hidden': 'true' }, '\u00d7')
        ]),
        D.h4({}, 'Upload')
      ];
    },

    renderFooter: function(){
      var buttons = [
        D.button({ type: 'button', className: 'plone-btn plone-btn-primary',
                   'data-dismiss': 'modal'}, 'Done')
      ];
      return D.div({ className: 'btn-container'}, buttons);
    },

    render: function(){
      return D.div({ className: 'modal-content' }, [
        D.div({ className: 'modal-header' }, this.renderHeader()),
        D.div({ className: 'modal-body'}, this.renderContent()),
        D.div({ className: 'modal-footer'}, this.renderFooter())
      ]);
    },

    removeFile: function(idx){
      this.state.files.splice(idx, 1);
      this.setState({
        files: this.state.files
      });
    },

    renderFileList: function(){
      var that = this;
      if(that.state.files.length === 0){
        return '';
      }
      return D.div({ className: 'file-list' }, [
        D.h3({}, 'Files'),
        D.ul({}, that.state.files.map(function(file, idx){
          return R.createElement(FileListing, {
            file: file, ref: file.uid, key: file.uid,
            idx: idx, parent: that, uploadFields: that.getUploadFields()});
        }))
      ]);
    },

    hasDnd: function(){
      return 'draggable' in document.createElement('span') && typeof(window.FileReader) != 'undefined';
    },

    getUploadFields: function(){
      var uploadFields = $('body').attr('data-file-upload-fields');
      if(uploadFields){
        uploadFields = $.parseJSON(uploadFields);
      }else{
        uploadFields = [];
      }
      return uploadFields;
    },

    getRequiredFields: function(){
      var required = [];
      this.getUploadFields().forEach(function(field){
        if(field['required']){
          required.push(field['name'])
        }
      });
      return required;
    },

    getDefaultProps: function(){
      return {
        id: 'upload-content-modal',
        title: 'Upload',
        location: null,
        onUploadFinished: function(){}
      };
    },

    getModalEl: function(){
      return this.props.parent.getModalEl();
    }
  };

  return {
    component: R.createClass(UploadComponent),
    klass: UploadComponent
  };
});

/* global define */


define('castle-url/components/add-content-modal',[
  'jquery',
  'castle-url/libs/react/react.min',
  'castle-url/components/modal',
  'castle-url/components/upload',
  'castle-url/components/utils',
  'mockup-utils',
  'castle-url/components/content-browser',
  'underscore'
], function($, R, Modal, Upload, cutils, utils, ContentBrowserComponent, _) {
  'use strict';

  var D = R.DOM;

  var notContentIds = [
    'plone-contentmenu-settings',
    'plone-contentmenu-more'];

  var _checkTimeout = 0;

  var AddContentTab = R.createClass({
    getInitialState: function(){
      return {
        selectedType: null,
        valid: false,
        basePath: '/',
        id: '',
        title: '',
        status: null,
        stateInfo: null,
        transitionTo: null,
        createdContent: [],
        zIndex: 3000,
        shown: false,
        preventClose: false
      };
    },

    contentTypeClicked: function(type, e){
      if(notContentIds.indexOf(type.id) !== -1){
        return;
      }
      var that = this;
      e.preventDefault();
      that.props.title = 'Add ' + type.title;
      that.setState({
        selectedType: type,
        basePath: type.folderPath || '/'
      }, function(){
        // auto focus title node after load
        $(that.refs.contentTitle.getDOMNode()).focus();
        that.props.parent.forceUpdate();
      });
    },

    createAndEditClicked: function(e){
      var that = this;
      that.createClicked(e, function(data){
        if(data.valid){
          window.location = data.edit_url;
        }
      });
    },

    createClicked: function(e, callback){
      e.preventDefault();
      var that = this;
      utils.loading.show();
      $.ajax({
        method: 'POST',
        url: $('body').attr('data-portal-url') + '/@@content-creator',
        data: $.extend({}, true, that.state, {
          action: 'create',
          _authenticator: utils.getAuthenticator()
        }),
        dataType: 'json'
      }).done(function(data){
        that.setState(data);
        if(callback && typeof(callback) === "function"){
          callback(data, that);
        }else{
          that.props.afterCreationCallback(data, that);
        }
      }).fail(function(){
        that.setState({
          status: 'Error validating with server. This should not happen. Contact support',
          valid: false
        });
      }).always(function(){
        utils.loading.hide();
      });
    },

    locationChanged: function(e){
      this.setState({
        basePath: e.target.value || '/',
        valid: false
      });
      this.check();
    },

    titleChanged: function(e){
      this.setState({
        title: e.target.value,
        id: e.target.value.replace(/ /g, '-').replace(/[^\w\s-]/gi, '').toLowerCase(),
        valid: false
      });
      this.check();
    },

    idChanged: function(e){
      this.setState({
        id: e.target.value,
        valid: false
      });
      this.check();
    },

    getFullPath: function(){
      var path = this.state.basePath;
      if(path[path.length - 1] !== '/'){
        path += '/';
      }
      return path + this.state.id;
    },

    check: function(){
      var that = this;

      clearTimeout(_checkTimeout);
      _checkTimeout = setTimeout(function(){
        if(!that.state.id || !that.state.title){
          return;
        }
        utils.loading.show();
        $.ajax({
          url: $('body').attr('data-portal-url') + '/@@content-creator',
          data: $.extend({}, true, that.state, {
            action: 'check'
          }),
          dataType: 'json'
        }).done(function(data){
          that.setState(data);
        }).fail(function(){
          that.setState({
            status: 'Error validating with server. This should not happen. Contact support',
            valid: false
          });
        }).always(function(){
          utils.loading.hide();
        });
      }, 500);
    },

    browsing: true,
    selectFolderClicked: function(e){
      e.preventDefault();
      var that = this;

      var query = new utils.QueryHelper({
        vocabularyUrl: $('body').attr('data-portal-url') + '/@@getVocabulary?name=plone.app.vocabularies.Catalog',
        batchSize: 18,
        pattern: this,
        sort_on: 'getObjPositionInParent',
        sort_order: 'ascending',
        attributes: ['UID', 'Title', 'portal_type', 'path', 'review_state', 'is_folderish'],
        baseCriteria: [{
          i: 'portal_type',
          o: 'plone.app.querystring.operation.list.contains',
          v: ['Folder']
        }]
      });
      query.currentPath = '/';

      var ContentBrowserBinder = cutils.BindComponentFactoryRoot(
          ContentBrowserComponent, function(){
            return {
              onSelectItem: function(item){
                that.setState({
                  basePath: item.path,
                  valid: false
                });
                that.check();
              },
              query: query
            };
          }, 'content-browser-react-container');
      ContentBrowserBinder({});
    },

    renderSelectionContent: function(){
      var that = this;
      var constrain = '';
      if(this.props.canConstrainTypes){
        constrain = D.div({ className: 'castle-constrain-types'}, [
          D.a({ href: this.props.constrainUrl,
                className: 'plone-btn plone-btn-default '}, 'Constrain allowed types')
        ]);
      }
      return D.div({ className: 'wrapper'}, [
        D.ul({ className: 'select-type'}, this.props.types.map(function(type){
          return D.li({ className: 'contenttype-' + type.safeId + '-container'},
            D.a({ className: 'contenttype-' + type.safeId, onClick: that.contentTypeClicked.bind(that, type)}, type.title)
          );
        })),
        constrain
      ]);
    },

    renderAddContent: function(){
      var that = this;

      var status = '';
      if(this.state.status){
        status = D.div({ className: 'portalMessage warning'}, [
          D.strong({}, 'Warning'),
          this.state.status
        ]);
      }
      var states = [D.option({}, 'Private')];
      if(this.state.stateInfo !== null){
        states = [D.option({}, this.state.stateInfo.initial.title)];
        _.each(_.keys(that.state.stateInfo.possible_states), function(state_id){
          var state = that.state.stateInfo.possible_states[state_id];
          states.push(D.option({ value: state.transition }, state.title));
        });
      }

      return D.div({ className: 'wrapper' }, [
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon', for_: 'contentTitle'}, 'Title'),
          D.input({ type: 'text', className: 'form-control', id: 'contentTitle',
                  placeholder: 'Title of content', value: this.state.title, ref: 'contentTitle',
                  onChange: this.titleChanged })
        ]),
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon', for_: 'contentId'}, 'ID'),
          D.input({ type: 'text', className: 'form-control', id: 'contentId',
                  placeholder: 'ID of the content', value: this.state.id,
                  onChange: this.idChanged })
        ]),
        D.div({ className: 'input-group'},[
          D.label({ className: 'input-group-addon'}, [
            'Folder ',
            D.a({ href: '#', className: 'contenttype-folder',
                  onClick: this.selectFolderClicked })
          ]),
          D.input({ type: 'text', className: 'form-control', id: 'contentLocation',
                  placeholder: 'Where on the site?', value: this.state.basePath,
                  onChange: this.locationChanged })
        ]),
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon' }, 'Url'),
          D.input({ type: 'text', className: 'form-control', value: this.getFullPath(), disabled: true })
        ]),
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon' }, 'State'),
          D.select({ className: 'form-control', onChange: that.stateSelected,
                     value: that.state.transitionTo, id: 'contentState',}, states)
        ]),
        status
      ]);
    },

    addAnotherClicked: function(e){
      this.setState({
        addAnother: e.target.value === 'add'
      });
    },

    stateSelected: function(e){
      this.setState({
        transitionTo: e.target.value
      });
    },

    renderHeader: function(){
      var title = 'Add';
      if(this.state.selectedType){
        title += ' ' + this.state.selectedType.title;
      }
      return [
        D.button({ type: 'button', className: 'close', 'data-dismiss': 'modal'}, [
          D.div({ className: 'close-button' }),
          D.span({ 'aria-hidden': 'true' }, '\u00d7')
        ]),
        D.h4({}, title)
      ];
    },

    render: function(){
      return D.div({ className: 'modal-content' }, [
        D.div({ className: 'modal-header' }, this.renderHeader()),
        D.div({ className: 'modal-body'}, this.renderContent()),
        D.div({ className: 'modal-footer'}, this.renderFooter())
      ]);
    },

    renderContent: function(){
      var that = this;
      var content;
      if(that.state.selectedType === null){
        content = that.renderSelectionContent();
      }else{
        content = that.renderAddContent();
      }

      return D.div({ className: 'pat-autotoc autotabs fullsize'}, [
        D.nav({ className: 'autotoc-nav'}, [
          this.props.parent.renderTabItem('add'),
          this.props.parent.renderTabItem('upload'),
          this.props.parent.renderTabItem('templates')
        ]),
        content
      ]);
    },

    renderFooter: function(){
      var buttons = [];
      if(this.state.selectedType !== null){
        buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-default', onClick: this.goBack }, 'Cancel'));
        var disabled = false;
        if(!this.state.valid){
          disabled = true;
        }
        buttons.push(D.button({ type: 'button', className: 'plone-btn btn-default',
                                onClick: this.createClicked, disabled: disabled }, 'Create'));
        if(this.props.allowEditAfterCreation){
          buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-primary',
                                onClick: this.createAndEditClicked, disabled: disabled }, 'Create and Edit'));
        }
      }else{
        buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-primary', 'data-dismiss': 'modal' }, 'Done'));
      }
      var contentList = '';
      if(this.state.createdContent.length > 0){
        contentList = D.div({ className: 'content-list'}, [
          D.h4({}, 'Created content'),
          D.ul({}, this.state.createdContent.map(function(content){
            return D.li({}, [
              content.title + ' | ',
              D.a({ href: content.url, target: '_blank' }, 'View'),
              ' | ',
              D.a({ href: content.edit_url, target: '_blank' }, 'Edit')
            ]);
          })),
          D.hr({})
        ]);
      }
      return D.div({}, [
        contentList,
        D.div({className: 'btn-container'}, buttons)

      ]);
    },

    goBack: function(e){
      e.preventDefault();
      this.setState({
        valid: false,
        id: '',
        title: '',
        selectedType: null,
        status: null,
        stateInfo: null,
        transitionTo: null
      });
    },

    getDefaultProps: function(){
      return {
        types: [],
        allowEditAfterCreation: true,
        afterCreationCallback: function(data, cmp){
          cmp.state.createdContent.push(data);
          cmp.setState({
            valid: false,
            id: '',
            title: '',
            selectedType: null,
            status: null,
            stateInfo: null,
            transitionTo: null
          });
        }
      };
    },

    getModalEl: function(){
      return this.props.parent.getModalEl();
    }

  });

  var AddTemplateTab = R.createClass({
    getInitialState: function(){
      return {
        selectedType: null,
        valid: false,
        basePath: '/',
        id: '',
        title: '',
        status: null,
        stateInfo: null,
        transitionTo: null,
        createdContent: [],
        zIndex: 3000,
        shown: false,
        preventClose: false
      };
    },

    contentTypeClicked: function(type, e){
      if(notContentIds.indexOf(type.id) !== -1){
        return;
      }
      var that = this;
      e.preventDefault();
      that.props.title = 'Add ' + type.title;
      that.setState({
        selectedType: type,
        basePath: type.folderPath || '/'
      }, function(){
        // auto focus title node after load
        $(that.refs.contentTitle.getDOMNode()).focus();
        that.props.parent.forceUpdate();
      });
    },

    createAndEditClicked: function(e){
      var that = this;
      that.createClicked(e, function(data){
        if(data.valid){
          window.location = data.edit_url;
        }
      });
    },

    createClicked: function(e, callback){
      e.preventDefault();
      var that = this;
      utils.loading.show();
      $.ajax({
        method: 'POST',
        url: $('body').attr('data-portal-url') + '/@@content-creator',
        data: $.extend({}, true, that.state, {
          action: 'create-from-template',
          _authenticator: utils.getAuthenticator()
        }),
        dataType: 'json'
      }).done(function(data){
        that.setState(data);
        if(callback && typeof(callback) === "function"){
          callback(data, that);
        }else{
          that.props.afterCreationCallback(data, that);
        }
      }).fail(function(){
        that.setState({
          status: 'Error validating with server. This should not happen. Contact support',
          valid: false
        });
      }).always(function(){
        utils.loading.hide();
      });
    },

    locationChanged: function(e){
      this.setState({
        basePath: e.target.value || '/',
        valid: false
      });
      this.check();
    },

    titleChanged: function(e){
      this.setState({
        title: e.target.value,
        id: e.target.value.replace(/ /g, '-').replace(/[^\w\s-]/gi, '').toLowerCase(),
        valid: false
      });
      this.check();
    },

    idChanged: function(e){
      this.setState({
        id: e.target.value,
        valid: false
      });
      this.check();
    },

    getFullPath: function(){
      var path = this.state.basePath;
      if(path[path.length - 1] !== '/'){
        path += '/';
      }
      return path + this.state.id;
    },

    check: function(){
      var that = this;

      clearTimeout(_checkTimeout);
      _checkTimeout = setTimeout(function(){
        if(!that.state.id || !that.state.title){
          return;
        }
        utils.loading.show();
        $.ajax({
          url: $('body').attr('data-portal-url') + '/@@content-creator',
          data: $.extend({}, true, that.state, {
            action: 'check'
          }),
          dataType: 'json'
        }).done(function(data){
          that.setState(data);
        }).fail(function(){
          that.setState({
            status: 'Error validating with server. This should not happen. Contact support',
            valid: false
          });
        }).always(function(){
          utils.loading.hide();
        });
      }, 500);
    },

    browsing: true,
    selectFolderClicked: function(e){
      e.preventDefault();
      var that = this;

      var query = new utils.QueryHelper({
        vocabularyUrl: $('body').attr('data-portal-url') + '/@@getVocabulary?name=plone.app.vocabularies.Catalog',
        batchSize: 18,
        pattern: this,
        sort_on: 'getObjPositionInParent',
        sort_order: 'ascending',
        attributes: ['UID', 'Title', 'portal_type', 'path', 'review_state', 'is_folderish'],
        baseCriteria: [{
          i: 'portal_type',
          o: 'plone.app.querystring.operation.list.contains',
          v: ['Folder']
        }]
      });
      query.currentPath = '/';

      var ContentBrowserBinder = cutils.BindComponentFactoryRoot(
          ContentBrowserComponent, function(){
            return {
              onSelectItem: function(item){
                that.setState({
                  basePath: item.path,
                  valid: false
                });
                that.check();
              },
              query: query
            };
          }, 'content-browser-react-container');
      ContentBrowserBinder({});
    },

    renderSelectionContent: function(){
      var that = this;
      var constrain = '';
      if(this.props.canConstrainTypes){
        constrain = D.div({ className: 'castle-constrain-types'}, [
          D.a({ href: this.props.constrainUrl,
                className: 'plone-btn plone-btn-default '}, 'Constrain allowed types')
        ]);
      }
      return D.div({ className: 'wrapper'}, [
        D.ul({ className: 'select-type'}, this.props.templates.map(function(type){
          return D.li({ className: 'contenttype-' + type.safeId + '-container'},
            D.a({ className: 'contenttype-' + type.safeId, onClick: that.contentTypeClicked.bind(that, type)}, type.title)
          );
        })),
        constrain
      ]);
    },

    renderTemplateContent: function(){
      var that = this;

      var status = '';
      if(this.state.status){
        status = D.div({ className: 'portalMessage warning'}, [
          D.strong({}, 'Warning'),
          this.state.status
        ]);
      }
      var states = [D.option({}, 'Private')];
      if(this.state.stateInfo !== null){
        states = [D.option({}, this.state.stateInfo.initial.title)];
        _.each(_.keys(that.state.stateInfo.possible_states), function(state_id){
          var state = that.state.stateInfo.possible_states[state_id];
          states.push(D.option({ value: state.transition }, state.title));
        });
      }

      return D.div({ className: 'wrapper' }, [
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon', for_: 'contentTitle'}, 'Title'),
          D.input({ type: 'text', className: 'form-control', id: 'contentTitle',
                  placeholder: 'Title of content', value: this.state.title, ref: 'contentTitle',
                  onChange: this.titleChanged })
        ]),
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon', for_: 'contentId'}, 'ID'),
          D.input({ type: 'text', className: 'form-control', id: 'contentId',
                  placeholder: 'ID of the content', value: this.state.id,
                  onChange: this.idChanged })
        ]),
        D.div({ className: 'input-group'},[
          D.label({ className: 'input-group-addon'}, [
            'Folder ',
            D.a({ href: '#', className: 'contenttype-folder',
                  onClick: this.selectFolderClicked })
          ]),
          D.input({ type: 'text', className: 'form-control', id: 'contentLocation',
                  placeholder: 'Where on the site?', value: this.state.basePath,
                  onChange: this.locationChanged })
        ]),
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon' }, 'Url'),
          D.input({ type: 'text', className: 'form-control', value: this.getFullPath(), disabled: true })
        ]),
        D.div({ className: 'input-group'}, [
          D.label({ className: 'input-group-addon' }, 'State'),
          D.select({ className: 'form-control', onChange: that.stateSelected,
                     value: that.state.transitionTo, id: 'contentState',}, states)
        ]),
        status
      ]);
    },

    addAnotherClicked: function(e){
      this.setState({
        addAnother: e.target.value === 'add'
      });
    },

    stateSelected: function(e){
      this.setState({
        transitionTo: e.target.value
      });
    },

    renderHeader: function(){
      var title = 'Add';
      if(this.state.selectedType){
        title += ' ' + this.state.selectedType.title;
      }
      return [
        D.button({ type: 'button', className: 'close', 'data-dismiss': 'modal'}, [
          D.div({ className: 'close-button' }),
          D.span({ 'aria-hidden': 'true' }, '\u00d7')
        ]),
        D.h4({}, title)
      ];
    },

    render: function(){
      return D.div({ className: 'modal-content' }, [
        D.div({ className: 'modal-header' }, this.renderHeader()),
        D.div({ className: 'modal-body'}, this.renderContent()),
        D.div({ className: 'modal-footer'}, this.renderFooter())
      ]);
    },

    renderContent: function(){
      var that = this;
      var content;
      if(that.state.selectedType === null){
        content = that.renderSelectionContent();
      }else{
        content = that.renderTemplateContent();
      }

      return D.div({ className: 'pat-autotoc autotabs fullsize'}, [
        D.nav({ className: 'autotoc-nav'}, [
          this.props.parent.renderTabItem('add'),
          this.props.parent.renderTabItem('upload'),
          this.props.parent.renderTabItem('templates')
        ]),
        content
      ]);
    },

    renderFooter: function(){
      var buttons = [];
      if(this.state.selectedType !== null){
        buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-default', onClick: this.goBack }, 'Cancel'));
        var disabled = false;
        if(!this.state.valid){
          disabled = true;
        }
        buttons.push(D.button({ type: 'button', className: 'plone-btn btn-default',
                                onClick: this.createClicked, disabled: disabled }, 'Create'));
        if(this.props.allowEditAfterCreation){
          buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-primary',
                                onClick: this.createAndEditClicked, disabled: disabled }, 'Create and Edit'));
        }
      }else{
        buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-primary', 'data-dismiss': 'modal' }, 'Done'));
      }
      var contentList = '';
      if(this.state.createdContent.length > 0){
        contentList = D.div({ className: 'content-list'}, [
          D.h4({}, 'Created content'),
          D.ul({}, this.state.createdContent.map(function(content){
            return D.li({}, [
              content.title + ' | ',
              D.a({ href: content.url, target: '_blank' }, 'View'),
              ' | ',
              D.a({ href: content.edit_url, target: '_blank' }, 'Edit')
            ]);
          })),
          D.hr({})
        ]);
      }
      return D.div({}, [
        contentList,
        D.div({className: 'btn-container'}, buttons)

      ]);
    },

    goBack: function(e){
      e.preventDefault();
      this.setState({
        valid: false,
        id: '',
        title: '',
        selectedType: null,
        status: null,
        stateInfo: null,
        transitionTo: null
      });
    },

    getDefaultProps: function(){
      return {
        templates: [],
        allowEditAfterCreation: true,
        afterCreationCallback: function(data, cmp){
          cmp.state.createdContent.push(data);
          cmp.setState({
            valid: false,
            id: '',
            title: '',
            selectedType: null,
            status: null,
            stateInfo: null,
            transitionTo: null
          });
        }
      };
    },

    getModalEl: function(){
      return this.props.parent.getModalEl();
    }

  });

  var AddContentModal = cutils.Class([Modal], {
    /* tabbed */
    tabs: {
      add: {
        Component: AddContentTab,
        id: 'add-content-modal',
        title: 'Add content',
        tabLabel: 'Add'
      },
      upload: {
        Component: Upload.component,
        id: 'upload-content-modal',
        title: 'Upload',
        tabLabel: 'Upload'
      },
      templates: {
        Component: AddTemplateTab,
        id: 'add-template-modal',
        title: 'Templates',
        tabLabel: 'Templates'
      }
    },

    getDefaultProps: function(){
      return {
        update: false
      }
    },

    getId: function(){
      return this.getTab().id;
    },

    getTitle: function(){
      return this.getTab().title;
    },

    getTab: function(){
      return this.tabs[this.state.selected];
    },

    getInitialState: function(){
      var initSelected = 'add';
      if (this.props.update) {
        initSelected = 'upload'
      }
      return cutils.extend(Modal.getInitialState.apply(this), {
        selected: initSelected
      });
    },

    renderTabItem: function(tabName){
      var tab = this.tabs[tabName];
      var className = 'autotoc-level-' + tabName;
      var label = tab.tabLabel;
      if(this.state.selected === tabName){
        className += ' active';
        if(tabName === 'add' && this.refs.tab && this.refs.tab.state.selectedType){
          label = label += ' ' + this.refs.tab.state.selectedType.title;
        }
      }
      return D.a({ href: '#' + tabName, className: className,
                   onClick: this.tabClicked.bind(this, tabName)}, label);
    },

    tabClicked: function(tabName, e){
      e.preventDefault();
      this.setState({
        selected: tabName
      });
    },

    renderContentContainer: function(){
      return R.createElement(this.getTab().Component, cutils.extend(this.props, {
        ref: 'tab',
        parent: this
      }));
    }

  });

  return AddContentModal;
});

/* Related items pattern.
 *
 * Options:
 *    vocabularyUrl(string): This is a URL to a JSON-formatted file used to populate the list (null)
 *    attributes(array): This list is passed to the server during an AJAX request to specify the attributes which should be included on each item. (['UID', 'Title', 'portal_type', 'path'])
 *    maximumSelectionSize(integer): The maximum number of items that can be selected in a multi-select control. If this number is less than 1 selection is not limited. (-1)
 *    selectableTypes(array): If the value is null all types are selectable. Otherwise, provide a list of strings to match item types that are selectable. (null)
 *    separator(string): Select2 option. String which separates multiple items. (',')
 *    tokenSeparators(array): Select2 option, refer to select2 documentation.
 *    ([",", " "])
 *    width(string): Specify a width for the widget. ('100%')
 *
 */


define('mockup-patterns-relateditems',[
  'jquery',
  'castle-url/libs/react/react.min',
  'underscore',
  'pat-base',
  'mockup-patterns-select2',
  'mockup-utils',
  'mockup-patterns-tree',
  'translate',
  'castle-url/components/content-browser',
  'castle-url/components/add-content-modal',
  'castle-url/components/utils'
], function($, R, _, Base, Select2, utils, Tree, _t,
            ContentBrowserComponent, AddContentModal, cutils) {
  'use strict';

  var D = R.DOM;

  var Select2ResultTemplate = _.template(
'<div class="pattern-relateditems-result  <% if (selected) { %>pattern-relateditems-active<% } %>">' +
'  <a href="#" class=" pattern-relateditems-result-select <% if (selectable) { %>selectable<% } %>">' +
'    <% if (typeof getIcon !== "undefined" && getIcon) { %><img src="<%- getURL %>/@@images/image/icon "> <% } %>' +
'    <span class="pattern-relateditems-result-title  <% if (typeof review_state !== "undefined") { %> state-<%- review_state %> <% } %>  " /span>' +
'    <span class="pattern-relateditems contenttype-<%- portal_type.toLowerCase() %>"><%- Title %></span>' +
'    <span class="pattern-relateditems-result-path"><%- path %></span>' +
'  </a>' +
'</div>');

  var RelatedItemsComponent = R.createClass({
    getInitialState: function(){
      return {
        selected: this.props.initial_selection,
        items: []
      };
    },

    getDefaultProps: function(){
      return {
        initial_selection: [],
        allowAdd: true,
        noItemsSelectedText: 'No items selected',
        portal_url: $('body').attr('data-portal-url')
      };
    },

    getQueryHelper: function(){
      var query = new utils.QueryHelper({
        vocabularyUrl: this.props.vocabularyUrl,
        batchSize: 30,
        pattern: this.props.parent,
        sort_on: 'getObjPositionInParent',
        sort_order: 'ascending',
        baseCriteria: this.props.baseCriteria.slice(),
        attributes: ['UID', 'Title', 'portal_type', 'path', 'review_state', 'is_folderish']
      });
      // get current path instead?
      // query.currentPath = '/';
      return query;
    },

    selectionUpdated: function(){
      this.props.updateValue(this.state.selected);
      this.load();
    },

    componentDidMount: function(){
      this.load();
      this.setupSelect2();
    },

    setupSelect2: function(){
      var that = this;
      var qh = new utils.QueryHelper({
        vocabularyUrl: this.props.vocabularyUrl,
        batchSize: 15,
        attributes: ['UID', 'Title', 'portal_type', 'path', 'review_state', 'is_folderish']
      });

      var ajax = qh.selectAjax();
      ajax.data = function(term, page){
        // override because we do not want sorting...
        var data = {
          query: JSON.stringify({
            criteria: qh.getCriterias(term)
          }),
          attributes: JSON.stringify(qh.options.attributes)
        };
        if (page) {
          data.batch = JSON.stringify(qh.getBatch(page));
        }
        return data;
      };
      ajax.quietMillis = 300;

      $(that.refs.select2.getDOMNode()).select2({
        placeholder: 'Type to search',
        minimumInputLength: 3,
        ajax: ajax,
        multiple: true,
        width: that.props.widget || 400,
        formatResult: function(item){
          item.selected = that.state.selected.indexOf(item.UID) !== -1;
          if (that.props.selectableTypes === null) {
            item.selectable = true;
          } else {
            item.selectable = _.indexOf(
              that.props.selectableTypes, item.portal_type) > -1;
          }
          var result = $(Select2ResultTemplate(item));
          result.on('click', function(){
            that.addSelection([item.UID]);
          });
          return result;
        }
      });
    },

    addSelection: function(selection){
      var that = this;
      var valid = [];
      selection.forEach(function(item){
        if(that.state.selected.indexOf(item) === -1){
          valid.push(item);
        }
      });
      if(that.props.maximumSelectionSize === 1){
        if(valid.length > 0){
          that.state.selected = [valid[0]];
        }
      }else{
        that.state.selected = that.state.selected.concat(valid);
      }
      that.selectionUpdated();
    },

    load: function(){
      var that = this;
      // load current selection...
      if(this.state.selected.length === 0){
        this.setState({
          items: []
        });
        return;
      }
      utils.loading.show();

      var criteria  = [{
        i: 'UID',
        o: 'plone.app.querystring.operation.list.contains',
        v: that.state.selected
      }];
      var method = 'GET';
      if(that.state.selected.length > 60){
        method = 'POST';
      }
      $.ajax({
        url: that.props.vocabularyUrl,
        dataType: 'JSON',
        type: method,
        data: {
          query: JSON.stringify({ criteria: criteria }),
          attributes: JSON.stringify([
            'Title', 'getURL', 'UID', 'id', 'path', 'portal_type',
            'review_state', 'is_folderish'
          ]),
          batch: JSON.stringify({
            page: 1,
            size: 500 // unlimited size here...
          })
        }
      }).done(function(data){
        // need to sort the results...
        var results = _.sortBy(data.results, function(item){
          return that.state.selected.indexOf(item.UID);
        });
        that.setState({
          items: results
        });
        if(that.props.input){
          $(that.props.input).trigger('loaded');
        }
      }).always(function(){
        utils.loading.hide();
      }).fail(function(){
        alert('error loading selection data');
      });
    },

    browseClicked: function(e){
      var that = this;
      e.preventDefault();

      var multiple = false;
      if(this.props.multiple && this.props.maximumSelectionSize !== 1){
        multiple = true;
      }
      var qh = that.getQueryHelper();
      var ContentBrowserBinder = cutils.BindComponentFactoryRoot(
        ContentBrowserComponent, function(){
          return {
            onSelectItem: function(item){
              that.addSelection([item.UID]);
            },
            onSelectItems: function(items){
              var uids = [];
              items.forEach(function(item){
                uids.push(item.UID);
              });
              that.addSelection(uids);
            },
            baseCriteria: qh.options.baseCriteria,
            query: qh,
            multiple: multiple,
            selectableTypes: that.props.selectableTypes
          };
        }, 'content-browser-react-container');

      var component = ContentBrowserBinder({});
      var newPath;
      if(that.props.selectableTypes && that.props.selectableTypes.length === 1){
        if(that.props.selectableTypes[0] === 'Image'){
          newPath = '/image-repository';
        }
        if(that.props.selectableTypes[0] === 'File'){
          newPath = '/file-repository';
        }
        if(that.props.selectableTypes[0] === 'Video'){
          newPath = '/video-repository';
        }
        if(that.props.selectableTypes[0] === 'Audio'){
          newPath = '/audio-repository';
        }
      }
      if(newPath){
        component.setPath(newPath);
        component.load();
      }
    },

    addClicked: function(e){
      var that = this;
      e.preventDefault();

      var tbarSettings = cutils.getToolbarSettings();

      var component = cutils.createModalComponent(AddContentModal, 'add-modal-react-container', {
        types: tbarSettings.add.types,
        allowEditAfterCreation: false,
        afterCreationCallback: function(data, component){
          that.addSelection([data.uid]);
          var $modal = component.getModalEl();
          $modal.modal('hide');
        },
        onHidden: function(e, component){
          var upload = component.refs.tab;
          if(upload && upload.state.files){
            var uids = [];
            _.each(upload.state.files, function(file){
              var listing = upload.refs[file.uid];
              if(listing.state.state === 'finished'){
                uids.push(listing.state.uid);
              }
            });
            that.addSelection(uids);
          }
        }
      });

      if(that.props.selectableTypes && (
          that.props.selectableTypes.indexOf('Image') !== -1 ||
          that.props.selectableTypes.indexOf('File') !== -1)){
        component.setState({selected: 'upload'});
      }
    },

    removeClicked: function(item, e){
      var that = this;
      e.preventDefault();
      var index = that.state.selected.indexOf(item.UID);
      if(index !== -1){
        that.state.selected.splice(index, 1);
      }
      that.selectionUpdated();
    },

    move: function(item, delta, e){
      var that = this;
      e.preventDefault();
      var index = that.state.selected.indexOf(item.UID);
      if(index !== -1){
        var uid = that.state.selected[index];
        that.state.selected[index] = that.state.selected[index + delta];
        that.state.selected[index + delta] = uid;
      }
      that.selectionUpdated();
    },

    renderSelected: function(){
      var that = this;
      var content;
      if(this.state.items.length === 0){
        content = D.p({ className: 'castle-relateditems-empty'},
                        this.props.noItemsSelectedText);
      } else {
        var items = [];
        that.state.items.forEach(function(item, idx){
          var iconClass = 'contenttype-document contenttype-' + item.portal_type.toLowerCase();
          if(item.portal_type === 'Folder'){
            iconClass = 'contenttype-folder';
          }
          var icon = D.span({className: iconClass, key: item.UID + '-icon'});

          var buttons = [
            D.button({ className: 'icon-trash plone-btn plone-btn-default',
                       onClick: that.removeClicked.bind(that, item)}, 'Remove')];
          if(idx !== 0){
            buttons.push(D.button({
              className: 'icon-move-up plone-btn plone-btn-default',
              onClick: that.move.bind(that, item, -1)}, 'Up'));
          }
          if(idx < (that.state.items.length - 1)){
            buttons.push(D.button({
              className: 'icon-move-down plone-btn plone-btn-default',
              onClick: that.move.bind(that, item, 1)}, 'Down'));
          }
          items.push(D.tr({}, [
            D.td({}, [icon, item.Title]),
            D.td({}, D.a({ href: that.props.portal_url + item.path + '/view', target: '_blank'}, item.path)),
            D.td({}, buttons)
          ]));
        });
        content = D.table({className: 'contents table'}, [
          D.thead({}, D.tr({}, [
            D.th({}, 'Title'),
            D.th({}, 'Path'),
            D.th({}, 'Actions')
          ])),
          D.tbody({}, items)
        ]);
      }
      return D.div({ className: 'castle-relateditems-selected'}, content);
    },

    render: function(){
      var buttons = [D.button({
          className: 'plone-btn plone-btn-default castle-btn-browse',
          onClick: this.browseClicked
        }, 'Browse')];
      if(this.props.allowAdd){
        buttons.push(D.button({
          className: 'plone-btn plone-btn-default castle-btn-add',
          onClick: this.addClicked
        }, 'Add'));
      }
      return D.div({className: 'castle-relateditems-container'}, [
        D.div({ className: 'castle-relateditems-selectors row'}, [
          D.div({ className: 'col-xs-12 col-md-3 castle-re-select'}, buttons),
          D.div({ className: 'col-xs-12 col-md-9 castle-re-search'}, [
            D.label({ className: 'visually-hidden', htmlFor: 'reSearch' }, 'Search'),
            D.input({ id: 'reSearch', ref: 'select2' }),
          ])
        ]),
        this.renderSelected()
      ]);
    }
  });

  var RelatedItems = Base.extend({
    browsing: true,
    name: 'relateditems',
    trigger: '.pat-relateditems',
    parser: 'mockup',
    currentPath: '/',
    defaults: {
      vocabularyUrl: null, // must be set to work
      width: '100%',
      multiple: true,
      tokenSeparators: [',', ' '],
      separator: ',',
      selectableTypes: null, // null means everything is selectable, otherwise a list of strings to match types that are selectable
      attributes: ['UID', 'Title', 'portal_type', 'path', 'getURL',
                   'getIcon','is_folderish','review_state'],
      maximumSelectionSize: -1,
      initialPath: null,
      baseCriteria: [],
      allowAdd: true,
      setupAjax: function() {
        // Setup the ajax object to use during requests
        var self = this;
        if (self.query.valid) {
          return self.query.selectAjax();
        }
        return {};
      }
    },

    init: function(){
      var that = this;

      if(that.options.initialPath){
        that.currentPath = that.options.initialPath;
      }

      var options = cutils.extend(this.options, {
        parent: this,
        input: this.$el[0],
        updateValue: function(selected){
          that.$el.attr('value', selected.join(that.options.separator));
          that.$el.trigger('change');
        }
      });
      var el = document.createElement('div');
      this.$el.parent().append(el);
      this.$el.hide();
      this.$el.parent().find('#reSearch').remove();

      // initialize value...
      var val = that.$el.attr('value');

      that.component = R.render(R.createElement(RelatedItemsComponent, options), el);
      this.$el[0].component = that.component;
      var selected;
      if(val){
        selected = val.split(that.options.separator);
      }else{
        selected = [];
      }
      that.component.setState({
        selected: selected
      });
      that.component.load();
    }
  });

  RelatedItems.Component = RelatedItemsComponent;

  return RelatedItems;

});

(function(root) {
define("tinymce", [], function() {
  return (function() {
// 4.7.13 (2018-05-16)
(function () {
(function () {
  'use strict';

  var noop = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
  };
  var noarg = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return f();
    };
  };
  var compose = function (fa, fb) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return fa(fb.apply(null, arguments));
    };
  };
  var constant = function (value) {
    return function () {
      return value;
    };
  };
  var identity = function (x) {
    return x;
  };
  var tripleEquals = function (a, b) {
    return a === b;
  };
  var curry = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = new Array(arguments.length - 1);
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      var newArgs = new Array(arguments.length);
      for (var j = 0; j < newArgs.length; j++)
        newArgs[j] = arguments[j];
      var all = args.concat(newArgs);
      return f.apply(null, all);
    };
  };
  var not = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return !f.apply(null, arguments);
    };
  };
  var die = function (msg) {
    return function () {
      throw new Error(msg);
    };
  };
  var apply = function (f) {
    return f();
  };
  var call = function (f) {
    f();
  };
  var never = constant(false);
  var always = constant(true);
  var $_eqpqvr6jh8lyw3s = {
    noop: noop,
    noarg: noarg,
    compose: compose,
    constant: constant,
    identity: identity,
    tripleEquals: tripleEquals,
    curry: curry,
    not: not,
    die: die,
    apply: apply,
    call: call,
    never: never,
    always: always
  };

  var never$1 = $_eqpqvr6jh8lyw3s.never;
  var always$1 = $_eqpqvr6jh8lyw3s.always;
  var none = function () {
    return NONE;
  };
  var NONE = function () {
    var eq = function (o) {
      return o.isNone();
    };
    var call = function (thunk) {
      return thunk();
    };
    var id = function (n) {
      return n;
    };
    var noop = function () {
    };
    var me = {
      fold: function (n, s) {
        return n();
      },
      is: never$1,
      isSome: never$1,
      isNone: always$1,
      getOr: id,
      getOrThunk: call,
      getOrDie: function (msg) {
        throw new Error(msg || 'error: getOrDie called on none.');
      },
      or: id,
      orThunk: call,
      map: none,
      ap: none,
      each: noop,
      bind: none,
      flatten: none,
      exists: never$1,
      forall: always$1,
      filter: none,
      equals: eq,
      equals_: eq,
      toArray: function () {
        return [];
      },
      toString: $_eqpqvr6jh8lyw3s.constant('none()')
    };
    if (Object.freeze)
      Object.freeze(me);
    return me;
  }();
  var some = function (a) {
    var constant_a = function () {
      return a;
    };
    var self = function () {
      return me;
    };
    var map = function (f) {
      return some(f(a));
    };
    var bind = function (f) {
      return f(a);
    };
    var me = {
      fold: function (n, s) {
        return s(a);
      },
      is: function (v) {
        return a === v;
      },
      isSome: always$1,
      isNone: never$1,
      getOr: constant_a,
      getOrThunk: constant_a,
      getOrDie: constant_a,
      or: self,
      orThunk: self,
      map: map,
      ap: function (optfab) {
        return optfab.fold(none, function (fab) {
          return some(fab(a));
        });
      },
      each: function (f) {
        f(a);
      },
      bind: bind,
      flatten: constant_a,
      exists: bind,
      forall: bind,
      filter: function (f) {
        return f(a) ? me : NONE;
      },
      equals: function (o) {
        return o.is(a);
      },
      equals_: function (o, elementEq) {
        return o.fold(never$1, function (b) {
          return elementEq(a, b);
        });
      },
      toArray: function () {
        return [a];
      },
      toString: function () {
        return 'some(' + a + ')';
      }
    };
    return me;
  };
  var from = function (value) {
    return value === null || value === undefined ? NONE : some(value);
  };
  var Option = {
    some: some,
    none: none,
    from: from
  };

  var typeOf = function (x) {
    if (x === null)
      return 'null';
    var t = typeof x;
    if (t === 'object' && Array.prototype.isPrototypeOf(x))
      return 'array';
    if (t === 'object' && String.prototype.isPrototypeOf(x))
      return 'string';
    return t;
  };
  var isType = function (type) {
    return function (value) {
      return typeOf(value) === type;
    };
  };
  var $_dp4g6d7jh8lyw3y = {
    isString: isType('string'),
    isObject: isType('object'),
    isArray: isType('array'),
    isNull: isType('null'),
    isBoolean: isType('boolean'),
    isUndefined: isType('undefined'),
    isFunction: isType('function'),
    isNumber: isType('number')
  };

  var rawIndexOf = function () {
    var pIndexOf = Array.prototype.indexOf;
    var fastIndex = function (xs, x) {
      return pIndexOf.call(xs, x);
    };
    var slowIndex = function (xs, x) {
      return slowIndexOf(xs, x);
    };
    return pIndexOf === undefined ? slowIndex : fastIndex;
  }();
  var indexOf = function (xs, x) {
    var r = rawIndexOf(xs, x);
    return r === -1 ? Option.none() : Option.some(r);
  };
  var contains = function (xs, x) {
    return rawIndexOf(xs, x) > -1;
  };
  var exists = function (xs, pred) {
    return findIndex(xs, pred).isSome();
  };
  var range = function (num, f) {
    var r = [];
    for (var i = 0; i < num; i++) {
      r.push(f(i));
    }
    return r;
  };
  var chunk = function (array, size) {
    var r = [];
    for (var i = 0; i < array.length; i += size) {
      var s = array.slice(i, i + size);
      r.push(s);
    }
    return r;
  };
  var map = function (xs, f) {
    var len = xs.length;
    var r = new Array(len);
    for (var i = 0; i < len; i++) {
      var x = xs[i];
      r[i] = f(x, i, xs);
    }
    return r;
  };
  var each = function (xs, f) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var eachr = function (xs, f) {
    for (var i = xs.length - 1; i >= 0; i--) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var partition = function (xs, pred) {
    var pass = [];
    var fail = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      var arr = pred(x, i, xs) ? pass : fail;
      arr.push(x);
    }
    return {
      pass: pass,
      fail: fail
    };
  };
  var filter = function (xs, pred) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        r.push(x);
      }
    }
    return r;
  };
  var groupBy = function (xs, f) {
    if (xs.length === 0) {
      return [];
    } else {
      var wasType = f(xs[0]);
      var r = [];
      var group = [];
      for (var i = 0, len = xs.length; i < len; i++) {
        var x = xs[i];
        var type = f(x);
        if (type !== wasType) {
          r.push(group);
          group = [];
        }
        wasType = type;
        group.push(x);
      }
      if (group.length !== 0) {
        r.push(group);
      }
      return r;
    }
  };
  var foldr = function (xs, f, acc) {
    eachr(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var foldl = function (xs, f, acc) {
    each(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var find = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(x);
      }
    }
    return Option.none();
  };
  var findIndex = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(i);
      }
    }
    return Option.none();
  };
  var slowIndexOf = function (xs, x) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (xs[i] === x) {
        return i;
      }
    }
    return -1;
  };
  var push = Array.prototype.push;
  var flatten = function (xs) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (!Array.prototype.isPrototypeOf(xs[i]))
        throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
      push.apply(r, xs[i]);
    }
    return r;
  };
  var bind = function (xs, f) {
    var output = map(xs, f);
    return flatten(output);
  };
  var forall = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      var x = xs[i];
      if (pred(x, i, xs) !== true) {
        return false;
      }
    }
    return true;
  };
  var equal = function (a1, a2) {
    return a1.length === a2.length && forall(a1, function (x, i) {
      return x === a2[i];
    });
  };
  var slice = Array.prototype.slice;
  var reverse = function (xs) {
    var r = slice.call(xs, 0);
    r.reverse();
    return r;
  };
  var difference = function (a1, a2) {
    return filter(a1, function (x) {
      return !contains(a2, x);
    });
  };
  var mapToObject = function (xs, f) {
    var r = {};
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      r[String(x)] = f(x, i);
    }
    return r;
  };
  var pure = function (x) {
    return [x];
  };
  var sort = function (xs, comparator) {
    var copy = slice.call(xs, 0);
    copy.sort(comparator);
    return copy;
  };
  var head = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  };
  var last = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  };
  var from$1 = $_dp4g6d7jh8lyw3y.isFunction(Array.from) ? Array.from : function (x) {
    return slice.call(x);
  };
  var $_5wjzy24jh8lyw2t = {
    map: map,
    each: each,
    eachr: eachr,
    partition: partition,
    filter: filter,
    groupBy: groupBy,
    indexOf: indexOf,
    foldr: foldr,
    foldl: foldl,
    find: find,
    findIndex: findIndex,
    flatten: flatten,
    bind: bind,
    forall: forall,
    exists: exists,
    contains: contains,
    equal: equal,
    reverse: reverse,
    chunk: chunk,
    difference: difference,
    mapToObject: mapToObject,
    pure: pure,
    sort: sort,
    range: range,
    head: head,
    last: last,
    from: from$1
  };

  var global = typeof window !== 'undefined' ? window : Function('return this;')();

  var path = function (parts, scope) {
    var o = scope !== undefined && scope !== null ? scope : global;
    for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i)
      o = o[parts[i]];
    return o;
  };
  var resolve = function (p, scope) {
    var parts = p.split('.');
    return path(parts, scope);
  };
  var step = function (o, part) {
    if (o[part] === undefined || o[part] === null)
      o[part] = {};
    return o[part];
  };
  var forge = function (parts, target) {
    var o = target !== undefined ? target : global;
    for (var i = 0; i < parts.length; ++i)
      o = step(o, parts[i]);
    return o;
  };
  var namespace = function (name, target) {
    var parts = name.split('.');
    return forge(parts, target);
  };
  var $_br50dmdjh8lyw6o = {
    path: path,
    resolve: resolve,
    forge: forge,
    namespace: namespace
  };

  var unsafe = function (name, scope) {
    return $_br50dmdjh8lyw6o.resolve(name, scope);
  };
  var getOrDie = function (name, scope) {
    var actual = unsafe(name, scope);
    if (actual === undefined || actual === null)
      throw name + ' not available on this browser';
    return actual;
  };
  var $_99xmy7cjh8lyw6k = { getOrDie: getOrDie };

  var url = function () {
    return $_99xmy7cjh8lyw6k.getOrDie('URL');
  };
  var createObjectURL = function (blob) {
    return url().createObjectURL(blob);
  };
  var revokeObjectURL = function (u) {
    url().revokeObjectURL(u);
  };
  var $_ge0pt0bjh8lyw6g = {
    createObjectURL: createObjectURL,
    revokeObjectURL: revokeObjectURL
  };

  var nav = navigator;
  var userAgent = nav.userAgent;
  var opera;
  var webkit;
  var ie;
  var ie11;
  var ie12;
  var gecko;
  var mac;
  var iDevice;
  var android;
  var fileApi;
  var phone;
  var tablet;
  var windowsPhone;
  var matchMediaQuery = function (query) {
    return 'matchMedia' in window ? matchMedia(query).matches : false;
  };
  opera = false;
  android = /Android/.test(userAgent);
  webkit = /WebKit/.test(userAgent);
  ie = !webkit && !opera && /MSIE/gi.test(userAgent) && /Explorer/gi.test(nav.appName);
  ie = ie && /MSIE (\w+)\./.exec(userAgent)[1];
  ie11 = userAgent.indexOf('Trident/') !== -1 && (userAgent.indexOf('rv:') !== -1 || nav.appName.indexOf('Netscape') !== -1) ? 11 : false;
  ie12 = userAgent.indexOf('Edge/') !== -1 && !ie && !ie11 ? 12 : false;
  ie = ie || ie11 || ie12;
  gecko = !webkit && !ie11 && /Gecko/.test(userAgent);
  mac = userAgent.indexOf('Mac') !== -1;
  iDevice = /(iPad|iPhone)/.test(userAgent);
  fileApi = 'FormData' in window && 'FileReader' in window && 'URL' in window && !!$_ge0pt0bjh8lyw6g.createObjectURL;
  phone = matchMediaQuery('only screen and (max-device-width: 480px)') && (android || iDevice);
  tablet = matchMediaQuery('only screen and (min-width: 800px)') && (android || iDevice);
  windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  if (ie12) {
    webkit = false;
  }
  var contentEditable = !iDevice || fileApi || parseInt(userAgent.match(/AppleWebKit\/(\d*)/)[1], 10) >= 534;
  var $_9bpim8ajh8lyw68 = {
    opera: opera,
    webkit: webkit,
    ie: ie,
    gecko: gecko,
    mac: mac,
    iOS: iDevice,
    android: android,
    contentEditable: contentEditable,
    transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
    caretAfter: ie !== 8,
    range: window.getSelection && 'Range' in window,
    documentMode: ie && !ie12 ? document.documentMode || 7 : 10,
    fileApi: fileApi,
    ceFalse: ie === false || ie > 8,
    cacheSuffix: null,
    container: null,
    overrideViewPort: null,
    experimentalShadowDom: false,
    canHaveCSP: ie === false || ie > 11,
    desktop: !phone && !tablet,
    windowsPhone: windowsPhone
  };

  var promise = function () {
    function bind(fn, thisArg) {
      return function () {
        fn.apply(thisArg, arguments);
      };
    }
    var isArray = Array.isArray || function (value) {
      return Object.prototype.toString.call(value) === '[object Array]';
    };
    var Promise = function (fn) {
      if (typeof this !== 'object') {
        throw new TypeError('Promises must be constructed via new');
      }
      if (typeof fn !== 'function') {
        throw new TypeError('not a function');
      }
      this._state = null;
      this._value = null;
      this._deferreds = [];
      doResolve(fn, bind(resolve, this), bind(reject, this));
    };
    var asap = Promise.immediateFn || typeof setImmediate === 'function' && setImmediate || function (fn) {
      setTimeout(fn, 1);
    };
    function handle(deferred) {
      var me = this;
      if (this._state === null) {
        this._deferreds.push(deferred);
        return;
      }
      asap(function () {
        var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
        if (cb === null) {
          (me._state ? deferred.resolve : deferred.reject)(me._value);
          return;
        }
        var ret;
        try {
          ret = cb(me._value);
        } catch (e) {
          deferred.reject(e);
          return;
        }
        deferred.resolve(ret);
      });
    }
    function resolve(newValue) {
      try {
        if (newValue === this) {
          throw new TypeError('A promise cannot be resolved with itself.');
        }
        if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
          var then = newValue.then;
          if (typeof then === 'function') {
            doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
            return;
          }
        }
        this._state = true;
        this._value = newValue;
        finale.call(this);
      } catch (e) {
        reject.call(this, e);
      }
    }
    function reject(newValue) {
      this._state = false;
      this._value = newValue;
      finale.call(this);
    }
    function finale() {
      for (var i = 0, len = this._deferreds.length; i < len; i++) {
        handle.call(this, this._deferreds[i]);
      }
      this._deferreds = null;
    }
    function Handler(onFulfilled, onRejected, resolve, reject) {
      this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
      this.onRejected = typeof onRejected === 'function' ? onRejected : null;
      this.resolve = resolve;
      this.reject = reject;
    }
    function doResolve(fn, onFulfilled, onRejected) {
      var done = false;
      try {
        fn(function (value) {
          if (done) {
            return;
          }
          done = true;
          onFulfilled(value);
        }, function (reason) {
          if (done) {
            return;
          }
          done = true;
          onRejected(reason);
        });
      } catch (ex) {
        if (done) {
          return;
        }
        done = true;
        onRejected(ex);
      }
    }
    Promise.prototype.catch = function (onRejected) {
      return this.then(null, onRejected);
    };
    Promise.prototype.then = function (onFulfilled, onRejected) {
      var me = this;
      return new Promise(function (resolve, reject) {
        handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
      });
    };
    Promise.all = function () {
      var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
      return new Promise(function (resolve, reject) {
        if (args.length === 0) {
          return resolve([]);
        }
        var remaining = args.length;
        function res(i, val) {
          try {
            if (val && (typeof val === 'object' || typeof val === 'function')) {
              var then = val.then;
              if (typeof then === 'function') {
                then.call(val, function (val) {
                  res(i, val);
                }, reject);
                return;
              }
            }
            args[i] = val;
            if (--remaining === 0) {
              resolve(args);
            }
          } catch (ex) {
            reject(ex);
          }
        }
        for (var i = 0; i < args.length; i++) {
          res(i, args[i]);
        }
      });
    };
    Promise.resolve = function (value) {
      if (value && typeof value === 'object' && value.constructor === Promise) {
        return value;
      }
      return new Promise(function (resolve) {
        resolve(value);
      });
    };
    Promise.reject = function (value) {
      return new Promise(function (resolve, reject) {
        reject(value);
      });
    };
    Promise.race = function (values) {
      return new Promise(function (resolve, reject) {
        for (var i = 0, len = values.length; i < len; i++) {
          values[i].then(resolve, reject);
        }
      });
    };
    return Promise;
  };
  var promiseObj = window.Promise ? window.Promise : promise();

  var requestAnimationFramePromise;
  var requestAnimationFrame = function (callback, element) {
    var i, requestAnimationFrameFunc = window.requestAnimationFrame;
    var vendors = [
      'ms',
      'moz',
      'webkit'
    ];
    var featurefill = function (callback) {
      window.setTimeout(callback, 0);
    };
    for (i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
      requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
    }
    if (!requestAnimationFrameFunc) {
      requestAnimationFrameFunc = featurefill;
    }
    requestAnimationFrameFunc(callback, element);
  };
  var wrappedSetTimeout = function (callback, time) {
    if (typeof time !== 'number') {
      time = 0;
    }
    return setTimeout(callback, time);
  };
  var wrappedSetInterval = function (callback, time) {
    if (typeof time !== 'number') {
      time = 1;
    }
    return setInterval(callback, time);
  };
  var wrappedClearTimeout = function (id) {
    return clearTimeout(id);
  };
  var wrappedClearInterval = function (id) {
    return clearInterval(id);
  };
  var debounce = function (callback, time) {
    var timer, func;
    func = function () {
      var args = arguments;
      clearTimeout(timer);
      timer = wrappedSetTimeout(function () {
        callback.apply(this, args);
      }, time);
    };
    func.stop = function () {
      clearTimeout(timer);
    };
    return func;
  };
  var $_8sy3pfhjh8lyw95 = {
    requestAnimationFrame: function (callback, element) {
      if (requestAnimationFramePromise) {
        requestAnimationFramePromise.then(callback);
        return;
      }
      requestAnimationFramePromise = new promiseObj(function (resolve) {
        if (!element) {
          element = document.body;
        }
        requestAnimationFrame(resolve, element);
      }).then(callback);
    },
    setTimeout: wrappedSetTimeout,
    setInterval: wrappedSetInterval,
    setEditorTimeout: function (editor, callback, time) {
      return wrappedSetTimeout(function () {
        if (!editor.removed) {
          callback();
        }
      }, time);
    },
    setEditorInterval: function (editor, callback, time) {
      var timer;
      timer = wrappedSetInterval(function () {
        if (!editor.removed) {
          callback();
        } else {
          clearInterval(timer);
        }
      }, time);
      return timer;
    },
    debounce: debounce,
    throttle: debounce,
    clearInterval: wrappedClearInterval,
    clearTimeout: wrappedClearTimeout
  };

  var eventExpandoPrefix = 'mce-data-';
  var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  var deprecated = {
    keyLocation: 1,
    layerX: 1,
    layerY: 1,
    returnValue: 1,
    webkitMovementX: 1,
    webkitMovementY: 1,
    keyIdentifier: 1
  };
  var hasIsDefaultPrevented = function (event) {
    return event.isDefaultPrevented === returnTrue || event.isDefaultPrevented === returnFalse;
  };
  var returnFalse = function () {
    return false;
  };
  var returnTrue = function () {
    return true;
  };
  var addEvent = function (target, name, callback, capture) {
    if (target.addEventListener) {
      target.addEventListener(name, callback, capture || false);
    } else if (target.attachEvent) {
      target.attachEvent('on' + name, callback);
    }
  };
  var removeEvent = function (target, name, callback, capture) {
    if (target.removeEventListener) {
      target.removeEventListener(name, callback, capture || false);
    } else if (target.detachEvent) {
      target.detachEvent('on' + name, callback);
    }
  };
  var getTargetFromShadowDom = function (event, defaultTarget) {
    var path, target = defaultTarget;
    path = event.path;
    if (path && path.length > 0) {
      target = path[0];
    }
    if (event.composedPath) {
      path = event.composedPath();
      if (path && path.length > 0) {
        target = path[0];
      }
    }
    return target;
  };
  var fix = function (originalEvent, data) {
    var name;
    var event = data || {};
    for (name in originalEvent) {
      if (!deprecated[name]) {
        event[name] = originalEvent[name];
      }
    }
    if (!event.target) {
      event.target = event.srcElement || document;
    }
    if ($_9bpim8ajh8lyw68.experimentalShadowDom) {
      event.target = getTargetFromShadowDom(originalEvent, event.target);
    }
    if (originalEvent && mouseEventRe.test(originalEvent.type) && originalEvent.pageX === undefined && originalEvent.clientX !== undefined) {
      var eventDoc = event.target.ownerDocument || document;
      var doc = eventDoc.documentElement;
      var body = eventDoc.body;
      event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
      event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
    }
    event.preventDefault = function () {
      event.isDefaultPrevented = returnTrue;
      if (originalEvent) {
        if (originalEvent.preventDefault) {
          originalEvent.preventDefault();
        } else {
          originalEvent.returnValue = false;
        }
      }
    };
    event.stopPropagation = function () {
      event.isPropagationStopped = returnTrue;
      if (originalEvent) {
        if (originalEvent.stopPropagation) {
          originalEvent.stopPropagation();
        } else {
          originalEvent.cancelBubble = true;
        }
      }
    };
    event.stopImmediatePropagation = function () {
      event.isImmediatePropagationStopped = returnTrue;
      event.stopPropagation();
    };
    if (hasIsDefaultPrevented(event) === false) {
      event.isDefaultPrevented = returnFalse;
      event.isPropagationStopped = returnFalse;
      event.isImmediatePropagationStopped = returnFalse;
    }
    if (typeof event.metaKey === 'undefined') {
      event.metaKey = false;
    }
    return event;
  };
  var bindOnReady = function (win, callback, eventUtils) {
    var doc = win.document, event = { type: 'ready' };
    if (eventUtils.domLoaded) {
      callback(event);
      return;
    }
    var isDocReady = function () {
      return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
    };
    var readyHandler = function () {
      if (!eventUtils.domLoaded) {
        eventUtils.domLoaded = true;
        callback(event);
      }
    };
    var waitForDomLoaded = function () {
      if (isDocReady()) {
        removeEvent(doc, 'readystatechange', waitForDomLoaded);
        readyHandler();
      }
    };
    var tryScroll = function () {
      try {
        doc.documentElement.doScroll('left');
      } catch (ex) {
        $_8sy3pfhjh8lyw95.setTimeout(tryScroll);
        return;
      }
      readyHandler();
    };
    if (doc.addEventListener && !($_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie < 11)) {
      if (isDocReady()) {
        readyHandler();
      } else {
        addEvent(win, 'DOMContentLoaded', readyHandler);
      }
    } else {
      addEvent(doc, 'readystatechange', waitForDomLoaded);
      if (doc.documentElement.doScroll && win.self === win.top) {
        tryScroll();
      }
    }
    addEvent(win, 'load', readyHandler);
  };
  var EventUtils = function () {
    var self = this;
    var events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave;
    expando = eventExpandoPrefix + (+new Date()).toString(32);
    hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
    hasFocusIn = 'onfocusin' in document.documentElement;
    mouseEnterLeave = {
      mouseenter: 'mouseover',
      mouseleave: 'mouseout'
    };
    count = 1;
    self.domLoaded = false;
    self.events = events;
    var executeHandlers = function (evt, id) {
      var callbackList, i, l, callback;
      var container = events[id];
      callbackList = container && container[evt.type];
      if (callbackList) {
        for (i = 0, l = callbackList.length; i < l; i++) {
          callback = callbackList[i];
          if (callback && callback.func.call(callback.scope, evt) === false) {
            evt.preventDefault();
          }
          if (evt.isImmediatePropagationStopped()) {
            return;
          }
        }
      }
    };
    self.bind = function (target, names, callback, scope) {
      var id, callbackList, i, name, fakeName, nativeHandler, capture;
      var win = window;
      var defaultNativeHandler = function (evt) {
        executeHandlers(fix(evt || win.event), id);
      };
      if (!target || target.nodeType === 3 || target.nodeType === 8) {
        return;
      }
      if (!target[expando]) {
        id = count++;
        target[expando] = id;
        events[id] = {};
      } else {
        id = target[expando];
      }
      scope = scope || target;
      names = names.split(' ');
      i = names.length;
      while (i--) {
        name = names[i];
        nativeHandler = defaultNativeHandler;
        fakeName = capture = false;
        if (name === 'DOMContentLoaded') {
          name = 'ready';
        }
        if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
          callback.call(scope, fix({ type: name }));
          continue;
        }
        if (!hasMouseEnterLeave) {
          fakeName = mouseEnterLeave[name];
          if (fakeName) {
            nativeHandler = function (evt) {
              var current, related;
              current = evt.currentTarget;
              related = evt.relatedTarget;
              if (related && current.contains) {
                related = current.contains(related);
              } else {
                while (related && related !== current) {
                  related = related.parentNode;
                }
              }
              if (!related) {
                evt = fix(evt || win.event);
                evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
                evt.target = current;
                executeHandlers(evt, id);
              }
            };
          }
        }
        if (!hasFocusIn && (name === 'focusin' || name === 'focusout')) {
          capture = true;
          fakeName = name === 'focusin' ? 'focus' : 'blur';
          nativeHandler = function (evt) {
            evt = fix(evt || win.event);
            evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
            executeHandlers(evt, id);
          };
        }
        callbackList = events[id][name];
        if (!callbackList) {
          events[id][name] = callbackList = [{
              func: callback,
              scope: scope
            }];
          callbackList.fakeName = fakeName;
          callbackList.capture = capture;
          callbackList.nativeHandler = nativeHandler;
          if (name === 'ready') {
            bindOnReady(target, nativeHandler, self);
          } else {
            addEvent(target, fakeName || name, nativeHandler, capture);
          }
        } else {
          if (name === 'ready' && self.domLoaded) {
            callback({ type: name });
          } else {
            callbackList.push({
              func: callback,
              scope: scope
            });
          }
        }
      }
      target = callbackList = 0;
      return callback;
    };
    self.unbind = function (target, names, callback) {
      var id, callbackList, i, ci, name, eventMap;
      if (!target || target.nodeType === 3 || target.nodeType === 8) {
        return self;
      }
      id = target[expando];
      if (id) {
        eventMap = events[id];
        if (names) {
          names = names.split(' ');
          i = names.length;
          while (i--) {
            name = names[i];
            callbackList = eventMap[name];
            if (callbackList) {
              if (callback) {
                ci = callbackList.length;
                while (ci--) {
                  if (callbackList[ci].func === callback) {
                    var nativeHandler = callbackList.nativeHandler;
                    var fakeName = callbackList.fakeName, capture = callbackList.capture;
                    callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
                    callbackList.nativeHandler = nativeHandler;
                    callbackList.fakeName = fakeName;
                    callbackList.capture = capture;
                    eventMap[name] = callbackList;
                  }
                }
              }
              if (!callback || callbackList.length === 0) {
                delete eventMap[name];
                removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
              }
            }
          }
        } else {
          for (name in eventMap) {
            callbackList = eventMap[name];
            removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
          }
          eventMap = {};
        }
        for (name in eventMap) {
          return self;
        }
        delete events[id];
        try {
          delete target[expando];
        } catch (ex) {
          target[expando] = null;
        }
      }
      return self;
    };
    self.fire = function (target, name, args) {
      var id;
      if (!target || target.nodeType === 3 || target.nodeType === 8) {
        return self;
      }
      args = fix(null, args);
      args.type = name;
      args.target = target;
      do {
        id = target[expando];
        if (id) {
          executeHandlers(args, id);
        }
        target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
      } while (target && !args.isPropagationStopped());
      return self;
    };
    self.clean = function (target) {
      var i, children;
      var unbind = self.unbind;
      if (!target || target.nodeType === 3 || target.nodeType === 8) {
        return self;
      }
      if (target[expando]) {
        unbind(target);
      }
      if (!target.getElementsByTagName) {
        target = target.document;
      }
      if (target && target.getElementsByTagName) {
        unbind(target);
        children = target.getElementsByTagName('*');
        i = children.length;
        while (i--) {
          target = children[i];
          if (target[expando]) {
            unbind(target);
          }
        }
      }
      return self;
    };
    self.destroy = function () {
      events = {};
    };
    self.cancel = function (e) {
      if (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
      }
      return false;
    };
  };
  EventUtils.Event = new EventUtils();
  EventUtils.Event.bind(window, 'ready', function () {
  });

  var i;
  var support;
  var Expr;
  var getText;
  var isXML;
  var tokenize;
  var compile;
  var select;
  var outermostContext;
  var sortInput;
  var hasDuplicate;
  var setDocument;
  var document$1;
  var docElem;
  var documentIsHTML;
  var rbuggyQSA;
  var rbuggyMatches;
  var matches;
  var contains$1;
  var expando = 'sizzle' + -new Date();
  var preferredDoc = window.document;
  var dirruns = 0;
  var done = 0;
  var classCache = createCache();
  var tokenCache = createCache();
  var compilerCache = createCache();
  var sortOrder = function (a, b) {
      if (a === b) {
        hasDuplicate = true;
      }
      return 0;
    };
  var strundefined = typeof undefined;
  var MAX_NEGATIVE = 1 << 31;
  var hasOwn = {}.hasOwnProperty;
  var arr = [];
  var pop = arr.pop;
  var push_native = arr.push;
  var push$1 = arr.push;
  var slice$1 = arr.slice;
  var indexOf$1 = arr.indexOf || function (elem) {
      var i = 0, len = this.length;
      for (; i < len; i++) {
        if (this[i] === elem) {
          return i;
        }
      }
      return -1;
    };
  var booleans = 'checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped';
  var whitespace = '[\\x20\\t\\r\\n\\f]';
  var identifier = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+';
  var attributes = '\\[' + whitespace + '*(' + identifier + ')(?:' + whitespace + '*([*^$|!~]?=)' + whitespace + '*(?:\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)"|(' + identifier + '))|)' + whitespace + '*\\]';
  var pseudos = ':(' + identifier + ')(?:\\((' + '(\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)")|' + '((?:\\\\.|[^\\\\()[\\]]|' + attributes + ')*)|' + '.*' + ')\\)|)';
  var rtrim = new RegExp('^' + whitespace + '+|((?:^|[^\\\\])(?:\\\\.)*)' + whitespace + '+$', 'g');
  var rcomma = new RegExp('^' + whitespace + '*,' + whitespace + '*');
  var rcombinators = new RegExp('^' + whitespace + '*([>+~]|' + whitespace + ')' + whitespace + '*');
  var rattributeQuotes = new RegExp('=' + whitespace + '*([^\\]\'"]*?)' + whitespace + '*\\]', 'g');
  var rpseudo = new RegExp(pseudos);
  var ridentifier = new RegExp('^' + identifier + '$');
  var matchExpr = {
      ID: new RegExp('^#(' + identifier + ')'),
      CLASS: new RegExp('^\\.(' + identifier + ')'),
      TAG: new RegExp('^(' + identifier + '|[*])'),
      ATTR: new RegExp('^' + attributes),
      PSEUDO: new RegExp('^' + pseudos),
      CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
      bool: new RegExp('^(?:' + booleans + ')$', 'i'),
      needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
    };
  var rinputs = /^(?:input|select|textarea|button)$/i;
  var rheader = /^h\d$/i;
  var rnative = /^[^{]+\{\s*\[native \w/;
  var rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/;
  var rsibling = /[+~]/;
  var rescape = /'|\\/g;
  var runescape = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig');
  var funescape = function (_, escaped, escapedWhitespace) {
      var high = '0x' + escaped - 65536;
      return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
    };
  try {
    push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
    arr[preferredDoc.childNodes.length].nodeType;
  } catch (e) {
    push$1 = {
      apply: arr.length ? function (target, els) {
        push_native.apply(target, slice$1.call(els));
      } : function (target, els) {
        var j = target.length, i = 0;
        while (target[j++] = els[i++]) {
        }
        target.length = j - 1;
      }
    };
  }
  var Sizzle = function (selector, context, results, seed) {
    var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
    if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
      setDocument(context);
    }
    context = context || document$1;
    results = results || [];
    if (!selector || typeof selector !== 'string') {
      return results;
    }
    if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
      return [];
    }
    if (documentIsHTML && !seed) {
      if (match = rquickExpr.exec(selector)) {
        if (m = match[1]) {
          if (nodeType === 9) {
            elem = context.getElementById(m);
            if (elem && elem.parentNode) {
              if (elem.id === m) {
                results.push(elem);
                return results;
              }
            } else {
              return results;
            }
          } else {
            if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains$1(context, elem) && elem.id === m) {
              results.push(elem);
              return results;
            }
          }
        } else if (match[2]) {
          push$1.apply(results, context.getElementsByTagName(selector));
          return results;
        } else if ((m = match[3]) && support.getElementsByClassName) {
          push$1.apply(results, context.getElementsByClassName(m));
          return results;
        }
      }
      if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
        nid = old = expando;
        newContext = context;
        newSelector = nodeType === 9 && selector;
        if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
          groups = tokenize(selector);
          if (old = context.getAttribute('id')) {
            nid = old.replace(rescape, '\\$&');
          } else {
            context.setAttribute('id', nid);
          }
          nid = '[id=\'' + nid + '\'] ';
          i = groups.length;
          while (i--) {
            groups[i] = nid + toSelector(groups[i]);
          }
          newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
          newSelector = groups.join(',');
        }
        if (newSelector) {
          try {
            push$1.apply(results, newContext.querySelectorAll(newSelector));
            return results;
          } catch (qsaError) {
          } finally {
            if (!old) {
              context.removeAttribute('id');
            }
          }
        }
      }
    }
    return select(selector.replace(rtrim, '$1'), context, results, seed);
  };
  function createCache() {
    var keys = [];
    function cache(key, value) {
      if (keys.push(key + ' ') > Expr.cacheLength) {
        delete cache[keys.shift()];
      }
      return cache[key + ' '] = value;
    }
    return cache;
  }
  function markFunction(fn) {
    fn[expando] = true;
    return fn;
  }
  function siblingCheck(a, b) {
    var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
    if (diff) {
      return diff;
    }
    if (cur) {
      while (cur = cur.nextSibling) {
        if (cur === b) {
          return -1;
        }
      }
    }
    return a ? 1 : -1;
  }
  function createInputPseudo(type) {
    return function (elem) {
      var name = elem.nodeName.toLowerCase();
      return name === 'input' && elem.type === type;
    };
  }
  function createButtonPseudo(type) {
    return function (elem) {
      var name = elem.nodeName.toLowerCase();
      return (name === 'input' || name === 'button') && elem.type === type;
    };
  }
  function createPositionalPseudo(fn) {
    return markFunction(function (argument) {
      argument = +argument;
      return markFunction(function (seed, matches) {
        var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
        while (i--) {
          if (seed[j = matchIndexes[i]]) {
            seed[j] = !(matches[j] = seed[j]);
          }
        }
      });
    });
  }
  function testContext(context) {
    return context && typeof context.getElementsByTagName !== strundefined && context;
  }
  support = Sizzle.support = {};
  isXML = Sizzle.isXML = function (elem) {
    var documentElement = elem && (elem.ownerDocument || elem).documentElement;
    return documentElement ? documentElement.nodeName !== 'HTML' : false;
  };
  setDocument = Sizzle.setDocument = function (node) {
    var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
    function getTop(win) {
      try {
        return win.top;
      } catch (ex) {
      }
      return null;
    }
    if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
      return document$1;
    }
    document$1 = doc;
    docElem = doc.documentElement;
    documentIsHTML = !isXML(doc);
    if (parent && parent !== getTop(parent)) {
      if (parent.addEventListener) {
        parent.addEventListener('unload', function () {
          setDocument();
        }, false);
      } else if (parent.attachEvent) {
        parent.attachEvent('onunload', function () {
          setDocument();
        });
      }
    }
    support.attributes = true;
    support.getElementsByTagName = true;
    support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
    support.getById = true;
    Expr.find.ID = function (id, context) {
      if (typeof context.getElementById !== strundefined && documentIsHTML) {
        var m = context.getElementById(id);
        return m && m.parentNode ? [m] : [];
      }
    };
    Expr.filter.ID = function (id) {
      var attrId = id.replace(runescape, funescape);
      return function (elem) {
        return elem.getAttribute('id') === attrId;
      };
    };
    Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
      if (typeof context.getElementsByTagName !== strundefined) {
        return context.getElementsByTagName(tag);
      }
    } : function (tag, context) {
      var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
      if (tag === '*') {
        while (elem = results[i++]) {
          if (elem.nodeType === 1) {
            tmp.push(elem);
          }
        }
        return tmp;
      }
      return results;
    };
    Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
      if (documentIsHTML) {
        return context.getElementsByClassName(className);
      }
    };
    rbuggyMatches = [];
    rbuggyQSA = [];
    support.disconnectedMatch = true;
    rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
    rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
    hasCompare = rnative.test(docElem.compareDocumentPosition);
    contains$1 = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
      var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
      return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
    } : function (a, b) {
      if (b) {
        while (b = b.parentNode) {
          if (b === a) {
            return true;
          }
        }
      }
      return false;
    };
    sortOrder = hasCompare ? function (a, b) {
      if (a === b) {
        hasDuplicate = true;
        return 0;
      }
      var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
      if (compare) {
        return compare;
      }
      compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
      if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
        if (a === doc || a.ownerDocument === preferredDoc && contains$1(preferredDoc, a)) {
          return -1;
        }
        if (b === doc || b.ownerDocument === preferredDoc && contains$1(preferredDoc, b)) {
          return 1;
        }
        return sortInput ? indexOf$1.call(sortInput, a) - indexOf$1.call(sortInput, b) : 0;
      }
      return compare & 4 ? -1 : 1;
    } : function (a, b) {
      if (a === b) {
        hasDuplicate = true;
        return 0;
      }
      var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
      if (!aup || !bup) {
        return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf$1.call(sortInput, a) - indexOf$1.call(sortInput, b) : 0;
      } else if (aup === bup) {
        return siblingCheck(a, b);
      }
      cur = a;
      while (cur = cur.parentNode) {
        ap.unshift(cur);
      }
      cur = b;
      while (cur = cur.parentNode) {
        bp.unshift(cur);
      }
      while (ap[i] === bp[i]) {
        i++;
      }
      return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
    };
    return doc;
  };
  Sizzle.matches = function (expr, elements) {
    return Sizzle(expr, null, null, elements);
  };
  Sizzle.matchesSelector = function (elem, expr) {
    if ((elem.ownerDocument || elem) !== document$1) {
      setDocument(elem);
    }
    expr = expr.replace(rattributeQuotes, '=\'$1\']');
    if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
      try {
        var ret = matches.call(elem, expr);
        if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
          return ret;
        }
      } catch (e) {
      }
    }
    return Sizzle(expr, document$1, null, [elem]).length > 0;
  };
  Sizzle.contains = function (context, elem) {
    if ((context.ownerDocument || context) !== document$1) {
      setDocument(context);
    }
    return contains$1(context, elem);
  };
  Sizzle.attr = function (elem, name) {
    if ((elem.ownerDocument || elem) !== document$1) {
      setDocument(elem);
    }
    var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
    return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  };
  Sizzle.error = function (msg) {
    throw new Error('Syntax error, unrecognized expression: ' + msg);
  };
  Sizzle.uniqueSort = function (results) {
    var elem, duplicates = [], j = 0, i = 0;
    hasDuplicate = !support.detectDuplicates;
    sortInput = !support.sortStable && results.slice(0);
    results.sort(sortOrder);
    if (hasDuplicate) {
      while (elem = results[i++]) {
        if (elem === results[i]) {
          j = duplicates.push(i);
        }
      }
      while (j--) {
        results.splice(duplicates[j], 1);
      }
    }
    sortInput = null;
    return results;
  };
  getText = Sizzle.getText = function (elem) {
    var node, ret = '', i = 0, nodeType = elem.nodeType;
    if (!nodeType) {
      while (node = elem[i++]) {
        ret += getText(node);
      }
    } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
      if (typeof elem.textContent === 'string') {
        return elem.textContent;
      } else {
        for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
          ret += getText(elem);
        }
      }
    } else if (nodeType === 3 || nodeType === 4) {
      return elem.nodeValue;
    }
    return ret;
  };
  Expr = Sizzle.selectors = {
    cacheLength: 50,
    createPseudo: markFunction,
    match: matchExpr,
    attrHandle: {},
    find: {},
    relative: {
      '>': {
        dir: 'parentNode',
        first: true
      },
      ' ': { dir: 'parentNode' },
      '+': {
        dir: 'previousSibling',
        first: true
      },
      '~': { dir: 'previousSibling' }
    },
    preFilter: {
      ATTR: function (match) {
        match[1] = match[1].replace(runescape, funescape);
        match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
        if (match[2] === '~=') {
          match[3] = ' ' + match[3] + ' ';
        }
        return match.slice(0, 4);
      },
      CHILD: function (match) {
        match[1] = match[1].toLowerCase();
        if (match[1].slice(0, 3) === 'nth') {
          if (!match[3]) {
            Sizzle.error(match[0]);
          }
          match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
          match[5] = +(match[7] + match[8] || match[3] === 'odd');
        } else if (match[3]) {
          Sizzle.error(match[0]);
        }
        return match;
      },
      PSEUDO: function (match) {
        var excess, unquoted = !match[6] && match[2];
        if (matchExpr.CHILD.test(match[0])) {
          return null;
        }
        if (match[3]) {
          match[2] = match[4] || match[5] || '';
        } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
          match[0] = match[0].slice(0, excess);
          match[2] = unquoted.slice(0, excess);
        }
        return match.slice(0, 3);
      }
    },
    filter: {
      TAG: function (nodeNameSelector) {
        var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
        return nodeNameSelector === '*' ? function () {
          return true;
        } : function (elem) {
          return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
        };
      },
      CLASS: function (className) {
        var pattern = classCache[className + ' '];
        return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
          return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
        });
      },
      ATTR: function (name, operator, check) {
        return function (elem) {
          var result = Sizzle.attr(elem, name);
          if (result == null) {
            return operator === '!=';
          }
          if (!operator) {
            return true;
          }
          result += '';
          return operator === '=' ? result === check : operator === '!=' ? result !== check : operator === '^=' ? check && result.indexOf(check) === 0 : operator === '*=' ? check && result.indexOf(check) > -1 : operator === '$=' ? check && result.slice(-check.length) === check : operator === '~=' ? (' ' + result + ' ').indexOf(check) > -1 : operator === '|=' ? result === check || result.slice(0, check.length + 1) === check + '-' : false;
        };
      },
      CHILD: function (type, what, argument, first, last) {
        var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
        return first === 1 && last === 0 ? function (elem) {
          return !!elem.parentNode;
        } : function (elem, context, xml) {
          var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
          if (parent) {
            if (simple) {
              while (dir) {
                node = elem;
                while (node = node[dir]) {
                  if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
                    return false;
                  }
                }
                start = dir = type === 'only' && !start && 'nextSibling';
              }
              return true;
            }
            start = [forward ? parent.firstChild : parent.lastChild];
            if (forward && useCache) {
              outerCache = parent[expando] || (parent[expando] = {});
              cache = outerCache[type] || [];
              nodeIndex = cache[0] === dirruns && cache[1];
              diff = cache[0] === dirruns && cache[2];
              node = nodeIndex && parent.childNodes[nodeIndex];
              while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
                if (node.nodeType === 1 && ++diff && node === elem) {
                  outerCache[type] = [
                    dirruns,
                    nodeIndex,
                    diff
                  ];
                  break;
                }
              }
            } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
              diff = cache[1];
            } else {
              while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
                if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
                  if (useCache) {
                    (node[expando] || (node[expando] = {}))[type] = [
                      dirruns,
                      diff
                    ];
                  }
                  if (node === elem) {
                    break;
                  }
                }
              }
            }
            diff -= last;
            return diff === first || diff % first === 0 && diff / first >= 0;
          }
        };
      },
      PSEUDO: function (pseudo, argument) {
        var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
        if (fn[expando]) {
          return fn(argument);
        }
        if (fn.length > 1) {
          args = [
            pseudo,
            pseudo,
            '',
            argument
          ];
          return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
            var idx, matched = fn(seed, argument), i = matched.length;
            while (i--) {
              idx = indexOf$1.call(seed, matched[i]);
              seed[idx] = !(matches[idx] = matched[i]);
            }
          }) : function (elem) {
            return fn(elem, 0, args);
          };
        }
        return fn;
      }
    },
    pseudos: {
      not: markFunction(function (selector) {
        var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
        return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
          var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
          while (i--) {
            if (elem = unmatched[i]) {
              seed[i] = !(matches[i] = elem);
            }
          }
        }) : function (elem, context, xml) {
          input[0] = elem;
          matcher(input, null, xml, results);
          return !results.pop();
        };
      }),
      has: markFunction(function (selector) {
        return function (elem) {
          return Sizzle(selector, elem).length > 0;
        };
      }),
      contains: markFunction(function (text) {
        text = text.replace(runescape, funescape);
        return function (elem) {
          return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
        };
      }),
      lang: markFunction(function (lang) {
        if (!ridentifier.test(lang || '')) {
          Sizzle.error('unsupported lang: ' + lang);
        }
        lang = lang.replace(runescape, funescape).toLowerCase();
        return function (elem) {
          var elemLang;
          do {
            if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
              elemLang = elemLang.toLowerCase();
              return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
            }
          } while ((elem = elem.parentNode) && elem.nodeType === 1);
          return false;
        };
      }),
      target: function (elem) {
        var hash = window.location && window.location.hash;
        return hash && hash.slice(1) === elem.id;
      },
      root: function (elem) {
        return elem === docElem;
      },
      focus: function (elem) {
        return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
      },
      enabled: function (elem) {
        return elem.disabled === false;
      },
      disabled: function (elem) {
        return elem.disabled === true;
      },
      checked: function (elem) {
        var nodeName = elem.nodeName.toLowerCase();
        return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
      },
      selected: function (elem) {
        if (elem.parentNode) {
          elem.parentNode.selectedIndex;
        }
        return elem.selected === true;
      },
      empty: function (elem) {
        for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
          if (elem.nodeType < 6) {
            return false;
          }
        }
        return true;
      },
      parent: function (elem) {
        return !Expr.pseudos.empty(elem);
      },
      header: function (elem) {
        return rheader.test(elem.nodeName);
      },
      input: function (elem) {
        return rinputs.test(elem.nodeName);
      },
      button: function (elem) {
        var name = elem.nodeName.toLowerCase();
        return name === 'input' && elem.type === 'button' || name === 'button';
      },
      text: function (elem) {
        var attr;
        return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
      },
      first: createPositionalPseudo(function () {
        return [0];
      }),
      last: createPositionalPseudo(function (matchIndexes, length) {
        return [length - 1];
      }),
      eq: createPositionalPseudo(function (matchIndexes, length, argument) {
        return [argument < 0 ? argument + length : argument];
      }),
      even: createPositionalPseudo(function (matchIndexes, length) {
        var i = 0;
        for (; i < length; i += 2) {
          matchIndexes.push(i);
        }
        return matchIndexes;
      }),
      odd: createPositionalPseudo(function (matchIndexes, length) {
        var i = 1;
        for (; i < length; i += 2) {
          matchIndexes.push(i);
        }
        return matchIndexes;
      }),
      lt: createPositionalPseudo(function (matchIndexes, length, argument) {
        var i = argument < 0 ? argument + length : argument;
        for (; --i >= 0;) {
          matchIndexes.push(i);
        }
        return matchIndexes;
      }),
      gt: createPositionalPseudo(function (matchIndexes, length, argument) {
        var i = argument < 0 ? argument + length : argument;
        for (; ++i < length;) {
          matchIndexes.push(i);
        }
        return matchIndexes;
      })
    }
  };
  Expr.pseudos.nth = Expr.pseudos.eq;
  for (i in {
      radio: true,
      checkbox: true,
      file: true,
      password: true,
      image: true
    }) {
    Expr.pseudos[i] = createInputPseudo(i);
  }
  for (i in {
      submit: true,
      reset: true
    }) {
    Expr.pseudos[i] = createButtonPseudo(i);
  }
  function setFilters() {
  }
  setFilters.prototype = Expr.filters = Expr.pseudos;
  Expr.setFilters = new setFilters();
  tokenize = Sizzle.tokenize = function (selector, parseOnly) {
    var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
    if (cached) {
      return parseOnly ? 0 : cached.slice(0);
    }
    soFar = selector;
    groups = [];
    preFilters = Expr.preFilter;
    while (soFar) {
      if (!matched || (match = rcomma.exec(soFar))) {
        if (match) {
          soFar = soFar.slice(match[0].length) || soFar;
        }
        groups.push(tokens = []);
      }
      matched = false;
      if (match = rcombinators.exec(soFar)) {
        matched = match.shift();
        tokens.push({
          value: matched,
          type: match[0].replace(rtrim, ' ')
        });
        soFar = soFar.slice(matched.length);
      }
      for (type in Expr.filter) {
        if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
          matched = match.shift();
          tokens.push({
            value: matched,
            type: type,
            matches: match
          });
          soFar = soFar.slice(matched.length);
        }
      }
      if (!matched) {
        break;
      }
    }
    return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  };
  function toSelector(tokens) {
    var i = 0, len = tokens.length, selector = '';
    for (; i < len; i++) {
      selector += tokens[i].value;
    }
    return selector;
  }
  function addCombinator(matcher, combinator, base) {
    var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
    return combinator.first ? function (elem, context, xml) {
      while (elem = elem[dir]) {
        if (elem.nodeType === 1 || checkNonElements) {
          return matcher(elem, context, xml);
        }
      }
    } : function (elem, context, xml) {
      var oldCache, outerCache, newCache = [
          dirruns,
          doneName
        ];
      if (xml) {
        while (elem = elem[dir]) {
          if (elem.nodeType === 1 || checkNonElements) {
            if (matcher(elem, context, xml)) {
              return true;
            }
          }
        }
      } else {
        while (elem = elem[dir]) {
          if (elem.nodeType === 1 || checkNonElements) {
            outerCache = elem[expando] || (elem[expando] = {});
            if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
              return newCache[2] = oldCache[2];
            } else {
              outerCache[dir] = newCache;
              if (newCache[2] = matcher(elem, context, xml)) {
                return true;
              }
            }
          }
        }
      }
    };
  }
  function elementMatcher(matchers) {
    return matchers.length > 1 ? function (elem, context, xml) {
      var i = matchers.length;
      while (i--) {
        if (!matchers[i](elem, context, xml)) {
          return false;
        }
      }
      return true;
    } : matchers[0];
  }
  function multipleContexts(selector, contexts, results) {
    var i = 0, len = contexts.length;
    for (; i < len; i++) {
      Sizzle(selector, contexts[i], results);
    }
    return results;
  }
  function condense(unmatched, map, filter, context, xml) {
    var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
    for (; i < len; i++) {
      if (elem = unmatched[i]) {
        if (!filter || filter(elem, context, xml)) {
          newUnmatched.push(elem);
          if (mapped) {
            map.push(i);
          }
        }
      }
    }
    return newUnmatched;
  }
  function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
    if (postFilter && !postFilter[expando]) {
      postFilter = setMatcher(postFilter);
    }
    if (postFinder && !postFinder[expando]) {
      postFinder = setMatcher(postFinder, postSelector);
    }
    return markFunction(function (seed, results, context, xml) {
      var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(selector || '*', context.nodeType ? [context] : context, []), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
      if (matcher) {
        matcher(matcherIn, matcherOut, context, xml);
      }
      if (postFilter) {
        temp = condense(matcherOut, postMap);
        postFilter(temp, [], context, xml);
        i = temp.length;
        while (i--) {
          if (elem = temp[i]) {
            matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
          }
        }
      }
      if (seed) {
        if (postFinder || preFilter) {
          if (postFinder) {
            temp = [];
            i = matcherOut.length;
            while (i--) {
              if (elem = matcherOut[i]) {
                temp.push(matcherIn[i] = elem);
              }
            }
            postFinder(null, matcherOut = [], temp, xml);
          }
          i = matcherOut.length;
          while (i--) {
            if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf$1.call(seed, elem) : preMap[i]) > -1) {
              seed[temp] = !(results[temp] = elem);
            }
          }
        }
      } else {
        matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
        if (postFinder) {
          postFinder(null, results, matcherOut, xml);
        } else {
          push$1.apply(results, matcherOut);
        }
      }
    });
  }
  function matcherFromTokens(tokens) {
    var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[' '], i = leadingRelative ? 1 : 0, matchContext = addCombinator(function (elem) {
        return elem === checkContext;
      }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
        return indexOf$1.call(checkContext, elem) > -1;
      }, implicitRelative, true), matchers = [function (elem, context, xml) {
          return !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
        }];
    for (; i < len; i++) {
      if (matcher = Expr.relative[tokens[i].type]) {
        matchers = [addCombinator(elementMatcher(matchers), matcher)];
      } else {
        matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
        if (matcher[expando]) {
          j = ++i;
          for (; j < len; j++) {
            if (Expr.relative[tokens[j].type]) {
              break;
            }
          }
          return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector(tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === ' ' ? '*' : '' })).replace(rtrim, '$1'), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
        }
        matchers.push(matcher);
      }
    }
    return elementMatcher(matchers);
  }
  function matcherFromGroupMatchers(elementMatchers, setMatchers) {
    var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
        var elem, j, matcher, matchedCount = 0, i = '0', unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find.TAG('*', outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
        if (outermost) {
          outermostContext = context !== document$1 && context;
        }
        for (; i !== len && (elem = elems[i]) != null; i++) {
          if (byElement && elem) {
            j = 0;
            while (matcher = elementMatchers[j++]) {
              if (matcher(elem, context, xml)) {
                results.push(elem);
                break;
              }
            }
            if (outermost) {
              dirruns = dirrunsUnique;
            }
          }
          if (bySet) {
            if (elem = !matcher && elem) {
              matchedCount--;
            }
            if (seed) {
              unmatched.push(elem);
            }
          }
        }
        matchedCount += i;
        if (bySet && i !== matchedCount) {
          j = 0;
          while (matcher = setMatchers[j++]) {
            matcher(unmatched, setMatched, context, xml);
          }
          if (seed) {
            if (matchedCount > 0) {
              while (i--) {
                if (!(unmatched[i] || setMatched[i])) {
                  setMatched[i] = pop.call(results);
                }
              }
            }
            setMatched = condense(setMatched);
          }
          push$1.apply(results, setMatched);
          if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
            Sizzle.uniqueSort(results);
          }
        }
        if (outermost) {
          dirruns = dirrunsUnique;
          outermostContext = contextBackup;
        }
        return unmatched;
      };
    return bySet ? markFunction(superMatcher) : superMatcher;
  }
  compile = Sizzle.compile = function (selector, match) {
    var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
    if (!cached) {
      if (!match) {
        match = tokenize(selector);
      }
      i = match.length;
      while (i--) {
        cached = matcherFromTokens(match[i]);
        if (cached[expando]) {
          setMatchers.push(cached);
        } else {
          elementMatchers.push(cached);
        }
      }
      cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
      cached.selector = selector;
    }
    return cached;
  };
  select = Sizzle.select = function (selector, context, results, seed) {
    var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
    results = results || [];
    if (match.length === 1) {
      tokens = match[0] = match[0].slice(0);
      if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
        context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
        if (!context) {
          return results;
        } else if (compiled) {
          context = context.parentNode;
        }
        selector = selector.slice(tokens.shift().value.length);
      }
      i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
      while (i--) {
        token = tokens[i];
        if (Expr.relative[type = token.type]) {
          break;
        }
        if (find = Expr.find[type]) {
          if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
            tokens.splice(i, 1);
            selector = seed.length && toSelector(tokens);
            if (!selector) {
              push$1.apply(results, seed);
              return results;
            }
            break;
          }
        }
      }
    }
    (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
    return results;
  };
  support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  support.detectDuplicates = !!hasDuplicate;
  setDocument();
  support.sortDetached = true;

  var isArray = Array.isArray;
  var toArray = function (obj) {
    var array = obj, i, l;
    if (!isArray(obj)) {
      array = [];
      for (i = 0, l = obj.length; i < l; i++) {
        array[i] = obj[i];
      }
    }
    return array;
  };
  var each$1 = function (o, cb, s) {
    var n, l;
    if (!o) {
      return 0;
    }
    s = s || o;
    if (o.length !== undefined) {
      for (n = 0, l = o.length; n < l; n++) {
        if (cb.call(s, o[n], n, o) === false) {
          return 0;
        }
      }
    } else {
      for (n in o) {
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false) {
            return 0;
          }
        }
      }
    }
    return 1;
  };
  var map$1 = function (array, callback) {
    var out = [];
    each$1(array, function (item, index) {
      out.push(callback(item, index, array));
    });
    return out;
  };
  var filter$1 = function (a, f) {
    var o = [];
    each$1(a, function (v, index) {
      if (!f || f(v, index, a)) {
        o.push(v);
      }
    });
    return o;
  };
  var indexOf$2 = function (a, v) {
    var i, l;
    if (a) {
      for (i = 0, l = a.length; i < l; i++) {
        if (a[i] === v) {
          return i;
        }
      }
    }
    return -1;
  };
  var reduce = function (collection, iteratee, accumulator, thisArg) {
    var i = 0;
    if (arguments.length < 3) {
      accumulator = collection[0];
    }
    for (; i < collection.length; i++) {
      accumulator = iteratee.call(thisArg, accumulator, collection[i], i);
    }
    return accumulator;
  };
  var findIndex$1 = function (array, predicate, thisArg) {
    var i, l;
    for (i = 0, l = array.length; i < l; i++) {
      if (predicate.call(thisArg, array[i], i, array)) {
        return i;
      }
    }
    return -1;
  };
  var find$1 = function (array, predicate, thisArg) {
    var idx = findIndex$1(array, predicate, thisArg);
    if (idx !== -1) {
      return array[idx];
    }
    return undefined;
  };
  var last$1 = function (collection) {
    return collection[collection.length - 1];
  };
  var $_9tjm51ljh8lywbq = {
    isArray: isArray,
    toArray: toArray,
    each: each$1,
    map: map$1,
    filter: filter$1,
    indexOf: indexOf$2,
    reduce: reduce,
    findIndex: findIndex$1,
    find: find$1,
    last: last$1
  };

  var whiteSpaceRegExp = /^\s*|\s*$/g;
  var trim = function (str) {
    return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  };
  var is = function (obj, type) {
    if (!type) {
      return obj !== undefined;
    }
    if (type === 'array' && $_9tjm51ljh8lywbq.isArray(obj)) {
      return true;
    }
    return typeof obj === type;
  };
  var makeMap = function (items, delim, map) {
    var i;
    items = items || [];
    delim = delim || ',';
    if (typeof items === 'string') {
      items = items.split(delim);
    }
    map = map || {};
    i = items.length;
    while (i--) {
      map[items[i]] = {};
    }
    return map;
  };
  var hasOwnProperty = function (obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
  };
  var create = function (s, p, root) {
    var self = this;
    var sp, ns, cn, scn, c, de = 0;
    s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
    cn = s[3].match(/(^|\.)(\w+)$/i)[2];
    ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
    if (ns[cn]) {
      return;
    }
    if (s[2] === 'static') {
      ns[cn] = p;
      if (this.onCreate) {
        this.onCreate(s[2], s[3], ns[cn]);
      }
      return;
    }
    if (!p[cn]) {
      p[cn] = function () {
      };
      de = 1;
    }
    ns[cn] = p[cn];
    self.extend(ns[cn].prototype, p);
    if (s[5]) {
      sp = self.resolve(s[5]).prototype;
      scn = s[5].match(/\.(\w+)$/i)[1];
      c = ns[cn];
      if (de) {
        ns[cn] = function () {
          return sp[scn].apply(this, arguments);
        };
      } else {
        ns[cn] = function () {
          this.parent = sp[scn];
          return c.apply(this, arguments);
        };
      }
      ns[cn].prototype[cn] = ns[cn];
      self.each(sp, function (f, n) {
        ns[cn].prototype[n] = sp[n];
      });
      self.each(p, function (f, n) {
        if (sp[n]) {
          ns[cn].prototype[n] = function () {
            this.parent = sp[n];
            return f.apply(this, arguments);
          };
        } else {
          if (n !== cn) {
            ns[cn].prototype[n] = f;
          }
        }
      });
    }
    self.each(p.static, function (f, n) {
      ns[cn][n] = f;
    });
  };
  var extend = function (obj, ext) {
    var x = [];
    for (var _i = 2; _i < arguments.length; _i++) {
      x[_i - 2] = arguments[_i];
    }
    var i, l, name;
    var args = arguments;
    var value;
    for (i = 1, l = args.length; i < l; i++) {
      ext = args[i];
      for (name in ext) {
        if (ext.hasOwnProperty(name)) {
          value = ext[name];
          if (value !== undefined) {
            obj[name] = value;
          }
        }
      }
    }
    return obj;
  };
  var walk = function (o, f, n, s) {
    s = s || this;
    if (o) {
      if (n) {
        o = o[n];
      }
      $_9tjm51ljh8lywbq.each(o, function (o, i) {
        if (f.call(s, o, i, n) === false) {
          return false;
        }
        walk(o, f, n, s);
      });
    }
  };
  var createNS = function (n, o) {
    var i, v;
    o = o || window;
    n = n.split('.');
    for (i = 0; i < n.length; i++) {
      v = n[i];
      if (!o[v]) {
        o[v] = {};
      }
      o = o[v];
    }
    return o;
  };
  var resolve$1 = function (n, o) {
    var i, l;
    o = o || window;
    n = n.split('.');
    for (i = 0, l = n.length; i < l; i++) {
      o = o[n[i]];
      if (!o) {
        break;
      }
    }
    return o;
  };
  var explode = function (s, d) {
    if (!s || is(s, 'array')) {
      return s;
    }
    return $_9tjm51ljh8lywbq.map(s.split(d || ','), trim);
  };
  var _addCacheSuffix = function (url) {
    var cacheSuffix = $_9bpim8ajh8lyw68.cacheSuffix;
    if (cacheSuffix) {
      url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
    }
    return url;
  };
  var $_ahowuxkjh8lywbj = {
    trim: trim,
    isArray: $_9tjm51ljh8lywbq.isArray,
    is: is,
    toArray: $_9tjm51ljh8lywbq.toArray,
    makeMap: makeMap,
    each: $_9tjm51ljh8lywbq.each,
    map: $_9tjm51ljh8lywbq.map,
    grep: $_9tjm51ljh8lywbq.filter,
    inArray: $_9tjm51ljh8lywbq.indexOf,
    hasOwn: hasOwnProperty,
    extend: extend,
    create: create,
    walk: walk,
    createNS: createNS,
    resolve: resolve$1,
    explode: explode,
    _addCacheSuffix: _addCacheSuffix
  };

  var doc = document;
  var push$2 = Array.prototype.push;
  var slice$2 = Array.prototype.slice;
  var rquickExpr$1 = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  var Event = EventUtils.Event;
  var skipUniques = $_ahowuxkjh8lywbj.makeMap('children,contents,next,prev');
  var isDefined = function (obj) {
    return typeof obj !== 'undefined';
  };
  var isString = function (obj) {
    return typeof obj === 'string';
  };
  var isWindow = function (obj) {
    return obj && obj === obj.window;
  };
  var createFragment = function (html, fragDoc) {
    var frag, node, container;
    fragDoc = fragDoc || doc;
    container = fragDoc.createElement('div');
    frag = fragDoc.createDocumentFragment();
    container.innerHTML = html;
    while (node = container.firstChild) {
      frag.appendChild(node);
    }
    return frag;
  };
  var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
    var i;
    if (isString(sourceItem)) {
      sourceItem = createFragment(sourceItem, getElementDocument(targetNodes[0]));
    } else if (sourceItem.length && !sourceItem.nodeType) {
      sourceItem = DomQuery.makeArray(sourceItem);
      if (reverse) {
        for (i = sourceItem.length - 1; i >= 0; i--) {
          domManipulate(targetNodes, sourceItem[i], callback, reverse);
        }
      } else {
        for (i = 0; i < sourceItem.length; i++) {
          domManipulate(targetNodes, sourceItem[i], callback, reverse);
        }
      }
      return targetNodes;
    }
    if (sourceItem.nodeType) {
      i = targetNodes.length;
      while (i--) {
        callback.call(targetNodes[i], sourceItem);
      }
    }
    return targetNodes;
  };
  var hasClass = function (node, className) {
    return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  };
  var wrap = function (elements, wrapper, all) {
    var lastParent, newWrapper;
    wrapper = DomQuery(wrapper)[0];
    elements.each(function () {
      var self = this;
      if (!all || lastParent !== self.parentNode) {
        lastParent = self.parentNode;
        newWrapper = wrapper.cloneNode(false);
        self.parentNode.insertBefore(newWrapper, self);
        newWrapper.appendChild(self);
      } else {
        newWrapper.appendChild(self);
      }
    });
    return elements;
  };
  var numericCssMap = $_ahowuxkjh8lywbj.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  var booleanMap = $_ahowuxkjh8lywbj.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  var propFix = {
    for: 'htmlFor',
    class: 'className',
    readonly: 'readOnly'
  };
  var cssFix = { float: 'cssFloat' };
  var attrHooks = {};
  var cssHooks = {};
  var DomQuery = function (selector, context) {
    return new DomQuery.fn.init(selector, context);
  };
  var inArray = function (item, array) {
    var i;
    if (array.indexOf) {
      return array.indexOf(item);
    }
    i = array.length;
    while (i--) {
      if (array[i] === item) {
        return i;
      }
    }
    return -1;
  };
  var whiteSpaceRegExp$1 = /^\s*|\s*$/g;
  var trim$1 = function (str) {
    return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$1, '');
  };
  var each$2 = function (obj, callback) {
    var length, key, i, value;
    if (obj) {
      length = obj.length;
      if (length === undefined) {
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            value = obj[key];
            if (callback.call(value, key, value) === false) {
              break;
            }
          }
        }
      } else {
        for (i = 0; i < length; i++) {
          value = obj[i];
          if (callback.call(value, i, value) === false) {
            break;
          }
        }
      }
    }
    return obj;
  };
  var grep = function (array, callback) {
    var out = [];
    each$2(array, function (i, item) {
      if (callback(item, i)) {
        out.push(item);
      }
    });
    return out;
  };
  var getElementDocument = function (element) {
    if (!element) {
      return doc;
    }
    if (element.nodeType === 9) {
      return element;
    }
    return element.ownerDocument;
  };
  DomQuery.fn = DomQuery.prototype = {
    constructor: DomQuery,
    selector: '',
    context: null,
    length: 0,
    init: function (selector, context) {
      var self = this;
      var match, node;
      if (!selector) {
        return self;
      }
      if (selector.nodeType) {
        self.context = self[0] = selector;
        self.length = 1;
        return self;
      }
      if (context && context.nodeType) {
        self.context = context;
      } else {
        if (context) {
          return DomQuery(selector).attr(context);
        }
        self.context = context = document;
      }
      if (isString(selector)) {
        self.selector = selector;
        if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
          match = [
            null,
            selector,
            null
          ];
        } else {
          match = rquickExpr$1.exec(selector);
        }
        if (match) {
          if (match[1]) {
            node = createFragment(selector, getElementDocument(context)).firstChild;
            while (node) {
              push$2.call(self, node);
              node = node.nextSibling;
            }
          } else {
            node = getElementDocument(context).getElementById(match[2]);
            if (!node) {
              return self;
            }
            if (node.id !== match[2]) {
              return self.find(selector);
            }
            self.length = 1;
            self[0] = node;
          }
        } else {
          return DomQuery(context).find(selector);
        }
      } else {
        this.add(selector, false);
      }
      return self;
    },
    toArray: function () {
      return $_ahowuxkjh8lywbj.toArray(this);
    },
    add: function (items, sort) {
      var self = this;
      var nodes, i;
      if (isString(items)) {
        return self.add(DomQuery(items));
      }
      if (sort !== false) {
        nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
        self.length = nodes.length;
        for (i = 0; i < nodes.length; i++) {
          self[i] = nodes[i];
        }
      } else {
        push$2.apply(self, DomQuery.makeArray(items));
      }
      return self;
    },
    attr: function (name, value) {
      var self = this;
      var hook;
      if (typeof name === 'object') {
        each$2(name, function (name, value) {
          self.attr(name, value);
        });
      } else if (isDefined(value)) {
        this.each(function () {
          var hook;
          if (this.nodeType === 1) {
            hook = attrHooks[name];
            if (hook && hook.set) {
              hook.set(this, value);
              return;
            }
            if (value === null) {
              this.removeAttribute(name, 2);
            } else {
              this.setAttribute(name, value, 2);
            }
          }
        });
      } else {
        if (self[0] && self[0].nodeType === 1) {
          hook = attrHooks[name];
          if (hook && hook.get) {
            return hook.get(self[0], name);
          }
          if (booleanMap[name]) {
            return self.prop(name) ? name : undefined;
          }
          value = self[0].getAttribute(name, 2);
          if (value === null) {
            value = undefined;
          }
        }
        return value;
      }
      return self;
    },
    removeAttr: function (name) {
      return this.attr(name, null);
    },
    prop: function (name, value) {
      var self = this;
      name = propFix[name] || name;
      if (typeof name === 'object') {
        each$2(name, function (name, value) {
          self.prop(name, value);
        });
      } else if (isDefined(value)) {
        this.each(function () {
          if (this.nodeType === 1) {
            this[name] = value;
          }
        });
      } else {
        if (self[0] && self[0].nodeType && name in self[0]) {
          return self[0][name];
        }
        return value;
      }
      return self;
    },
    css: function (name, value) {
      var self = this;
      var elm, hook;
      var camel = function (name) {
        return name.replace(/-(\D)/g, function (a, b) {
          return b.toUpperCase();
        });
      };
      var dashed = function (name) {
        return name.replace(/[A-Z]/g, function (a) {
          return '-' + a;
        });
      };
      if (typeof name === 'object') {
        each$2(name, function (name, value) {
          self.css(name, value);
        });
      } else {
        if (isDefined(value)) {
          name = camel(name);
          if (typeof value === 'number' && !numericCssMap[name]) {
            value = value.toString() + 'px';
          }
          self.each(function () {
            var style = this.style;
            hook = cssHooks[name];
            if (hook && hook.set) {
              hook.set(this, value);
              return;
            }
            try {
              this.style[cssFix[name] || name] = value;
            } catch (ex) {
            }
            if (value === null || value === '') {
              if (style.removeProperty) {
                style.removeProperty(dashed(name));
              } else {
                style.removeAttribute(name);
              }
            }
          });
        } else {
          elm = self[0];
          hook = cssHooks[name];
          if (hook && hook.get) {
            return hook.get(elm);
          }
          if (elm.ownerDocument.defaultView) {
            try {
              return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
            } catch (ex) {
              return undefined;
            }
          } else if (elm.currentStyle) {
            return elm.currentStyle[camel(name)];
          } else {
            return '';
          }
        }
      }
      return self;
    },
    remove: function () {
      var self = this;
      var node, i = this.length;
      while (i--) {
        node = self[i];
        Event.clean(node);
        if (node.parentNode) {
          node.parentNode.removeChild(node);
        }
      }
      return this;
    },
    empty: function () {
      var self = this;
      var node, i = this.length;
      while (i--) {
        node = self[i];
        while (node.firstChild) {
          node.removeChild(node.firstChild);
        }
      }
      return this;
    },
    html: function (value) {
      var self = this;
      var i;
      if (isDefined(value)) {
        i = self.length;
        try {
          while (i--) {
            self[i].innerHTML = value;
          }
        } catch (ex) {
          DomQuery(self[i]).empty().append(value);
        }
        return self;
      }
      return self[0] ? self[0].innerHTML : '';
    },
    text: function (value) {
      var self = this;
      var i;
      if (isDefined(value)) {
        i = self.length;
        while (i--) {
          if ('innerText' in self[i]) {
            self[i].innerText = value;
          } else {
            self[0].textContent = value;
          }
        }
        return self;
      }
      return self[0] ? self[0].innerText || self[0].textContent : '';
    },
    append: function () {
      return domManipulate(this, arguments, function (node) {
        if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
          this.appendChild(node);
        }
      });
    },
    prepend: function () {
      return domManipulate(this, arguments, function (node) {
        if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
          this.insertBefore(node, this.firstChild);
        }
      }, true);
    },
    before: function () {
      var self = this;
      if (self[0] && self[0].parentNode) {
        return domManipulate(self, arguments, function (node) {
          this.parentNode.insertBefore(node, this);
        });
      }
      return self;
    },
    after: function () {
      var self = this;
      if (self[0] && self[0].parentNode) {
        return domManipulate(self, arguments, function (node) {
          this.parentNode.insertBefore(node, this.nextSibling);
        }, true);
      }
      return self;
    },
    appendTo: function (val) {
      DomQuery(val).append(this);
      return this;
    },
    prependTo: function (val) {
      DomQuery(val).prepend(this);
      return this;
    },
    replaceWith: function (content) {
      return this.before(content).remove();
    },
    wrap: function (content) {
      return wrap(this, content);
    },
    wrapAll: function (content) {
      return wrap(this, content, true);
    },
    wrapInner: function (content) {
      this.each(function () {
        DomQuery(this).contents().wrapAll(content);
      });
      return this;
    },
    unwrap: function () {
      return this.parent().each(function () {
        DomQuery(this).replaceWith(this.childNodes);
      });
    },
    clone: function () {
      var result = [];
      this.each(function () {
        result.push(this.cloneNode(true));
      });
      return DomQuery(result);
    },
    addClass: function (className) {
      return this.toggleClass(className, true);
    },
    removeClass: function (className) {
      return this.toggleClass(className, false);
    },
    toggleClass: function (className, state) {
      var self = this;
      if (typeof className !== 'string') {
        return self;
      }
      if (className.indexOf(' ') !== -1) {
        each$2(className.split(' '), function () {
          self.toggleClass(this, state);
        });
      } else {
        self.each(function (index, node) {
          var existingClassName, classState;
          classState = hasClass(node, className);
          if (classState !== state) {
            existingClassName = node.className;
            if (classState) {
              node.className = trim$1((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
            } else {
              node.className += existingClassName ? ' ' + className : className;
            }
          }
        });
      }
      return self;
    },
    hasClass: function (className) {
      return hasClass(this[0], className);
    },
    each: function (callback) {
      return each$2(this, callback);
    },
    on: function (name, callback) {
      return this.each(function () {
        Event.bind(this, name, callback);
      });
    },
    off: function (name, callback) {
      return this.each(function () {
        Event.unbind(this, name, callback);
      });
    },
    trigger: function (name) {
      return this.each(function () {
        if (typeof name === 'object') {
          Event.fire(this, name.type, name);
        } else {
          Event.fire(this, name);
        }
      });
    },
    show: function () {
      return this.css('display', '');
    },
    hide: function () {
      return this.css('display', 'none');
    },
    slice: function () {
      return new DomQuery(slice$2.apply(this, arguments));
    },
    eq: function (index) {
      return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
    },
    first: function () {
      return this.eq(0);
    },
    last: function () {
      return this.eq(-1);
    },
    find: function (selector) {
      var i, l;
      var ret = [];
      for (i = 0, l = this.length; i < l; i++) {
        DomQuery.find(selector, this[i], ret);
      }
      return DomQuery(ret);
    },
    filter: function (selector) {
      if (typeof selector === 'function') {
        return DomQuery(grep(this.toArray(), function (item, i) {
          return selector(i, item);
        }));
      }
      return DomQuery(DomQuery.filter(selector, this.toArray()));
    },
    closest: function (selector) {
      var result = [];
      if (selector instanceof DomQuery) {
        selector = selector[0];
      }
      this.each(function (i, node) {
        while (node) {
          if (typeof selector === 'string' && DomQuery(node).is(selector)) {
            result.push(node);
            break;
          } else if (node === selector) {
            result.push(node);
            break;
          }
          node = node.parentNode;
        }
      });
      return DomQuery(result);
    },
    offset: function (offset) {
      var elm, doc, docElm;
      var x = 0, y = 0, pos;
      if (!offset) {
        elm = this[0];
        if (elm) {
          doc = elm.ownerDocument;
          docElm = doc.documentElement;
          if (elm.getBoundingClientRect) {
            pos = elm.getBoundingClientRect();
            x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
            y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
          }
        }
        return {
          left: x,
          top: y
        };
      }
      return this.css(offset);
    },
    push: push$2,
    sort: [].sort,
    splice: [].splice
  };
  $_ahowuxkjh8lywbj.extend(DomQuery, {
    extend: $_ahowuxkjh8lywbj.extend,
    makeArray: function (object) {
      if (isWindow(object) || object.nodeType) {
        return [object];
      }
      return $_ahowuxkjh8lywbj.toArray(object);
    },
    inArray: inArray,
    isArray: $_ahowuxkjh8lywbj.isArray,
    each: each$2,
    trim: trim$1,
    grep: grep,
    find: Sizzle,
    expr: Sizzle.selectors,
    unique: Sizzle.uniqueSort,
    text: Sizzle.getText,
    contains: Sizzle.contains,
    filter: function (expr, elems, not) {
      var i = elems.length;
      if (not) {
        expr = ':not(' + expr + ')';
      }
      while (i--) {
        if (elems[i].nodeType !== 1) {
          elems.splice(i, 1);
        }
      }
      if (elems.length === 1) {
        elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
      } else {
        elems = DomQuery.find.matches(expr, elems);
      }
      return elems;
    }
  });
  var dir = function (el, prop, until) {
    var matched = [];
    var cur = el[prop];
    if (typeof until !== 'string' && until instanceof DomQuery) {
      until = until[0];
    }
    while (cur && cur.nodeType !== 9) {
      if (until !== undefined) {
        if (cur === until) {
          break;
        }
        if (typeof until === 'string' && DomQuery(cur).is(until)) {
          break;
        }
      }
      if (cur.nodeType === 1) {
        matched.push(cur);
      }
      cur = cur[prop];
    }
    return matched;
  };
  var sibling = function (node, siblingName, nodeType, until) {
    var result = [];
    if (until instanceof DomQuery) {
      until = until[0];
    }
    for (; node; node = node[siblingName]) {
      if (nodeType && node.nodeType !== nodeType) {
        continue;
      }
      if (until !== undefined) {
        if (node === until) {
          break;
        }
        if (typeof until === 'string' && DomQuery(node).is(until)) {
          break;
        }
      }
      result.push(node);
    }
    return result;
  };
  var firstSibling = function (node, siblingName, nodeType) {
    for (node = node[siblingName]; node; node = node[siblingName]) {
      if (node.nodeType === nodeType) {
        return node;
      }
    }
    return null;
  };
  each$2({
    parent: function (node) {
      var parent = node.parentNode;
      return parent && parent.nodeType !== 11 ? parent : null;
    },
    parents: function (node) {
      return dir(node, 'parentNode');
    },
    next: function (node) {
      return firstSibling(node, 'nextSibling', 1);
    },
    prev: function (node) {
      return firstSibling(node, 'previousSibling', 1);
    },
    children: function (node) {
      return sibling(node.firstChild, 'nextSibling', 1);
    },
    contents: function (node) {
      return $_ahowuxkjh8lywbj.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
    }
  }, function (name, fn) {
    DomQuery.fn[name] = function (selector) {
      var self = this;
      var result = [];
      self.each(function () {
        var nodes = fn.call(result, this, selector, result);
        if (nodes) {
          if (DomQuery.isArray(nodes)) {
            result.push.apply(result, nodes);
          } else {
            result.push(nodes);
          }
        }
      });
      if (this.length > 1) {
        if (!skipUniques[name]) {
          result = DomQuery.unique(result);
        }
        if (name.indexOf('parents') === 0) {
          result = result.reverse();
        }
      }
      result = DomQuery(result);
      if (selector) {
        return result.filter(selector);
      }
      return result;
    };
  });
  each$2({
    parentsUntil: function (node, until) {
      return dir(node, 'parentNode', until);
    },
    nextUntil: function (node, until) {
      return sibling(node, 'nextSibling', 1, until).slice(1);
    },
    prevUntil: function (node, until) {
      return sibling(node, 'previousSibling', 1, until).slice(1);
    }
  }, function (name, fn) {
    DomQuery.fn[name] = function (selector, filter) {
      var self = this;
      var result = [];
      self.each(function () {
        var nodes = fn.call(result, this, selector, result);
        if (nodes) {
          if (DomQuery.isArray(nodes)) {
            result.push.apply(result, nodes);
          } else {
            result.push(nodes);
          }
        }
      });
      if (this.length > 1) {
        result = DomQuery.unique(result);
        if (name.indexOf('parents') === 0 || name === 'prevUntil') {
          result = result.reverse();
        }
      }
      result = DomQuery(result);
      if (filter) {
        return result.filter(filter);
      }
      return result;
    };
  });
  DomQuery.fn.is = function (selector) {
    return !!selector && this.filter(selector).length > 0;
  };
  DomQuery.fn.init.prototype = DomQuery.fn;
  DomQuery.overrideDefaults = function (callback) {
    var defaults;
    var sub = function (selector, context) {
      defaults = defaults || callback();
      if (arguments.length === 0) {
        selector = defaults.element;
      }
      if (!context) {
        context = defaults.context;
      }
      return new sub.fn.init(selector, context);
    };
    DomQuery.extend(sub, this);
    return sub;
  };
  var appendHooks = function (targetHooks, prop, hooks) {
    each$2(hooks, function (name, func) {
      targetHooks[name] = targetHooks[name] || {};
      targetHooks[name][prop] = func;
    });
  };
  if ($_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie < 8) {
    appendHooks(attrHooks, 'get', {
      maxlength: function (elm) {
        var value = elm.maxLength;
        if (value === 2147483647) {
          return undefined;
        }
        return value;
      },
      size: function (elm) {
        var value = elm.size;
        if (value === 20) {
          return undefined;
        }
        return value;
      },
      class: function (elm) {
        return elm.className;
      },
      style: function (elm) {
        var value = elm.style.cssText;
        if (value.length === 0) {
          return undefined;
        }
        return value;
      }
    });
    appendHooks(attrHooks, 'set', {
      class: function (elm, value) {
        elm.className = value;
      },
      style: function (elm, value) {
        elm.style.cssText = value;
      }
    });
  }
  if ($_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie < 9) {
    cssFix.float = 'styleFloat';
    appendHooks(cssHooks, 'set', {
      opacity: function (elm, value) {
        var style = elm.style;
        if (value === null || value === '') {
          style.removeAttribute('filter');
        } else {
          style.zoom = 1;
          style.filter = 'alpha(opacity=' + value * 100 + ')';
        }
      }
    });
  }
  DomQuery.attrHooks = attrHooks;
  DomQuery.cssHooks = cssHooks;

  var cached = function (f) {
    var called = false;
    var r;
    return function () {
      if (!called) {
        called = true;
        r = f.apply(null, arguments);
      }
      return r;
    };
  };
  var $_bbi2igojh8lywc9 = { cached: cached };

  var firstMatch = function (regexes, s) {
    for (var i = 0; i < regexes.length; i++) {
      var x = regexes[i];
      if (x.test(s))
        return x;
    }
    return undefined;
  };
  var find$2 = function (regexes, agent) {
    var r = firstMatch(regexes, agent);
    if (!r)
      return {
        major: 0,
        minor: 0
      };
    var group = function (i) {
      return Number(agent.replace(r, '$' + i));
    };
    return nu(group(1), group(2));
  };
  var detect = function (versionRegexes, agent) {
    var cleanedAgent = String(agent).toLowerCase();
    if (versionRegexes.length === 0)
      return unknown();
    return find$2(versionRegexes, cleanedAgent);
  };
  var unknown = function () {
    return nu(0, 0);
  };
  var nu = function (major, minor) {
    return {
      major: major,
      minor: minor
    };
  };
  var $_a84zfnrjh8lywch = {
    nu: nu,
    detect: detect,
    unknown: unknown
  };

  var edge = 'Edge';
  var chrome = 'Chrome';
  var ie$1 = 'IE';
  var opera$1 = 'Opera';
  var firefox = 'Firefox';
  var safari = 'Safari';
  var isBrowser = function (name, current) {
    return function () {
      return current === name;
    };
  };
  var unknown$1 = function () {
    return nu$1({
      current: undefined,
      version: $_a84zfnrjh8lywch.unknown()
    });
  };
  var nu$1 = function (info) {
    var current = info.current;
    var version = info.version;
    return {
      current: current,
      version: version,
      isEdge: isBrowser(edge, current),
      isChrome: isBrowser(chrome, current),
      isIE: isBrowser(ie$1, current),
      isOpera: isBrowser(opera$1, current),
      isFirefox: isBrowser(firefox, current),
      isSafari: isBrowser(safari, current)
    };
  };
  var $_dckbfzqjh8lywcd = {
    unknown: unknown$1,
    nu: nu$1,
    edge: $_eqpqvr6jh8lyw3s.constant(edge),
    chrome: $_eqpqvr6jh8lyw3s.constant(chrome),
    ie: $_eqpqvr6jh8lyw3s.constant(ie$1),
    opera: $_eqpqvr6jh8lyw3s.constant(opera$1),
    firefox: $_eqpqvr6jh8lyw3s.constant(firefox),
    safari: $_eqpqvr6jh8lyw3s.constant(safari)
  };

  var windows = 'Windows';
  var ios = 'iOS';
  var android$1 = 'Android';
  var linux = 'Linux';
  var osx = 'OSX';
  var solaris = 'Solaris';
  var freebsd = 'FreeBSD';
  var isOS = function (name, current) {
    return function () {
      return current === name;
    };
  };
  var unknown$2 = function () {
    return nu$2({
      current: undefined,
      version: $_a84zfnrjh8lywch.unknown()
    });
  };
  var nu$2 = function (info) {
    var current = info.current;
    var version = info.version;
    return {
      current: current,
      version: version,
      isWindows: isOS(windows, current),
      isiOS: isOS(ios, current),
      isAndroid: isOS(android$1, current),
      isOSX: isOS(osx, current),
      isLinux: isOS(linux, current),
      isSolaris: isOS(solaris, current),
      isFreeBSD: isOS(freebsd, current)
    };
  };
  var $_dixfehsjh8lywcw = {
    unknown: unknown$2,
    nu: nu$2,
    windows: $_eqpqvr6jh8lyw3s.constant(windows),
    ios: $_eqpqvr6jh8lyw3s.constant(ios),
    android: $_eqpqvr6jh8lyw3s.constant(android$1),
    linux: $_eqpqvr6jh8lyw3s.constant(linux),
    osx: $_eqpqvr6jh8lyw3s.constant(osx),
    solaris: $_eqpqvr6jh8lyw3s.constant(solaris),
    freebsd: $_eqpqvr6jh8lyw3s.constant(freebsd)
  };

  function DeviceType (os, browser, userAgent) {
    var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
    var isiPhone = os.isiOS() && !isiPad;
    var isAndroid3 = os.isAndroid() && os.version.major === 3;
    var isAndroid4 = os.isAndroid() && os.version.major === 4;
    var isTablet = isiPad || isAndroid3 || isAndroid4 && /mobile/i.test(userAgent) === true;
    var isTouch = os.isiOS() || os.isAndroid();
    var isPhone = isTouch && !isTablet;
    var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
    return {
      isiPad: $_eqpqvr6jh8lyw3s.constant(isiPad),
      isiPhone: $_eqpqvr6jh8lyw3s.constant(isiPhone),
      isTablet: $_eqpqvr6jh8lyw3s.constant(isTablet),
      isPhone: $_eqpqvr6jh8lyw3s.constant(isPhone),
      isTouch: $_eqpqvr6jh8lyw3s.constant(isTouch),
      isAndroid: os.isAndroid,
      isiOS: os.isiOS,
      isWebView: $_eqpqvr6jh8lyw3s.constant(iOSwebview)
    };
  }

  var detect$1 = function (candidates, userAgent) {
    var agent = String(userAgent).toLowerCase();
    return $_5wjzy24jh8lyw2t.find(candidates, function (candidate) {
      return candidate.search(agent);
    });
  };
  var detectBrowser = function (browsers, userAgent) {
    return detect$1(browsers, userAgent).map(function (browser) {
      var version = $_a84zfnrjh8lywch.detect(browser.versionRegexes, userAgent);
      return {
        current: browser.name,
        version: version
      };
    });
  };
  var detectOs = function (oses, userAgent) {
    return detect$1(oses, userAgent).map(function (os) {
      var version = $_a84zfnrjh8lywch.detect(os.versionRegexes, userAgent);
      return {
        current: os.name,
        version: version
      };
    });
  };
  var $_deu818ujh8lywd4 = {
    detectBrowser: detectBrowser,
    detectOs: detectOs
  };

  var addToStart = function (str, prefix) {
    return prefix + str;
  };
  var addToEnd = function (str, suffix) {
    return str + suffix;
  };
  var removeFromStart = function (str, numChars) {
    return str.substring(numChars);
  };
  var removeFromEnd = function (str, numChars) {
    return str.substring(0, str.length - numChars);
  };
  var $_4h6f09xjh8lywdm = {
    addToStart: addToStart,
    addToEnd: addToEnd,
    removeFromStart: removeFromStart,
    removeFromEnd: removeFromEnd
  };

  var first = function (str, count) {
    return str.substr(0, count);
  };
  var last$2 = function (str, count) {
    return str.substr(str.length - count, str.length);
  };
  var head$1 = function (str) {
    return str === '' ? Option.none() : Option.some(str.substr(0, 1));
  };
  var tail = function (str) {
    return str === '' ? Option.none() : Option.some(str.substring(1));
  };
  var $_amulxnyjh8lywdo = {
    first: first,
    last: last$2,
    head: head$1,
    tail: tail
  };

  var checkRange = function (str, substr, start) {
    if (substr === '')
      return true;
    if (str.length < substr.length)
      return false;
    var x = str.substr(start, start + substr.length);
    return x === substr;
  };
  var supplant = function (str, obj) {
    var isStringOrNumber = function (a) {
      var t = typeof a;
      return t === 'string' || t === 'number';
    };
    return str.replace(/\${([^{}]*)}/g, function (a, b) {
      var value = obj[b];
      return isStringOrNumber(value) ? value : a;
    });
  };
  var removeLeading = function (str, prefix) {
    return startsWith(str, prefix) ? $_4h6f09xjh8lywdm.removeFromStart(str, prefix.length) : str;
  };
  var removeTrailing = function (str, prefix) {
    return endsWith(str, prefix) ? $_4h6f09xjh8lywdm.removeFromEnd(str, prefix.length) : str;
  };
  var ensureLeading = function (str, prefix) {
    return startsWith(str, prefix) ? str : $_4h6f09xjh8lywdm.addToStart(str, prefix);
  };
  var ensureTrailing = function (str, prefix) {
    return endsWith(str, prefix) ? str : $_4h6f09xjh8lywdm.addToEnd(str, prefix);
  };
  var contains$2 = function (str, substr) {
    return str.indexOf(substr) !== -1;
  };
  var capitalize = function (str) {
    return $_amulxnyjh8lywdo.head(str).bind(function (head) {
      return $_amulxnyjh8lywdo.tail(str).map(function (tail) {
        return head.toUpperCase() + tail;
      });
    }).getOr(str);
  };
  var startsWith = function (str, prefix) {
    return checkRange(str, prefix, 0);
  };
  var endsWith = function (str, suffix) {
    return checkRange(str, suffix, str.length - suffix.length);
  };
  var trim$2 = function (str) {
    return str.replace(/^\s+|\s+$/g, '');
  };
  var lTrim = function (str) {
    return str.replace(/^\s+/g, '');
  };
  var rTrim = function (str) {
    return str.replace(/\s+$/g, '');
  };
  var $_4w196awjh8lywdj = {
    supplant: supplant,
    startsWith: startsWith,
    removeLeading: removeLeading,
    removeTrailing: removeTrailing,
    ensureLeading: ensureLeading,
    ensureTrailing: ensureTrailing,
    endsWith: endsWith,
    contains: contains$2,
    trim: trim$2,
    lTrim: lTrim,
    rTrim: rTrim,
    capitalize: capitalize
  };

  var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  var checkContains = function (target) {
    return function (uastring) {
      return $_4w196awjh8lywdj.contains(uastring, target);
    };
  };
  var browsers = [
    {
      name: 'Edge',
      versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
      search: function (uastring) {
        var monstrosity = $_4w196awjh8lywdj.contains(uastring, 'edge/') && $_4w196awjh8lywdj.contains(uastring, 'chrome') && $_4w196awjh8lywdj.contains(uastring, 'safari') && $_4w196awjh8lywdj.contains(uastring, 'applewebkit');
        return monstrosity;
      }
    },
    {
      name: 'Chrome',
      versionRegexes: [
        /.*?chrome\/([0-9]+)\.([0-9]+).*/,
        normalVersionRegex
      ],
      search: function (uastring) {
        return $_4w196awjh8lywdj.contains(uastring, 'chrome') && !$_4w196awjh8lywdj.contains(uastring, 'chromeframe');
      }
    },
    {
      name: 'IE',
      versionRegexes: [
        /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
        /.*?rv:([0-9]+)\.([0-9]+).*/
      ],
      search: function (uastring) {
        return $_4w196awjh8lywdj.contains(uastring, 'msie') || $_4w196awjh8lywdj.contains(uastring, 'trident');
      }
    },
    {
      name: 'Opera',
      versionRegexes: [
        normalVersionRegex,
        /.*?opera\/([0-9]+)\.([0-9]+).*/
      ],
      search: checkContains('opera')
    },
    {
      name: 'Firefox',
      versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
      search: checkContains('firefox')
    },
    {
      name: 'Safari',
      versionRegexes: [
        normalVersionRegex,
        /.*?cpu os ([0-9]+)_([0-9]+).*/
      ],
      search: function (uastring) {
        return ($_4w196awjh8lywdj.contains(uastring, 'safari') || $_4w196awjh8lywdj.contains(uastring, 'mobile/')) && $_4w196awjh8lywdj.contains(uastring, 'applewebkit');
      }
    }
  ];
  var oses = [
    {
      name: 'Windows',
      search: checkContains('win'),
      versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
    },
    {
      name: 'iOS',
      search: function (uastring) {
        return $_4w196awjh8lywdj.contains(uastring, 'iphone') || $_4w196awjh8lywdj.contains(uastring, 'ipad');
      },
      versionRegexes: [
        /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
        /.*cpu os ([0-9]+)_([0-9]+).*/,
        /.*cpu iphone os ([0-9]+)_([0-9]+).*/
      ]
    },
    {
      name: 'Android',
      search: checkContains('android'),
      versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
    },
    {
      name: 'OSX',
      search: checkContains('os x'),
      versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
    },
    {
      name: 'Linux',
      search: checkContains('linux'),
      versionRegexes: []
    },
    {
      name: 'Solaris',
      search: checkContains('sunos'),
      versionRegexes: []
    },
    {
      name: 'FreeBSD',
      search: checkContains('freebsd'),
      versionRegexes: []
    }
  ];
  var $_8gakxrvjh8lywdb = {
    browsers: $_eqpqvr6jh8lyw3s.constant(browsers),
    oses: $_eqpqvr6jh8lyw3s.constant(oses)
  };

  var detect$2 = function (userAgent) {
    var browsers = $_8gakxrvjh8lywdb.browsers();
    var oses = $_8gakxrvjh8lywdb.oses();
    var browser = $_deu818ujh8lywd4.detectBrowser(browsers, userAgent).fold($_dckbfzqjh8lywcd.unknown, $_dckbfzqjh8lywcd.nu);
    var os = $_deu818ujh8lywd4.detectOs(oses, userAgent).fold($_dixfehsjh8lywcw.unknown, $_dixfehsjh8lywcw.nu);
    var deviceType = DeviceType(os, browser, userAgent);
    return {
      browser: browser,
      os: os,
      deviceType: deviceType
    };
  };
  var $_3cj09epjh8lywcb = { detect: detect$2 };

  var detect$3 = $_bbi2igojh8lywc9.cached(function () {
    var userAgent = navigator.userAgent;
    return $_3cj09epjh8lywcb.detect(userAgent);
  });
  var $_9hkktfnjh8lywc6 = { detect: detect$3 };

  var fromHtml = function (html, scope) {
    var doc = scope || document;
    var div = doc.createElement('div');
    div.innerHTML = html;
    if (!div.hasChildNodes() || div.childNodes.length > 1) {
      console.error('HTML does not have a single root node', html);
      throw 'HTML must have a single root node';
    }
    return fromDom(div.childNodes[0]);
  };
  var fromTag = function (tag, scope) {
    var doc = scope || document;
    var node = doc.createElement(tag);
    return fromDom(node);
  };
  var fromText = function (text, scope) {
    var doc = scope || document;
    var node = doc.createTextNode(text);
    return fromDom(node);
  };
  var fromDom = function (node) {
    if (node === null || node === undefined)
      throw new Error('Node cannot be null or undefined');
    return { dom: $_eqpqvr6jh8lyw3s.constant(node) };
  };
  var fromPoint = function (doc, x, y) {
    return Option.from(doc.dom().elementFromPoint(x, y)).map(fromDom);
  };
  var $_cgttw3zjh8lywdq = {
    fromHtml: fromHtml,
    fromTag: fromTag,
    fromText: fromText,
    fromDom: fromDom,
    fromPoint: fromPoint
  };

  var $_2ctxk11jh8lywdy = {
    ATTRIBUTE: 2,
    CDATA_SECTION: 4,
    COMMENT: 8,
    DOCUMENT: 9,
    DOCUMENT_TYPE: 10,
    DOCUMENT_FRAGMENT: 11,
    ELEMENT: 1,
    TEXT: 3,
    PROCESSING_INSTRUCTION: 7,
    ENTITY_REFERENCE: 5,
    ENTITY: 6,
    NOTATION: 12
  };

  var name$1 = function (element) {
    var r = element.dom().nodeName;
    return r.toLowerCase();
  };
  var type = function (element) {
    return element.dom().nodeType;
  };
  var value = function (element) {
    return element.dom().nodeValue;
  };
  var isType$1 = function (t) {
    return function (element) {
      return type(element) === t;
    };
  };
  var isComment = function (element) {
    return type(element) === $_2ctxk11jh8lywdy.COMMENT || name$1(element) === '#comment';
  };
  var isElement = isType$1($_2ctxk11jh8lywdy.ELEMENT);
  var isText = isType$1($_2ctxk11jh8lywdy.TEXT);
  var isDocument = isType$1($_2ctxk11jh8lywdy.DOCUMENT);
  var $_7j1jt210jh8lywdx = {
    name: name$1,
    type: type,
    value: value,
    isElement: isElement,
    isText: isText,
    isDocument: isDocument,
    isComment: isComment
  };

  var keys = function () {
    var fastKeys = Object.keys;
    var slowKeys = function (o) {
      var r = [];
      for (var i in o) {
        if (o.hasOwnProperty(i)) {
          r.push(i);
        }
      }
      return r;
    };
    return fastKeys === undefined ? slowKeys : fastKeys;
  }();
  var each$3 = function (obj, f) {
    var props = keys(obj);
    for (var k = 0, len = props.length; k < len; k++) {
      var i = props[k];
      var x = obj[i];
      f(x, i, obj);
    }
  };
  var objectMap = function (obj, f) {
    return tupleMap(obj, function (x, i, obj) {
      return {
        k: i,
        v: f(x, i, obj)
      };
    });
  };
  var tupleMap = function (obj, f) {
    var r = {};
    each$3(obj, function (x, i) {
      var tuple = f(x, i, obj);
      r[tuple.k] = tuple.v;
    });
    return r;
  };
  var bifilter = function (obj, pred) {
    var t = {};
    var f = {};
    each$3(obj, function (x, i) {
      var branch = pred(x, i) ? t : f;
      branch[i] = x;
    });
    return {
      t: t,
      f: f
    };
  };
  var mapToArray = function (obj, f) {
    var r = [];
    each$3(obj, function (value, name) {
      r.push(f(value, name));
    });
    return r;
  };
  var find$3 = function (obj, pred) {
    var props = keys(obj);
    for (var k = 0, len = props.length; k < len; k++) {
      var i = props[k];
      var x = obj[i];
      if (pred(x, i, obj)) {
        return Option.some(x);
      }
    }
    return Option.none();
  };
  var values = function (obj) {
    return mapToArray(obj, function (v) {
      return v;
    });
  };
  var size = function (obj) {
    return values(obj).length;
  };
  var $_g63v2c13jh8lywej = {
    bifilter: bifilter,
    each: each$3,
    map: objectMap,
    mapToArray: mapToArray,
    tupleMap: tupleMap,
    find: find$3,
    keys: keys,
    values: values,
    size: size
  };

  var rawSet = function (dom, key, value) {
    if ($_dp4g6d7jh8lyw3y.isString(value) || $_dp4g6d7jh8lyw3y.isBoolean(value) || $_dp4g6d7jh8lyw3y.isNumber(value)) {
      dom.setAttribute(key, value + '');
    } else {
      console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
      throw new Error('Attribute value was not simple');
    }
  };
  var set = function (element, key, value) {
    rawSet(element.dom(), key, value);
  };
  var setAll = function (element, attrs) {
    var dom = element.dom();
    $_g63v2c13jh8lywej.each(attrs, function (v, k) {
      rawSet(dom, k, v);
    });
  };
  var get = function (element, key) {
    var v = element.dom().getAttribute(key);
    return v === null ? undefined : v;
  };
  var has = function (element, key) {
    var dom = element.dom();
    return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  };
  var remove = function (element, key) {
    element.dom().removeAttribute(key);
  };
  var hasNone = function (element) {
    var attrs = element.dom().attributes;
    return attrs === undefined || attrs === null || attrs.length === 0;
  };
  var clone = function (element) {
    return $_5wjzy24jh8lyw2t.foldl(element.dom().attributes, function (acc, attr) {
      acc[attr.name] = attr.value;
      return acc;
    }, {});
  };
  var transferOne = function (source, destination, attr) {
    if (has(source, attr) && !has(destination, attr))
      set(destination, attr, get(source, attr));
  };
  var transfer = function (source, destination, attrs) {
    if (!$_7j1jt210jh8lywdx.isElement(source) || !$_7j1jt210jh8lywdx.isElement(destination))
      return;
    $_5wjzy24jh8lyw2t.each(attrs, function (attr) {
      transferOne(source, destination, attr);
    });
  };
  var $_3da62i14jh8lyweo = {
    clone: clone,
    set: set,
    setAll: setAll,
    get: get,
    has: has,
    remove: remove,
    hasNone: hasNone,
    transfer: transfer
  };

  var inBody = function (element) {
    var dom = $_7j1jt210jh8lywdx.isText(element) ? element.dom().parentNode : element.dom();
    return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  };
  var body = $_bbi2igojh8lywc9.cached(function () {
    return getBody($_cgttw3zjh8lywdq.fromDom(document));
  });
  var getBody = function (doc) {
    var body = doc.dom().body;
    if (body === null || body === undefined)
      throw 'Body is not available yet';
    return $_cgttw3zjh8lywdq.fromDom(body);
  };
  var $_boa99a15jh8lywey = {
    body: body,
    getBody: getBody,
    inBody: inBody
  };

  var isSupported = function (dom) {
    return dom.style !== undefined;
  };
  var $_fjd24o16jh8lywfc = { isSupported: isSupported };

  var internalSet = function (dom, property, value) {
    if (!$_dp4g6d7jh8lyw3y.isString(value)) {
      console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
      throw new Error('CSS value must be a string: ' + value);
    }
    if ($_fjd24o16jh8lywfc.isSupported(dom))
      dom.style.setProperty(property, value);
  };
  var internalRemove = function (dom, property) {
    if ($_fjd24o16jh8lywfc.isSupported(dom))
      dom.style.removeProperty(property);
  };
  var set$1 = function (element, property, value) {
    var dom = element.dom();
    internalSet(dom, property, value);
  };
  var setAll$1 = function (element, css) {
    var dom = element.dom();
    $_g63v2c13jh8lywej.each(css, function (v, k) {
      internalSet(dom, k, v);
    });
  };
  var setOptions = function (element, css) {
    var dom = element.dom();
    $_g63v2c13jh8lywej.each(css, function (v, k) {
      v.fold(function () {
        internalRemove(dom, k);
      }, function (value) {
        internalSet(dom, k, value);
      });
    });
  };
  var get$1 = function (element, property) {
    var dom = element.dom();
    var styles = window.getComputedStyle(dom);
    var r = styles.getPropertyValue(property);
    var v = r === '' && !$_boa99a15jh8lywey.inBody(element) ? getUnsafeProperty(dom, property) : r;
    return v === null ? undefined : v;
  };
  var getUnsafeProperty = function (dom, property) {
    return $_fjd24o16jh8lywfc.isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  };
  var getRaw = function (element, property) {
    var dom = element.dom();
    var raw = getUnsafeProperty(dom, property);
    return Option.from(raw).filter(function (r) {
      return r.length > 0;
    });
  };
  var getAllRaw = function (element) {
    var css = {};
    var dom = element.dom();
    if ($_fjd24o16jh8lywfc.isSupported(dom)) {
      for (var i = 0; i < dom.style.length; i++) {
        var ruleName = dom.style.item(i);
        css[ruleName] = dom.style[ruleName];
      }
    }
    return css;
  };
  var isValidValue = function (tag, property, value) {
    var element = $_cgttw3zjh8lywdq.fromTag(tag);
    set$1(element, property, value);
    var style = getRaw(element, property);
    return style.isSome();
  };
  var remove$1 = function (element, property) {
    var dom = element.dom();
    internalRemove(dom, property);
    if ($_3da62i14jh8lyweo.has(element, 'style') && $_4w196awjh8lywdj.trim($_3da62i14jh8lyweo.get(element, 'style')) === '') {
      $_3da62i14jh8lyweo.remove(element, 'style');
    }
  };
  var preserve = function (element, f) {
    var oldStyles = $_3da62i14jh8lyweo.get(element, 'style');
    var result = f(element);
    var restore = oldStyles === undefined ? $_3da62i14jh8lyweo.remove : $_3da62i14jh8lyweo.set;
    restore(element, 'style', oldStyles);
    return result;
  };
  var copy = function (source, target) {
    var sourceDom = source.dom();
    var targetDom = target.dom();
    if ($_fjd24o16jh8lywfc.isSupported(sourceDom) && $_fjd24o16jh8lywfc.isSupported(targetDom)) {
      targetDom.style.cssText = sourceDom.style.cssText;
    }
  };
  var reflow = function (e) {
    return e.dom().offsetWidth;
  };
  var transferOne$1 = function (source, destination, style) {
    getRaw(source, style).each(function (value) {
      if (getRaw(destination, style).isNone())
        set$1(destination, style, value);
    });
  };
  var transfer$1 = function (source, destination, styles) {
    if (!$_7j1jt210jh8lywdx.isElement(source) || !$_7j1jt210jh8lywdx.isElement(destination))
      return;
    $_5wjzy24jh8lyw2t.each(styles, function (style) {
      transferOne$1(source, destination, style);
    });
  };
  var $_36knnd12jh8lywe1 = {
    copy: copy,
    set: set$1,
    preserve: preserve,
    setAll: setAll$1,
    setOptions: setOptions,
    remove: remove$1,
    get: get$1,
    getRaw: getRaw,
    getAllRaw: getAllRaw,
    isValidValue: isValidValue,
    reflow: reflow,
    transfer: transfer$1
  };

  function Immutable () {
    var fields = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      fields[_i] = arguments[_i];
    }
    return function () {
      var values = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        values[_i] = arguments[_i];
      }
      if (fields.length !== values.length) {
        throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
      }
      var struct = {};
      $_5wjzy24jh8lyw2t.each(fields, function (name, i) {
        struct[name] = $_eqpqvr6jh8lyw3s.constant(values[i]);
      });
      return struct;
    };
  }

  var sort$1 = function (arr) {
    return arr.slice(0).sort();
  };
  var reqMessage = function (required, keys) {
    throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
  };
  var unsuppMessage = function (unsupported) {
    throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
  };
  var validateStrArr = function (label, array) {
    if (!$_dp4g6d7jh8lyw3y.isArray(array))
      throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
    $_5wjzy24jh8lyw2t.each(array, function (a) {
      if (!$_dp4g6d7jh8lyw3y.isString(a))
        throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
    });
  };
  var invalidTypeMessage = function (incorrect, type) {
    throw new Error('All values need to be of type: ' + type + '. Keys (' + sort$1(incorrect).join(', ') + ') were not.');
  };
  var checkDupes = function (everything) {
    var sorted = sort$1(everything);
    var dupe = $_5wjzy24jh8lyw2t.find(sorted, function (s, i) {
      return i < sorted.length - 1 && s === sorted[i + 1];
    });
    dupe.each(function (d) {
      throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
    });
  };
  var $_8ab5mm1bjh8lywg2 = {
    sort: sort$1,
    reqMessage: reqMessage,
    unsuppMessage: unsuppMessage,
    validateStrArr: validateStrArr,
    invalidTypeMessage: invalidTypeMessage,
    checkDupes: checkDupes
  };

  function MixedBag (required, optional) {
    var everything = required.concat(optional);
    if (everything.length === 0)
      throw new Error('You must specify at least one required or optional field.');
    $_8ab5mm1bjh8lywg2.validateStrArr('required', required);
    $_8ab5mm1bjh8lywg2.validateStrArr('optional', optional);
    $_8ab5mm1bjh8lywg2.checkDupes(everything);
    return function (obj) {
      var keys = $_g63v2c13jh8lywej.keys(obj);
      var allReqd = $_5wjzy24jh8lyw2t.forall(required, function (req) {
        return $_5wjzy24jh8lyw2t.contains(keys, req);
      });
      if (!allReqd)
        $_8ab5mm1bjh8lywg2.reqMessage(required, keys);
      var unsupported = $_5wjzy24jh8lyw2t.filter(keys, function (key) {
        return !$_5wjzy24jh8lyw2t.contains(everything, key);
      });
      if (unsupported.length > 0)
        $_8ab5mm1bjh8lywg2.unsuppMessage(unsupported);
      var r = {};
      $_5wjzy24jh8lyw2t.each(required, function (req) {
        r[req] = $_eqpqvr6jh8lyw3s.constant(obj[req]);
      });
      $_5wjzy24jh8lyw2t.each(optional, function (opt) {
        r[opt] = $_eqpqvr6jh8lyw3s.constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
      });
      return r;
    };
  }

  var $_4jz0ce18jh8lywft = {
    immutable: Immutable,
    immutableBag: MixedBag
  };

  var toArray$1 = function (target, f) {
    var r = [];
    var recurse = function (e) {
      r.push(e);
      return f(e);
    };
    var cur = f(target);
    do {
      cur = cur.bind(recurse);
    } while (cur.isSome());
    return r;
  };
  var $_42xx4d1cjh8lywg4 = { toArray: toArray$1 };

  var node = function () {
    var f = $_99xmy7cjh8lyw6k.getOrDie('Node');
    return f;
  };
  var compareDocumentPosition = function (a, b, match) {
    return (a.compareDocumentPosition(b) & match) !== 0;
  };
  var documentPositionPreceding = function (a, b) {
    return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_PRECEDING);
  };
  var documentPositionContainedBy = function (a, b) {
    return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_CONTAINED_BY);
  };
  var $_1zkvjk1ejh8lywgg = {
    documentPositionPreceding: documentPositionPreceding,
    documentPositionContainedBy: documentPositionContainedBy
  };

  var ELEMENT = $_2ctxk11jh8lywdy.ELEMENT;
  var DOCUMENT = $_2ctxk11jh8lywdy.DOCUMENT;
  var is$1 = function (element, selector) {
    var elem = element.dom();
    if (elem.nodeType !== ELEMENT)
      return false;
    else if (elem.matches !== undefined)
      return elem.matches(selector);
    else if (elem.msMatchesSelector !== undefined)
      return elem.msMatchesSelector(selector);
    else if (elem.webkitMatchesSelector !== undefined)
      return elem.webkitMatchesSelector(selector);
    else if (elem.mozMatchesSelector !== undefined)
      return elem.mozMatchesSelector(selector);
    else
      throw new Error('Browser lacks native selectors');
  };
  var bypassSelector = function (dom) {
    return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT || dom.childElementCount === 0;
  };
  var all = function (selector, scope) {
    var base = scope === undefined ? document : scope.dom();
    return bypassSelector(base) ? [] : $_5wjzy24jh8lyw2t.map(base.querySelectorAll(selector), $_cgttw3zjh8lywdq.fromDom);
  };
  var one = function (selector, scope) {
    var base = scope === undefined ? document : scope.dom();
    return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map($_cgttw3zjh8lywdq.fromDom);
  };
  var $_5h4ipt1fjh8lywgi = {
    all: all,
    is: is$1,
    one: one
  };

  var eq = function (e1, e2) {
    return e1.dom() === e2.dom();
  };
  var isEqualNode = function (e1, e2) {
    return e1.dom().isEqualNode(e2.dom());
  };
  var member = function (element, elements) {
    return $_5wjzy24jh8lyw2t.exists(elements, $_eqpqvr6jh8lyw3s.curry(eq, element));
  };
  var regularContains = function (e1, e2) {
    var d1 = e1.dom(), d2 = e2.dom();
    return d1 === d2 ? false : d1.contains(d2);
  };
  var ieContains = function (e1, e2) {
    return $_1zkvjk1ejh8lywgg.documentPositionContainedBy(e1.dom(), e2.dom());
  };
  var browser = $_9hkktfnjh8lywc6.detect().browser;
  var contains$3 = browser.isIE() ? ieContains : regularContains;
  var $_5f6gpb1djh8lywg5 = {
    eq: eq,
    isEqualNode: isEqualNode,
    member: member,
    contains: contains$3,
    is: $_5h4ipt1fjh8lywgi.is
  };

  var owner = function (element) {
    return $_cgttw3zjh8lywdq.fromDom(element.dom().ownerDocument);
  };
  var documentElement = function (element) {
    var doc = owner(element);
    return $_cgttw3zjh8lywdq.fromDom(doc.dom().documentElement);
  };
  var defaultView = function (element) {
    var el = element.dom();
    var defaultView = el.ownerDocument.defaultView;
    return $_cgttw3zjh8lywdq.fromDom(defaultView);
  };
  var parent = function (element) {
    var dom = element.dom();
    return Option.from(dom.parentNode).map($_cgttw3zjh8lywdq.fromDom);
  };
  var findIndex$2 = function (element) {
    return parent(element).bind(function (p) {
      var kin = children(p);
      return $_5wjzy24jh8lyw2t.findIndex(kin, function (elem) {
        return $_5f6gpb1djh8lywg5.eq(element, elem);
      });
    });
  };
  var parents = function (element, isRoot) {
    var stop = $_dp4g6d7jh8lyw3y.isFunction(isRoot) ? isRoot : $_eqpqvr6jh8lyw3s.constant(false);
    var dom = element.dom();
    var ret = [];
    while (dom.parentNode !== null && dom.parentNode !== undefined) {
      var rawParent = dom.parentNode;
      var parent = $_cgttw3zjh8lywdq.fromDom(rawParent);
      ret.push(parent);
      if (stop(parent) === true)
        break;
      else
        dom = rawParent;
    }
    return ret;
  };
  var siblings = function (element) {
    var filterSelf = function (elements) {
      return $_5wjzy24jh8lyw2t.filter(elements, function (x) {
        return !$_5f6gpb1djh8lywg5.eq(element, x);
      });
    };
    return parent(element).map(children).map(filterSelf).getOr([]);
  };
  var offsetParent = function (element) {
    var dom = element.dom();
    return Option.from(dom.offsetParent).map($_cgttw3zjh8lywdq.fromDom);
  };
  var prevSibling = function (element) {
    var dom = element.dom();
    return Option.from(dom.previousSibling).map($_cgttw3zjh8lywdq.fromDom);
  };
  var nextSibling = function (element) {
    var dom = element.dom();
    return Option.from(dom.nextSibling).map($_cgttw3zjh8lywdq.fromDom);
  };
  var prevSiblings = function (element) {
    return $_5wjzy24jh8lyw2t.reverse($_42xx4d1cjh8lywg4.toArray(element, prevSibling));
  };
  var nextSiblings = function (element) {
    return $_42xx4d1cjh8lywg4.toArray(element, nextSibling);
  };
  var children = function (element) {
    var dom = element.dom();
    return $_5wjzy24jh8lyw2t.map(dom.childNodes, $_cgttw3zjh8lywdq.fromDom);
  };
  var child = function (element, index) {
    var children = element.dom().childNodes;
    return Option.from(children[index]).map($_cgttw3zjh8lywdq.fromDom);
  };
  var firstChild = function (element) {
    return child(element, 0);
  };
  var lastChild = function (element) {
    return child(element, element.dom().childNodes.length - 1);
  };
  var childNodesCount = function (element) {
    return element.dom().childNodes.length;
  };
  var hasChildNodes = function (element) {
    return element.dom().hasChildNodes();
  };
  var spot = $_4jz0ce18jh8lywft.immutable('element', 'offset');
  var leaf = function (element, offset) {
    var cs = children(element);
    return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  };
  var $_a43q0i17jh8lywfe = {
    owner: owner,
    defaultView: defaultView,
    documentElement: documentElement,
    parent: parent,
    findIndex: findIndex$2,
    parents: parents,
    siblings: siblings,
    prevSibling: prevSibling,
    offsetParent: offsetParent,
    prevSiblings: prevSiblings,
    nextSibling: nextSibling,
    nextSiblings: nextSiblings,
    children: children,
    child: child,
    firstChild: firstChild,
    lastChild: lastChild,
    childNodesCount: childNodesCount,
    hasChildNodes: hasChildNodes,
    leaf: leaf
  };

  var browser$1 = $_9hkktfnjh8lywc6.detect().browser;
  var firstElement = function (nodes) {
    return $_5wjzy24jh8lyw2t.find(nodes, $_7j1jt210jh8lywdx.isElement);
  };
  var getTableCaptionDeltaY = function (elm) {
    if (browser$1.isFirefox() && $_7j1jt210jh8lywdx.name(elm) === 'table') {
      return firstElement($_a43q0i17jh8lywfe.children(elm)).filter(function (elm) {
        return $_7j1jt210jh8lywdx.name(elm) === 'caption';
      }).bind(function (caption) {
        return firstElement($_a43q0i17jh8lywfe.nextSiblings(caption)).map(function (body) {
          var bodyTop = body.dom().offsetTop;
          var captionTop = caption.dom().offsetTop;
          var captionHeight = caption.dom().offsetHeight;
          return bodyTop <= captionTop ? -captionHeight : 0;
        });
      }).getOr(0);
    } else {
      return 0;
    }
  };
  var getPos = function (body, elm, rootElm) {
    var x = 0, y = 0, offsetParent;
    var doc = body.ownerDocument;
    var pos;
    rootElm = rootElm ? rootElm : body;
    if (elm) {
      if (rootElm === body && elm.getBoundingClientRect && $_36knnd12jh8lywe1.get($_cgttw3zjh8lywdq.fromDom(body), 'position') === 'static') {
        pos = elm.getBoundingClientRect();
        x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
        y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
        return {
          x: x,
          y: y
        };
      }
      offsetParent = elm;
      while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType) {
        x += offsetParent.offsetLeft || 0;
        y += offsetParent.offsetTop || 0;
        offsetParent = offsetParent.offsetParent;
      }
      offsetParent = elm.parentNode;
      while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType) {
        x -= offsetParent.scrollLeft || 0;
        y -= offsetParent.scrollTop || 0;
        offsetParent = offsetParent.parentNode;
      }
      y += getTableCaptionDeltaY($_cgttw3zjh8lywdq.fromDom(elm));
    }
    return {
      x: x,
      y: y
    };
  };
  var $_6pe7rlmjh8lywbu = { getPos: getPos };

  var nu$3 = function (baseFn) {
    var data = Option.none();
    var callbacks = [];
    var map = function (f) {
      return nu$3(function (nCallback) {
        get(function (data) {
          nCallback(f(data));
        });
      });
    };
    var get = function (nCallback) {
      if (isReady())
        call(nCallback);
      else
        callbacks.push(nCallback);
    };
    var set = function (x) {
      data = Option.some(x);
      run(callbacks);
      callbacks = [];
    };
    var isReady = function () {
      return data.isSome();
    };
    var run = function (cbs) {
      $_5wjzy24jh8lyw2t.each(cbs, call);
    };
    var call = function (cb) {
      data.each(function (x) {
        setTimeout(function () {
          cb(x);
        }, 0);
      });
    };
    baseFn(set);
    return {
      get: get,
      map: map,
      isReady: isReady
    };
  };
  var pure$1 = function (a) {
    return nu$3(function (callback) {
      callback(a);
    });
  };
  var LazyValue = {
    nu: nu$3,
    pure: pure$1
  };

  var bounce = function (f) {
    return function () {
      var args = Array.prototype.slice.call(arguments);
      var me = this;
      setTimeout(function () {
        f.apply(me, args);
      }, 0);
    };
  };
  var $_fhsj121jjh8lywh5 = { bounce: bounce };

  var nu$4 = function (baseFn) {
    var get = function (callback) {
      baseFn($_fhsj121jjh8lywh5.bounce(callback));
    };
    var map = function (fab) {
      return nu$4(function (callback) {
        get(function (a) {
          var value = fab(a);
          callback(value);
        });
      });
    };
    var bind = function (aFutureB) {
      return nu$4(function (callback) {
        get(function (a) {
          aFutureB(a).get(callback);
        });
      });
    };
    var anonBind = function (futureB) {
      return nu$4(function (callback) {
        get(function (a) {
          futureB.get(callback);
        });
      });
    };
    var toLazy = function () {
      return LazyValue.nu(get);
    };
    return {
      map: map,
      bind: bind,
      anonBind: anonBind,
      toLazy: toLazy,
      get: get
    };
  };
  var pure$2 = function (a) {
    return nu$4(function (callback) {
      callback(a);
    });
  };
  var Future = {
    nu: nu$4,
    pure: pure$2
  };

  var par = function (asyncValues, nu) {
    return nu(function (callback) {
      var r = [];
      var count = 0;
      var cb = function (i) {
        return function (value) {
          r[i] = value;
          count++;
          if (count >= asyncValues.length) {
            callback(r);
          }
        };
      };
      if (asyncValues.length === 0) {
        callback([]);
      } else {
        $_5wjzy24jh8lyw2t.each(asyncValues, function (asyncValue, i) {
          asyncValue.get(cb(i));
        });
      }
    });
  };
  var $_8nbwrm1ljh8lywh8 = { par: par };

  var par$1 = function (futures) {
    return $_8nbwrm1ljh8lywh8.par(futures, Future.nu);
  };
  var mapM = function (array, fn) {
    var futures = $_5wjzy24jh8lyw2t.map(array, fn);
    return par$1(futures);
  };
  var compose$1 = function (f, g) {
    return function (a) {
      return g(a).bind(f);
    };
  };
  var $_5lpsz51kjh8lywh6 = {
    par: par$1,
    mapM: mapM,
    compose: compose$1
  };

  var value$1 = function (o) {
    var is = function (v) {
      return o === v;
    };
    var or = function (opt) {
      return value$1(o);
    };
    var orThunk = function (f) {
      return value$1(o);
    };
    var map = function (f) {
      return value$1(f(o));
    };
    var each = function (f) {
      f(o);
    };
    var bind = function (f) {
      return f(o);
    };
    var fold = function (_, onValue) {
      return onValue(o);
    };
    var exists = function (f) {
      return f(o);
    };
    var forall = function (f) {
      return f(o);
    };
    var toOption = function () {
      return Option.some(o);
    };
    return {
      is: is,
      isValue: $_eqpqvr6jh8lyw3s.always,
      isError: $_eqpqvr6jh8lyw3s.never,
      getOr: $_eqpqvr6jh8lyw3s.constant(o),
      getOrThunk: $_eqpqvr6jh8lyw3s.constant(o),
      getOrDie: $_eqpqvr6jh8lyw3s.constant(o),
      or: or,
      orThunk: orThunk,
      fold: fold,
      map: map,
      each: each,
      bind: bind,
      exists: exists,
      forall: forall,
      toOption: toOption
    };
  };
  var error = function (message) {
    var getOrThunk = function (f) {
      return f();
    };
    var getOrDie = function () {
      return $_eqpqvr6jh8lyw3s.die(String(message))();
    };
    var or = function (opt) {
      return opt;
    };
    var orThunk = function (f) {
      return f();
    };
    var map = function (f) {
      return error(message);
    };
    var bind = function (f) {
      return error(message);
    };
    var fold = function (onError, _) {
      return onError(message);
    };
    return {
      is: $_eqpqvr6jh8lyw3s.never,
      isValue: $_eqpqvr6jh8lyw3s.never,
      isError: $_eqpqvr6jh8lyw3s.always,
      getOr: $_eqpqvr6jh8lyw3s.identity,
      getOrThunk: getOrThunk,
      getOrDie: getOrDie,
      or: or,
      orThunk: orThunk,
      fold: fold,
      map: map,
      each: $_eqpqvr6jh8lyw3s.noop,
      bind: bind,
      exists: $_eqpqvr6jh8lyw3s.never,
      forall: $_eqpqvr6jh8lyw3s.always,
      toOption: Option.none
    };
  };
  var Result = {
    value: value$1,
    error: error
  };

  function StyleSheetLoader(document, settings) {
    var idCount = 0;
    var loadedStates = {};
    var maxLoadTime;
    settings = settings || {};
    maxLoadTime = settings.maxLoadTime || 5000;
    var appendToHead = function (node) {
      document.getElementsByTagName('head')[0].appendChild(node);
    };
    var load = function (url, loadedCallback, errorCallback) {
      var link, style, startTime, state;
      var passed = function () {
        var callbacks = state.passed;
        var i = callbacks.length;
        while (i--) {
          callbacks[i]();
        }
        state.status = 2;
        state.passed = [];
        state.failed = [];
      };
      var failed = function () {
        var callbacks = state.failed;
        var i = callbacks.length;
        while (i--) {
          callbacks[i]();
        }
        state.status = 3;
        state.passed = [];
        state.failed = [];
      };
      var isOldWebKit = function () {
        var webKitChunks = navigator.userAgent.match(/WebKit\/(\d*)/);
        return !!(webKitChunks && parseInt(webKitChunks[1], 10) < 536);
      };
      var wait = function (testCallback, waitCallback) {
        if (!testCallback()) {
          if (new Date().getTime() - startTime < maxLoadTime) {
            $_8sy3pfhjh8lyw95.setTimeout(waitCallback);
          } else {
            failed();
          }
        }
      };
      var waitForWebKitLinkLoaded = function () {
        wait(function () {
          var styleSheets = document.styleSheets;
          var styleSheet, i = styleSheets.length, owner;
          while (i--) {
            styleSheet = styleSheets[i];
            owner = styleSheet.ownerNode ? styleSheet.ownerNode : styleSheet.owningElement;
            if (owner && owner.id === link.id) {
              passed();
              return true;
            }
          }
        }, waitForWebKitLinkLoaded);
      };
      var waitForGeckoLinkLoaded = function () {
        wait(function () {
          try {
            var cssRules = style.sheet.cssRules;
            passed();
            return !!cssRules;
          } catch (ex) {
          }
        }, waitForGeckoLinkLoaded);
      };
      url = $_ahowuxkjh8lywbj._addCacheSuffix(url);
      if (!loadedStates[url]) {
        state = {
          passed: [],
          failed: []
        };
        loadedStates[url] = state;
      } else {
        state = loadedStates[url];
      }
      if (loadedCallback) {
        state.passed.push(loadedCallback);
      }
      if (errorCallback) {
        state.failed.push(errorCallback);
      }
      if (state.status === 1) {
        return;
      }
      if (state.status === 2) {
        passed();
        return;
      }
      if (state.status === 3) {
        failed();
        return;
      }
      state.status = 1;
      link = document.createElement('link');
      link.rel = 'stylesheet';
      link.type = 'text/css';
      link.id = 'u' + idCount++;
      link.async = false;
      link.defer = false;
      startTime = new Date().getTime();
      if ('onload' in link && !isOldWebKit()) {
        link.onload = waitForWebKitLinkLoaded;
        link.onerror = failed;
      } else {
        if (navigator.userAgent.indexOf('Firefox') > 0) {
          style = document.createElement('style');
          style.textContent = '@import "' + url + '"';
          waitForGeckoLinkLoaded();
          appendToHead(style);
          return;
        }
        waitForWebKitLinkLoaded();
      }
      appendToHead(link);
      link.href = url;
    };
    var loadF = function (url) {
      return Future.nu(function (resolve) {
        load(url, $_eqpqvr6jh8lyw3s.compose(resolve, $_eqpqvr6jh8lyw3s.constant(Result.value(url))), $_eqpqvr6jh8lyw3s.compose(resolve, $_eqpqvr6jh8lyw3s.constant(Result.error(url))));
      });
    };
    var unbox = function (result) {
      return result.fold($_eqpqvr6jh8lyw3s.identity, $_eqpqvr6jh8lyw3s.identity);
    };
    var loadAll = function (urls, success, failure) {
      $_5lpsz51kjh8lywh6.par($_5wjzy24jh8lyw2t.map(urls, loadF)).get(function (result) {
        var parts = $_5wjzy24jh8lyw2t.partition(result, function (r) {
          return r.isValue();
        });
        if (parts.fail.length > 0) {
          failure(parts.fail.map(unbox));
        } else {
          success(parts.pass.map(unbox));
        }
      });
    };
    return {
      load: load,
      loadAll: loadAll
    };
  }

  function TreeWalker (startNode, rootNode) {
    var node = startNode;
    var findSibling = function (node, startName, siblingName, shallow) {
      var sibling, parent;
      if (node) {
        if (!shallow && node[startName]) {
          return node[startName];
        }
        if (node !== rootNode) {
          sibling = node[siblingName];
          if (sibling) {
            return sibling;
          }
          for (parent = node.parentNode; parent && parent !== rootNode; parent = parent.parentNode) {
            sibling = parent[siblingName];
            if (sibling) {
              return sibling;
            }
          }
        }
      }
    };
    var findPreviousNode = function (node, startName, siblingName, shallow) {
      var sibling, parent, child;
      if (node) {
        sibling = node[siblingName];
        if (rootNode && sibling === rootNode) {
          return;
        }
        if (sibling) {
          if (!shallow) {
            for (child = sibling[startName]; child; child = child[startName]) {
              if (!child[startName]) {
                return child;
              }
            }
          }
          return sibling;
        }
        parent = node.parentNode;
        if (parent && parent !== rootNode) {
          return parent;
        }
      }
    };
    this.current = function () {
      return node;
    };
    this.next = function (shallow) {
      node = findSibling(node, 'firstChild', 'nextSibling', shallow);
      return node;
    };
    this.prev = function (shallow) {
      node = findSibling(node, 'lastChild', 'previousSibling', shallow);
      return node;
    };
    this.prev2 = function (shallow) {
      node = findPreviousNode(node, 'lastChild', 'previousSibling', shallow);
      return node;
    };
  }

  var blocks = [
    'article',
    'aside',
    'details',
    'div',
    'dt',
    'figcaption',
    'footer',
    'form',
    'fieldset',
    'header',
    'hgroup',
    'html',
    'main',
    'nav',
    'section',
    'summary',
    'body',
    'p',
    'dl',
    'multicol',
    'dd',
    'figure',
    'address',
    'center',
    'blockquote',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'listing',
    'xmp',
    'pre',
    'plaintext',
    'menu',
    'dir',
    'ul',
    'ol',
    'li',
    'hr',
    'table',
    'tbody',
    'thead',
    'tfoot',
    'th',
    'tr',
    'td',
    'caption'
  ];
  var voids = [
    'area',
    'base',
    'basefont',
    'br',
    'col',
    'frame',
    'hr',
    'img',
    'input',
    'isindex',
    'link',
    'meta',
    'param',
    'embed',
    'source',
    'wbr',
    'track'
  ];
  var tableCells = [
    'td',
    'th'
  ];
  var tableSections = [
    'thead',
    'tbody',
    'tfoot'
  ];
  var textBlocks = [
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'p',
    'div',
    'address',
    'pre',
    'form',
    'blockquote',
    'center',
    'dir',
    'fieldset',
    'header',
    'footer',
    'article',
    'section',
    'hgroup',
    'aside',
    'nav',
    'figure'
  ];
  var headings = [
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6'
  ];
  var listItems = [
    'li',
    'dd',
    'dt'
  ];
  var lists = [
    'ul',
    'ol',
    'dl'
  ];
  var wsElements = [
    'pre',
    'script',
    'textarea',
    'style'
  ];
  var lazyLookup = function (items) {
    var lookup;
    return function (node) {
      lookup = lookup ? lookup : $_5wjzy24jh8lyw2t.mapToObject(items, $_eqpqvr6jh8lyw3s.constant(true));
      return lookup.hasOwnProperty($_7j1jt210jh8lywdx.name(node));
    };
  };
  var isHeading = lazyLookup(headings);
  var isBlock = lazyLookup(blocks);
  var isInline = function (node) {
    return $_7j1jt210jh8lywdx.isElement(node) && !isBlock(node);
  };
  var isBr = function (node) {
    return $_7j1jt210jh8lywdx.isElement(node) && $_7j1jt210jh8lywdx.name(node) === 'br';
  };
  var isTextBlock = lazyLookup(textBlocks);
  var isList = lazyLookup(lists);
  var isListItem = lazyLookup(listItems);
  var isVoid = lazyLookup(voids);
  var isTableSection = lazyLookup(tableSections);
  var isTableCell = lazyLookup(tableCells);
  var isWsPreserveElement = lazyLookup(wsElements);

  var isNodeType = function (type) {
    return function (node) {
      return !!node && node.nodeType === type;
    };
  };
  var isElement$1 = isNodeType(1);
  var matchNodeNames = function (names) {
    var items = names.toLowerCase().split(' ');
    return function (node) {
      var i, name;
      if (node && node.nodeType) {
        name = node.nodeName.toLowerCase();
        for (i = 0; i < items.length; i++) {
          if (name === items[i]) {
            return true;
          }
        }
      }
      return false;
    };
  };
  var matchStyleValues = function (name, values) {
    var items = values.toLowerCase().split(' ');
    return function (node) {
      var i, cssValue;
      if (isElement$1(node)) {
        for (i = 0; i < items.length; i++) {
          var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
          cssValue = computed ? computed.getPropertyValue(name) : null;
          if (cssValue === items[i]) {
            return true;
          }
        }
      }
      return false;
    };
  };
  var hasPropValue = function (propName, propValue) {
    return function (node) {
      return isElement$1(node) && node[propName] === propValue;
    };
  };
  var hasAttribute = function (attrName, attrValue) {
    return function (node) {
      return isElement$1(node) && node.hasAttribute(attrName);
    };
  };
  var hasAttributeValue = function (attrName, attrValue) {
    return function (node) {
      return isElement$1(node) && node.getAttribute(attrName) === attrValue;
    };
  };
  var isBogus = function (node) {
    return isElement$1(node) && node.hasAttribute('data-mce-bogus');
  };
  var isBogusAll = function (node) {
    return isElement$1(node) && node.getAttribute('data-mce-bogus') === 'all';
  };
  var isTable = function (node) {
    return isElement$1(node) && node.tagName === 'TABLE';
  };
  var hasContentEditableState = function (value) {
    return function (node) {
      if (isElement$1(node)) {
        if (node.contentEditable === value) {
          return true;
        }
        if (node.getAttribute('data-mce-contenteditable') === value) {
          return true;
        }
      }
      return false;
    };
  };
  var isText$1 = isNodeType(3);
  var isComment$1 = isNodeType(8);
  var isDocument$1 = isNodeType(9);
  var isBr$1 = matchNodeNames('br');
  var isContentEditableTrue = hasContentEditableState('true');
  var isContentEditableFalse = hasContentEditableState('false');
  var $_5oonaz1qjh8lywhz = {
    isText: isText$1,
    isElement: isElement$1,
    isComment: isComment$1,
    isDocument: isDocument$1,
    isBr: isBr$1,
    isContentEditableTrue: isContentEditableTrue,
    isContentEditableFalse: isContentEditableFalse,
    matchNodeNames: matchNodeNames,
    hasPropValue: hasPropValue,
    hasAttribute: hasAttribute,
    hasAttributeValue: hasAttributeValue,
    matchStyleValues: matchStyleValues,
    isBogus: isBogus,
    isBogusAll: isBogusAll,
    isTable: isTable
  };

  var surroundedBySpans = function (node) {
    var previousIsSpan = node.previousSibling && node.previousSibling.nodeName === 'SPAN';
    var nextIsSpan = node.nextSibling && node.nextSibling.nodeName === 'SPAN';
    return previousIsSpan && nextIsSpan;
  };
  var isBookmarkNode = function (node) {
    return node && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  };
  var trimNode = function (dom, node) {
    var i, children = node.childNodes;
    if ($_5oonaz1qjh8lywhz.isElement(node) && isBookmarkNode(node)) {
      return;
    }
    for (i = children.length - 1; i >= 0; i--) {
      trimNode(dom, children[i]);
    }
    if ($_5oonaz1qjh8lywhz.isDocument(node) === false) {
      if ($_5oonaz1qjh8lywhz.isText(node) && node.nodeValue.length > 0) {
        var trimmedLength = $_ahowuxkjh8lywbj.trim(node.nodeValue).length;
        if (dom.isBlock(node.parentNode) || trimmedLength > 0) {
          return;
        }
        if (trimmedLength === 0 && surroundedBySpans(node)) {
          return;
        }
      } else if ($_5oonaz1qjh8lywhz.isElement(node)) {
        children = node.childNodes;
        if (children.length === 1 && isBookmarkNode(children[0])) {
          node.parentNode.insertBefore(children[0], node);
        }
        if (children.length || isVoid($_cgttw3zjh8lywdq.fromDom(node))) {
          return;
        }
      }
      dom.remove(node);
    }
    return node;
  };
  var $_cm6fub1ojh8lywhl = { trimNode: trimNode };

  var makeMap$1 = $_ahowuxkjh8lywbj.makeMap;
  var namedEntities;
  var baseEntities;
  var reverseEntities;
  var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  var rawCharsRegExp = /[<>&\"\']/g;
  var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  var asciiMap = {
    128: '\u20AC',
    130: '\u201A',
    131: '\u0192',
    132: '\u201E',
    133: '\u2026',
    134: '\u2020',
    135: '\u2021',
    136: '\u02c6',
    137: '\u2030',
    138: '\u0160',
    139: '\u2039',
    140: '\u0152',
    142: '\u017d',
    145: '\u2018',
    146: '\u2019',
    147: '\u201C',
    148: '\u201D',
    149: '\u2022',
    150: '\u2013',
    151: '\u2014',
    152: '\u02DC',
    153: '\u2122',
    154: '\u0161',
    155: '\u203A',
    156: '\u0153',
    158: '\u017e',
    159: '\u0178'
  };
  baseEntities = {
    '"': '&quot;',
    '\'': '&#39;',
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
    '`': '&#96;'
  };
  reverseEntities = {
    '&lt;': '<',
    '&gt;': '>',
    '&amp;': '&',
    '&quot;': '"',
    '&apos;': '\''
  };
  var nativeDecode = function (text) {
    var elm;
    elm = $_cgttw3zjh8lywdq.fromTag('div').dom();
    elm.innerHTML = text;
    return elm.textContent || elm.innerText || text;
  };
  var buildEntitiesLookup = function (items, radix) {
    var i, chr, entity;
    var lookup = {};
    if (items) {
      items = items.split(',');
      radix = radix || 10;
      for (i = 0; i < items.length; i += 2) {
        chr = String.fromCharCode(parseInt(items[i], radix));
        if (!baseEntities[chr]) {
          entity = '&' + items[i + 1] + ';';
          lookup[chr] = entity;
          lookup[entity] = chr;
        }
      }
      return lookup;
    }
  };
  namedEntities = buildEntitiesLookup('50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32);
  var encodeRaw = function (text, attr) {
    return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
      return baseEntities[chr] || chr;
    });
  };
  var encodeAllRaw = function (text) {
    return ('' + text).replace(rawCharsRegExp, function (chr) {
      return baseEntities[chr] || chr;
    });
  };
  var encodeNumeric = function (text, attr) {
    return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
      if (chr.length > 1) {
        return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
      }
      return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
    });
  };
  var encodeNamed = function (text, attr, entities) {
    entities = entities || namedEntities;
    return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
      return baseEntities[chr] || entities[chr] || chr;
    });
  };
  var getEncodeFunc = function (name, entities) {
    var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
    var encodeNamedAndNumeric = function (text, attr) {
      return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
        if (baseEntities[chr] !== undefined) {
          return baseEntities[chr];
        }
        if (entitiesMap[chr] !== undefined) {
          return entitiesMap[chr];
        }
        if (chr.length > 1) {
          return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
        }
        return '&#' + chr.charCodeAt(0) + ';';
      });
    };
    var encodeCustomNamed = function (text, attr) {
      return encodeNamed(text, attr, entitiesMap);
    };
    var nameMap = makeMap$1(name.replace(/\+/g, ','));
    if (nameMap.named && nameMap.numeric) {
      return encodeNamedAndNumeric;
    }
    if (nameMap.named) {
      if (entities) {
        return encodeCustomNamed;
      }
      return encodeNamed;
    }
    if (nameMap.numeric) {
      return encodeNumeric;
    }
    return encodeRaw;
  };
  var decode = function (text) {
    return text.replace(entityRegExp, function (all, numeric) {
      if (numeric) {
        if (numeric.charAt(0).toLowerCase() === 'x') {
          numeric = parseInt(numeric.substr(1), 16);
        } else {
          numeric = parseInt(numeric, 10);
        }
        if (numeric > 65535) {
          numeric -= 65536;
          return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
        }
        return asciiMap[numeric] || String.fromCharCode(numeric);
      }
      return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
    });
  };
  var $_gex7a11rjh8lywi4 = {
    encodeRaw: encodeRaw,
    encodeAllRaw: encodeAllRaw,
    encodeNumeric: encodeNumeric,
    encodeNamed: encodeNamed,
    getEncodeFunc: getEncodeFunc,
    decode: decode
  };

  var mapCache = {};
  var dummyObj = {};
  var makeMap$2 = $_ahowuxkjh8lywbj.makeMap;
  var each$4 = $_ahowuxkjh8lywbj.each;
  var extend$1 = $_ahowuxkjh8lywbj.extend;
  var explode$1 = $_ahowuxkjh8lywbj.explode;
  var inArray$1 = $_ahowuxkjh8lywbj.inArray;
  var split = function (items, delim) {
    items = $_ahowuxkjh8lywbj.trim(items);
    return items ? items.split(delim || ' ') : [];
  };
  var compileSchema = function (type) {
    var schema = {};
    var globalAttributes, blockContent;
    var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
    var add = function (name, attributes, children) {
      var ni, attributesOrder, element;
      var arrayToMap = function (array, obj) {
        var map = {};
        var i, l;
        for (i = 0, l = array.length; i < l; i++) {
          map[array[i]] = obj || {};
        }
        return map;
      };
      children = children || [];
      attributes = attributes || '';
      if (typeof children === 'string') {
        children = split(children);
      }
      name = split(name);
      ni = name.length;
      while (ni--) {
        attributesOrder = split([
          globalAttributes,
          attributes
        ].join(' '));
        element = {
          attributes: arrayToMap(attributesOrder),
          attributesOrder: attributesOrder,
          children: arrayToMap(children, dummyObj)
        };
        schema[name[ni]] = element;
      }
    };
    var addAttrs = function (name, attributes) {
      var ni, schemaItem, i, l;
      name = split(name);
      ni = name.length;
      attributes = split(attributes);
      while (ni--) {
        schemaItem = schema[name[ni]];
        for (i = 0, l = attributes.length; i < l; i++) {
          schemaItem.attributes[attributes[i]] = {};
          schemaItem.attributesOrder.push(attributes[i]);
        }
      }
    };
    if (mapCache[type]) {
      return mapCache[type];
    }
    globalAttributes = 'id accesskey class dir lang style tabindex title role';
    blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
    phrasingContent = 'a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd ' + 'label map noscript object q s samp script select small span strong sub sup ' + 'textarea u var #text #comment';
    if (type !== 'html4') {
      globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
      blockContent += ' article aside details dialog figure header footer hgroup section nav';
      phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
    }
    if (type !== 'html5-strict') {
      globalAttributes += ' xml:lang';
      html4PhrasingContent = 'acronym applet basefont big font strike tt';
      phrasingContent = [
        phrasingContent,
        html4PhrasingContent
      ].join(' ');
      each$4(split(html4PhrasingContent), function (name) {
        add(name, '', phrasingContent);
      });
      html4BlockContent = 'center dir isindex noframes';
      blockContent = [
        blockContent,
        html4BlockContent
      ].join(' ');
      flowContent = [
        blockContent,
        phrasingContent
      ].join(' ');
      each$4(split(html4BlockContent), function (name) {
        add(name, '', flowContent);
      });
    }
    flowContent = flowContent || [
      blockContent,
      phrasingContent
    ].join(' ');
    add('html', 'manifest', 'head body');
    add('head', '', 'base command link meta noscript script style title');
    add('title hr noscript br');
    add('base', 'href target');
    add('link', 'href rel media hreflang type sizes hreflang');
    add('meta', 'name http-equiv content charset');
    add('style', 'media type scoped');
    add('script', 'src async defer type charset');
    add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
    add('address dt dd div caption', '', flowContent);
    add('h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn', '', phrasingContent);
    add('blockquote', 'cite', flowContent);
    add('ol', 'reversed start type', 'li');
    add('ul', '', 'li');
    add('li', 'value', flowContent);
    add('dl', '', 'dt dd');
    add('a', 'href target rel media hreflang type', phrasingContent);
    add('q', 'cite', phrasingContent);
    add('ins del', 'cite datetime', flowContent);
    add('img', 'src sizes srcset alt usemap ismap width height');
    add('iframe', 'src name width height', flowContent);
    add('embed', 'src type width height');
    add('object', 'data type typemustmatch name usemap form width height', [
      flowContent,
      'param'
    ].join(' '));
    add('param', 'name value');
    add('map', 'name', [
      flowContent,
      'area'
    ].join(' '));
    add('area', 'alt coords shape href target rel media hreflang type');
    add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
    add('colgroup', 'span', 'col');
    add('col', 'span');
    add('tbody thead tfoot', '', 'tr');
    add('tr', '', 'td th');
    add('td', 'colspan rowspan headers', flowContent);
    add('th', 'colspan rowspan headers scope abbr', flowContent);
    add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
    add('fieldset', 'disabled form name', [
      flowContent,
      'legend'
    ].join(' '));
    add('label', 'form for', phrasingContent);
    add('input', 'accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate ' + 'formtarget height list max maxlength min multiple name pattern readonly required size src step type value width');
    add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
    add('select', 'disabled form multiple name required size', 'option optgroup');
    add('optgroup', 'disabled label', 'option');
    add('option', 'disabled label selected value');
    add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
    add('menu', 'type label', [
      flowContent,
      'li'
    ].join(' '));
    add('noscript', '', flowContent);
    if (type !== 'html4') {
      add('wbr');
      add('ruby', '', [
        phrasingContent,
        'rt rp'
      ].join(' '));
      add('figcaption', '', flowContent);
      add('mark rt rp summary bdi', '', phrasingContent);
      add('canvas', 'width height', flowContent);
      add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
        flowContent,
        'track source'
      ].join(' '));
      add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
        flowContent,
        'track source'
      ].join(' '));
      add('picture', '', 'img source');
      add('source', 'src srcset type media sizes');
      add('track', 'kind src srclang label default');
      add('datalist', '', [
        phrasingContent,
        'option'
      ].join(' '));
      add('article section nav aside header footer', '', flowContent);
      add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
      add('figure', '', [
        flowContent,
        'figcaption'
      ].join(' '));
      add('time', 'datetime', phrasingContent);
      add('dialog', 'open', flowContent);
      add('command', 'type label icon disabled checked radiogroup command');
      add('output', 'for form name', phrasingContent);
      add('progress', 'value max', phrasingContent);
      add('meter', 'value min max low high optimum', phrasingContent);
      add('details', 'open', [
        flowContent,
        'summary'
      ].join(' '));
      add('keygen', 'autofocus challenge disabled form keytype name');
    }
    if (type !== 'html5-strict') {
      addAttrs('script', 'language xml:space');
      addAttrs('style', 'xml:space');
      addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
      addAttrs('embed', 'align name hspace vspace');
      addAttrs('param', 'valuetype type');
      addAttrs('a', 'charset name rev shape coords');
      addAttrs('br', 'clear');
      addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
      addAttrs('img', 'name longdesc align border hspace vspace');
      addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
      addAttrs('font basefont', 'size color face');
      addAttrs('input', 'usemap align');
      addAttrs('select', 'onchange');
      addAttrs('textarea');
      addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
      addAttrs('ul', 'type compact');
      addAttrs('li', 'type');
      addAttrs('ol dl menu dir', 'compact');
      addAttrs('pre', 'width xml:space');
      addAttrs('hr', 'align noshade size width');
      addAttrs('isindex', 'prompt');
      addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
      addAttrs('col', 'width align char charoff valign');
      addAttrs('colgroup', 'width align char charoff valign');
      addAttrs('thead', 'align char charoff valign');
      addAttrs('tr', 'align char charoff valign bgcolor');
      addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
      addAttrs('form', 'accept');
      addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
      addAttrs('tfoot', 'align char charoff valign');
      addAttrs('tbody', 'align char charoff valign');
      addAttrs('area', 'nohref');
      addAttrs('body', 'background bgcolor text link vlink alink');
    }
    if (type !== 'html4') {
      addAttrs('input button select textarea', 'autofocus');
      addAttrs('input textarea', 'placeholder');
      addAttrs('a', 'download');
      addAttrs('link script img', 'crossorigin');
      addAttrs('iframe', 'sandbox seamless allowfullscreen');
    }
    each$4(split('a form meter progress dfn'), function (name) {
      if (schema[name]) {
        delete schema[name].children[name];
      }
    });
    delete schema.caption.children.table;
    delete schema.script;
    mapCache[type] = schema;
    return schema;
  };
  var compileElementMap = function (value, mode) {
    var styles;
    if (value) {
      styles = {};
      if (typeof value === 'string') {
        value = { '*': value };
      }
      each$4(value, function (value, key) {
        styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$1(value, /[, ]/);
      });
    }
    return styles;
  };
  function Schema(settings) {
    var elements = {};
    var children = {};
    var patternElements = [];
    var validStyles;
    var invalidStyles;
    var schemaItems;
    var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap, validClasses;
    var blockElementsMap, nonEmptyElementsMap, moveCaretBeforeOnEnterElementsMap, textBlockElementsMap, textInlineElementsMap;
    var customElementsMap = {}, specialElements = {};
    var createLookupTable = function (option, defaultValue, extendWith) {
      var value = settings[option];
      if (!value) {
        value = mapCache[option];
        if (!value) {
          value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
          value = extend$1(value, extendWith);
          mapCache[option] = value;
        }
      } else {
        value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
      }
      return value;
    };
    settings = settings || {};
    schemaItems = compileSchema(settings.schema);
    if (settings.verify_html === false) {
      settings.valid_elements = '*[*]';
    }
    validStyles = compileElementMap(settings.valid_styles);
    invalidStyles = compileElementMap(settings.invalid_styles, 'map');
    validClasses = compileElementMap(settings.valid_classes, 'map');
    whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
    selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
    shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
    boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
    nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object ' + 'script pre code', shortEndedElementsMap);
    moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', 'table', nonEmptyElementsMap);
    textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside nav figure');
    blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex option ' + 'datalist select optgroup figcaption details summary', textBlockElementsMap);
    textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
    each$4((settings.special || 'script noscript noframes noembed title style textarea xmp').split(' '), function (name) {
      specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
    });
    var patternToRegExp = function (str) {
      return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
    };
    var addValidElements = function (validElements) {
      var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, key, value;
      var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)\])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
      if (validElements) {
        validElements = split(validElements, ',');
        if (elements['@']) {
          globalAttributes = elements['@'].attributes;
          globalAttributesOrder = elements['@'].attributesOrder;
        }
        for (ei = 0, el = validElements.length; ei < el; ei++) {
          matches = elementRuleRegExp.exec(validElements[ei]);
          if (matches) {
            prefix = matches[1];
            elementName = matches[2];
            outputName = matches[3];
            attrData = matches[5];
            attributes = {};
            attributesOrder = [];
            element = {
              attributes: attributes,
              attributesOrder: attributesOrder
            };
            if (prefix === '#') {
              element.paddEmpty = true;
            }
            if (prefix === '-') {
              element.removeEmpty = true;
            }
            if (matches[4] === '!') {
              element.removeEmptyAttrs = true;
            }
            if (globalAttributes) {
              for (key in globalAttributes) {
                attributes[key] = globalAttributes[key];
              }
              attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
            }
            if (attrData) {
              attrData = split(attrData, '|');
              for (ai = 0, al = attrData.length; ai < al; ai++) {
                matches = attrRuleRegExp.exec(attrData[ai]);
                if (matches) {
                  attr = {};
                  attrType = matches[1];
                  attrName = matches[2].replace(/[\\:]:/g, ':');
                  prefix = matches[3];
                  value = matches[4];
                  if (attrType === '!') {
                    element.attributesRequired = element.attributesRequired || [];
                    element.attributesRequired.push(attrName);
                    attr.required = true;
                  }
                  if (attrType === '-') {
                    delete attributes[attrName];
                    attributesOrder.splice(inArray$1(attributesOrder, attrName), 1);
                    continue;
                  }
                  if (prefix) {
                    if (prefix === '=') {
                      element.attributesDefault = element.attributesDefault || [];
                      element.attributesDefault.push({
                        name: attrName,
                        value: value
                      });
                      attr.defaultValue = value;
                    }
                    if (prefix === ':') {
                      element.attributesForced = element.attributesForced || [];
                      element.attributesForced.push({
                        name: attrName,
                        value: value
                      });
                      attr.forcedValue = value;
                    }
                    if (prefix === '<') {
                      attr.validValues = makeMap$2(value, '?');
                    }
                  }
                  if (hasPatternsRegExp.test(attrName)) {
                    element.attributePatterns = element.attributePatterns || [];
                    attr.pattern = patternToRegExp(attrName);
                    element.attributePatterns.push(attr);
                  } else {
                    if (!attributes[attrName]) {
                      attributesOrder.push(attrName);
                    }
                    attributes[attrName] = attr;
                  }
                }
              }
            }
            if (!globalAttributes && elementName === '@') {
              globalAttributes = attributes;
              globalAttributesOrder = attributesOrder;
            }
            if (outputName) {
              element.outputName = elementName;
              elements[outputName] = element;
            }
            if (hasPatternsRegExp.test(elementName)) {
              element.pattern = patternToRegExp(elementName);
              patternElements.push(element);
            } else {
              elements[elementName] = element;
            }
          }
        }
      }
    };
    var setValidElements = function (validElements) {
      elements = {};
      patternElements = [];
      addValidElements(validElements);
      each$4(schemaItems, function (element, name) {
        children[name] = element.children;
      });
    };
    var addCustomElements = function (customElements) {
      var customElementRegExp = /^(~)?(.+)$/;
      if (customElements) {
        mapCache.text_block_elements = mapCache.block_elements = null;
        each$4(split(customElements, ','), function (rule) {
          var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
          children[name] = children[cloneName];
          customElementsMap[name] = cloneName;
          if (!inline) {
            blockElementsMap[name.toUpperCase()] = {};
            blockElementsMap[name] = {};
          }
          if (!elements[name]) {
            var customRule = elements[cloneName];
            customRule = extend$1({}, customRule);
            delete customRule.removeEmptyAttrs;
            delete customRule.removeEmpty;
            elements[name] = customRule;
          }
          each$4(children, function (element, elmName) {
            if (element[cloneName]) {
              children[elmName] = element = extend$1({}, children[elmName]);
              element[name] = element[cloneName];
            }
          });
        });
      }
    };
    var addValidChildren = function (validChildren) {
      var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/;
      mapCache[settings.schema] = null;
      if (validChildren) {
        each$4(split(validChildren, ','), function (rule) {
          var matches = childRuleRegExp.exec(rule);
          var parent, prefix;
          if (matches) {
            prefix = matches[1];
            if (prefix) {
              parent = children[matches[2]];
            } else {
              parent = children[matches[2]] = { '#comment': {} };
            }
            parent = children[matches[2]];
            each$4(split(matches[3], '|'), function (child) {
              if (prefix === '-') {
                delete parent[child];
              } else {
                parent[child] = {};
              }
            });
          }
        });
      }
    };
    var getElementRule = function (name) {
      var element = elements[name], i;
      if (element) {
        return element;
      }
      i = patternElements.length;
      while (i--) {
        element = patternElements[i];
        if (element.pattern.test(name)) {
          return element;
        }
      }
    };
    if (!settings.valid_elements) {
      each$4(schemaItems, function (element, name) {
        elements[name] = {
          attributes: element.attributes,
          attributesOrder: element.attributesOrder
        };
        children[name] = element.children;
      });
      if (settings.schema !== 'html5') {
        each$4(split('strong/b em/i'), function (item) {
          item = split(item, '/');
          elements[item[1]].outputName = item[0];
        });
      }
      each$4(split('ol ul sub sup blockquote span font a table tbody tr strong em b i'), function (name) {
        if (elements[name]) {
          elements[name].removeEmpty = true;
        }
      });
      each$4(split('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
        elements[name].paddEmpty = true;
      });
      each$4(split('span'), function (name) {
        elements[name].removeEmptyAttrs = true;
      });
    } else {
      setValidElements(settings.valid_elements);
    }
    addCustomElements(settings.custom_elements);
    addValidChildren(settings.valid_children);
    addValidElements(settings.extended_valid_elements);
    addValidChildren('+ol[ul|ol],+ul[ul|ol]');
    each$4({
      dd: 'dl',
      dt: 'dl',
      li: 'ul ol',
      td: 'tr',
      th: 'tr',
      tr: 'tbody thead tfoot',
      tbody: 'table',
      thead: 'table',
      tfoot: 'table',
      legend: 'fieldset',
      area: 'map',
      param: 'video audio object'
    }, function (parents, item) {
      if (elements[item]) {
        elements[item].parentsRequired = split(parents);
      }
    });
    if (settings.invalid_elements) {
      each$4(explode$1(settings.invalid_elements), function (item) {
        if (elements[item]) {
          delete elements[item];
        }
      });
    }
    if (!getElementRule('span')) {
      addValidElements('span[!data-mce-type|*]');
    }
    var getValidStyles = function () {
      return validStyles;
    };
    var getInvalidStyles = function () {
      return invalidStyles;
    };
    var getValidClasses = function () {
      return validClasses;
    };
    var getBoolAttrs = function () {
      return boolAttrMap;
    };
    var getBlockElements = function () {
      return blockElementsMap;
    };
    var getTextBlockElements = function () {
      return textBlockElementsMap;
    };
    var getTextInlineElements = function () {
      return textInlineElementsMap;
    };
    var getShortEndedElements = function () {
      return shortEndedElementsMap;
    };
    var getSelfClosingElements = function () {
      return selfClosingElementsMap;
    };
    var getNonEmptyElements = function () {
      return nonEmptyElementsMap;
    };
    var getMoveCaretBeforeOnEnterElements = function () {
      return moveCaretBeforeOnEnterElementsMap;
    };
    var getWhiteSpaceElements = function () {
      return whiteSpaceElementsMap;
    };
    var getSpecialElements = function () {
      return specialElements;
    };
    var isValidChild = function (name, child) {
      var parent = children[name.toLowerCase()];
      return !!(parent && parent[child.toLowerCase()]);
    };
    var isValid = function (name, attr) {
      var attrPatterns, i;
      var rule = getElementRule(name);
      if (rule) {
        if (attr) {
          if (rule.attributes[attr]) {
            return true;
          }
          attrPatterns = rule.attributePatterns;
          if (attrPatterns) {
            i = attrPatterns.length;
            while (i--) {
              if (attrPatterns[i].pattern.test(name)) {
                return true;
              }
            }
          }
        } else {
          return true;
        }
      }
      return false;
    };
    var getCustomElements = function () {
      return customElementsMap;
    };
    return {
      children: children,
      elements: elements,
      getValidStyles: getValidStyles,
      getValidClasses: getValidClasses,
      getBlockElements: getBlockElements,
      getInvalidStyles: getInvalidStyles,
      getShortEndedElements: getShortEndedElements,
      getTextBlockElements: getTextBlockElements,
      getTextInlineElements: getTextInlineElements,
      getBoolAttrs: getBoolAttrs,
      getElementRule: getElementRule,
      getSelfClosingElements: getSelfClosingElements,
      getNonEmptyElements: getNonEmptyElements,
      getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
      getWhiteSpaceElements: getWhiteSpaceElements,
      getSpecialElements: getSpecialElements,
      isValidChild: isValidChild,
      isValid: isValid,
      getCustomElements: getCustomElements,
      addValidElements: addValidElements,
      setValidElements: setValidElements,
      addCustomElements: addCustomElements,
      addValidChildren: addValidChildren
    };
  }

  var toHex = function (match, r, g, b) {
    var hex = function (val) {
      val = parseInt(val, 10).toString(16);
      return val.length > 1 ? val : '0' + val;
    };
    return '#' + hex(r) + hex(g) + hex(b);
  };
  function Styles(settings, schema) {
    var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
    var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
    var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
    var trimRightRegExp = /\s+$/;
    var i;
    var encodingLookup = {};
    var encodingItems;
    var validStyles;
    var invalidStyles;
    var invisibleChar = '\uFEFF';
    settings = settings || {};
    if (schema) {
      validStyles = schema.getValidStyles();
      invalidStyles = schema.getInvalidStyles();
    }
    encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
    for (i = 0; i < encodingItems.length; i++) {
      encodingLookup[encodingItems[i]] = invisibleChar + i;
      encodingLookup[invisibleChar + i] = encodingItems[i];
    }
    return {
      toHex: function (color) {
        return color.replace(rgbRegExp, toHex);
      },
      parse: function (css) {
        var styles = {};
        var matches, name, value, isEncoded;
        var urlConverter = settings.url_converter;
        var urlConverterScope = settings.url_converter_scope || this;
        var compress = function (prefix, suffix, noJoin) {
          var top, right, bottom, left;
          top = styles[prefix + '-top' + suffix];
          if (!top) {
            return;
          }
          right = styles[prefix + '-right' + suffix];
          if (!right) {
            return;
          }
          bottom = styles[prefix + '-bottom' + suffix];
          if (!bottom) {
            return;
          }
          left = styles[prefix + '-left' + suffix];
          if (!left) {
            return;
          }
          var box = [
            top,
            right,
            bottom,
            left
          ];
          i = box.length - 1;
          while (i--) {
            if (box[i] !== box[i + 1]) {
              break;
            }
          }
          if (i > -1 && noJoin) {
            return;
          }
          styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
          delete styles[prefix + '-top' + suffix];
          delete styles[prefix + '-right' + suffix];
          delete styles[prefix + '-bottom' + suffix];
          delete styles[prefix + '-left' + suffix];
        };
        var canCompress = function (key) {
          var value = styles[key], i;
          if (!value) {
            return;
          }
          value = value.split(' ');
          i = value.length;
          while (i--) {
            if (value[i] !== value[0]) {
              return false;
            }
          }
          styles[key] = value[0];
          return true;
        };
        var compress2 = function (target, a, b, c) {
          if (!canCompress(a)) {
            return;
          }
          if (!canCompress(b)) {
            return;
          }
          if (!canCompress(c)) {
            return;
          }
          styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
          delete styles[a];
          delete styles[b];
          delete styles[c];
        };
        var encode = function (str) {
          isEncoded = true;
          return encodingLookup[str];
        };
        var decode = function (str, keepSlashes) {
          if (isEncoded) {
            str = str.replace(/\uFEFF[0-9]/g, function (str) {
              return encodingLookup[str];
            });
          }
          if (!keepSlashes) {
            str = str.replace(/\\([\'\";:])/g, '$1');
          }
          return str;
        };
        var decodeSingleHexSequence = function (escSeq) {
          return String.fromCharCode(parseInt(escSeq.slice(1), 16));
        };
        var decodeHexSequences = function (value) {
          return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
        };
        var processUrl = function (match, url, url2, url3, str, str2) {
          str = str || str2;
          if (str) {
            str = decode(str);
            return '\'' + str.replace(/\'/g, '\\\'') + '\'';
          }
          url = decode(url || url2 || url3);
          if (!settings.allow_script_urls) {
            var scriptUrl = url.replace(/[\s\r\n]+/g, '');
            if (/(java|vb)script:/i.test(scriptUrl)) {
              return '';
            }
            if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
              return '';
            }
          }
          if (urlConverter) {
            url = urlConverter.call(urlConverterScope, url, 'style');
          }
          return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
        };
        if (css) {
          css = css.replace(/[\u0000-\u001F]/g, '');
          css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
            return str.replace(/[;:]/g, encode);
          });
          while (matches = styleRegExp.exec(css)) {
            styleRegExp.lastIndex = matches.index + matches[0].length;
            name = matches[1].replace(trimRightRegExp, '').toLowerCase();
            value = matches[2].replace(trimRightRegExp, '');
            if (name && value) {
              name = decodeHexSequences(name);
              value = decodeHexSequences(value);
              if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
                continue;
              }
              if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
                continue;
              }
              if (name === 'font-weight' && value === '700') {
                value = 'bold';
              } else if (name === 'color' || name === 'background-color') {
                value = value.toLowerCase();
              }
              value = value.replace(rgbRegExp, toHex);
              value = value.replace(urlOrStrRegExp, processUrl);
              styles[name] = isEncoded ? decode(value, true) : value;
            }
          }
          compress('border', '', true);
          compress('border', '-width');
          compress('border', '-color');
          compress('border', '-style');
          compress('padding', '');
          compress('margin', '');
          compress2('border', 'border-width', 'border-style', 'border-color');
          if (styles.border === 'medium none') {
            delete styles.border;
          }
          if (styles['border-image'] === 'none') {
            delete styles['border-image'];
          }
        }
        return styles;
      },
      serialize: function (styles, elementName) {
        var css = '', name, value;
        var serializeStyles = function (name) {
          var styleList, i, l, value;
          styleList = validStyles[name];
          if (styleList) {
            for (i = 0, l = styleList.length; i < l; i++) {
              name = styleList[i];
              value = styles[name];
              if (value) {
                css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
              }
            }
          }
        };
        var isValid = function (name, elementName) {
          var styleMap;
          styleMap = invalidStyles['*'];
          if (styleMap && styleMap[name]) {
            return false;
          }
          styleMap = invalidStyles[elementName];
          if (styleMap && styleMap[name]) {
            return false;
          }
          return true;
        };
        if (elementName && validStyles) {
          serializeStyles('*');
          serializeStyles(elementName);
        } else {
          for (name in styles) {
            value = styles[name];
            if (value && (!invalidStyles || isValid(name, elementName))) {
              css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
            }
          }
        }
        return css;
      }
    };
  }

  var each$5 = $_ahowuxkjh8lywbj.each;
  var grep$1 = $_ahowuxkjh8lywbj.grep;
  var isIE = $_9bpim8ajh8lyw68.ie;
  var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  var whiteSpaceRegExp$2 = /^[ \t\r\n]*$/;
  var setupAttrHooks = function (styles, settings, getContext) {
    var attrHooks = {};
    var keepValues = settings.keep_values;
    var keepUrlHook = {
      set: function ($elm, value, name) {
        if (settings.url_converter) {
          value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
        }
        $elm.attr('data-mce-' + name, value).attr(name, value);
      },
      get: function ($elm, name) {
        return $elm.attr('data-mce-' + name) || $elm.attr(name);
      }
    };
    attrHooks = {
      style: {
        set: function ($elm, value) {
          if (value !== null && typeof value === 'object') {
            $elm.css(value);
            return;
          }
          if (keepValues) {
            $elm.attr('data-mce-style', value);
          }
          $elm.attr('style', value);
        },
        get: function ($elm) {
          var value = $elm.attr('data-mce-style') || $elm.attr('style');
          value = styles.serialize(styles.parse(value), $elm[0].nodeName);
          return value;
        }
      }
    };
    if (keepValues) {
      attrHooks.href = attrHooks.src = keepUrlHook;
    }
    return attrHooks;
  };
  var updateInternalStyleAttr = function (styles, $elm) {
    var rawValue = $elm.attr('style');
    var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
    if (!value) {
      value = null;
    }
    $elm.attr('data-mce-style', value);
  };
  var findNodeIndex = function (node, normalized) {
    var idx = 0, lastNodeType, nodeType;
    if (node) {
      for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
        nodeType = node.nodeType;
        if (normalized && nodeType === 3) {
          if (nodeType === lastNodeType || !node.nodeValue.length) {
            continue;
          }
        }
        idx++;
        lastNodeType = nodeType;
      }
    }
    return idx;
  };
  function DOMUtils(doc, settings) {
    var _this = this;
    if (settings === void 0) {
      settings = {};
    }
    var attrHooks;
    var addedStyles = {};
    var win = window;
    var files = {};
    var counter = 0;
    var stdMode = true;
    var boxModel = true;
    var styleSheetLoader = StyleSheetLoader(doc);
    var boundEvents = [];
    var schema = settings.schema ? settings.schema : Schema({});
    var styles = Styles({
      url_converter: settings.url_converter,
      url_converter_scope: settings.url_converter_scope
    }, settings.schema);
    var events = settings.ownEvents ? new EventUtils(settings.proxy) : EventUtils.Event;
    var blockElementsMap = schema.getBlockElements();
    var $ = DomQuery.overrideDefaults(function () {
      return {
        context: doc,
        element: self.getRoot()
      };
    });
    var isBlock = function (node) {
      if (typeof node === 'string') {
        return !!blockElementsMap[node];
      } else if (node) {
        var type = node.nodeType;
        if (type) {
          return !!(type === 1 && blockElementsMap[node.nodeName]);
        }
      }
      return false;
    };
    var get = function (elm) {
      if (elm && doc && typeof elm === 'string') {
        var node = doc.getElementById(elm);
        if (node && node.id !== elm) {
          return doc.getElementsByName(elm)[1];
        } else {
          return node;
        }
      }
      return elm;
    };
    var $$ = function (elm) {
      if (typeof elm === 'string') {
        elm = get(elm);
      }
      return $(elm);
    };
    var getAttrib = function (elm, name, defaultVal) {
      var hook, value;
      var $elm = $$(elm);
      if ($elm.length) {
        hook = attrHooks[name];
        if (hook && hook.get) {
          value = hook.get($elm, name);
        } else {
          value = $elm.attr(name);
        }
      }
      if (typeof value === 'undefined') {
        value = defaultVal || '';
      }
      return value;
    };
    var getAttribs = function (elm) {
      var node = get(elm);
      if (!node) {
        return [];
      }
      return node.attributes;
    };
    var setAttrib = function (elm, name, value) {
      var originalValue, hook;
      if (value === '') {
        value = null;
      }
      var $elm = $$(elm);
      originalValue = $elm.attr(name);
      if (!$elm.length) {
        return;
      }
      hook = attrHooks[name];
      if (hook && hook.set) {
        hook.set($elm, value, name);
      } else {
        $elm.attr(name, value);
      }
      if (originalValue !== value && settings.onSetAttrib) {
        settings.onSetAttrib({
          attrElm: $elm,
          attrName: name,
          attrValue: value
        });
      }
    };
    var clone = function (node, deep) {
      if (!isIE || node.nodeType !== 1 || deep) {
        return node.cloneNode(deep);
      }
      if (!deep) {
        var clone_1 = doc.createElement(node.nodeName);
        each$5(getAttribs(node), function (attr) {
          setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
        });
        return clone_1;
      }
      return null;
    };
    var getRoot = function () {
      return settings.root_element || doc.body;
    };
    var getViewPort = function (argWin) {
      var actWin = !argWin ? win : argWin;
      var doc = actWin.document;
      var rootElm = boxModel ? doc.documentElement : doc.body;
      return {
        x: actWin.pageXOffset || rootElm.scrollLeft,
        y: actWin.pageYOffset || rootElm.scrollTop,
        w: actWin.innerWidth || rootElm.clientWidth,
        h: actWin.innerHeight || rootElm.clientHeight
      };
    };
    var getPos = function (elm, rootElm) {
      return $_6pe7rlmjh8lywbu.getPos(doc.body, get(elm), rootElm);
    };
    var setStyle = function (elm, name, value) {
      var $elm = $$(elm).css(name, value);
      if (settings.update_styles) {
        updateInternalStyleAttr(styles, $elm);
      }
    };
    var setStyles = function (elm, stylesArg) {
      var $elm = $$(elm).css(stylesArg);
      if (settings.update_styles) {
        updateInternalStyleAttr(styles, $elm);
      }
    };
    var getStyle = function (elm, name, computed) {
      var $elm = $$(elm);
      if (computed) {
        return $elm.css(name);
      }
      name = name.replace(/-(\D)/g, function (a, b) {
        return b.toUpperCase();
      });
      if (name === 'float') {
        name = $_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie < 12 ? 'styleFloat' : 'cssFloat';
      }
      return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
    };
    var getSize = function (elm) {
      var w, h;
      elm = get(elm);
      w = getStyle(elm, 'width');
      h = getStyle(elm, 'height');
      if (w.indexOf('px') === -1) {
        w = 0;
      }
      if (h.indexOf('px') === -1) {
        h = 0;
      }
      return {
        w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
        h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
      };
    };
    var getRect = function (elm) {
      var pos, size;
      elm = get(elm);
      pos = getPos(elm);
      size = getSize(elm);
      return {
        x: pos.x,
        y: pos.y,
        w: size.w,
        h: size.h
      };
    };
    var is = function (elm, selector) {
      var i;
      if (!elm) {
        return false;
      }
      if (!Array.isArray(elm)) {
        if (selector === '*') {
          return elm.nodeType === 1;
        }
        if (simpleSelectorRe.test(selector)) {
          var selectors = selector.toLowerCase().split(/,/);
          var elmName = elm.nodeName.toLowerCase();
          for (i = selectors.length - 1; i >= 0; i--) {
            if (selectors[i] === elmName) {
              return true;
            }
          }
          return false;
        }
        if (elm.nodeType && elm.nodeType !== 1) {
          return false;
        }
      }
      var elms = !Array.isArray(elm) ? [elm] : elm;
      return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
    };
    var getParents = function (elm, selector, root, collect) {
      var result = [];
      var selectorVal;
      var node = get(elm);
      collect = collect === undefined;
      root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
      if ($_ahowuxkjh8lywbj.is(selector, 'string')) {
        selectorVal = selector;
        if (selector === '*') {
          selector = function (node) {
            return node.nodeType === 1;
          };
        } else {
          selector = function (node) {
            return is(node, selectorVal);
          };
        }
      }
      while (node) {
        if (node === root || !node.nodeType || node.nodeType === 9) {
          break;
        }
        if (!selector || typeof selector === 'function' && selector(node)) {
          if (collect) {
            result.push(node);
          } else {
            return [node];
          }
        }
        node = node.parentNode;
      }
      return collect ? result : null;
    };
    var getParent = function (node, selector, root) {
      var parents = getParents(node, selector, root, false);
      return parents && parents.length > 0 ? parents[0] : null;
    };
    var _findSib = function (node, selector, name) {
      var func = selector;
      if (node) {
        if (typeof selector === 'string') {
          func = function (node) {
            return is(node, selector);
          };
        }
        for (node = node[name]; node; node = node[name]) {
          if (typeof func === 'function' && func(node)) {
            return node;
          }
        }
      }
      return null;
    };
    var getNext = function (node, selector) {
      return _findSib(node, selector, 'nextSibling');
    };
    var getPrev = function (node, selector) {
      return _findSib(node, selector, 'previousSibling');
    };
    var select = function (selector, scope) {
      return Sizzle(selector, get(scope) || settings.root_element || doc, []);
    };
    var run = function (elm, func, scope) {
      var result;
      var node = typeof elm === 'string' ? get(elm) : elm;
      if (!node) {
        return false;
      }
      if ($_ahowuxkjh8lywbj.isArray(node) && (node.length || node.length === 0)) {
        result = [];
        each$5(node, function (elm, i) {
          if (elm) {
            if (typeof elm === 'string') {
              elm = get(elm);
            }
            result.push(func.call(scope, elm, i));
          }
        });
        return result;
      }
      var context = scope ? scope : _this;
      return func.call(context, node);
    };
    var setAttribs = function (elm, attrs) {
      $$(elm).each(function (i, node) {
        each$5(attrs, function (value, name) {
          setAttrib(node, name, value);
        });
      });
    };
    var setHTML = function (elm, html) {
      var $elm = $$(elm);
      if (isIE) {
        $elm.each(function (i, target) {
          if (target.canHaveHTML === false) {
            return;
          }
          while (target.firstChild) {
            target.removeChild(target.firstChild);
          }
          try {
            target.innerHTML = '<br>' + html;
            target.removeChild(target.firstChild);
          } catch (ex) {
            DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
          }
          return html;
        });
      } else {
        $elm.html(html);
      }
    };
    var add = function (parentElm, name, attrs, html, create) {
      return run(parentElm, function (parentElm) {
        var newElm = typeof name === 'string' ? doc.createElement(name) : name;
        setAttribs(newElm, attrs);
        if (html) {
          if (typeof html !== 'string' && html.nodeType) {
            newElm.appendChild(html);
          } else if (typeof html === 'string') {
            setHTML(newElm, html);
          }
        }
        return !create ? parentElm.appendChild(newElm) : newElm;
      });
    };
    var create = function (name, attrs, html) {
      return add(doc.createElement(name), name, attrs, html, true);
    };
    var decode = $_gex7a11rjh8lywi4.decode;
    var encode = $_gex7a11rjh8lywi4.encodeAllRaw;
    var createHTML = function (name, attrs, html) {
      var outHtml = '', key;
      outHtml += '<' + name;
      for (key in attrs) {
        if (attrs.hasOwnProperty(key) && attrs[key] !== null && typeof attrs[key] !== 'undefined') {
          outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
        }
      }
      if (typeof html !== 'undefined') {
        return outHtml + '>' + html + '</' + name + '>';
      }
      return outHtml + ' />';
    };
    var createFragment = function (html) {
      var node;
      var container = doc.createElement('div');
      var frag = doc.createDocumentFragment();
      if (html) {
        container.innerHTML = html;
      }
      while (node = container.firstChild) {
        frag.appendChild(node);
      }
      return frag;
    };
    var remove = function (node, keepChildren) {
      var $node = $$(node);
      if (keepChildren) {
        $node.each(function () {
          var child;
          while (child = this.firstChild) {
            if (child.nodeType === 3 && child.data.length === 0) {
              this.removeChild(child);
            } else {
              this.parentNode.insertBefore(child, this);
            }
          }
        }).remove();
      } else {
        $node.remove();
      }
      return $node.length > 1 ? $node.toArray() : $node[0];
    };
    var removeAllAttribs = function (e) {
      return run(e, function (e) {
        var i;
        var attrs = e.attributes;
        for (i = attrs.length - 1; i >= 0; i--) {
          e.removeAttributeNode(attrs.item(i));
        }
      });
    };
    var parseStyle = function (cssText) {
      return styles.parse(cssText);
    };
    var serializeStyle = function (stylesArg, name) {
      return styles.serialize(stylesArg, name);
    };
    var addStyle = function (cssText) {
      var head, styleElm;
      if (self !== DOMUtils.DOM && doc === document) {
        if (addedStyles[cssText]) {
          return;
        }
        addedStyles[cssText] = true;
      }
      styleElm = doc.getElementById('mceDefaultStyles');
      if (!styleElm) {
        styleElm = doc.createElement('style');
        styleElm.id = 'mceDefaultStyles';
        styleElm.type = 'text/css';
        head = doc.getElementsByTagName('head')[0];
        if (head.firstChild) {
          head.insertBefore(styleElm, head.firstChild);
        } else {
          head.appendChild(styleElm);
        }
      }
      if (styleElm.styleSheet) {
        styleElm.styleSheet.cssText += cssText;
      } else {
        styleElm.appendChild(doc.createTextNode(cssText));
      }
    };
    var loadCSS = function (url) {
      var head;
      if (self !== DOMUtils.DOM && doc === document) {
        DOMUtils.DOM.loadCSS(url);
        return;
      }
      if (!url) {
        url = '';
      }
      head = doc.getElementsByTagName('head')[0];
      each$5(url.split(','), function (url) {
        var link;
        url = $_ahowuxkjh8lywbj._addCacheSuffix(url);
        if (files[url]) {
          return;
        }
        files[url] = true;
        link = create('link', {
          rel: 'stylesheet',
          href: url
        });
        head.appendChild(link);
      });
    };
    var toggleClass = function (elm, cls, state) {
      $$(elm).toggleClass(cls, state).each(function () {
        if (this.className === '') {
          DomQuery(this).attr('class', null);
        }
      });
    };
    var addClass = function (elm, cls) {
      $$(elm).addClass(cls);
    };
    var removeClass = function (elm, cls) {
      toggleClass(elm, cls, false);
    };
    var hasClass = function (elm, cls) {
      return $$(elm).hasClass(cls);
    };
    var show = function (elm) {
      $$(elm).show();
    };
    var hide = function (elm) {
      $$(elm).hide();
    };
    var isHidden = function (elm) {
      return $$(elm).css('display') === 'none';
    };
    var uniqueId = function (prefix) {
      return (!prefix ? 'mce_' : prefix) + counter++;
    };
    var getOuterHTML = function (elm) {
      var node = typeof elm === 'string' ? get(elm) : elm;
      return $_5oonaz1qjh8lywhz.isElement(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
    };
    var setOuterHTML = function (elm, html) {
      $$(elm).each(function () {
        try {
          if ('outerHTML' in this) {
            this.outerHTML = html;
            return;
          }
        } catch (ex) {
        }
        remove(DomQuery(this).html(html), true);
      });
    };
    var insertAfter = function (node, reference) {
      var referenceNode = get(reference);
      return run(node, function (node) {
        var parent, nextSibling;
        parent = referenceNode.parentNode;
        nextSibling = referenceNode.nextSibling;
        if (nextSibling) {
          parent.insertBefore(node, nextSibling);
        } else {
          parent.appendChild(node);
        }
        return node;
      });
    };
    var replace = function (newElm, oldElm, keepChildren) {
      return run(oldElm, function (oldElm) {
        if ($_ahowuxkjh8lywbj.is(oldElm, 'array')) {
          newElm = newElm.cloneNode(true);
        }
        if (keepChildren) {
          each$5(grep$1(oldElm.childNodes), function (node) {
            newElm.appendChild(node);
          });
        }
        return oldElm.parentNode.replaceChild(newElm, oldElm);
      });
    };
    var rename = function (elm, name) {
      var newElm;
      if (elm.nodeName !== name.toUpperCase()) {
        newElm = create(name);
        each$5(getAttribs(elm), function (attrNode) {
          setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
        });
        replace(newElm, elm, true);
      }
      return newElm || elm;
    };
    var findCommonAncestor = function (a, b) {
      var ps = a, pe;
      while (ps) {
        pe = b;
        while (pe && ps !== pe) {
          pe = pe.parentNode;
        }
        if (ps === pe) {
          break;
        }
        ps = ps.parentNode;
      }
      if (!ps && a.ownerDocument) {
        return a.ownerDocument.documentElement;
      }
      return ps;
    };
    var toHex = function (rgbVal) {
      return styles.toHex($_ahowuxkjh8lywbj.trim(rgbVal));
    };
    var isEmpty = function (node, elements) {
      var i, attributes, type, whitespace, walker, name, brCount = 0;
      node = node.firstChild;
      if (node) {
        walker = new TreeWalker(node, node.parentNode);
        elements = elements || (schema ? schema.getNonEmptyElements() : null);
        whitespace = schema ? schema.getWhiteSpaceElements() : {};
        do {
          type = node.nodeType;
          if ($_5oonaz1qjh8lywhz.isElement(node)) {
            var bogusVal = node.getAttribute('data-mce-bogus');
            if (bogusVal) {
              node = walker.next(bogusVal === 'all');
              continue;
            }
            name = node.nodeName.toLowerCase();
            if (elements && elements[name]) {
              if (name === 'br') {
                brCount++;
                node = walker.next();
                continue;
              }
              return false;
            }
            attributes = getAttribs(node);
            i = attributes.length;
            while (i--) {
              name = attributes[i].nodeName;
              if (name === 'name' || name === 'data-mce-bookmark') {
                return false;
              }
            }
          }
          if (type === 8) {
            return false;
          }
          if (type === 3 && !whiteSpaceRegExp$2.test(node.nodeValue)) {
            return false;
          }
          if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && whiteSpaceRegExp$2.test(node.nodeValue)) {
            return false;
          }
          node = walker.next();
        } while (node);
      }
      return brCount <= 1;
    };
    var createRng = function () {
      return doc.createRange();
    };
    var split = function (parentElm, splitElm, replacementElm) {
      var r = createRng(), bef, aft, pa;
      if (parentElm && splitElm) {
        r.setStart(parentElm.parentNode, findNodeIndex(parentElm));
        r.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
        bef = r.extractContents();
        r = createRng();
        r.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
        r.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
        aft = r.extractContents();
        pa = parentElm.parentNode;
        pa.insertBefore($_cm6fub1ojh8lywhl.trimNode(self, bef), parentElm);
        if (replacementElm) {
          pa.insertBefore(replacementElm, parentElm);
        } else {
          pa.insertBefore(splitElm, parentElm);
        }
        pa.insertBefore($_cm6fub1ojh8lywhl.trimNode(self, aft), parentElm);
        remove(parentElm);
        return replacementElm || splitElm;
      }
    };
    var bind = function (target, name, func, scope) {
      if ($_ahowuxkjh8lywbj.isArray(target)) {
        var i = target.length;
        while (i--) {
          target[i] = bind(target[i], name, func, scope);
        }
        return target;
      }
      if (settings.collect && (target === doc || target === win)) {
        boundEvents.push([
          target,
          name,
          func,
          scope
        ]);
      }
      return events.bind(target, name, func, scope || self);
    };
    var unbind = function (target, name, func) {
      var i;
      if ($_ahowuxkjh8lywbj.isArray(target)) {
        i = target.length;
        while (i--) {
          target[i] = unbind(target[i], name, func);
        }
        return target;
      }
      if (boundEvents && (target === doc || target === win)) {
        i = boundEvents.length;
        while (i--) {
          var item = boundEvents[i];
          if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
            events.unbind(item[0], item[1], item[2]);
          }
        }
      }
      return events.unbind(target, name, func);
    };
    var fire = function (target, name, evt) {
      return events.fire(target, name, evt);
    };
    var getContentEditable = function (node) {
      if (node && $_5oonaz1qjh8lywhz.isElement(node)) {
        var contentEditable = node.getAttribute('data-mce-contenteditable');
        if (contentEditable && contentEditable !== 'inherit') {
          return contentEditable;
        }
        return node.contentEditable !== 'inherit' ? node.contentEditable : null;
      } else {
        return null;
      }
    };
    var getContentEditableParent = function (node) {
      var root = getRoot();
      var state = null;
      for (; node && node !== root; node = node.parentNode) {
        state = getContentEditable(node);
        if (state !== null) {
          break;
        }
      }
      return state;
    };
    var destroy = function () {
      if (boundEvents) {
        var i = boundEvents.length;
        while (i--) {
          var item = boundEvents[i];
          events.unbind(item[0], item[1], item[2]);
        }
      }
      if (Sizzle.setDocument) {
        Sizzle.setDocument();
      }
    };
    var isChildOf = function (node, parent) {
      while (node) {
        if (parent === node) {
          return true;
        }
        node = node.parentNode;
      }
      return false;
    };
    var dumpRng = function (r) {
      return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
    };
    var self = {
      doc: doc,
      settings: settings,
      win: win,
      files: files,
      stdMode: stdMode,
      boxModel: boxModel,
      styleSheetLoader: styleSheetLoader,
      boundEvents: boundEvents,
      styles: styles,
      schema: schema,
      events: events,
      isBlock: isBlock,
      $: $,
      $$: $$,
      root: null,
      clone: clone,
      getRoot: getRoot,
      getViewPort: getViewPort,
      getRect: getRect,
      getSize: getSize,
      getParent: getParent,
      getParents: getParents,
      get: get,
      getNext: getNext,
      getPrev: getPrev,
      select: select,
      is: is,
      add: add,
      create: create,
      createHTML: createHTML,
      createFragment: createFragment,
      remove: remove,
      setStyle: setStyle,
      getStyle: getStyle,
      setStyles: setStyles,
      removeAllAttribs: removeAllAttribs,
      setAttrib: setAttrib,
      setAttribs: setAttribs,
      getAttrib: getAttrib,
      getPos: getPos,
      parseStyle: parseStyle,
      serializeStyle: serializeStyle,
      addStyle: addStyle,
      loadCSS: loadCSS,
      addClass: addClass,
      removeClass: removeClass,
      hasClass: hasClass,
      toggleClass: toggleClass,
      show: show,
      hide: hide,
      isHidden: isHidden,
      uniqueId: uniqueId,
      setHTML: setHTML,
      getOuterHTML: getOuterHTML,
      setOuterHTML: setOuterHTML,
      decode: decode,
      encode: encode,
      insertAfter: insertAfter,
      replace: replace,
      rename: rename,
      findCommonAncestor: findCommonAncestor,
      toHex: toHex,
      run: run,
      getAttribs: getAttribs,
      isEmpty: isEmpty,
      createRng: createRng,
      nodeIndex: findNodeIndex,
      split: split,
      bind: bind,
      unbind: unbind,
      fire: fire,
      getContentEditable: getContentEditable,
      getContentEditableParent: getContentEditableParent,
      destroy: destroy,
      isChildOf: isChildOf,
      dumpRng: dumpRng
    };
    attrHooks = setupAttrHooks(styles, settings, function () {
      return self;
    });
    return self;
  }
  (function (DOMUtils) {
    DOMUtils.DOM = DOMUtils(document);
    DOMUtils.nodeIndex = findNodeIndex;
  }(DOMUtils || (DOMUtils = {})));
  var DOMUtils$1 = DOMUtils;

  var DOM = DOMUtils$1.DOM;
  var each$6 = $_ahowuxkjh8lywbj.each;
  var grep$2 = $_ahowuxkjh8lywbj.grep;
  var isFunction = function (f) {
    return typeof f === 'function';
  };
  var ScriptLoader = function () {
    var QUEUED = 0;
    var LOADING = 1;
    var LOADED = 2;
    var FAILED = 3;
    var states = {};
    var queue = [];
    var scriptLoadedCallbacks = {};
    var queueLoadedCallbacks = [];
    var loading = 0;
    var loadScript = function (url, success, failure) {
      var dom = DOM;
      var elm, id;
      var done = function () {
        dom.remove(id);
        if (elm) {
          elm.onreadystatechange = elm.onload = elm = null;
        }
        success();
      };
      var error = function () {
        if (isFunction(failure)) {
          failure();
        } else {
          if (typeof console !== 'undefined' && console.log) {
            console.log('Failed to load script: ' + url);
          }
        }
      };
      id = dom.uniqueId();
      elm = document.createElement('script');
      elm.id = id;
      elm.type = 'text/javascript';
      elm.src = $_ahowuxkjh8lywbj._addCacheSuffix(url);
      if ('onreadystatechange' in elm) {
        elm.onreadystatechange = function () {
          if (/loaded|complete/.test(elm.readyState)) {
            done();
          }
        };
      } else {
        elm.onload = done;
      }
      elm.onerror = error;
      (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
    };
    this.isDone = function (url) {
      return states[url] === LOADED;
    };
    this.markDone = function (url) {
      states[url] = LOADED;
    };
    this.add = this.load = function (url, success, scope, failure) {
      var state = states[url];
      if (state === undefined) {
        queue.push(url);
        states[url] = QUEUED;
      }
      if (success) {
        if (!scriptLoadedCallbacks[url]) {
          scriptLoadedCallbacks[url] = [];
        }
        scriptLoadedCallbacks[url].push({
          success: success,
          failure: failure,
          scope: scope || this
        });
      }
    };
    this.remove = function (url) {
      delete states[url];
      delete scriptLoadedCallbacks[url];
    };
    this.loadQueue = function (success, scope, failure) {
      this.loadScripts(queue, success, scope, failure);
    };
    this.loadScripts = function (scripts, success, scope, failure) {
      var loadScripts;
      var failures = [];
      var execCallbacks = function (name, url) {
        each$6(scriptLoadedCallbacks[url], function (callback) {
          if (isFunction(callback[name])) {
            callback[name].call(callback.scope);
          }
        });
        scriptLoadedCallbacks[url] = undefined;
      };
      queueLoadedCallbacks.push({
        success: success,
        failure: failure,
        scope: scope || this
      });
      loadScripts = function () {
        var loadingScripts = grep$2(scripts);
        scripts.length = 0;
        each$6(loadingScripts, function (url) {
          if (states[url] === LOADED) {
            execCallbacks('success', url);
            return;
          }
          if (states[url] === FAILED) {
            execCallbacks('failure', url);
            return;
          }
          if (states[url] !== LOADING) {
            states[url] = LOADING;
            loading++;
            loadScript(url, function () {
              states[url] = LOADED;
              loading--;
              execCallbacks('success', url);
              loadScripts();
            }, function () {
              states[url] = FAILED;
              loading--;
              failures.push(url);
              execCallbacks('failure', url);
              loadScripts();
            });
          }
        });
        if (!loading) {
          var notifyCallbacks = queueLoadedCallbacks.slice(0);
          queueLoadedCallbacks.length = 0;
          each$6(notifyCallbacks, function (callback) {
            if (failures.length === 0) {
              if (isFunction(callback.success)) {
                callback.success.call(callback.scope);
              }
            } else {
              if (isFunction(callback.failure)) {
                callback.failure.call(callback.scope, failures);
              }
            }
          });
        }
      };
      loadScripts();
    };
  };
  ScriptLoader.ScriptLoader = new ScriptLoader();

  var each$7 = $_ahowuxkjh8lywbj.each;
  function AddOnManager() {
    var _this = this;
    var items = [];
    var urls = {};
    var lookup = {};
    var _listeners = [];
    var get = function (name) {
      if (lookup[name]) {
        return lookup[name].instance;
      }
      return undefined;
    };
    var dependencies = function (name) {
      var result;
      if (lookup[name]) {
        result = lookup[name].dependencies;
      }
      return result || [];
    };
    var requireLangPack = function (name, languages) {
      var language = AddOnManager.language;
      if (language && AddOnManager.languageLoad !== false) {
        if (languages) {
          languages = ',' + languages + ',';
          if (languages.indexOf(',' + language.substr(0, 2) + ',') !== -1) {
            language = language.substr(0, 2);
          } else if (languages.indexOf(',' + language + ',') === -1) {
            return;
          }
        }
        ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
      }
    };
    var add = function (id, addOn, dependencies) {
      items.push(addOn);
      lookup[id] = {
        instance: addOn,
        dependencies: dependencies
      };
      var result = $_5wjzy24jh8lyw2t.partition(_listeners, function (listener) {
        return listener.name === id;
      });
      _listeners = result.fail;
      each$7(result.pass, function (listener) {
        listener.callback();
      });
      return addOn;
    };
    var remove = function (name) {
      delete urls[name];
      delete lookup[name];
    };
    var createUrl = function (baseUrl, dep) {
      if (typeof dep === 'object') {
        return dep;
      }
      return typeof baseUrl === 'string' ? {
        prefix: '',
        resource: dep,
        suffix: ''
      } : {
        prefix: baseUrl.prefix,
        resource: dep,
        suffix: baseUrl.suffix
      };
    };
    var addComponents = function (pluginName, scripts) {
      var pluginUrl = _this.urls[pluginName];
      each$7(scripts, function (script) {
        ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
      });
    };
    var loadDependencies = function (addOnUrl, success, scope) {
      var deps = dependencies(name);
      each$7(deps, function (dep) {
        var newUrl = createUrl(addOnUrl, dep);
        load(newUrl.resource, newUrl, undefined, undefined);
      });
      if (success) {
        if (scope) {
          success.call(scope);
        } else {
          success.call(ScriptLoader);
        }
      }
    };
    var load = function (name, addOnUrl, success, scope, failure) {
      if (urls[name]) {
        return;
      }
      var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
      if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
        urlString = AddOnManager.baseURL + '/' + urlString;
      }
      urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
      if (lookup[name]) {
        loadDependencies(addOnUrl, success, scope);
      } else {
        ScriptLoader.ScriptLoader.add(urlString, function () {
          return loadDependencies(addOnUrl, success, scope);
        }, scope, failure);
      }
    };
    var waitFor = function (name, callback) {
      if (lookup.hasOwnProperty(name)) {
        callback();
      } else {
        _listeners.push({
          name: name,
          callback: callback
        });
      }
    };
    return {
      items: items,
      urls: urls,
      lookup: lookup,
      _listeners: _listeners,
      get: get,
      dependencies: dependencies,
      requireLangPack: requireLangPack,
      add: add,
      remove: remove,
      createUrl: createUrl,
      addComponents: addComponents,
      load: load,
      waitFor: waitFor
    };
  }
  (function (AddOnManager) {
    AddOnManager.PluginManager = AddOnManager();
    AddOnManager.ThemeManager = AddOnManager();
  }(AddOnManager || (AddOnManager = {})));

  var ZWSP = '\uFEFF';
  var isZwsp = function (chr) {
    return chr === ZWSP;
  };
  var trim$3 = function (text) {
    return text.replace(new RegExp(ZWSP, 'g'), '');
  };
  var $_d383mr21jh8lywlv = {
    isZwsp: isZwsp,
    ZWSP: ZWSP,
    trim: trim$3
  };

  var isElement$2 = $_5oonaz1qjh8lywhz.isElement;
  var isText$2 = $_5oonaz1qjh8lywhz.isText;
  var isCaretContainerBlock = function (node) {
    if (isText$2(node)) {
      node = node.parentNode;
    }
    return isElement$2(node) && node.hasAttribute('data-mce-caret');
  };
  var isCaretContainerInline = function (node) {
    return isText$2(node) && $_d383mr21jh8lywlv.isZwsp(node.data);
  };
  var isCaretContainer = function (node) {
    return isCaretContainerBlock(node) || isCaretContainerInline(node);
  };
  var hasContent = function (node) {
    return node.firstChild !== node.lastChild || !$_5oonaz1qjh8lywhz.isBr(node.firstChild);
  };
  var insertInline = function (node, before) {
    var doc, sibling, textNode, parentNode;
    doc = node.ownerDocument;
    textNode = doc.createTextNode($_d383mr21jh8lywlv.ZWSP);
    parentNode = node.parentNode;
    if (!before) {
      sibling = node.nextSibling;
      if (isText$2(sibling)) {
        if (isCaretContainer(sibling)) {
          return sibling;
        }
        if (startsWithCaretContainer(sibling)) {
          sibling.splitText(1);
          return sibling;
        }
      }
      if (node.nextSibling) {
        parentNode.insertBefore(textNode, node.nextSibling);
      } else {
        parentNode.appendChild(textNode);
      }
    } else {
      sibling = node.previousSibling;
      if (isText$2(sibling)) {
        if (isCaretContainer(sibling)) {
          return sibling;
        }
        if (endsWithCaretContainer(sibling)) {
          return sibling.splitText(sibling.data.length - 1);
        }
      }
      parentNode.insertBefore(textNode, node);
    }
    return textNode;
  };
  var isBeforeInline = function (pos) {
    var container = pos.container();
    return pos && $_5oonaz1qjh8lywhz.isText(container) && container.data.charAt(pos.offset()) === $_d383mr21jh8lywlv.ZWSP;
  };
  var isAfterInline = function (pos) {
    var container = pos.container();
    return pos && $_5oonaz1qjh8lywhz.isText(container) && container.data.charAt(pos.offset() - 1) === $_d383mr21jh8lywlv.ZWSP;
  };
  var createBogusBr = function () {
    var br = document.createElement('br');
    br.setAttribute('data-mce-bogus', '1');
    return br;
  };
  var insertBlock = function (blockName, node, before) {
    var doc, blockNode, parentNode;
    doc = node.ownerDocument;
    blockNode = doc.createElement(blockName);
    blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
    blockNode.setAttribute('data-mce-bogus', 'all');
    blockNode.appendChild(createBogusBr());
    parentNode = node.parentNode;
    if (!before) {
      if (node.nextSibling) {
        parentNode.insertBefore(blockNode, node.nextSibling);
      } else {
        parentNode.appendChild(blockNode);
      }
    } else {
      parentNode.insertBefore(blockNode, node);
    }
    return blockNode;
  };
  var startsWithCaretContainer = function (node) {
    return isText$2(node) && node.data[0] === $_d383mr21jh8lywlv.ZWSP;
  };
  var endsWithCaretContainer = function (node) {
    return isText$2(node) && node.data[node.data.length - 1] === $_d383mr21jh8lywlv.ZWSP;
  };
  var trimBogusBr = function (elm) {
    var brs = elm.getElementsByTagName('br');
    var lastBr = brs[brs.length - 1];
    if ($_5oonaz1qjh8lywhz.isBogus(lastBr)) {
      lastBr.parentNode.removeChild(lastBr);
    }
  };
  var showCaretContainerBlock = function (caretContainer) {
    if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
      trimBogusBr(caretContainer);
      caretContainer.removeAttribute('data-mce-caret');
      caretContainer.removeAttribute('data-mce-bogus');
      caretContainer.removeAttribute('style');
      caretContainer.removeAttribute('_moz_abspos');
      return caretContainer;
    }
    return null;
  };
  var isRangeInCaretContainerBlock = function (range) {
    return isCaretContainerBlock(range.startContainer);
  };

  var isContentEditableTrue$1 = $_5oonaz1qjh8lywhz.isContentEditableTrue;
  var isContentEditableFalse$1 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var isBr$2 = $_5oonaz1qjh8lywhz.isBr;
  var isText$3 = $_5oonaz1qjh8lywhz.isText;
  var isInvalidTextElement = $_5oonaz1qjh8lywhz.matchNodeNames('script style textarea');
  var isAtomicInline = $_5oonaz1qjh8lywhz.matchNodeNames('img input textarea hr iframe video audio object');
  var isTable$1 = $_5oonaz1qjh8lywhz.matchNodeNames('table');
  var isCaretContainer$1 = isCaretContainer;
  var isCaretCandidate = function (node) {
    if (isCaretContainer$1(node)) {
      return false;
    }
    if (isText$3(node)) {
      if (isInvalidTextElement(node.parentNode)) {
        return false;
      }
      return true;
    }
    return isAtomicInline(node) || isBr$2(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
  };
  var isUnselectable = function (node) {
    return $_5oonaz1qjh8lywhz.isElement(node) && node.getAttribute('unselectable') === 'true';
  };
  var isNonUiContentEditableFalse = function (node) {
    return isUnselectable(node) === false && isContentEditableFalse$1(node);
  };
  var isInEditable = function (node, root) {
    for (node = node.parentNode; node && node !== root; node = node.parentNode) {
      if (isNonUiContentEditableFalse(node)) {
        return false;
      }
      if (isContentEditableTrue$1(node)) {
        return true;
      }
    }
    return true;
  };
  var isAtomicContentEditableFalse = function (node) {
    if (!isNonUiContentEditableFalse(node)) {
      return false;
    }
    return $_9tjm51ljh8lywbq.reduce(node.getElementsByTagName('*'), function (result, elm) {
      return result || isContentEditableTrue$1(elm);
    }, false) !== true;
  };
  var isAtomic = function (node) {
    return isAtomicInline(node) || isAtomicContentEditableFalse(node);
  };
  var isEditableCaretCandidate = function (node, root) {
    return isCaretCandidate(node) && isInEditable(node, root);
  };

  var round = Math.round;
  var clone$1 = function (rect) {
    if (!rect) {
      return {
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
        width: 0,
        height: 0
      };
    }
    return {
      left: round(rect.left),
      top: round(rect.top),
      bottom: round(rect.bottom),
      right: round(rect.right),
      width: round(rect.width),
      height: round(rect.height)
    };
  };
  var collapse = function (rect, toStart) {
    rect = clone$1(rect);
    if (toStart) {
      rect.right = rect.left;
    } else {
      rect.left = rect.left + rect.width;
      rect.right = rect.left;
    }
    rect.width = 0;
    return rect;
  };
  var isEqual = function (rect1, rect2) {
    return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  };
  var isValidOverflow = function (overflowY, rect1, rect2) {
    return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  };
  var isAbove = function (rect1, rect2) {
    if (rect1.bottom - rect1.height / 2 < rect2.top) {
      return true;
    }
    if (rect1.top > rect2.bottom) {
      return false;
    }
    return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  };
  var isBelow = function (rect1, rect2) {
    if (rect1.top > rect2.bottom) {
      return true;
    }
    if (rect1.bottom < rect2.top) {
      return false;
    }
    return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  };
  var containsXY = function (rect, clientX, clientY) {
    return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  };
  var overflowX = function (outer, inner) {
    if (inner.left > outer.left && inner.right < outer.right) {
      return 0;
    } else {
      return inner.left < outer.left ? inner.left - outer.left : inner.right - outer.right;
    }
  };
  var overflowY = function (outer, inner) {
    if (inner.top > outer.top && inner.bottom < outer.bottom) {
      return 0;
    } else {
      return inner.top < outer.top ? inner.top - outer.top : inner.bottom - outer.bottom;
    }
  };
  var getOverflow = function (outer, inner) {
    return {
      x: overflowX(outer, inner),
      y: overflowY(outer, inner)
    };
  };

  var getSelectedNode = function (range) {
    var startContainer = range.startContainer, startOffset = range.startOffset;
    if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
      return startContainer.childNodes[startOffset];
    }
    return null;
  };
  var getNode = function (container, offset) {
    if (container.nodeType === 1 && container.hasChildNodes()) {
      if (offset >= container.childNodes.length) {
        offset = container.childNodes.length - 1;
      }
      container = container.childNodes[offset];
    }
    return container;
  };

  var extendingChars = new RegExp('[\u0300-\u036f\u0483-\u0487\u0488-\u0489\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a' + '\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0' + '\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08E3-\u0902\u093a\u093c' + '\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2-\u09e3' + '\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc' + '\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57' + '\u0b62-\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c00\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56' + '\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc-\u0ccd\u0cd5-\u0cd6\u0ce2-\u0ce3\u0d01\u0d3e\u0d41-\u0d44' + '\u0d4d\u0d57\u0d62-\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9' + '\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97' + '\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074' + '\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5' + '\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18' + '\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1ABE\u1b00-\u1b03\u1b34' + '\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9' + '\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9' + '\u1dc0-\u1df5\u1dfc-\u1dff\u200c-\u200d\u20d0-\u20dc\u20DD-\u20E0\u20e1\u20E2-\u20E4\u20e5-\u20f0\u2cef-\u2cf1' + '\u2d7f\u2de0-\u2dff\u302a-\u302d\u302e-\u302f\u3099-\u309a\ua66f\uA670-\uA672\ua674-\ua67d\uA69E-\ua69f\ua6f0-\ua6f1' + '\ua802\ua806\ua80b\ua825-\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc' + '\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1' + '\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\uFE2F\uff9e-\uff9f]');
  var isExtendingChar = function (ch) {
    return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  };

  var slice$3 = [].slice;
  var constant$1 = function (value) {
    return function () {
      return value;
    };
  };
  var negate = function (predicate) {
    return function (x) {
      return !predicate(x);
    };
  };
  var compose$2 = function (f, g) {
    return function (x) {
      return f(g(x));
    };
  };
  var or = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
    var args = slice$3.call(arguments);
    return function (x) {
      for (var i = 0; i < args.length; i++) {
        if (args[i](x)) {
          return true;
        }
      }
      return false;
    };
  };
  var and = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
    var args = slice$3.call(arguments);
    return function (x) {
      for (var i = 0; i < args.length; i++) {
        if (!args[i](x)) {
          return false;
        }
      }
      return true;
    };
  };
  var curry$1 = function (fn) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = slice$3.call(arguments);
    if (args.length - 1 >= fn.length) {
      return fn.apply(this, args.slice(1));
    }
    return function () {
      var tempArgs = args.concat([].slice.call(arguments));
      return curry$1.apply(this, tempArgs);
    };
  };
  var noop$1 = function () {
  };
  var $_8aqzj925jh8lywmj = {
    constant: constant$1,
    negate: negate,
    and: and,
    or: or,
    curry: curry$1,
    compose: compose$2,
    noop: noop$1
  };

  var cat = function (arr) {
    var r = [];
    var push = function (x) {
      r.push(x);
    };
    for (var i = 0; i < arr.length; i++) {
      arr[i].each(push);
    }
    return r;
  };
  var findMap = function (arr, f) {
    for (var i = 0; i < arr.length; i++) {
      var r = f(arr[i], i);
      if (r.isSome()) {
        return r;
      }
    }
    return Option.none();
  };
  var liftN = function (arr, f) {
    var r = [];
    for (var i = 0; i < arr.length; i++) {
      var x = arr[i];
      if (x.isSome()) {
        r.push(x.getOrDie());
      } else {
        return Option.none();
      }
    }
    return Option.some(f.apply(null, r));
  };
  var $_b8twwq26jh8lywmm = {
    cat: cat,
    findMap: findMap,
    liftN: liftN
  };

  var isElement$3 = $_5oonaz1qjh8lywhz.isElement;
  var isCaretCandidate$1 = isCaretCandidate;
  var isBlock$1 = $_5oonaz1qjh8lywhz.matchStyleValues('display', 'block table');
  var isFloated = $_5oonaz1qjh8lywhz.matchStyleValues('float', 'left right');
  var isValidElementCaretCandidate = $_8aqzj925jh8lywmj.and(isElement$3, isCaretCandidate$1, $_8aqzj925jh8lywmj.negate(isFloated));
  var isNotPre = $_8aqzj925jh8lywmj.negate($_5oonaz1qjh8lywhz.matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  var isText$4 = $_5oonaz1qjh8lywhz.isText;
  var isBr$3 = $_5oonaz1qjh8lywhz.isBr;
  var nodeIndex = DOMUtils$1.nodeIndex;
  var resolveIndex = getNode;
  var createRange = function (doc) {
    return 'createRange' in doc ? doc.createRange() : DOMUtils$1.DOM.createRng();
  };
  var isWhiteSpace = function (chr) {
    return chr && /[\r\n\t ]/.test(chr);
  };
  var isRange = function (rng) {
    return !!rng.setStart && !!rng.setEnd;
  };
  var isHiddenWhiteSpaceRange = function (range) {
    var container = range.startContainer;
    var offset = range.startOffset;
    var text;
    if (isWhiteSpace(range.toString()) && isNotPre(container.parentNode) && $_5oonaz1qjh8lywhz.isText(container)) {
      text = container.data;
      if (isWhiteSpace(text[offset - 1]) || isWhiteSpace(text[offset + 1])) {
        return true;
      }
    }
    return false;
  };
  var getBrClientRect = function (brNode) {
    var doc = brNode.ownerDocument;
    var rng = createRange(doc);
    var nbsp = doc.createTextNode('\xA0');
    var parentNode = brNode.parentNode;
    var clientRect;
    parentNode.insertBefore(nbsp, brNode);
    rng.setStart(nbsp, 0);
    rng.setEnd(nbsp, 1);
    clientRect = clone$1(rng.getBoundingClientRect());
    parentNode.removeChild(nbsp);
    return clientRect;
  };
  var getBoundingClientRectWebKitText = function (rng) {
    var sc = rng.startContainer;
    var ec = rng.endContainer;
    var so = rng.startOffset;
    var eo = rng.endOffset;
    if (sc === ec && $_5oonaz1qjh8lywhz.isText(ec) && so === 0 && eo === 1) {
      var newRng = rng.cloneRange();
      newRng.setEndAfter(ec);
      return getBoundingClientRect(newRng);
    } else {
      return null;
    }
  };
  var isZeroRect = function (r) {
    return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  };
  var getBoundingClientRect = function (item) {
    var clientRect, clientRects;
    clientRects = item.getClientRects();
    if (clientRects.length > 0) {
      clientRect = clone$1(clientRects[0]);
    } else {
      clientRect = clone$1(item.getBoundingClientRect());
    }
    if (!isRange(item) && isBr$3(item) && isZeroRect(clientRect)) {
      return getBrClientRect(item);
    }
    if (isZeroRect(clientRect) && isRange(item)) {
      return getBoundingClientRectWebKitText(item);
    }
    return clientRect;
  };
  var collapseAndInflateWidth = function (clientRect, toStart) {
    var newClientRect = collapse(clientRect, toStart);
    newClientRect.width = 1;
    newClientRect.right = newClientRect.left + 1;
    return newClientRect;
  };
  var getCaretPositionClientRects = function (caretPosition) {
    var clientRects = [];
    var beforeNode, node;
    var addUniqueAndValidRect = function (clientRect) {
      if (clientRect.height === 0) {
        return;
      }
      if (clientRects.length > 0) {
        if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
          return;
        }
      }
      clientRects.push(clientRect);
    };
    var addCharacterOffset = function (container, offset) {
      var range = createRange(container.ownerDocument);
      if (offset < container.data.length) {
        if (isExtendingChar(container.data[offset])) {
          return clientRects;
        }
        if (isExtendingChar(container.data[offset - 1])) {
          range.setStart(container, offset);
          range.setEnd(container, offset + 1);
          if (!isHiddenWhiteSpaceRange(range)) {
            addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
            return clientRects;
          }
        }
      }
      if (offset > 0) {
        range.setStart(container, offset - 1);
        range.setEnd(container, offset);
        if (!isHiddenWhiteSpaceRange(range)) {
          addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
        }
      }
      if (offset < container.data.length) {
        range.setStart(container, offset);
        range.setEnd(container, offset + 1);
        if (!isHiddenWhiteSpaceRange(range)) {
          addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), true));
        }
      }
    };
    if (isText$4(caretPosition.container())) {
      addCharacterOffset(caretPosition.container(), caretPosition.offset());
      return clientRects;
    }
    if (isElement$3(caretPosition.container())) {
      if (caretPosition.isAtEnd()) {
        node = resolveIndex(caretPosition.container(), caretPosition.offset());
        if (isText$4(node)) {
          addCharacterOffset(node, node.data.length);
        }
        if (isValidElementCaretCandidate(node) && !isBr$3(node)) {
          addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
        }
      } else {
        node = resolveIndex(caretPosition.container(), caretPosition.offset());
        if (isText$4(node)) {
          addCharacterOffset(node, 0);
        }
        if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
          addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
          return clientRects;
        }
        beforeNode = resolveIndex(caretPosition.container(), caretPosition.offset() - 1);
        if (isValidElementCaretCandidate(beforeNode) && !isBr$3(beforeNode)) {
          if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
            addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(beforeNode), false));
          }
        }
        if (isValidElementCaretCandidate(node)) {
          addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), true));
        }
      }
    }
    return clientRects;
  };
  function CaretPosition(container, offset, clientRects) {
    var isAtStart = function () {
      if (isText$4(container)) {
        return offset === 0;
      }
      return offset === 0;
    };
    var isAtEnd = function () {
      if (isText$4(container)) {
        return offset >= container.data.length;
      }
      return offset >= container.childNodes.length;
    };
    var toRange = function () {
      var range;
      range = createRange(container.ownerDocument);
      range.setStart(container, offset);
      range.setEnd(container, offset);
      return range;
    };
    var getClientRects = function () {
      if (!clientRects) {
        clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
      }
      return clientRects;
    };
    var isVisible = function () {
      return getClientRects().length > 0;
    };
    var isEqual$$1 = function (caretPosition) {
      return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
    };
    var getNode$$1 = function (before) {
      return resolveIndex(container, before ? offset - 1 : offset);
    };
    return {
      container: $_8aqzj925jh8lywmj.constant(container),
      offset: $_8aqzj925jh8lywmj.constant(offset),
      toRange: toRange,
      getClientRects: getClientRects,
      isVisible: isVisible,
      isAtStart: isAtStart,
      isAtEnd: isAtEnd,
      isEqual: isEqual$$1,
      getNode: getNode$$1
    };
  }
  (function (CaretPosition) {
    CaretPosition.fromRangeStart = function (range) {
      return CaretPosition(range.startContainer, range.startOffset);
    };
    CaretPosition.fromRangeEnd = function (range) {
      return CaretPosition(range.endContainer, range.endOffset);
    };
    CaretPosition.after = function (node) {
      return CaretPosition(node.parentNode, nodeIndex(node) + 1);
    };
    CaretPosition.before = function (node) {
      return CaretPosition(node.parentNode, nodeIndex(node));
    };
    CaretPosition.isAbove = function (pos1, pos2) {
      return $_b8twwq26jh8lywmm.liftN([
        $_5wjzy24jh8lyw2t.head(pos2.getClientRects()),
        $_5wjzy24jh8lyw2t.last(pos1.getClientRects())
      ], isAbove).getOr(false);
    };
    CaretPosition.isBelow = function (pos1, pos2) {
      return $_b8twwq26jh8lywmm.liftN([
        $_5wjzy24jh8lyw2t.last(pos2.getClientRects()),
        $_5wjzy24jh8lyw2t.head(pos1.getClientRects())
      ], isBelow).getOr(false);
    };
    CaretPosition.isAtStart = function (pos) {
      return pos ? pos.isAtStart() : false;
    };
    CaretPosition.isAtEnd = function (pos) {
      return pos ? pos.isAtEnd() : false;
    };
    CaretPosition.isTextPosition = function (pos) {
      return pos ? $_5oonaz1qjh8lywhz.isText(pos.container()) : false;
    };
    CaretPosition.isElementPosition = function (pos) {
      return CaretPosition.isTextPosition(pos) === false;
    };
  }(CaretPosition || (CaretPosition = {})));
  var CaretPosition$1 = CaretPosition;

  var isElement$4 = $_5oonaz1qjh8lywhz.isElement;
  var isText$5 = $_5oonaz1qjh8lywhz.isText;
  var removeNode = function (node) {
    var parentNode = node.parentNode;
    if (parentNode) {
      parentNode.removeChild(node);
    }
  };
  var getNodeValue = function (node) {
    try {
      return node.nodeValue;
    } catch (ex) {
      return '';
    }
  };
  var setNodeValue = function (node, text) {
    if (text.length === 0) {
      removeNode(node);
    } else {
      node.nodeValue = text;
    }
  };
  var trimCount = function (text) {
    var trimmedText = $_d383mr21jh8lywlv.trim(text);
    return {
      count: text.length - trimmedText.length,
      text: trimmedText
    };
  };
  var removeUnchanged = function (caretContainer, pos) {
    remove$2(caretContainer);
    return pos;
  };
  var removeTextAndReposition = function (caretContainer, pos) {
    var before = trimCount(caretContainer.data.substr(0, pos.offset()));
    var after = trimCount(caretContainer.data.substr(pos.offset()));
    var text = before.text + after.text;
    if (text.length > 0) {
      setNodeValue(caretContainer, text);
      return CaretPosition$1(caretContainer, pos.offset() - before.count);
    } else {
      return pos;
    }
  };
  var removeElementAndReposition = function (caretContainer, pos) {
    var parentNode = pos.container();
    var newPosition = $_5wjzy24jh8lyw2t.indexOf($_5wjzy24jh8lyw2t.from(parentNode.childNodes), caretContainer).map(function (index) {
      return index < pos.offset() ? CaretPosition$1(parentNode, pos.offset() - 1) : pos;
    }).getOr(pos);
    remove$2(caretContainer);
    return newPosition;
  };
  var removeTextCaretContainer = function (caretContainer, pos) {
    return isText$5(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  };
  var removeElementCaretContainer = function (caretContainer, pos) {
    return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  };
  var removeAndReposition = function (container, pos) {
    return CaretPosition$1.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  };
  var remove$2 = function (caretContainerNode) {
    if (isElement$4(caretContainerNode) && isCaretContainer(caretContainerNode)) {
      if (hasContent(caretContainerNode)) {
        caretContainerNode.removeAttribute('data-mce-caret');
      } else {
        removeNode(caretContainerNode);
      }
    }
    if (isText$5(caretContainerNode)) {
      var text = $_d383mr21jh8lywlv.trim(getNodeValue(caretContainerNode));
      setNodeValue(caretContainerNode, text);
    }
  };
  var $_9nl16f2ajh8lywne = {
    removeAndReposition: removeAndReposition,
    remove: remove$2
  };

  var walkToPositionIn = function (forward, root, start) {
    var position = forward ? CaretPosition$1.before(start) : CaretPosition$1.after(start);
    return fromPosition(forward, root, position);
  };
  var afterElement = function (node) {
    return $_5oonaz1qjh8lywhz.isBr(node) ? CaretPosition$1.before(node) : CaretPosition$1.after(node);
  };
  var isBeforeOrStart = function (position) {
    if (CaretPosition$1.isTextPosition(position)) {
      return position.offset() === 0;
    } else {
      return isCaretCandidate(position.getNode());
    }
  };
  var isAfterOrEnd = function (position) {
    if (CaretPosition$1.isTextPosition(position)) {
      var container = position.container();
      return position.offset() === container.data.length;
    } else {
      return isCaretCandidate(position.getNode(true));
    }
  };
  var isBeforeAfterSameElement = function (from, to) {
    return !CaretPosition$1.isTextPosition(from) && !CaretPosition$1.isTextPosition(to) && from.getNode() === to.getNode(true);
  };
  var isAtBr = function (position) {
    return !CaretPosition$1.isTextPosition(position) && $_5oonaz1qjh8lywhz.isBr(position.getNode());
  };
  var shouldSkipPosition = function (forward, from, to) {
    if (forward) {
      return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
    } else {
      return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
    }
  };
  var fromPosition = function (forward, root, pos) {
    var walker = CaretWalker(root);
    return Option.from(forward ? walker.next(pos) : walker.prev(pos));
  };
  var navigate = function (forward, root, from) {
    return fromPosition(forward, root, from).bind(function (to) {
      if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
        return fromPosition(forward, root, to);
      } else {
        return Option.some(to);
      }
    });
  };
  var positionIn = function (forward, element) {
    var startNode = forward ? element.firstChild : element.lastChild;
    if ($_5oonaz1qjh8lywhz.isText(startNode)) {
      return Option.some(CaretPosition$1(startNode, forward ? 0 : startNode.data.length));
    } else if (startNode) {
      if (isCaretCandidate(startNode)) {
        return Option.some(forward ? CaretPosition$1.before(startNode) : afterElement(startNode));
      } else {
        return walkToPositionIn(forward, element, startNode);
      }
    } else {
      return Option.none();
    }
  };
  var $_9kvypj2cjh8lywnz = {
    fromPosition: fromPosition,
    nextPosition: $_eqpqvr6jh8lyw3s.curry(fromPosition, true),
    prevPosition: $_eqpqvr6jh8lyw3s.curry(fromPosition, false),
    navigate: navigate,
    positionIn: positionIn,
    firstPositionIn: $_eqpqvr6jh8lyw3s.curry(positionIn, true),
    lastPositionIn: $_eqpqvr6jh8lyw3s.curry(positionIn, false)
  };

  var isContentEditableTrue$2 = $_5oonaz1qjh8lywhz.isContentEditableTrue;
  var isContentEditableFalse$2 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var showCaret = function (direction, editor, node, before, scrollIntoView) {
    return editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView);
  };
  var getNodeRange = function (node) {
    var rng = node.ownerDocument.createRange();
    rng.selectNode(node);
    return rng;
  };
  var selectNode = function (editor, node) {
    var e = editor.fire('BeforeObjectSelected', { target: node });
    if (e.isDefaultPrevented()) {
      return null;
    }
    return getNodeRange(node);
  };
  var renderCaretAtRange = function (editor, range, scrollIntoView) {
    var normalizedRange = normalizeRange(1, editor.getBody(), range);
    var caretPosition = CaretPosition$1.fromRangeStart(normalizedRange);
    var caretPositionNode = caretPosition.getNode();
    if (isContentEditableFalse$2(caretPositionNode)) {
      return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
    }
    var caretPositionBeforeNode = caretPosition.getNode(true);
    if (isContentEditableFalse$2(caretPositionBeforeNode)) {
      return showCaret(1, editor, caretPositionBeforeNode, false, false);
    }
    var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
      return isContentEditableFalse$2(node) || isContentEditableTrue$2(node);
    });
    if (isContentEditableFalse$2(ceRoot)) {
      return showCaret(1, editor, ceRoot, false, scrollIntoView);
    }
    return null;
  };
  var renderRangeCaret = function (editor, range, scrollIntoView) {
    if (!range || !range.collapsed) {
      return range;
    }
    var caretRange = renderCaretAtRange(editor, range, scrollIntoView);
    if (caretRange) {
      return caretRange;
    }
    return range;
  };

  var BreakType;
  (function (BreakType) {
    BreakType[BreakType['Br'] = 0] = 'Br';
    BreakType[BreakType['Block'] = 1] = 'Block';
    BreakType[BreakType['Wrap'] = 2] = 'Wrap';
    BreakType[BreakType['Eol'] = 3] = 'Eol';
  }(BreakType || (BreakType = {})));
  var flip = function (direction, positions) {
    return direction === HDirection.Backwards ? positions.reverse() : positions;
  };
  var walk$1 = function (direction, caretWalker, pos) {
    return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  };
  var getBreakType = function (scope, direction, currentPos, nextPos) {
    if ($_5oonaz1qjh8lywhz.isBr(nextPos.getNode(direction === HDirection.Forwards))) {
      return BreakType.Br;
    } else if (isInSameBlock(currentPos, nextPos) === false) {
      return BreakType.Block;
    } else {
      return BreakType.Wrap;
    }
  };
  var getPositionsUntil = function (predicate, direction, scope, start) {
    var caretWalker = CaretWalker(scope);
    var currentPos = start, nextPos;
    var positions = [];
    while (currentPos) {
      nextPos = walk$1(direction, caretWalker, currentPos);
      if (!nextPos) {
        break;
      }
      if ($_5oonaz1qjh8lywhz.isBr(nextPos.getNode(false))) {
        if (direction === HDirection.Forwards) {
          return {
            positions: flip(direction, positions).concat([nextPos]),
            breakType: BreakType.Br,
            breakAt: Option.some(nextPos)
          };
        } else {
          return {
            positions: flip(direction, positions),
            breakType: BreakType.Br,
            breakAt: Option.some(nextPos)
          };
        }
      }
      if (!nextPos.isVisible()) {
        currentPos = nextPos;
        continue;
      }
      if (predicate(currentPos, nextPos)) {
        var breakType = getBreakType(scope, direction, currentPos, nextPos);
        return {
          positions: flip(direction, positions),
          breakType: breakType,
          breakAt: Option.some(nextPos)
        };
      }
      positions.push(nextPos);
      currentPos = nextPos;
    }
    return {
      positions: flip(direction, positions),
      breakType: BreakType.Eol,
      breakAt: Option.none()
    };
  };
  var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
    return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
      var positions = getPositionsUntilBreak(scope, pos).positions;
      return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
    }).getOr([]);
  };
  var findClosestHorizontalPositionFromPoint = function (positions, x) {
    return $_5wjzy24jh8lyw2t.foldl(positions, function (acc, newPos) {
      return acc.fold(function () {
        return Option.some(newPos);
      }, function (lastPos) {
        return $_b8twwq26jh8lywmm.liftN([
          $_5wjzy24jh8lyw2t.head(lastPos.getClientRects()),
          $_5wjzy24jh8lyw2t.head(newPos.getClientRects())
        ], function (lastRect, newRect) {
          var lastDist = Math.abs(x - lastRect.left);
          var newDist = Math.abs(x - newRect.left);
          return newDist <= lastDist ? newPos : lastPos;
        }).or(acc);
      });
    }, Option.none());
  };
  var findClosestHorizontalPosition = function (positions, pos) {
    return $_5wjzy24jh8lyw2t.head(pos.getClientRects()).bind(function (targetRect) {
      return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
    });
  };
  var getPositionsUntilPreviousLine = $_eqpqvr6jh8lyw3s.curry(getPositionsUntil, CaretPosition.isAbove, -1);
  var getPositionsUntilNextLine = $_eqpqvr6jh8lyw3s.curry(getPositionsUntil, CaretPosition.isBelow, 1);
  var getPositionsAbove = $_eqpqvr6jh8lyw3s.curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  var getPositionsBelow = $_eqpqvr6jh8lyw3s.curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  var getFirstLinePositions = function (scope) {
    return $_9kvypj2cjh8lywnz.firstPositionIn(scope).map(function (pos) {
      return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
    }).getOr([]);
  };
  var getLastLinePositions = function (scope) {
    return $_9kvypj2cjh8lywnz.lastPositionIn(scope).map(function (pos) {
      return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
    }).getOr([]);
  };

  var all$1 = function (predicate) {
    return descendants($_boa99a15jh8lywey.body(), predicate);
  };
  var ancestors = function (scope, predicate, isRoot) {
    return $_5wjzy24jh8lyw2t.filter($_a43q0i17jh8lywfe.parents(scope, isRoot), predicate);
  };
  var siblings$1 = function (scope, predicate) {
    return $_5wjzy24jh8lyw2t.filter($_a43q0i17jh8lywfe.siblings(scope), predicate);
  };
  var children$1 = function (scope, predicate) {
    return $_5wjzy24jh8lyw2t.filter($_a43q0i17jh8lywfe.children(scope), predicate);
  };
  var descendants = function (scope, predicate) {
    var result = [];
    $_5wjzy24jh8lyw2t.each($_a43q0i17jh8lywfe.children(scope), function (x) {
      if (predicate(x)) {
        result = result.concat([x]);
      }
      result = result.concat(descendants(x, predicate));
    });
    return result;
  };
  var $_6y3ft32hjh8lywp5 = {
    all: all$1,
    ancestors: ancestors,
    siblings: siblings$1,
    children: children$1,
    descendants: descendants
  };

  var all$2 = function (selector) {
    return $_5h4ipt1fjh8lywgi.all(selector);
  };
  var ancestors$1 = function (scope, selector, isRoot) {
    return $_6y3ft32hjh8lywp5.ancestors(scope, function (e) {
      return $_5h4ipt1fjh8lywgi.is(e, selector);
    }, isRoot);
  };
  var siblings$2 = function (scope, selector) {
    return $_6y3ft32hjh8lywp5.siblings(scope, function (e) {
      return $_5h4ipt1fjh8lywgi.is(e, selector);
    });
  };
  var children$2 = function (scope, selector) {
    return $_6y3ft32hjh8lywp5.children(scope, function (e) {
      return $_5h4ipt1fjh8lywgi.is(e, selector);
    });
  };
  var descendants$1 = function (scope, selector) {
    return $_5h4ipt1fjh8lywgi.all(selector, scope);
  };
  var $_eebxu2gjh8lywp3 = {
    all: all$2,
    ancestors: ancestors$1,
    siblings: siblings$2,
    children: children$2,
    descendants: descendants$1
  };

  var deflate = function (rect, delta) {
    return {
      left: rect.left - delta,
      top: rect.top - delta,
      right: rect.right + delta * 2,
      bottom: rect.bottom + delta * 2,
      width: rect.width + delta,
      height: rect.height + delta
    };
  };
  var getCorners = function (getYAxisValue, tds) {
    return $_5wjzy24jh8lyw2t.bind(tds, function (td) {
      var rect = deflate(td.getBoundingClientRect(), -1);
      return [
        {
          x: rect.left,
          y: getYAxisValue(rect),
          cell: td
        },
        {
          x: rect.right,
          y: getYAxisValue(rect),
          cell: td
        }
      ];
    });
  };
  var findClosestCorner = function (corners, x, y) {
    return $_5wjzy24jh8lyw2t.foldl(corners, function (acc, newCorner) {
      return acc.fold(function () {
        return Option.some(newCorner);
      }, function (oldCorner) {
        var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
        var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
        return Option.some(newDist < oldDist ? newCorner : oldCorner);
      });
    }, Option.none());
  };
  var getClosestCell = function (getYAxisValue, isTargetCorner, table, x, y) {
    var cells = $_eebxu2gjh8lywp3.descendants($_cgttw3zjh8lywdq.fromDom(table), 'td,th').map(function (e) {
      return e.dom();
    });
    var corners = $_5wjzy24jh8lyw2t.filter(getCorners(getYAxisValue, cells), function (corner) {
      return isTargetCorner(corner, y);
    });
    return findClosestCorner(corners, x, y).map(function (corner) {
      return corner.cell;
    });
  };
  var getBottomValue = function (rect) {
    return rect.bottom;
  };
  var getTopValue = function (rect) {
    return rect.top;
  };
  var isAbove$1 = function (corner, y) {
    return corner.y < y;
  };
  var isBelow$1 = function (corner, y) {
    return corner.y > y;
  };
  var getClosestCellAbove = $_eqpqvr6jh8lyw3s.curry(getClosestCell, getBottomValue, isAbove$1);
  var getClosestCellBelow = $_eqpqvr6jh8lyw3s.curry(getClosestCell, getTopValue, isBelow$1);
  var findClosestPositionInAboveCell = function (table, pos) {
    return $_5wjzy24jh8lyw2t.head(pos.getClientRects()).bind(function (rect) {
      return getClosestCellAbove(table, rect.left, rect.top);
    }).bind(function (cell) {
      return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
    });
  };
  var findClosestPositionInBelowCell = function (table, pos) {
    return $_5wjzy24jh8lyw2t.last(pos.getClientRects()).bind(function (rect) {
      return getClosestCellBelow(table, rect.left, rect.top);
    }).bind(function (cell) {
      return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
    });
  };

  var getPos$1 = function (elm) {
    var x = 0, y = 0;
    var offsetParent = elm;
    while (offsetParent && offsetParent.nodeType) {
      x += offsetParent.offsetLeft || 0;
      y += offsetParent.offsetTop || 0;
      offsetParent = offsetParent.offsetParent;
    }
    return {
      x: x,
      y: y
    };
  };
  var fireScrollIntoViewEvent = function (editor, elm, alignToTop) {
    var scrollEvent = {
      elm: elm,
      alignToTop: alignToTop
    };
    editor.fire('scrollIntoView', scrollEvent);
    return scrollEvent.isDefaultPrevented();
  };
  var scrollElementIntoView = function (editor, elm, alignToTop) {
    var y, viewPort;
    var dom = editor.dom;
    var root = dom.getRoot();
    var viewPortY, viewPortH, offsetY = 0;
    if (fireScrollIntoViewEvent(editor, elm, alignToTop)) {
      return;
    }
    if (!$_5oonaz1qjh8lywhz.isElement(elm)) {
      return;
    }
    if (alignToTop === false) {
      offsetY = elm.offsetHeight;
    }
    if (root.nodeName !== 'BODY') {
      var scrollContainer = editor.selection.getScrollContainer();
      if (scrollContainer) {
        y = getPos$1(elm).y - getPos$1(scrollContainer).y + offsetY;
        viewPortH = scrollContainer.clientHeight;
        viewPortY = scrollContainer.scrollTop;
        if (y < viewPortY || y + 25 > viewPortY + viewPortH) {
          scrollContainer.scrollTop = y < viewPortY ? y : y - viewPortH + 25;
        }
        return;
      }
    }
    viewPort = dom.getViewPort(editor.getWin());
    y = dom.getPos(elm).y + offsetY;
    viewPortY = viewPort.y;
    viewPortH = viewPort.h;
    if (y < viewPort.y || y + 25 > viewPortY + viewPortH) {
      editor.getWin().scrollTo(0, y < viewPortY ? y : y - viewPortH + 25);
    }
  };
  var getViewPortRect = function (editor) {
    if (editor.inline) {
      return editor.getBody().getBoundingClientRect();
    } else {
      var win = editor.getWin();
      return {
        left: 0,
        right: win.innerWidth,
        top: 0,
        bottom: win.innerHeight,
        width: win.innerWidth,
        height: win.innerHeight
      };
    }
  };
  var scrollBy = function (editor, dx, dy) {
    if (editor.inline) {
      editor.getBody().scrollLeft += dx;
      editor.getBody().scrollTop += dy;
    } else {
      editor.getWin().scrollBy(dx, dy);
    }
  };
  var scrollRangeIntoView = function (editor, rng) {
    $_5wjzy24jh8lyw2t.head(CaretPosition.fromRangeStart(rng).getClientRects()).each(function (rngRect) {
      var bodyRect = getViewPortRect(editor);
      var overflow = getOverflow(bodyRect, rngRect);
      var margin = 4;
      var dx = overflow.x > 0 ? overflow.x + margin : overflow.x - margin;
      var dy = overflow.y > 0 ? overflow.y + margin : overflow.y - margin;
      scrollBy(editor, overflow.x !== 0 ? dx : 0, overflow.y !== 0 ? dy : 0);
    });
  };
  var $_cosk3k2ijh8lywpa = {
    scrollElementIntoView: scrollElementIntoView,
    scrollRangeIntoView: scrollRangeIntoView
  };

  var getBodySetting = function (editor, name, defaultValue) {
    var value = editor.getParam(name, defaultValue);
    if (value.indexOf('=') !== -1) {
      var bodyObj = editor.getParam(name, '', 'hash');
      return bodyObj.hasOwnProperty(editor.id) ? bodyObj[editor.id] : defaultValue;
    } else {
      return value;
    }
  };
  var getIframeAttrs = function (editor) {
    return editor.getParam('iframe_attrs', {});
  };
  var getDocType = function (editor) {
    return editor.getParam('doctype', '<!DOCTYPE html>');
  };
  var getDocumentBaseUrl = function (editor) {
    return editor.getParam('document_base_url', '');
  };
  var getBodyId = function (editor) {
    return getBodySetting(editor, 'body_id', 'tinymce');
  };
  var getBodyClass = function (editor) {
    return getBodySetting(editor, 'body_class', '');
  };
  var getContentSecurityPolicy = function (editor) {
    return editor.getParam('content_security_policy', '');
  };
  var shouldPutBrInPre = function (editor) {
    return editor.getParam('br_in_pre', true);
  };
  var getForcedRootBlock = function (editor) {
    if (editor.getParam('force_p_newlines', false)) {
      return 'p';
    }
    var block = editor.getParam('forced_root_block', 'p');
    return block === false ? '' : block;
  };
  var getForcedRootBlockAttrs = function (editor) {
    return editor.getParam('forced_root_block_attrs', {});
  };
  var getBrNewLineSelector = function (editor) {
    return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  };
  var getNoNewLineSelector = function (editor) {
    return editor.getParam('no_newline_selector', '');
  };
  var shouldKeepStyles = function (editor) {
    return editor.getParam('keep_styles', true);
  };
  var shouldEndContainerOnEmptyBlock = function (editor) {
    return editor.getParam('end_container_on_empty_block', false);
  };
  var getFontStyleValues = function (editor) {
    return $_ahowuxkjh8lywbj.explode(editor.getParam('font_size_style_values', ''));
  };
  var getFontSizeClasses = function (editor) {
    return $_ahowuxkjh8lywbj.explode(editor.getParam('font_size_classes', ''));
  };
  var $_66vr6g2jjh8lywpf = {
    getIframeAttrs: getIframeAttrs,
    getDocType: getDocType,
    getDocumentBaseUrl: getDocumentBaseUrl,
    getBodyId: getBodyId,
    getBodyClass: getBodyClass,
    getContentSecurityPolicy: getContentSecurityPolicy,
    shouldPutBrInPre: shouldPutBrInPre,
    getForcedRootBlock: getForcedRootBlock,
    getForcedRootBlockAttrs: getForcedRootBlockAttrs,
    getBrNewLineSelector: getBrNewLineSelector,
    getNoNewLineSelector: getNoNewLineSelector,
    shouldKeepStyles: shouldKeepStyles,
    shouldEndContainerOnEmptyBlock: shouldEndContainerOnEmptyBlock,
    getFontStyleValues: getFontStyleValues,
    getFontSizeClasses: getFontSizeClasses
  };

  var before = function (marker, element) {
    var parent = $_a43q0i17jh8lywfe.parent(marker);
    parent.each(function (v) {
      v.dom().insertBefore(element.dom(), marker.dom());
    });
  };
  var after = function (marker, element) {
    var sibling = $_a43q0i17jh8lywfe.nextSibling(marker);
    sibling.fold(function () {
      var parent = $_a43q0i17jh8lywfe.parent(marker);
      parent.each(function (v) {
        append(v, element);
      });
    }, function (v) {
      before(v, element);
    });
  };
  var prepend = function (parent, element) {
    var firstChild = $_a43q0i17jh8lywfe.firstChild(parent);
    firstChild.fold(function () {
      append(parent, element);
    }, function (v) {
      parent.dom().insertBefore(element.dom(), v.dom());
    });
  };
  var append = function (parent, element) {
    parent.dom().appendChild(element.dom());
  };
  var appendAt = function (parent, element, index) {
    $_a43q0i17jh8lywfe.child(parent, index).fold(function () {
      append(parent, element);
    }, function (v) {
      before(v, element);
    });
  };
  var wrap$1 = function (element, wrapper) {
    before(element, wrapper);
    append(wrapper, element);
  };
  var $_4m7u2e2kjh8lywpi = {
    before: before,
    after: after,
    prepend: prepend,
    append: append,
    appendAt: appendAt,
    wrap: wrap$1
  };

  var browser$2 = $_9hkktfnjh8lywc6.detect().browser;
  var isFakeCaretTableBrowser = function () {
    return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  };
  var moveToRange = function (editor, rng) {
    editor.selection.setRng(rng);
    $_cosk3k2ijh8lywpa.scrollRangeIntoView(editor, rng);
  };
  var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
    var lineInfo = getPositionsUntil(scope, pos);
    if (lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0) {
      return lineInfo.breakAt.map(function (breakPos) {
        return getPositionsUntil(scope, breakPos).breakAt.isNone();
      }).getOr(true);
    } else {
      return lineInfo.breakAt.isNone();
    }
  };
  var isAtFirstTableCellLine = $_8aqzj925jh8lywmj.curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  var isAtLastTableCellLine = $_8aqzj925jh8lywmj.curry(isAtTableCellLine, getPositionsUntilNextLine);
  var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
    var caretPos = CaretPosition$1.fromRangeStart(rng);
    return $_9kvypj2cjh8lywnz.positionIn(!forward, table).map(function (pos) {
      return pos.isEqual(caretPos);
    }).getOr(false);
  };
  var navigateHorizontally = function (editor, forward, table, td) {
    var rng = editor.selection.getRng();
    var direction = forward ? 1 : -1;
    if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
      var newRng = showCaret(direction, editor, table, !forward, true);
      moveToRange(editor, newRng);
      return true;
    }
    return false;
  };
  var getClosestAbovePosition = function (root, table, start) {
    return findClosestPositionInAboveCell(table, start).orThunk(function () {
      return $_5wjzy24jh8lyw2t.head(start.getClientRects()).bind(function (rect) {
        return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition$1.before(table)), rect.left);
      });
    }).getOr(CaretPosition$1.before(table));
  };
  var getClosestBelowPosition = function (root, table, start) {
    return findClosestPositionInBelowCell(table, start).orThunk(function () {
      return $_5wjzy24jh8lyw2t.head(start.getClientRects()).bind(function (rect) {
        return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition$1.after(table)), rect.left);
      });
    }).getOr(CaretPosition$1.after(table));
  };
  var getTable = function (previous, pos) {
    var node = pos.getNode(previous);
    return $_5oonaz1qjh8lywhz.isElement(node) && node.nodeName === 'TABLE' ? Option.some(node) : Option.none();
  };
  var renderBlock = function (down, editor, table, pos) {
    var forcedRootBlock = $_66vr6g2jjh8lywpf.getForcedRootBlock(editor);
    if (forcedRootBlock) {
      editor.undoManager.transact(function () {
        var element = $_cgttw3zjh8lywdq.fromTag(forcedRootBlock);
        $_3da62i14jh8lyweo.setAll(element, $_66vr6g2jjh8lywpf.getForcedRootBlockAttrs(editor));
        $_4m7u2e2kjh8lywpi.append(element, $_cgttw3zjh8lywdq.fromTag('br'));
        if (down) {
          $_4m7u2e2kjh8lywpi.after($_cgttw3zjh8lywdq.fromDom(table), element);
        } else {
          $_4m7u2e2kjh8lywpi.before($_cgttw3zjh8lywdq.fromDom(table), element);
        }
        var rng = editor.dom.createRng();
        rng.setStart(element.dom(), 0);
        rng.setEnd(element.dom(), 0);
        moveToRange(editor, rng);
      });
    } else {
      moveToRange(editor, pos.toRange());
    }
  };
  var moveCaret = function (editor, down, pos) {
    var table = down ? getTable(true, pos) : getTable(false, pos);
    var last = down === false;
    table.fold(function () {
      return moveToRange(editor, pos.toRange());
    }, function (table) {
      return $_9kvypj2cjh8lywnz.positionIn(last, editor.getBody()).filter(function (lastPos) {
        return lastPos.isEqual(pos);
      }).fold(function () {
        return moveToRange(editor, pos.toRange());
      }, function (_) {
        return renderBlock(down, editor, table, pos);
      });
    });
  };
  var navigateVertically = function (editor, down, table, td) {
    var rng = editor.selection.getRng();
    var pos = CaretPosition$1.fromRangeStart(rng);
    var root = editor.getBody();
    if (!down && isAtFirstTableCellLine(td, pos)) {
      var newPos = getClosestAbovePosition(root, table, pos);
      moveCaret(editor, down, newPos);
      return true;
    } else if (down && isAtLastTableCellLine(td, pos)) {
      var newPos = getClosestBelowPosition(root, table, pos);
      moveCaret(editor, down, newPos);
      return true;
    } else {
      return false;
    }
  };
  var moveH = function (editor, forward) {
    return function () {
      return Option.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
        return Option.from(editor.dom.getParent(td, 'table')).map(function (table) {
          return navigateHorizontally(editor, forward, table, td);
        });
      }).getOr(false);
    };
  };
  var moveV = function (editor, forward) {
    return function () {
      return Option.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
        return Option.from(editor.dom.getParent(td, 'table')).map(function (table) {
          return navigateVertically(editor, forward, table, td);
        });
      }).getOr(false);
    };
  };

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var isContentEditableFalse$3 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var isTableCell$1 = function (node) {
    return $_5oonaz1qjh8lywhz.isElement(node) && /^(TD|TH)$/i.test(node.tagName);
  };
  var getAbsoluteClientRect = function (root, element, before) {
    var clientRect = collapse(element.getBoundingClientRect(), before);
    var docElm, scrollX, scrollY, margin, rootRect;
    if (root.tagName === 'BODY') {
      docElm = root.ownerDocument.documentElement;
      scrollX = root.scrollLeft || docElm.scrollLeft;
      scrollY = root.scrollTop || docElm.scrollTop;
    } else {
      rootRect = root.getBoundingClientRect();
      scrollX = root.scrollLeft - rootRect.left;
      scrollY = root.scrollTop - rootRect.top;
    }
    clientRect.left += scrollX;
    clientRect.right += scrollX;
    clientRect.top += scrollY;
    clientRect.bottom += scrollY;
    clientRect.width = 1;
    margin = element.offsetWidth - element.clientWidth;
    if (margin > 0) {
      if (before) {
        margin *= -1;
      }
      clientRect.left += margin;
      clientRect.right += margin;
    }
    return clientRect;
  };
  var trimInlineCaretContainers = function (root) {
    var contentEditableFalseNodes, node, sibling, i, data;
    contentEditableFalseNodes = DomQuery('*[contentEditable=false]', root);
    for (i = 0; i < contentEditableFalseNodes.length; i++) {
      node = contentEditableFalseNodes[i];
      sibling = node.previousSibling;
      if (endsWithCaretContainer(sibling)) {
        data = sibling.data;
        if (data.length === 1) {
          sibling.parentNode.removeChild(sibling);
        } else {
          sibling.deleteData(data.length - 1, 1);
        }
      }
      sibling = node.nextSibling;
      if (startsWithCaretContainer(sibling)) {
        data = sibling.data;
        if (data.length === 1) {
          sibling.parentNode.removeChild(sibling);
        } else {
          sibling.deleteData(0, 1);
        }
      }
    }
  };
  var FakeCaret = function (root, isBlock, hasFocus) {
    var lastVisualCaret = Cell(Option.none());
    var cursorInterval, caretContainerNode;
    var show = function (before, element) {
      var clientRect, rng;
      hide();
      if (isTableCell$1(element)) {
        return null;
      }
      if (isBlock(element)) {
        caretContainerNode = insertBlock('p', element, before);
        clientRect = getAbsoluteClientRect(root, element, before);
        DomQuery(caretContainerNode).css('top', clientRect.top);
        var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(clientRect).appendTo(root)[0];
        lastVisualCaret.set(Option.some({
          caret: caret,
          element: element,
          before: before
        }));
        lastVisualCaret.get().each(function (caretState) {
          if (before) {
            DomQuery(caretState.caret).addClass('mce-visual-caret-before');
          }
        });
        startBlink();
        rng = element.ownerDocument.createRange();
        rng.setStart(caretContainerNode, 0);
        rng.setEnd(caretContainerNode, 0);
      } else {
        caretContainerNode = insertInline(element, before);
        rng = element.ownerDocument.createRange();
        if (isContentEditableFalse$3(caretContainerNode.nextSibling)) {
          rng.setStart(caretContainerNode, 0);
          rng.setEnd(caretContainerNode, 0);
        } else {
          rng.setStart(caretContainerNode, 1);
          rng.setEnd(caretContainerNode, 1);
        }
        return rng;
      }
      return rng;
    };
    var hide = function () {
      trimInlineCaretContainers(root);
      if (caretContainerNode) {
        $_9nl16f2ajh8lywne.remove(caretContainerNode);
        caretContainerNode = null;
      }
      lastVisualCaret.get().each(function (caretState) {
        DomQuery(caretState.caret).remove();
        lastVisualCaret.set(Option.none());
      });
      clearInterval(cursorInterval);
    };
    var startBlink = function () {
      cursorInterval = $_8sy3pfhjh8lyw95.setInterval(function () {
        if (hasFocus()) {
          DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
        } else {
          DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
        }
      }, 500);
    };
    var reposition = function () {
      lastVisualCaret.get().each(function (caretState) {
        var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
        DomQuery(caretState.caret).css(clientRect);
      });
    };
    var destroy = function () {
      return $_8sy3pfhjh8lyw95.clearInterval(cursorInterval);
    };
    var getCss = function () {
      return '.mce-visual-caret {' + 'position: absolute;' + 'background-color: black;' + 'background-color: currentcolor;' + '}' + '.mce-visual-caret-hidden {' + 'display: none;' + '}' + '*[data-mce-caret] {' + 'position: absolute;' + 'left: -1000px;' + 'right: auto;' + 'top: 0;' + 'margin: 0;' + 'padding: 0;' + '}';
    };
    return {
      show: show,
      hide: hide,
      getCss: getCss,
      reposition: reposition,
      destroy: destroy
    };
  };
  var isFakeCaretTarget = function (node) {
    return isContentEditableFalse$3(node) || $_5oonaz1qjh8lywhz.isTable(node) && isFakeCaretTableBrowser();
  };

  var isContentEditableFalse$4 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var isBlockLike = $_5oonaz1qjh8lywhz.matchStyleValues('display', 'block table table-cell table-caption list-item');
  var isCaretContainer$2 = isCaretContainer;
  var isCaretContainerBlock$1 = isCaretContainerBlock;
  var curry$2 = $_8aqzj925jh8lywmj.curry;
  var isElement$5 = $_5oonaz1qjh8lywhz.isElement;
  var isCaretCandidate$2 = isCaretCandidate;
  var isForwards = function (direction) {
    return direction > 0;
  };
  var isBackwards = function (direction) {
    return direction < 0;
  };
  var skipCaretContainers = function (walk, shallow) {
    var node;
    while (node = walk(shallow)) {
      if (!isCaretContainerBlock$1(node)) {
        return node;
      }
    }
    return null;
  };
  var findNode = function (node, direction, predicateFn, rootNode, shallow) {
    var walker = new TreeWalker(node, rootNode);
    if (isBackwards(direction)) {
      if (isContentEditableFalse$4(node) || isCaretContainerBlock$1(node)) {
        node = skipCaretContainers(walker.prev, true);
        if (predicateFn(node)) {
          return node;
        }
      }
      while (node = skipCaretContainers(walker.prev, shallow)) {
        if (predicateFn(node)) {
          return node;
        }
      }
    }
    if (isForwards(direction)) {
      if (isContentEditableFalse$4(node) || isCaretContainerBlock$1(node)) {
        node = skipCaretContainers(walker.next, true);
        if (predicateFn(node)) {
          return node;
        }
      }
      while (node = skipCaretContainers(walker.next, shallow)) {
        if (predicateFn(node)) {
          return node;
        }
      }
    }
    return null;
  };
  var getParentBlock = function (node, rootNode) {
    while (node && node !== rootNode) {
      if (isBlockLike(node)) {
        return node;
      }
      node = node.parentNode;
    }
    return null;
  };
  var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
    return getParentBlock(caretPosition1.container(), rootNode) === getParentBlock(caretPosition2.container(), rootNode);
  };
  var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
    var container, offset;
    if (!caretPosition) {
      return null;
    }
    container = caretPosition.container();
    offset = caretPosition.offset();
    if (!isElement$5(container)) {
      return null;
    }
    return container.childNodes[offset + relativeOffset];
  };
  var beforeAfter = function (before, node) {
    var range = node.ownerDocument.createRange();
    if (before) {
      range.setStartBefore(node);
      range.setEndBefore(node);
    } else {
      range.setStartAfter(node);
      range.setEndAfter(node);
    }
    return range;
  };
  var isNodesInSameBlock = function (root, node1, node2) {
    return getParentBlock(node1, root) === getParentBlock(node2, root);
  };
  var lean = function (left, root, node) {
    var sibling, siblingName;
    if (left) {
      siblingName = 'previousSibling';
    } else {
      siblingName = 'nextSibling';
    }
    while (node && node !== root) {
      sibling = node[siblingName];
      if (isCaretContainer$2(sibling)) {
        sibling = sibling[siblingName];
      }
      if (isContentEditableFalse$4(sibling)) {
        if (isNodesInSameBlock(root, sibling, node)) {
          return sibling;
        }
        break;
      }
      if (isCaretCandidate$2(sibling)) {
        break;
      }
      node = node.parentNode;
    }
    return null;
  };
  var before$1 = curry$2(beforeAfter, true);
  var after$1 = curry$2(beforeAfter, false);
  var normalizeRange = function (direction, root, range) {
    var node, container, offset, location;
    var leanLeft = curry$2(lean, true, root);
    var leanRight = curry$2(lean, false, root);
    container = range.startContainer;
    offset = range.startOffset;
    if (isCaretContainerBlock(container)) {
      if (!isElement$5(container)) {
        container = container.parentNode;
      }
      location = container.getAttribute('data-mce-caret');
      if (location === 'before') {
        node = container.nextSibling;
        if (isFakeCaretTarget(node)) {
          return before$1(node);
        }
      }
      if (location === 'after') {
        node = container.previousSibling;
        if (isFakeCaretTarget(node)) {
          return after$1(node);
        }
      }
    }
    if (!range.collapsed) {
      return range;
    }
    if ($_5oonaz1qjh8lywhz.isText(container)) {
      if (isCaretContainer$2(container)) {
        if (direction === 1) {
          node = leanRight(container);
          if (node) {
            return before$1(node);
          }
          node = leanLeft(container);
          if (node) {
            return after$1(node);
          }
        }
        if (direction === -1) {
          node = leanLeft(container);
          if (node) {
            return after$1(node);
          }
          node = leanRight(container);
          if (node) {
            return before$1(node);
          }
        }
        return range;
      }
      if (endsWithCaretContainer(container) && offset >= container.data.length - 1) {
        if (direction === 1) {
          node = leanRight(container);
          if (node) {
            return before$1(node);
          }
        }
        return range;
      }
      if (startsWithCaretContainer(container) && offset <= 1) {
        if (direction === -1) {
          node = leanLeft(container);
          if (node) {
            return after$1(node);
          }
        }
        return range;
      }
      if (offset === container.data.length) {
        node = leanRight(container);
        if (node) {
          return before$1(node);
        }
        return range;
      }
      if (offset === 0) {
        node = leanLeft(container);
        if (node) {
          return after$1(node);
        }
        return range;
      }
    }
    return range;
  };
  var isNextToContentEditableFalse = function (relativeOffset, caretPosition) {
    var node = getChildNodeAtRelativeOffset(relativeOffset, caretPosition);
    return isContentEditableFalse$4(node) && !$_5oonaz1qjh8lywhz.isBogusAll(node);
  };
  var isNextToTable = function (relativeOffset, caretPosition) {
    return $_5oonaz1qjh8lywhz.isTable(getChildNodeAtRelativeOffset(relativeOffset, caretPosition));
  };
  var getRelativeCefElm = function (forward, caretPosition) {
    return Option.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$4);
  };
  var getNormalizedRangeEndPoint = function (direction, root, range) {
    var normalizedRange = normalizeRange(direction, root, range);
    if (direction === -1) {
      return CaretPosition.fromRangeStart(normalizedRange);
    }
    return CaretPosition.fromRangeEnd(normalizedRange);
  };
  var isBeforeContentEditableFalse = curry$2(isNextToContentEditableFalse, 0);
  var isAfterContentEditableFalse = curry$2(isNextToContentEditableFalse, -1);
  var isBeforeTable = curry$2(isNextToTable, 0);
  var isAfterTable = curry$2(isNextToTable, -1);

  var HDirection;
  (function (HDirection) {
    HDirection[HDirection['Backwards'] = -1] = 'Backwards';
    HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  }(HDirection || (HDirection = {})));
  var isContentEditableFalse$5 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var isText$6 = $_5oonaz1qjh8lywhz.isText;
  var isElement$6 = $_5oonaz1qjh8lywhz.isElement;
  var isBr$4 = $_5oonaz1qjh8lywhz.isBr;
  var isCaretCandidate$3 = isCaretCandidate;
  var isAtomic$1 = isAtomic;
  var isEditableCaretCandidate$1 = isEditableCaretCandidate;
  var getParents = function (node, root) {
    var parents = [];
    while (node && node !== root) {
      parents.push(node);
      node = node.parentNode;
    }
    return parents;
  };
  var nodeAtIndex = function (container, offset) {
    if (container.hasChildNodes() && offset < container.childNodes.length) {
      return container.childNodes[offset];
    }
    return null;
  };
  var getCaretCandidatePosition = function (direction, node) {
    if (isForwards(direction)) {
      if (isCaretCandidate$3(node.previousSibling) && !isText$6(node.previousSibling)) {
        return CaretPosition$1.before(node);
      }
      if (isText$6(node)) {
        return CaretPosition$1(node, 0);
      }
    }
    if (isBackwards(direction)) {
      if (isCaretCandidate$3(node.nextSibling) && !isText$6(node.nextSibling)) {
        return CaretPosition$1.after(node);
      }
      if (isText$6(node)) {
        return CaretPosition$1(node, node.data.length);
      }
    }
    if (isBackwards(direction)) {
      if (isBr$4(node)) {
        return CaretPosition$1.before(node);
      }
      return CaretPosition$1.after(node);
    }
    return CaretPosition$1.before(node);
  };
  var isBrBeforeBlock = function (node, root) {
    var next;
    if (!$_5oonaz1qjh8lywhz.isBr(node)) {
      return false;
    }
    next = findCaretPosition(1, CaretPosition$1.after(node), root);
    if (!next) {
      return false;
    }
    return !isInSameBlock(CaretPosition$1.before(node), CaretPosition$1.before(next), root);
  };
  var findCaretPosition = function (direction, startPos, root) {
    var node, nextNode, innerNode;
    var rootContentEditableFalseElm, caretPosition;
    if (!isElement$6(root) || !startPos) {
      return null;
    }
    if (startPos.isEqual(CaretPosition$1.after(root)) && root.lastChild) {
      caretPosition = CaretPosition$1.after(root.lastChild);
      if (isBackwards(direction) && isCaretCandidate$3(root.lastChild) && isElement$6(root.lastChild)) {
        return isBr$4(root.lastChild) ? CaretPosition$1.before(root.lastChild) : caretPosition;
      }
    } else {
      caretPosition = startPos;
    }
    var container = caretPosition.container();
    var offset = caretPosition.offset();
    if (isText$6(container)) {
      if (isBackwards(direction) && offset > 0) {
        return CaretPosition$1(container, --offset);
      }
      if (isForwards(direction) && offset < container.length) {
        return CaretPosition$1(container, ++offset);
      }
      node = container;
    } else {
      if (isBackwards(direction) && offset > 0) {
        nextNode = nodeAtIndex(container, offset - 1);
        if (isCaretCandidate$3(nextNode)) {
          if (!isAtomic$1(nextNode)) {
            innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
            if (innerNode) {
              if (isText$6(innerNode)) {
                return CaretPosition$1(innerNode, innerNode.data.length);
              }
              return CaretPosition$1.after(innerNode);
            }
          }
          if (isText$6(nextNode)) {
            return CaretPosition$1(nextNode, nextNode.data.length);
          }
          return CaretPosition$1.before(nextNode);
        }
      }
      if (isForwards(direction) && offset < container.childNodes.length) {
        nextNode = nodeAtIndex(container, offset);
        if (isCaretCandidate$3(nextNode)) {
          if (isBr$4(nextNode) && root.lastChild === nextNode) {
            return null;
          }
          if (isBrBeforeBlock(nextNode, root)) {
            return findCaretPosition(direction, CaretPosition$1.after(nextNode), root);
          }
          if (!isAtomic$1(nextNode)) {
            innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
            if (innerNode) {
              if (isText$6(innerNode)) {
                return CaretPosition$1(innerNode, 0);
              }
              return CaretPosition$1.before(innerNode);
            }
          }
          if (isText$6(nextNode)) {
            return CaretPosition$1(nextNode, 0);
          }
          return CaretPosition$1.after(nextNode);
        }
      }
      node = nextNode ? nextNode : caretPosition.getNode();
    }
    if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
      node = findNode(node, direction, $_8aqzj925jh8lywmj.constant(true), root, true);
      if (isEditableCaretCandidate$1(node, root)) {
        return getCaretCandidatePosition(direction, node);
      }
    }
    nextNode = findNode(node, direction, isEditableCaretCandidate$1, root);
    rootContentEditableFalseElm = $_9tjm51ljh8lywbq.last($_9tjm51ljh8lywbq.filter(getParents(container, root), isContentEditableFalse$5));
    if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
      if (isForwards(direction)) {
        caretPosition = CaretPosition$1.after(rootContentEditableFalseElm);
      } else {
        caretPosition = CaretPosition$1.before(rootContentEditableFalseElm);
      }
      return caretPosition;
    }
    if (nextNode) {
      return getCaretCandidatePosition(direction, nextNode);
    }
    return null;
  };
  var CaretWalker = function (root) {
    return {
      next: function (caretPosition) {
        return findCaretPosition(HDirection.Forwards, caretPosition, root);
      },
      prev: function (caretPosition) {
        return findCaretPosition(HDirection.Backwards, caretPosition, root);
      }
    };
  };

  var hasOnlyOneChild = function (node) {
    return node.firstChild && node.firstChild === node.lastChild;
  };
  var isPaddingNode = function (node) {
    return node.name === 'br' || node.value === '\xA0';
  };
  var isPaddedEmptyBlock = function (schema, node) {
    var blockElements = schema.getBlockElements();
    return blockElements[node.name] && hasOnlyOneChild(node) && isPaddingNode(node.firstChild);
  };
  var isEmptyFragmentElement = function (schema, node) {
    var nonEmptyElements = schema.getNonEmptyElements();
    return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  };
  var isListFragment = function (schema, fragment) {
    var firstChild = fragment.firstChild;
    var lastChild = fragment.lastChild;
    if (firstChild && firstChild.name === 'meta') {
      firstChild = firstChild.next;
    }
    if (lastChild && lastChild.attr('id') === 'mce_marker') {
      lastChild = lastChild.prev;
    }
    if (isEmptyFragmentElement(schema, lastChild)) {
      lastChild = lastChild.prev;
    }
    if (!firstChild || firstChild !== lastChild) {
      return false;
    }
    return firstChild.name === 'ul' || firstChild.name === 'ol';
  };
  var cleanupDomFragment = function (domFragment) {
    var firstChild = domFragment.firstChild;
    var lastChild = domFragment.lastChild;
    if (firstChild && firstChild.nodeName === 'META') {
      firstChild.parentNode.removeChild(firstChild);
    }
    if (lastChild && lastChild.id === 'mce_marker') {
      lastChild.parentNode.removeChild(lastChild);
    }
    return domFragment;
  };
  var toDomFragment = function (dom, serializer, fragment) {
    var html = serializer.serialize(fragment);
    var domFragment = dom.createFragment(html);
    return cleanupDomFragment(domFragment);
  };
  var listItems$1 = function (elm) {
    return $_ahowuxkjh8lywbj.grep(elm.childNodes, function (child) {
      return child.nodeName === 'LI';
    });
  };
  var isPadding = function (node) {
    return node.data === '\xA0' || $_5oonaz1qjh8lywhz.isBr(node);
  };
  var isListItemPadded = function (node) {
    return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  };
  var isEmptyOrPadded = function (elm) {
    return !elm.firstChild || isListItemPadded(elm);
  };
  var trimListItems = function (elms) {
    return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  };
  var getParentLi = function (dom, node) {
    var parentBlock = dom.getParent(node, dom.isBlock);
    return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  };
  var isParentBlockLi = function (dom, node) {
    return !!getParentLi(dom, node);
  };
  var getSplit = function (parentNode, rng) {
    var beforeRng = rng.cloneRange();
    var afterRng = rng.cloneRange();
    beforeRng.setStartBefore(parentNode);
    afterRng.setEndAfter(parentNode);
    return [
      beforeRng.cloneContents(),
      afterRng.cloneContents()
    ];
  };
  var findFirstIn = function (node, rootNode) {
    var caretPos = CaretPosition$1.before(node);
    var caretWalker = CaretWalker(rootNode);
    var newCaretPos = caretWalker.next(caretPos);
    return newCaretPos ? newCaretPos.toRange() : null;
  };
  var findLastOf = function (node, rootNode) {
    var caretPos = CaretPosition$1.after(node);
    var caretWalker = CaretWalker(rootNode);
    var newCaretPos = caretWalker.prev(caretPos);
    return newCaretPos ? newCaretPos.toRange() : null;
  };
  var insertMiddle = function (target, elms, rootNode, rng) {
    var parts = getSplit(target, rng);
    var parentElm = target.parentNode;
    parentElm.insertBefore(parts[0], target);
    $_ahowuxkjh8lywbj.each(elms, function (li) {
      parentElm.insertBefore(li, target);
    });
    parentElm.insertBefore(parts[1], target);
    parentElm.removeChild(target);
    return findLastOf(elms[elms.length - 1], rootNode);
  };
  var insertBefore = function (target, elms, rootNode) {
    var parentElm = target.parentNode;
    $_ahowuxkjh8lywbj.each(elms, function (elm) {
      parentElm.insertBefore(elm, target);
    });
    return findFirstIn(target, rootNode);
  };
  var insertAfter = function (target, elms, rootNode, dom) {
    dom.insertAfter(elms.reverse(), target);
    return findLastOf(elms[0], rootNode);
  };
  var insertAtCaret = function (serializer, dom, rng, fragment) {
    var domFragment = toDomFragment(dom, serializer, fragment);
    var liTarget = getParentLi(dom, rng.startContainer);
    var liElms = trimListItems(listItems$1(domFragment.firstChild));
    var BEGINNING = 1, END = 2;
    var rootNode = dom.getRoot();
    var isAt = function (location) {
      var caretPos = CaretPosition$1.fromRangeStart(rng);
      var caretWalker = CaretWalker(dom.getRoot());
      var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
      return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
    };
    if (isAt(BEGINNING)) {
      return insertBefore(liTarget, liElms, rootNode);
    } else if (isAt(END)) {
      return insertAfter(liTarget, liElms, rootNode, dom);
    }
    return insertMiddle(liTarget, liElms, rootNode, rng);
  };
  var $_eajoh11xjh8lywl6 = {
    isListFragment: isListFragment,
    insertAtCaret: insertAtCaret,
    isParentBlockLi: isParentBlockLi,
    trimListItems: trimListItems,
    listItems: listItems$1
  };

  var isText$7 = $_5oonaz1qjh8lywhz.isText;
  var isBogus$1 = $_5oonaz1qjh8lywhz.isBogus;
  var nodeIndex$1 = DOMUtils$1.nodeIndex;
  var normalizedParent = function (node) {
    var parentNode = node.parentNode;
    if (isBogus$1(parentNode)) {
      return normalizedParent(parentNode);
    }
    return parentNode;
  };
  var getChildNodes = function (node) {
    if (!node) {
      return [];
    }
    return $_9tjm51ljh8lywbq.reduce(node.childNodes, function (result, node) {
      if (isBogus$1(node) && node.nodeName !== 'BR') {
        result = result.concat(getChildNodes(node));
      } else {
        result.push(node);
      }
      return result;
    }, []);
  };
  var normalizedTextOffset = function (node, offset) {
    while (node = node.previousSibling) {
      if (!isText$7(node)) {
        break;
      }
      offset += node.data.length;
    }
    return offset;
  };
  var equal$1 = function (a) {
    return function (b) {
      return a === b;
    };
  };
  var normalizedNodeIndex = function (node) {
    var nodes, index, numTextFragments;
    nodes = getChildNodes(normalizedParent(node));
    index = $_9tjm51ljh8lywbq.findIndex(nodes, equal$1(node), node);
    nodes = nodes.slice(0, index + 1);
    numTextFragments = $_9tjm51ljh8lywbq.reduce(nodes, function (result, node, i) {
      if (isText$7(node) && isText$7(nodes[i - 1])) {
        result++;
      }
      return result;
    }, 0);
    nodes = $_9tjm51ljh8lywbq.filter(nodes, $_5oonaz1qjh8lywhz.matchNodeNames(node.nodeName));
    index = $_9tjm51ljh8lywbq.findIndex(nodes, equal$1(node), node);
    return index - numTextFragments;
  };
  var createPathItem = function (node) {
    var name;
    if (isText$7(node)) {
      name = 'text()';
    } else {
      name = node.nodeName.toLowerCase();
    }
    return name + '[' + normalizedNodeIndex(node) + ']';
  };
  var parentsUntil = function (root, node, predicate) {
    var parents = [];
    for (node = node.parentNode; node !== root; node = node.parentNode) {
      if (predicate && predicate(node)) {
        break;
      }
      parents.push(node);
    }
    return parents;
  };
  var create$1 = function (root, caretPosition) {
    var container, offset, path = [], outputOffset, childNodes, parents;
    container = caretPosition.container();
    offset = caretPosition.offset();
    if (isText$7(container)) {
      outputOffset = normalizedTextOffset(container, offset);
    } else {
      childNodes = container.childNodes;
      if (offset >= childNodes.length) {
        outputOffset = 'after';
        offset = childNodes.length - 1;
      } else {
        outputOffset = 'before';
      }
      container = childNodes[offset];
    }
    path.push(createPathItem(container));
    parents = parentsUntil(root, container);
    parents = $_9tjm51ljh8lywbq.filter(parents, $_8aqzj925jh8lywmj.negate($_5oonaz1qjh8lywhz.isBogus));
    path = path.concat($_9tjm51ljh8lywbq.map(parents, function (node) {
      return createPathItem(node);
    }));
    return path.reverse().join('/') + ',' + outputOffset;
  };
  var resolvePathItem = function (node, name, index) {
    var nodes = getChildNodes(node);
    nodes = $_9tjm51ljh8lywbq.filter(nodes, function (node, index) {
      return !isText$7(node) || !isText$7(nodes[index - 1]);
    });
    nodes = $_9tjm51ljh8lywbq.filter(nodes, $_5oonaz1qjh8lywhz.matchNodeNames(name));
    return nodes[index];
  };
  var findTextPosition = function (container, offset) {
    var node = container, targetOffset = 0, dataLen;
    while (isText$7(node)) {
      dataLen = node.data.length;
      if (offset >= targetOffset && offset <= targetOffset + dataLen) {
        container = node;
        offset = offset - targetOffset;
        break;
      }
      if (!isText$7(node.nextSibling)) {
        container = node;
        offset = dataLen;
        break;
      }
      targetOffset += dataLen;
      node = node.nextSibling;
    }
    if (isText$7(container) && offset > container.data.length) {
      offset = container.data.length;
    }
    return CaretPosition$1(container, offset);
  };
  var resolve$2 = function (root, path) {
    var parts, container, offset;
    if (!path) {
      return null;
    }
    parts = path.split(',');
    path = parts[0].split('/');
    offset = parts.length > 1 ? parts[1] : 'before';
    container = $_9tjm51ljh8lywbq.reduce(path, function (result, value) {
      value = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
      if (!value) {
        return null;
      }
      if (value[1] === 'text()') {
        value[1] = '#text';
      }
      return resolvePathItem(result, value[1], parseInt(value[2], 10));
    }, root);
    if (!container) {
      return null;
    }
    if (!isText$7(container)) {
      if (offset === 'after') {
        offset = nodeIndex$1(container) + 1;
      } else {
        offset = nodeIndex$1(container);
      }
      return CaretPosition$1(container.parentNode, offset);
    }
    return findTextPosition(container, parseInt(offset, 10));
  };

  var isContentEditableFalse$6 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var getNormalizedTextOffset = function (trim, container, offset) {
    var node, trimmedOffset;
    trimmedOffset = trim(container.data.slice(0, offset)).length;
    for (node = container.previousSibling; node && $_5oonaz1qjh8lywhz.isText(node); node = node.previousSibling) {
      trimmedOffset += trim(node.data).length;
    }
    return trimmedOffset;
  };
  var getPoint = function (dom, trim, normalized, rng, start) {
    var container = rng[start ? 'startContainer' : 'endContainer'];
    var offset = rng[start ? 'startOffset' : 'endOffset'];
    var point = [];
    var childNodes, after = 0;
    var root = dom.getRoot();
    if ($_5oonaz1qjh8lywhz.isText(container)) {
      point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
    } else {
      childNodes = container.childNodes;
      if (offset >= childNodes.length && childNodes.length) {
        after = 1;
        offset = Math.max(0, childNodes.length - 1);
      }
      point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
    }
    for (; container && container !== root; container = container.parentNode) {
      point.push(dom.nodeIndex(container, normalized));
    }
    return point;
  };
  var getLocation = function (trim, selection, normalized, rng) {
    var dom = selection.dom, bookmark = {};
    bookmark.start = getPoint(dom, trim, normalized, rng, true);
    if (!selection.isCollapsed()) {
      bookmark.end = getPoint(dom, trim, normalized, rng, false);
    }
    return bookmark;
  };
  var trimEmptyTextNode = function (node) {
    if ($_5oonaz1qjh8lywhz.isText(node) && node.data.length === 0) {
      node.parentNode.removeChild(node);
    }
  };
  var findIndex$3 = function (dom, name, element) {
    var count = 0;
    $_ahowuxkjh8lywbj.each(dom.select(name), function (node) {
      if (node.getAttribute('data-mce-bogus') === 'all') {
        return;
      }
      if (node === element) {
        return false;
      }
      count++;
    });
    return count;
  };
  var moveEndPoint = function (rng, start) {
    var container, offset, childNodes;
    var prefix = start ? 'start' : 'end';
    container = rng[prefix + 'Container'];
    offset = rng[prefix + 'Offset'];
    if ($_5oonaz1qjh8lywhz.isElement(container) && container.nodeName === 'TR') {
      childNodes = container.childNodes;
      container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
      if (container) {
        offset = start ? 0 : container.childNodes.length;
        rng['set' + (start ? 'Start' : 'End')](container, offset);
      }
    }
  };
  var normalizeTableCellSelection = function (rng) {
    moveEndPoint(rng, true);
    moveEndPoint(rng, false);
    return rng;
  };
  var findSibling = function (node, offset) {
    var sibling;
    if ($_5oonaz1qjh8lywhz.isElement(node)) {
      node = getNode(node, offset);
      if (isContentEditableFalse$6(node)) {
        return node;
      }
    }
    if (isCaretContainer(node)) {
      if ($_5oonaz1qjh8lywhz.isText(node) && isCaretContainerBlock(node)) {
        node = node.parentNode;
      }
      sibling = node.previousSibling;
      if (isContentEditableFalse$6(sibling)) {
        return sibling;
      }
      sibling = node.nextSibling;
      if (isContentEditableFalse$6(sibling)) {
        return sibling;
      }
    }
  };
  var findAdjacentContentEditableFalseElm = function (rng) {
    return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  };
  var getOffsetBookmark = function (trim, normalized, selection) {
    var element = selection.getNode();
    var name = element ? element.nodeName : null;
    var rng = selection.getRng();
    if (isContentEditableFalse$6(element) || name === 'IMG') {
      return {
        name: name,
        index: findIndex$3(selection.dom, name, element)
      };
    }
    var sibling = findAdjacentContentEditableFalseElm(rng);
    if (sibling) {
      name = sibling.tagName;
      return {
        name: name,
        index: findIndex$3(selection.dom, name, sibling)
      };
    }
    return getLocation(trim, selection, normalized, rng);
  };
  var getCaretBookmark = function (selection) {
    var rng = selection.getRng();
    return {
      start: create$1(selection.dom.getRoot(), CaretPosition$1.fromRangeStart(rng)),
      end: create$1(selection.dom.getRoot(), CaretPosition$1.fromRangeEnd(rng))
    };
  };
  var getRangeBookmark = function (selection) {
    return { rng: selection.getRng() };
  };
  var createBookmarkSpan = function (dom, id, filled) {
    var args = {
      'data-mce-type': 'bookmark',
      'id': id,
      'style': 'overflow:hidden;line-height:0px'
    };
    return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  };
  var getPersistentBookmark = function (selection, filled) {
    var dom = selection.dom;
    var rng = selection.getRng();
    var id = dom.uniqueId();
    var collapsed = selection.isCollapsed();
    var element = selection.getNode();
    var name = element.nodeName;
    if (name === 'IMG') {
      return {
        name: name,
        index: findIndex$3(dom, name, element)
      };
    }
    var rng2 = normalizeTableCellSelection(rng.cloneRange());
    if (!collapsed) {
      rng2.collapse(false);
      var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
      rng2.insertNode(endBookmarkNode);
      trimEmptyTextNode(endBookmarkNode.nextSibling);
    }
    rng = normalizeTableCellSelection(rng);
    rng.collapse(true);
    var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
    rng.insertNode(startBookmarkNode);
    trimEmptyTextNode(startBookmarkNode.previousSibling);
    selection.moveToBookmark({
      id: id,
      keep: 1
    });
    return { id: id };
  };
  var getBookmark = function (selection, type, normalized) {
    if (type === 2) {
      return getOffsetBookmark($_d383mr21jh8lywlv.trim, normalized, selection);
    } else if (type === 3) {
      return getCaretBookmark(selection);
    } else if (type) {
      return getRangeBookmark(selection);
    } else {
      return getPersistentBookmark(selection, false);
    }
  };
  var $_8b82yg2ojh8lywpq = {
    getBookmark: getBookmark,
    getUndoBookmark: $_eqpqvr6jh8lyw3s.curry(getOffsetBookmark, $_eqpqvr6jh8lyw3s.identity, true),
    getPersistentBookmark: getPersistentBookmark
  };

  var CARET_ID = '_mce_caret';
  var isCaretNode = function (node) {
    return $_5oonaz1qjh8lywhz.isElement(node) && node.id === CARET_ID;
  };
  var getParentCaretContainer = function (body, node) {
    while (node && node !== body) {
      if (node.id === CARET_ID) {
        return node;
      }
      node = node.parentNode;
    }
    return null;
  };

  var isStringPathBookmark = function (bookmark) {
    return typeof bookmark.start === 'string';
  };
  var isRangeBookmark = function (bookmark) {
    return bookmark.hasOwnProperty('rng');
  };
  var isIdBookmark = function (bookmark) {
    return bookmark.hasOwnProperty('id');
  };
  var isIndexBookmark = function (bookmark) {
    return bookmark.hasOwnProperty('name');
  };
  var isPathBookmark = function (bookmark) {
    return $_ahowuxkjh8lywbj.isArray(bookmark.start);
  };

  var addBogus = function (dom, node) {
    if (dom.isBlock(node) && !node.innerHTML && !$_9bpim8ajh8lyw68.ie) {
      node.innerHTML = '<br data-mce-bogus="1" />';
    }
    return node;
  };
  var resolveCaretPositionBookmark = function (dom, bookmark) {
    var rng, pos;
    rng = dom.createRng();
    pos = resolve$2(dom.getRoot(), bookmark.start);
    rng.setStart(pos.container(), pos.offset());
    pos = resolve$2(dom.getRoot(), bookmark.end);
    rng.setEnd(pos.container(), pos.offset());
    return rng;
  };
  var insertZwsp = function (node, rng) {
    var textNode = node.ownerDocument.createTextNode($_d383mr21jh8lywlv.ZWSP);
    node.appendChild(textNode);
    rng.setStart(textNode, 0);
    rng.setEnd(textNode, 0);
  };
  var isEmpty = function (node) {
    return node.hasChildNodes() === false;
  };
  var tryFindRangePosition = function (node, rng) {
    return $_9kvypj2cjh8lywnz.lastPositionIn(node).fold(function () {
      return false;
    }, function (pos) {
      rng.setStart(pos.container(), pos.offset());
      rng.setEnd(pos.container(), pos.offset());
      return true;
    });
  };
  var padEmptyCaretContainer = function (root, node, rng) {
    if (isEmpty(node) && getParentCaretContainer(root, node)) {
      insertZwsp(node, rng);
      return true;
    } else {
      return false;
    }
  };
  var setEndPoint = function (dom, start, bookmark, rng) {
    var point = bookmark[start ? 'start' : 'end'];
    var i, node, offset, children;
    var root = dom.getRoot();
    if (point) {
      offset = point[0];
      for (node = root, i = point.length - 1; i >= 1; i--) {
        children = node.childNodes;
        if (padEmptyCaretContainer(root, node, rng)) {
          return true;
        }
        if (point[i] > children.length - 1) {
          if (padEmptyCaretContainer(root, node, rng)) {
            return true;
          }
          return tryFindRangePosition(node, rng);
        }
        node = children[point[i]];
      }
      if (node.nodeType === 3) {
        offset = Math.min(point[0], node.nodeValue.length);
      }
      if (node.nodeType === 1) {
        offset = Math.min(point[0], node.childNodes.length);
      }
      if (start) {
        rng.setStart(node, offset);
      } else {
        rng.setEnd(node, offset);
      }
    }
    return true;
  };
  var isValidTextNode = function (node) {
    return $_5oonaz1qjh8lywhz.isText(node) && node.data.length > 0;
  };
  var restoreEndPoint = function (dom, suffix, bookmark) {
    var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
    var keep = bookmark.keep;
    var container, offset;
    if (marker) {
      node = marker.parentNode;
      if (suffix === 'start') {
        if (!keep) {
          idx = dom.nodeIndex(marker);
        } else {
          if (marker.hasChildNodes()) {
            node = marker.firstChild;
            idx = 1;
          } else if (isValidTextNode(marker.nextSibling)) {
            node = marker.nextSibling;
            idx = 0;
          } else if (isValidTextNode(marker.previousSibling)) {
            node = marker.previousSibling;
            idx = marker.previousSibling.data.length;
          } else {
            node = marker.parentNode;
            idx = dom.nodeIndex(marker) + 1;
          }
        }
        container = node;
        offset = idx;
      } else {
        if (!keep) {
          idx = dom.nodeIndex(marker);
        } else {
          if (marker.hasChildNodes()) {
            node = marker.firstChild;
            idx = 1;
          } else if (isValidTextNode(marker.previousSibling)) {
            node = marker.previousSibling;
            idx = marker.previousSibling.data.length;
          } else {
            node = marker.parentNode;
            idx = dom.nodeIndex(marker);
          }
        }
        container = node;
        offset = idx;
      }
      if (!keep) {
        prev = marker.previousSibling;
        next = marker.nextSibling;
        $_ahowuxkjh8lywbj.each($_ahowuxkjh8lywbj.grep(marker.childNodes), function (node) {
          if ($_5oonaz1qjh8lywhz.isText(node)) {
            node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
          }
        });
        while (marker = dom.get(bookmark.id + '_' + suffix)) {
          dom.remove(marker, true);
        }
        if (prev && next && prev.nodeType === next.nodeType && $_5oonaz1qjh8lywhz.isText(prev) && !$_9bpim8ajh8lyw68.opera) {
          idx = prev.nodeValue.length;
          prev.appendData(next.nodeValue);
          dom.remove(next);
          if (suffix === 'start') {
            container = prev;
            offset = idx;
          } else {
            container = prev;
            offset = idx;
          }
        }
      }
      return Option.some(CaretPosition$1(container, offset));
    } else {
      return Option.none();
    }
  };
  var alt = function (o1, o2) {
    return o1.isSome() ? o1 : o2;
  };
  var resolvePaths = function (dom, bookmark) {
    var rng = dom.createRng();
    if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
      return Option.some(rng);
    } else {
      return Option.none();
    }
  };
  var resolveId = function (dom, bookmark) {
    var startPos = restoreEndPoint(dom, 'start', bookmark);
    var endPos = restoreEndPoint(dom, 'end', bookmark);
    return $_b8twwq26jh8lywmm.liftN([
      startPos,
      alt(endPos, startPos)
    ], function (spos, epos) {
      var rng = dom.createRng();
      rng.setStart(addBogus(dom, spos.container()), spos.offset());
      rng.setEnd(addBogus(dom, epos.container()), epos.offset());
      return rng;
    });
  };
  var resolveIndex$1 = function (dom, bookmark) {
    return Option.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
      var rng = dom.createRng();
      rng.selectNode(elm);
      return rng;
    });
  };
  var resolve$3 = function (selection, bookmark) {
    var dom = selection.dom;
    if (bookmark) {
      if (isPathBookmark(bookmark)) {
        return resolvePaths(dom, bookmark);
      } else if (isStringPathBookmark(bookmark)) {
        return Option.some(resolveCaretPositionBookmark(dom, bookmark));
      } else if (isIdBookmark(bookmark)) {
        return resolveId(dom, bookmark);
      } else if (isIndexBookmark(bookmark)) {
        return resolveIndex$1(dom, bookmark);
      } else if (isRangeBookmark(bookmark)) {
        return Option.some(bookmark.rng);
      }
    }
    return Option.none();
  };
  var $_bncspc2qjh8lywq4 = { resolve: resolve$3 };

  var getBookmark$1 = function (selection, type, normalized) {
    return $_8b82yg2ojh8lywpq.getBookmark(selection, type, normalized);
  };
  var moveToBookmark = function (selection, bookmark) {
    $_bncspc2qjh8lywq4.resolve(selection, bookmark).each(function (rng) {
      selection.setRng(rng);
    });
  };
  var isBookmarkNode$1 = function (node) {
    return $_5oonaz1qjh8lywhz.isElement(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  };
  var $_eyp5ec2njh8lywpo = {
    getBookmark: getBookmark$1,
    moveToBookmark: moveToBookmark,
    isBookmarkNode: isBookmarkNode$1
  };

  var each$8 = $_ahowuxkjh8lywbj.each;
  var ElementUtils = function (dom) {
    this.compare = function (node1, node2) {
      if (node1.nodeName !== node2.nodeName) {
        return false;
      }
      var getAttribs = function (node) {
        var attribs = {};
        each$8(dom.getAttribs(node), function (attr) {
          var name = attr.nodeName.toLowerCase();
          if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
            attribs[name] = dom.getAttrib(node, name);
          }
        });
        return attribs;
      };
      var compareObjects = function (obj1, obj2) {
        var value, name;
        for (name in obj1) {
          if (obj1.hasOwnProperty(name)) {
            value = obj2[name];
            if (typeof value === 'undefined') {
              return false;
            }
            if (obj1[name] !== value) {
              return false;
            }
            delete obj2[name];
          }
        }
        for (name in obj2) {
          if (obj2.hasOwnProperty(name)) {
            return false;
          }
        }
        return true;
      };
      if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
        return false;
      }
      if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
        return false;
      }
      return !$_eyp5ec2njh8lywpo.isBookmarkNode(node1) && !$_eyp5ec2njh8lywpo.isBookmarkNode(node2);
    };
  };

  var before$2 = function (marker, elements) {
    $_5wjzy24jh8lyw2t.each(elements, function (x) {
      $_4m7u2e2kjh8lywpi.before(marker, x);
    });
  };
  var after$2 = function (marker, elements) {
    $_5wjzy24jh8lyw2t.each(elements, function (x, i) {
      var e = i === 0 ? marker : elements[i - 1];
      $_4m7u2e2kjh8lywpi.after(e, x);
    });
  };
  var prepend$1 = function (parent, elements) {
    $_5wjzy24jh8lyw2t.each(elements.slice().reverse(), function (x) {
      $_4m7u2e2kjh8lywpi.prepend(parent, x);
    });
  };
  var append$1 = function (parent, elements) {
    $_5wjzy24jh8lyw2t.each(elements, function (x) {
      $_4m7u2e2kjh8lywpi.append(parent, x);
    });
  };
  var $_9hl8mu2vjh8lywr4 = {
    before: before$2,
    after: after$2,
    prepend: prepend$1,
    append: append$1
  };

  var empty = function (element) {
    element.dom().textContent = '';
    $_5wjzy24jh8lyw2t.each($_a43q0i17jh8lywfe.children(element), function (rogue) {
      remove$3(rogue);
    });
  };
  var remove$3 = function (element) {
    var dom = element.dom();
    if (dom.parentNode !== null)
      dom.parentNode.removeChild(dom);
  };
  var unwrap = function (wrapper) {
    var children = $_a43q0i17jh8lywfe.children(wrapper);
    if (children.length > 0)
      $_9hl8mu2vjh8lywr4.before(wrapper, children);
    remove$3(wrapper);
  };
  var $_bfmuql2ujh8lywr1 = {
    empty: empty,
    remove: remove$3,
    unwrap: unwrap
  };

  function NodeValue (is, name) {
    var get = function (element) {
      if (!is(element))
        throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
      return getOption(element).getOr('');
    };
    var getOptionIE10 = function (element) {
      try {
        return getOptionSafe(element);
      } catch (e) {
        return Option.none();
      }
    };
    var getOptionSafe = function (element) {
      return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
    };
    var browser = $_9hkktfnjh8lywc6.detect().browser;
    var getOption = browser.isIE() && browser.version.major === 10 ? getOptionIE10 : getOptionSafe;
    var set = function (element, value) {
      if (!is(element))
        throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
      element.dom().nodeValue = value;
    };
    return {
      get: get,
      getOption: getOption,
      set: set
    };
  }

  var api = NodeValue($_7j1jt210jh8lywdx.isText, 'text');
  var get$2 = function (element) {
    return api.get(element);
  };
  var getOption = function (element) {
    return api.getOption(element);
  };
  var set$2 = function (element, value) {
    api.set(element, value);
  };
  var $_lh5l42wjh8lywr8 = {
    get: get$2,
    getOption: getOption,
    set: set$2
  };

  var getLastChildren = function (elm) {
    var children = [];
    var rawNode = elm.dom();
    while (rawNode) {
      children.push($_cgttw3zjh8lywdq.fromDom(rawNode));
      rawNode = rawNode.lastChild;
    }
    return children;
  };
  var removeTrailingBr = function (elm) {
    var allBrs = $_eebxu2gjh8lywp3.descendants(elm, 'br');
    var brs = $_5wjzy24jh8lyw2t.filter(getLastChildren(elm).slice(-1), isBr);
    if (allBrs.length === brs.length) {
      $_5wjzy24jh8lyw2t.each(brs, $_bfmuql2ujh8lywr1.remove);
    }
  };
  var fillWithPaddingBr = function (elm) {
    $_bfmuql2ujh8lywr1.empty(elm);
    $_4m7u2e2kjh8lywpi.append(elm, $_cgttw3zjh8lywdq.fromHtml('<br data-mce-bogus="1">'));
  };
  var isPaddingContents = function (elm) {
    return $_7j1jt210jh8lywdx.isText(elm) ? $_lh5l42wjh8lywr8.get(elm) === '\xA0' : isBr(elm);
  };
  var isPaddedElement = function (elm) {
    return $_5wjzy24jh8lyw2t.filter($_a43q0i17jh8lywfe.children(elm), isPaddingContents).length === 1;
  };
  var trimBlockTrailingBr = function (elm) {
    $_a43q0i17jh8lywfe.lastChild(elm).each(function (lastChild) {
      $_a43q0i17jh8lywfe.prevSibling(lastChild).each(function (lastChildPrevSibling) {
        if (isBlock(elm) && isBr(lastChild) && isBlock(lastChildPrevSibling)) {
          $_bfmuql2ujh8lywr1.remove(lastChild);
        }
      });
    });
  };
  var $_2bvsfb2tjh8lywqo = {
    removeTrailingBr: removeTrailingBr,
    fillWithPaddingBr: fillWithPaddingBr,
    isPaddedElement: isPaddedElement,
    trimBlockTrailingBr: trimBlockTrailingBr
  };

  var makeMap$3 = $_ahowuxkjh8lywbj.makeMap;
  function Writer (settings) {
    var html = [];
    var indent, indentBefore, indentAfter, encode, htmlOutput;
    settings = settings || {};
    indent = settings.indent;
    indentBefore = makeMap$3(settings.indent_before || '');
    indentAfter = makeMap$3(settings.indent_after || '');
    encode = $_gex7a11rjh8lywi4.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
    htmlOutput = settings.element_format === 'html';
    return {
      start: function (name, attrs, empty) {
        var i, l, attr, value;
        if (indent && indentBefore[name] && html.length > 0) {
          value = html[html.length - 1];
          if (value.length > 0 && value !== '\n') {
            html.push('\n');
          }
        }
        html.push('<', name);
        if (attrs) {
          for (i = 0, l = attrs.length; i < l; i++) {
            attr = attrs[i];
            html.push(' ', attr.name, '="', encode(attr.value, true), '"');
          }
        }
        if (!empty || htmlOutput) {
          html[html.length] = '>';
        } else {
          html[html.length] = ' />';
        }
        if (empty && indent && indentAfter[name] && html.length > 0) {
          value = html[html.length - 1];
          if (value.length > 0 && value !== '\n') {
            html.push('\n');
          }
        }
      },
      end: function (name) {
        var value;
        html.push('</', name, '>');
        if (indent && indentAfter[name] && html.length > 0) {
          value = html[html.length - 1];
          if (value.length > 0 && value !== '\n') {
            html.push('\n');
          }
        }
      },
      text: function (text, raw) {
        if (text.length > 0) {
          html[html.length] = raw ? text : encode(text);
        }
      },
      cdata: function (text) {
        html.push('<![CDATA[', text, ']]>');
      },
      comment: function (text) {
        html.push('<!--', text, '-->');
      },
      pi: function (name, text) {
        if (text) {
          html.push('<?', name, ' ', encode(text), '?>');
        } else {
          html.push('<?', name, '?>');
        }
        if (indent) {
          html.push('\n');
        }
      },
      doctype: function (text) {
        html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
      },
      reset: function () {
        html.length = 0;
      },
      getContent: function () {
        return html.join('').replace(/\n$/, '');
      }
    };
  }

  function HtmlSerializer (settings, schema) {
    if (schema === void 0) {
      schema = Schema();
    }
    var writer = Writer(settings);
    settings = settings || {};
    settings.validate = 'validate' in settings ? settings.validate : true;
    var serialize = function (node) {
      var handlers, validate;
      validate = settings.validate;
      handlers = {
        3: function (node) {
          writer.text(node.value, node.raw);
        },
        8: function (node) {
          writer.comment(node.value);
        },
        7: function (node) {
          writer.pi(node.name, node.value);
        },
        10: function (node) {
          writer.doctype(node.value);
        },
        4: function (node) {
          writer.cdata(node.value);
        },
        11: function (node) {
          if (node = node.firstChild) {
            do {
              walk(node);
            } while (node = node.next);
          }
        }
      };
      writer.reset();
      var walk = function (node) {
        var handler = handlers[node.type];
        var name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
        if (!handler) {
          name = node.name;
          isEmpty = node.shortEnded;
          attrs = node.attributes;
          if (validate && attrs && attrs.length > 1) {
            sortedAttrs = [];
            sortedAttrs.map = {};
            elementRule = schema.getElementRule(node.name);
            if (elementRule) {
              for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
                attrName = elementRule.attributesOrder[i];
                if (attrName in attrs.map) {
                  attrValue = attrs.map[attrName];
                  sortedAttrs.map[attrName] = attrValue;
                  sortedAttrs.push({
                    name: attrName,
                    value: attrValue
                  });
                }
              }
              for (i = 0, l = attrs.length; i < l; i++) {
                attrName = attrs[i].name;
                if (!(attrName in sortedAttrs.map)) {
                  attrValue = attrs.map[attrName];
                  sortedAttrs.map[attrName] = attrValue;
                  sortedAttrs.push({
                    name: attrName,
                    value: attrValue
                  });
                }
              }
              attrs = sortedAttrs;
            }
          }
          writer.start(node.name, attrs, isEmpty);
          if (!isEmpty) {
            if (node = node.firstChild) {
              do {
                walk(node);
              } while (node = node.next);
            }
            writer.end(name);
          }
        } else {
          handler(node);
        }
      };
      if (node.type === 1 && !settings.inner) {
        walk(node);
      } else {
        handlers[11](node);
      }
      return writer.getContent();
    };
    return { serialize: serialize };
  }

  var createRange$1 = function (sc, so, ec, eo) {
    var rng = document.createRange();
    rng.setStart(sc, so);
    rng.setEnd(ec, eo);
    return rng;
  };
  var normalizeBlockSelectionRange = function (rng) {
    var startPos = CaretPosition$1.fromRangeStart(rng);
    var endPos = CaretPosition$1.fromRangeEnd(rng);
    var rootNode = rng.commonAncestorContainer;
    return $_9kvypj2cjh8lywnz.fromPosition(false, rootNode, endPos).map(function (newEndPos) {
      if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
        return createRange$1(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
      } else {
        return rng;
      }
    }).getOr(rng);
  };
  var normalize = function (rng) {
    return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  };
  var $_cnbluh30jh8lywrn = { normalize: normalize };

  var isTableCell$2 = $_5oonaz1qjh8lywhz.matchNodeNames('td th');
  var validInsertion = function (editor, value, parentNode) {
    if (parentNode.getAttribute('data-mce-bogus') === 'all') {
      parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
    } else {
      var node = parentNode.firstChild;
      var node2 = parentNode.lastChild;
      if (!node || node === node2 && node.nodeName === 'BR') {
        editor.dom.setHTML(parentNode, value);
      } else {
        editor.selection.setContent(value);
      }
    }
  };
  var trimBrsFromTableCell = function (dom, elm) {
    Option.from(dom.getParent(elm, 'td,th')).map($_cgttw3zjh8lywdq.fromDom).each($_2bvsfb2tjh8lywqo.trimBlockTrailingBr);
  };
  var insertHtmlAtCaret = function (editor, value, details) {
    var parser, serializer, parentNode, rootNode, fragment, args;
    var marker, rng, node, node2, bookmarkHtml, merge;
    var textInlineElements = editor.schema.getTextInlineElements();
    var selection = editor.selection, dom = editor.dom;
    var trimOrPaddLeftRight = function (html) {
      var rng, container, offset;
      rng = selection.getRng();
      container = rng.startContainer;
      offset = rng.startOffset;
      var hasSiblingText = function (siblingName) {
        return container[siblingName] && container[siblingName].nodeType === 3;
      };
      if (container.nodeType === 3) {
        if (offset > 0) {
          html = html.replace(/^&nbsp;/, ' ');
        } else if (!hasSiblingText('previousSibling')) {
          html = html.replace(/^ /, '&nbsp;');
        }
        if (offset < container.length) {
          html = html.replace(/&nbsp;(<br>|)$/, ' ');
        } else if (!hasSiblingText('nextSibling')) {
          html = html.replace(/(&nbsp;| )(<br>|)$/, '&nbsp;');
        }
      }
      return html;
    };
    var trimNbspAfterDeleteAndPaddValue = function () {
      var rng, container, offset;
      rng = selection.getRng();
      container = rng.startContainer;
      offset = rng.startOffset;
      if (container.nodeType === 3 && rng.collapsed) {
        if (container.data[offset] === '\xA0') {
          container.deleteData(offset, 1);
          if (!/[\u00a0| ]$/.test(value)) {
            value += ' ';
          }
        } else if (container.data[offset - 1] === '\xA0') {
          container.deleteData(offset - 1, 1);
          if (!/[\u00a0| ]$/.test(value)) {
            value = ' ' + value;
          }
        }
      }
    };
    var reduceInlineTextElements = function () {
      if (merge) {
        var root_1 = editor.getBody(), elementUtils_1 = new ElementUtils(dom);
        $_ahowuxkjh8lywbj.each(dom.select('*[data-mce-fragment]'), function (node) {
          for (var testNode = node.parentNode; testNode && testNode !== root_1; testNode = testNode.parentNode) {
            if (textInlineElements[node.nodeName.toLowerCase()] && elementUtils_1.compare(testNode, node)) {
              dom.remove(node, true);
            }
          }
        });
      }
    };
    var markFragmentElements = function (fragment) {
      var node = fragment;
      while (node = node.walk()) {
        if (node.type === 1) {
          node.attr('data-mce-fragment', '1');
        }
      }
    };
    var umarkFragmentElements = function (elm) {
      $_ahowuxkjh8lywbj.each(elm.getElementsByTagName('*'), function (elm) {
        elm.removeAttribute('data-mce-fragment');
      });
    };
    var isPartOfFragment = function (node) {
      return !!node.getAttribute('data-mce-fragment');
    };
    var canHaveChildren = function (node) {
      return node && !editor.schema.getShortEndedElements()[node.nodeName];
    };
    var moveSelectionToMarker = function (marker) {
      var parentEditableFalseElm, parentBlock, nextRng;
      var getContentEditableFalseParent = function (node) {
        var root = editor.getBody();
        for (; node && node !== root; node = node.parentNode) {
          if (editor.dom.getContentEditable(node) === 'false') {
            return node;
          }
        }
        return null;
      };
      if (!marker) {
        return;
      }
      selection.scrollIntoView(marker);
      parentEditableFalseElm = getContentEditableFalseParent(marker);
      if (parentEditableFalseElm) {
        dom.remove(marker);
        selection.select(parentEditableFalseElm);
        return;
      }
      rng = dom.createRng();
      node = marker.previousSibling;
      if (node && node.nodeType === 3) {
        rng.setStart(node, node.nodeValue.length);
        if (!$_9bpim8ajh8lyw68.ie) {
          node2 = marker.nextSibling;
          if (node2 && node2.nodeType === 3) {
            node.appendData(node2.data);
            node2.parentNode.removeChild(node2);
          }
        }
      } else {
        rng.setStartBefore(marker);
        rng.setEndBefore(marker);
      }
      var findNextCaretRng = function (rng) {
        var caretPos = CaretPosition$1.fromRangeStart(rng);
        var caretWalker = CaretWalker(editor.getBody());
        caretPos = caretWalker.next(caretPos);
        if (caretPos) {
          return caretPos.toRange();
        }
      };
      parentBlock = dom.getParent(marker, dom.isBlock);
      dom.remove(marker);
      if (parentBlock && dom.isEmpty(parentBlock)) {
        editor.$(parentBlock).empty();
        rng.setStart(parentBlock, 0);
        rng.setEnd(parentBlock, 0);
        if (!isTableCell$2(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
          rng = nextRng;
          dom.remove(parentBlock);
        } else {
          dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
        }
      }
      selection.setRng(rng);
    };
    if (/^ | $/.test(value)) {
      value = trimOrPaddLeftRight(value);
    }
    parser = editor.parser;
    merge = details.merge;
    serializer = HtmlSerializer({ validate: editor.settings.validate }, editor.schema);
    bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;&#x200B;</span>';
    args = {
      content: value,
      format: 'html',
      selection: true,
      paste: details.paste
    };
    args = editor.fire('BeforeSetContent', args);
    if (args.isDefaultPrevented()) {
      editor.fire('SetContent', {
        content: args.content,
        format: 'html',
        selection: true,
        paste: details.paste
      });
      return;
    }
    value = args.content;
    if (value.indexOf('{$caret}') === -1) {
      value += '{$caret}';
    }
    value = value.replace(/\{\$caret\}/, bookmarkHtml);
    rng = selection.getRng();
    var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
    var body = editor.getBody();
    if (caretElement === body && selection.isCollapsed()) {
      if (dom.isBlock(body.firstChild) && canHaveChildren(body.firstChild) && dom.isEmpty(body.firstChild)) {
        rng = dom.createRng();
        rng.setStart(body.firstChild, 0);
        rng.setEnd(body.firstChild, 0);
        selection.setRng(rng);
      }
    }
    if (!selection.isCollapsed()) {
      editor.selection.setRng($_cnbluh30jh8lywrn.normalize(editor.selection.getRng()));
      editor.getDoc().execCommand('Delete', false, null);
      trimNbspAfterDeleteAndPaddValue();
    }
    parentNode = selection.getNode();
    var parserArgs = {
      context: parentNode.nodeName.toLowerCase(),
      data: details.data,
      insert: true
    };
    fragment = parser.parse(value, parserArgs);
    if (details.paste === true && $_eajoh11xjh8lywl6.isListFragment(editor.schema, fragment) && $_eajoh11xjh8lywl6.isParentBlockLi(dom, parentNode)) {
      rng = $_eajoh11xjh8lywl6.insertAtCaret(serializer, dom, editor.selection.getRng(), fragment);
      editor.selection.setRng(rng);
      editor.fire('SetContent', args);
      return;
    }
    markFragmentElements(fragment);
    node = fragment.lastChild;
    if (node.attr('id') === 'mce_marker') {
      marker = node;
      for (node = node.prev; node; node = node.walk(true)) {
        if (node.type === 3 || !dom.isBlock(node.name)) {
          if (editor.schema.isValidChild(node.parent.name, 'span')) {
            node.parent.insert(marker, node, node.name === 'br');
          }
          break;
        }
      }
    }
    editor._selectionOverrides.showBlockCaretContainer(parentNode);
    if (!parserArgs.invalid) {
      value = serializer.serialize(fragment);
      validInsertion(editor, value, parentNode);
    } else {
      selection.setContent(bookmarkHtml);
      parentNode = selection.getNode();
      rootNode = editor.getBody();
      if (parentNode.nodeType === 9) {
        parentNode = node = rootNode;
      } else {
        node = parentNode;
      }
      while (node !== rootNode) {
        parentNode = node;
        node = node.parentNode;
      }
      value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
      value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
        return serializer.serialize(fragment);
      })));
      if (parentNode === rootNode) {
        dom.setHTML(rootNode, value);
      } else {
        dom.setOuterHTML(parentNode, value);
      }
    }
    reduceInlineTextElements();
    moveSelectionToMarker(dom.get('mce_marker'));
    umarkFragmentElements(editor.getBody());
    trimBrsFromTableCell(editor.dom, editor.selection.getStart());
    editor.fire('SetContent', args);
    editor.addVisual();
  };
  var processValue = function (value) {
    var details;
    if (typeof value !== 'string') {
      details = $_ahowuxkjh8lywbj.extend({
        paste: value.paste,
        data: { paste: value.paste }
      }, value);
      return {
        content: value.content,
        details: details
      };
    }
    return {
      content: value,
      details: {}
    };
  };
  var insertAtCaret$1 = function (editor, value) {
    var result = processValue(value);
    insertHtmlAtCaret(editor, result.content, result.details);
  };
  var $_13xltl1wjh8lywkr = { insertAtCaret: insertAtCaret$1 };

  function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
    return is(scope, a) ? Option.some(scope) : $_dp4g6d7jh8lyw3y.isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  }

  var first$1 = function (predicate) {
    return descendant($_boa99a15jh8lywey.body(), predicate);
  };
  var ancestor = function (scope, predicate, isRoot) {
    var element = scope.dom();
    var stop = $_dp4g6d7jh8lyw3y.isFunction(isRoot) ? isRoot : $_eqpqvr6jh8lyw3s.constant(false);
    while (element.parentNode) {
      element = element.parentNode;
      var el = $_cgttw3zjh8lywdq.fromDom(element);
      if (predicate(el))
        return Option.some(el);
      else if (stop(el))
        break;
    }
    return Option.none();
  };
  var closest = function (scope, predicate, isRoot) {
    var is = function (scope) {
      return predicate(scope);
    };
    return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  };
  var sibling$1 = function (scope, predicate) {
    var element = scope.dom();
    if (!element.parentNode)
      return Option.none();
    return child$1($_cgttw3zjh8lywdq.fromDom(element.parentNode), function (x) {
      return !$_5f6gpb1djh8lywg5.eq(scope, x) && predicate(x);
    });
  };
  var child$1 = function (scope, predicate) {
    var result = $_5wjzy24jh8lyw2t.find(scope.dom().childNodes, $_eqpqvr6jh8lyw3s.compose(predicate, $_cgttw3zjh8lywdq.fromDom));
    return result.map($_cgttw3zjh8lywdq.fromDom);
  };
  var descendant = function (scope, predicate) {
    var descend = function (element) {
      for (var i = 0; i < element.childNodes.length; i++) {
        if (predicate($_cgttw3zjh8lywdq.fromDom(element.childNodes[i])))
          return Option.some($_cgttw3zjh8lywdq.fromDom(element.childNodes[i]));
        var res = descend(element.childNodes[i]);
        if (res.isSome())
          return res;
      }
      return Option.none();
    };
    return descend(scope.dom());
  };
  var $_6hl03835jh8lywsm = {
    first: first$1,
    ancestor: ancestor,
    closest: closest,
    sibling: sibling$1,
    child: child$1,
    descendant: descendant
  };

  var sectionResult = $_4jz0ce18jh8lywft.immutable('sections', 'settings');
  var detection = $_9hkktfnjh8lywc6.detect();
  var isTouch = detection.deviceType.isTouch();
  var mobilePlugins = [
    'lists',
    'autolink',
    'autosave'
  ];
  var defaultMobileSettings = { theme: 'mobile' };
  var normalizePlugins = function (plugins) {
    var pluginNames = $_dp4g6d7jh8lyw3y.isArray(plugins) ? plugins.join(' ') : plugins;
    var trimmedPlugins = $_5wjzy24jh8lyw2t.map($_dp4g6d7jh8lyw3y.isString(pluginNames) ? pluginNames.split(' ') : [], $_4w196awjh8lywdj.trim);
    return $_5wjzy24jh8lyw2t.filter(trimmedPlugins, function (item) {
      return item.length > 0;
    });
  };
  var filterMobilePlugins = function (plugins) {
    return $_5wjzy24jh8lyw2t.filter(plugins, $_eqpqvr6jh8lyw3s.curry($_5wjzy24jh8lyw2t.contains, mobilePlugins));
  };
  var extractSections = function (keys, settings) {
    var result = $_g63v2c13jh8lywej.bifilter(settings, function (value, key) {
      return $_5wjzy24jh8lyw2t.contains(keys, key);
    });
    return sectionResult(result.t, result.f);
  };
  var getSection = function (sectionResult, name, defaults) {
    var sections = sectionResult.sections();
    var sectionSettings = sections.hasOwnProperty(name) ? sections[name] : {};
    return $_ahowuxkjh8lywbj.extend({}, defaults, sectionSettings);
  };
  var hasSection = function (sectionResult, name) {
    return sectionResult.sections().hasOwnProperty(name);
  };
  var getDefaultSettings = function (id, documentBaseUrl, editor) {
    return {
      id: id,
      theme: 'modern',
      delta_width: 0,
      delta_height: 0,
      popup_css: '',
      plugins: '',
      document_base_url: documentBaseUrl,
      add_form_submit_trigger: true,
      submit_patch: true,
      add_unload_trigger: true,
      convert_urls: true,
      relative_urls: true,
      remove_script_host: true,
      object_resizing: true,
      doctype: '<!DOCTYPE html>',
      visual: true,
      font_size_style_values: 'xx-small,x-small,small,medium,large,x-large,xx-large',
      font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
      forced_root_block: 'p',
      hidden_input: true,
      render_ui: true,
      indentation: '30px',
      inline_styles: true,
      convert_fonts_to_spans: true,
      indent: 'simple',
      indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
      indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
      entity_encoding: 'named',
      url_converter: editor.convertURL,
      url_converter_scope: editor,
      ie7_compat: true
    };
  };
  var getExternalPlugins = function (overrideSettings, settings) {
    var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
    if (overrideSettings && overrideSettings.external_plugins) {
      return $_ahowuxkjh8lywbj.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
    } else {
      return userDefinedExternalPlugins;
    }
  };
  var combinePlugins = function (forcedPlugins, plugins) {
    return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  };
  var processPlugins = function (isTouchDevice, sectionResult, defaultOverrideSettings, settings) {
    var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
    var plugins = normalizePlugins(settings.plugins);
    var platformPlugins = isTouchDevice && hasSection(sectionResult, 'mobile') ? filterMobilePlugins(plugins) : plugins;
    var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
    return $_ahowuxkjh8lywbj.extend(settings, { plugins: combinedPlugins.join(' ') });
  };
  var isOnMobile = function (isTouchDevice, sectionResult) {
    var isInline = sectionResult.settings().inline;
    return isTouchDevice && hasSection(sectionResult, 'mobile') && !isInline;
  };
  var combineSettings = function (isTouchDevice, defaultSettings, defaultOverrideSettings, settings) {
    var sectionResult = extractSections(['mobile'], settings);
    var extendedSettings = $_ahowuxkjh8lywbj.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isTouchDevice, sectionResult) ? getSection(sectionResult, 'mobile', defaultMobileSettings) : {}, {
      validate: true,
      content_editable: sectionResult.settings().inline,
      external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult.settings())
    });
    return processPlugins(isTouchDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  };
  var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
    var defaultSettings = getDefaultSettings(id, documentBaseUrl, editor);
    return combineSettings(isTouch, defaultSettings, defaultOverrideSettings, settings);
  };
  var getFiltered = function (predicate, editor, name) {
    return Option.from(editor.settings[name]).filter(predicate);
  };
  var getString = $_eqpqvr6jh8lyw3s.curry(getFiltered, $_dp4g6d7jh8lyw3y.isString);
  var getParamObject = function (value) {
    var output = {};
    if (typeof value === 'string') {
      $_5wjzy24jh8lyw2t.each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
        var arr = val.split('=');
        if (arr.length > 1) {
          output[$_ahowuxkjh8lywbj.trim(arr[0])] = $_ahowuxkjh8lywbj.trim(arr[1]);
        } else {
          output[$_ahowuxkjh8lywbj.trim(arr[0])] = $_ahowuxkjh8lywbj.trim(arr);
        }
      });
    } else {
      output = value;
    }
    return output;
  };
  var isArrayOf = function (p) {
    return function (a) {
      return $_dp4g6d7jh8lyw3y.isArray(a) && $_5wjzy24jh8lyw2t.forall(a, p);
    };
  };
  var getParam = function (editor, name, defaultVal, type) {
    var value = name in editor.settings ? editor.settings[name] : defaultVal;
    if (type === 'hash') {
      return getParamObject(value);
    } else if (type === 'string') {
      return getFiltered($_dp4g6d7jh8lyw3y.isString, editor, name).getOr(defaultVal);
    } else if (type === 'number') {
      return getFiltered($_dp4g6d7jh8lyw3y.isNumber, editor, name).getOr(defaultVal);
    } else if (type === 'boolean') {
      return getFiltered($_dp4g6d7jh8lyw3y.isBoolean, editor, name).getOr(defaultVal);
    } else if (type === 'object') {
      return getFiltered($_dp4g6d7jh8lyw3y.isObject, editor, name).getOr(defaultVal);
    } else if (type === 'array') {
      return getFiltered($_dp4g6d7jh8lyw3y.isArray, editor, name).getOr(defaultVal);
    } else if (type === 'string[]') {
      return getFiltered(isArrayOf($_dp4g6d7jh8lyw3y.isString), editor, name).getOr(defaultVal);
    } else if (type === 'function') {
      return getFiltered($_dp4g6d7jh8lyw3y.isFunction, editor, name).getOr(defaultVal);
    } else {
      return value;
    }
  };

  var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  var hasStrongRtl = function (text) {
    return strongRtl.test(text);
  };

  var isInlineTarget = function (editor, elm) {
    var selector = getString(editor, 'inline_boundaries_selector').getOr('a[href],code');
    return $_5h4ipt1fjh8lywgi.is($_cgttw3zjh8lywdq.fromDom(elm), selector);
  };
  var isRtl = function (element) {
    return DOMUtils$1.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  };
  var findInlineParents = function (isInlineTarget, rootNode, pos) {
    return $_5wjzy24jh8lyw2t.filter(DOMUtils$1.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  };
  var findRootInline = function (isInlineTarget, rootNode, pos) {
    var parents = findInlineParents(isInlineTarget, rootNode, pos);
    return Option.from(parents[parents.length - 1]);
  };
  var hasSameParentBlock = function (rootNode, node1, node2) {
    var block1 = getParentBlock(node1, rootNode);
    var block2 = getParentBlock(node2, rootNode);
    return block1 && block1 === block2;
  };
  var isAtZwsp = function (pos) {
    return isBeforeInline(pos) || isAfterInline(pos);
  };
  var normalizePosition = function (forward, pos) {
    var container = pos.container(), offset = pos.offset();
    if (forward) {
      if (isCaretContainerInline(container)) {
        if ($_5oonaz1qjh8lywhz.isText(container.nextSibling)) {
          return CaretPosition$1(container.nextSibling, 0);
        } else {
          return CaretPosition$1.after(container);
        }
      } else {
        return isBeforeInline(pos) ? CaretPosition$1(container, offset + 1) : pos;
      }
    } else {
      if (isCaretContainerInline(container)) {
        if ($_5oonaz1qjh8lywhz.isText(container.previousSibling)) {
          return CaretPosition$1(container.previousSibling, container.previousSibling.data.length);
        } else {
          return CaretPosition$1.before(container);
        }
      } else {
        return isAfterInline(pos) ? CaretPosition$1(container, offset - 1) : pos;
      }
    }
  };
  var normalizeForwards = $_eqpqvr6jh8lyw3s.curry(normalizePosition, true);
  var normalizeBackwards = $_eqpqvr6jh8lyw3s.curry(normalizePosition, false);
  var $_231v7s37jh8lywt3 = {
    isInlineTarget: isInlineTarget,
    findRootInline: findRootInline,
    isRtl: isRtl,
    isAtZwsp: isAtZwsp,
    normalizePosition: normalizePosition,
    normalizeForwards: normalizeForwards,
    normalizeBackwards: normalizeBackwards,
    hasSameParentBlock: hasSameParentBlock
  };

  var isBeforeRoot = function (rootNode) {
    return function (elm) {
      return $_5f6gpb1djh8lywg5.eq(rootNode, $_cgttw3zjh8lywdq.fromDom(elm.dom().parentNode));
    };
  };
  var getParentBlock$1 = function (rootNode, elm) {
    return $_5f6gpb1djh8lywg5.contains(rootNode, elm) ? $_6hl03835jh8lywsm.closest(elm, function (element) {
      return isTextBlock(element) || isListItem(element);
    }, isBeforeRoot(rootNode)) : Option.none();
  };
  var placeCaretInEmptyBody = function (editor) {
    var body = editor.getBody();
    var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
    editor.selection.setCursorLocation(node, 0);
  };
  var paddEmptyBody = function (editor) {
    if (editor.dom.isEmpty(editor.getBody())) {
      editor.setContent('');
      placeCaretInEmptyBody(editor);
    }
  };
  var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
    return $_b8twwq26jh8lywmm.liftN([
      $_9kvypj2cjh8lywnz.firstPositionIn(elm),
      $_9kvypj2cjh8lywnz.lastPositionIn(elm)
    ], function (firstPos, lastPos) {
      var normalizedFirstPos = $_231v7s37jh8lywt3.normalizePosition(true, firstPos);
      var normalizedLastPos = $_231v7s37jh8lywt3.normalizePosition(false, lastPos);
      var normalizedFromPos = $_231v7s37jh8lywt3.normalizePosition(false, fromPos);
      if (forward) {
        return $_9kvypj2cjh8lywnz.nextPosition(elm, normalizedFromPos).map(function (nextPos) {
          return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
        }).getOr(false);
      } else {
        return $_9kvypj2cjh8lywnz.prevPosition(elm, normalizedFromPos).map(function (prevPos) {
          return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
        }).getOr(false);
      }
    }).getOr(true);
  };
  var $_aj8isd34jh8lyws4 = {
    getParentBlock: getParentBlock$1,
    paddEmptyBody: paddEmptyBody,
    willDeleteLastPositionInElement: willDeleteLastPositionInElement
  };

  var first$2 = function (selector) {
    return $_5h4ipt1fjh8lywgi.one(selector);
  };
  var ancestor$1 = function (scope, selector, isRoot) {
    return $_6hl03835jh8lywsm.ancestor(scope, function (e) {
      return $_5h4ipt1fjh8lywgi.is(e, selector);
    }, isRoot);
  };
  var sibling$2 = function (scope, selector) {
    return $_6hl03835jh8lywsm.sibling(scope, function (e) {
      return $_5h4ipt1fjh8lywgi.is(e, selector);
    });
  };
  var child$2 = function (scope, selector) {
    return $_6hl03835jh8lywsm.child(scope, function (e) {
      return $_5h4ipt1fjh8lywgi.is(e, selector);
    });
  };
  var descendant$1 = function (scope, selector) {
    return $_5h4ipt1fjh8lywgi.one(selector, scope);
  };
  var closest$1 = function (scope, selector, isRoot) {
    return ClosestOrAncestor($_5h4ipt1fjh8lywgi.is, ancestor$1, scope, selector, isRoot);
  };
  var $_7sg18r3cjh8lywu1 = {
    first: first$2,
    ancestor: ancestor$1,
    sibling: sibling$2,
    child: child$2,
    descendant: descendant$1,
    closest: closest$1
  };

  var any = function (selector) {
    return $_7sg18r3cjh8lywu1.first(selector).isSome();
  };
  var ancestor$2 = function (scope, selector, isRoot) {
    return $_7sg18r3cjh8lywu1.ancestor(scope, selector, isRoot).isSome();
  };
  var sibling$3 = function (scope, selector) {
    return $_7sg18r3cjh8lywu1.sibling(scope, selector).isSome();
  };
  var child$3 = function (scope, selector) {
    return $_7sg18r3cjh8lywu1.child(scope, selector).isSome();
  };
  var descendant$2 = function (scope, selector) {
    return $_7sg18r3cjh8lywu1.descendant(scope, selector).isSome();
  };
  var closest$2 = function (scope, selector, isRoot) {
    return $_7sg18r3cjh8lywu1.closest(scope, selector, isRoot).isSome();
  };
  var $_8b29ae3bjh8lywu0 = {
    any: any,
    ancestor: ancestor$2,
    sibling: sibling$3,
    child: child$3,
    descendant: descendant$2,
    closest: closest$2
  };

  var hasWhitespacePreserveParent = function (rootNode, node) {
    var rootElement = $_cgttw3zjh8lywdq.fromDom(rootNode);
    var startNode = $_cgttw3zjh8lywdq.fromDom(node);
    return $_8b29ae3bjh8lywu0.ancestor(startNode, 'pre,code', $_eqpqvr6jh8lyw3s.curry($_5f6gpb1djh8lywg5.eq, rootElement));
  };
  var isWhitespace = function (rootNode, node) {
    return $_5oonaz1qjh8lywhz.isText(node) && /^[ \t\r\n]*$/.test(node.data) && hasWhitespacePreserveParent(rootNode, node) === false;
  };
  var isNamedAnchor = function (node) {
    return $_5oonaz1qjh8lywhz.isElement(node) && node.nodeName === 'A' && node.hasAttribute('name');
  };
  var isContent = function (rootNode, node) {
    return isCaretCandidate(node) && isWhitespace(rootNode, node) === false || isNamedAnchor(node) || isBookmark(node);
  };
  var isBookmark = $_5oonaz1qjh8lywhz.hasAttribute('data-mce-bookmark');
  var isBogus$2 = $_5oonaz1qjh8lywhz.hasAttribute('data-mce-bogus');
  var isBogusAll$1 = $_5oonaz1qjh8lywhz.hasAttributeValue('data-mce-bogus', 'all');
  var isEmptyNode = function (targetNode) {
    var walker, node, brCount = 0;
    if (isContent(targetNode, targetNode)) {
      return false;
    } else {
      node = targetNode.firstChild;
      if (!node) {
        return true;
      }
      walker = new TreeWalker(node, targetNode);
      do {
        if (isBogusAll$1(node)) {
          node = walker.next(true);
          continue;
        }
        if (isBogus$2(node)) {
          node = walker.next();
          continue;
        }
        if ($_5oonaz1qjh8lywhz.isBr(node)) {
          brCount++;
          node = walker.next();
          continue;
        }
        if (isContent(targetNode, node)) {
          return false;
        }
        node = walker.next();
      } while (node);
      return brCount <= 1;
    }
  };
  var isEmpty$1 = function (elm) {
    return isEmptyNode(elm.dom());
  };
  var $_b1urh33ajh8lywts = { isEmpty: isEmpty$1 };

  var BlockPosition = $_4jz0ce18jh8lywft.immutable('block', 'position');
  var BlockBoundary = $_4jz0ce18jh8lywft.immutable('from', 'to');
  var getBlockPosition = function (rootNode, pos) {
    var rootElm = $_cgttw3zjh8lywdq.fromDom(rootNode);
    var containerElm = $_cgttw3zjh8lywdq.fromDom(pos.container());
    return $_aj8isd34jh8lyws4.getParentBlock(rootElm, containerElm).map(function (block) {
      return BlockPosition(block, pos);
    });
  };
  var isDifferentBlocks = function (blockBoundary) {
    return $_5f6gpb1djh8lywg5.eq(blockBoundary.from().block(), blockBoundary.to().block()) === false;
  };
  var hasSameParent = function (blockBoundary) {
    return $_a43q0i17jh8lywfe.parent(blockBoundary.from().block()).bind(function (parent1) {
      return $_a43q0i17jh8lywfe.parent(blockBoundary.to().block()).filter(function (parent2) {
        return $_5f6gpb1djh8lywg5.eq(parent1, parent2);
      });
    }).isSome();
  };
  var isEditable = function (blockBoundary) {
    return $_5oonaz1qjh8lywhz.isContentEditableFalse(blockBoundary.from().block()) === false && $_5oonaz1qjh8lywhz.isContentEditableFalse(blockBoundary.to().block()) === false;
  };
  var skipLastBr = function (rootNode, forward, blockPosition) {
    if ($_5oonaz1qjh8lywhz.isBr(blockPosition.position().getNode()) && $_b1urh33ajh8lywts.isEmpty(blockPosition.block()) === false) {
      return $_9kvypj2cjh8lywnz.positionIn(false, blockPosition.block().dom()).bind(function (lastPositionInBlock) {
        if (lastPositionInBlock.isEqual(blockPosition.position())) {
          return $_9kvypj2cjh8lywnz.fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
            return getBlockPosition(rootNode, to);
          });
        } else {
          return Option.some(blockPosition);
        }
      }).getOr(blockPosition);
    } else {
      return blockPosition;
    }
  };
  var readFromRange = function (rootNode, forward, rng) {
    var fromBlockPos = getBlockPosition(rootNode, CaretPosition$1.fromRangeStart(rng));
    var toBlockPos = fromBlockPos.bind(function (blockPos) {
      return $_9kvypj2cjh8lywnz.fromPosition(forward, rootNode, blockPos.position()).bind(function (to) {
        return getBlockPosition(rootNode, to).map(function (blockPos) {
          return skipLastBr(rootNode, forward, blockPos);
        });
      });
    });
    return $_b8twwq26jh8lywmm.liftN([
      fromBlockPos,
      toBlockPos
    ], BlockBoundary).filter(function (blockBoundary) {
      return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable(blockBoundary);
    });
  };
  var read = function (rootNode, forward, rng) {
    return rng.collapsed ? readFromRange(rootNode, forward, rng) : Option.none();
  };
  var $_bmbex333jh8lywru = { read: read };

  var dropLast = function (xs) {
    return xs.slice(0, -1);
  };
  var parentsUntil$1 = function (startNode, rootElm, predicate) {
    if ($_5f6gpb1djh8lywg5.contains(rootElm, startNode)) {
      return dropLast($_a43q0i17jh8lywfe.parents(startNode, function (elm) {
        return predicate(elm) || $_5f6gpb1djh8lywg5.eq(elm, rootElm);
      }));
    } else {
      return [];
    }
  };
  var parents$1 = function (startNode, rootElm) {
    return parentsUntil$1(startNode, rootElm, $_eqpqvr6jh8lyw3s.constant(false));
  };
  var parentsAndSelf = function (startNode, rootElm) {
    return [startNode].concat(parents$1(startNode, rootElm));
  };
  var $_dyxtub3ejh8lywxq = {
    parentsUntil: parentsUntil$1,
    parents: parents$1,
    parentsAndSelf: parentsAndSelf
  };

  var getChildrenUntilBlockBoundary = function (block) {
    var children = $_a43q0i17jh8lywfe.children(block);
    return $_5wjzy24jh8lyw2t.findIndex(children, isBlock).fold(function () {
      return children;
    }, function (index) {
      return children.slice(0, index);
    });
  };
  var extractChildren = function (block) {
    var children = getChildrenUntilBlockBoundary(block);
    $_5wjzy24jh8lyw2t.each(children, function (node) {
      $_bfmuql2ujh8lywr1.remove(node);
    });
    return children;
  };
  var trimBr = function (first, block) {
    $_9kvypj2cjh8lywnz.positionIn(first, block.dom()).each(function (position) {
      var node = position.getNode();
      if ($_5oonaz1qjh8lywhz.isBr(node)) {
        $_bfmuql2ujh8lywr1.remove($_cgttw3zjh8lywdq.fromDom(node));
      }
    });
  };
  var removeEmptyRoot = function (rootNode, block) {
    var parents = $_dyxtub3ejh8lywxq.parentsAndSelf(block, rootNode);
    return $_5wjzy24jh8lyw2t.find(parents.reverse(), $_b1urh33ajh8lywts.isEmpty).each($_bfmuql2ujh8lywr1.remove);
  };
  var findParentInsertPoint = function (toBlock, block) {
    var parents = $_a43q0i17jh8lywfe.parents(block, function (elm) {
      return $_5f6gpb1djh8lywg5.eq(elm, toBlock);
    });
    return Option.from(parents[parents.length - 2]);
  };
  var getInsertionPoint = function (fromBlock, toBlock) {
    if ($_5f6gpb1djh8lywg5.contains(toBlock, fromBlock)) {
      return $_a43q0i17jh8lywfe.parent(fromBlock).bind(function (parent) {
        return $_5f6gpb1djh8lywg5.eq(parent, toBlock) ? Option.some(fromBlock) : findParentInsertPoint(toBlock, fromBlock);
      });
    } else {
      return Option.none();
    }
  };
  var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
    if ($_b1urh33ajh8lywts.isEmpty(toBlock)) {
      $_bfmuql2ujh8lywr1.remove(toBlock);
      if ($_b1urh33ajh8lywts.isEmpty(fromBlock)) {
        $_2bvsfb2tjh8lywqo.fillWithPaddingBr(fromBlock);
      }
      return $_9kvypj2cjh8lywnz.firstPositionIn(fromBlock.dom());
    } else {
      trimBr(true, fromBlock);
      trimBr(false, toBlock);
      var children_1 = extractChildren(fromBlock);
      return getInsertionPoint(fromBlock, toBlock).fold(function () {
        removeEmptyRoot(rootNode, fromBlock);
        var position = $_9kvypj2cjh8lywnz.lastPositionIn(toBlock.dom());
        $_5wjzy24jh8lyw2t.each(children_1, function (node) {
          $_4m7u2e2kjh8lywpi.append(toBlock, node);
        });
        return position;
      }, function (target) {
        var position = $_9kvypj2cjh8lywnz.prevPosition(toBlock.dom(), CaretPosition$1.before(target.dom()));
        $_5wjzy24jh8lyw2t.each(children_1, function (node) {
          $_4m7u2e2kjh8lywpi.before(target, node);
        });
        removeEmptyRoot(rootNode, fromBlock);
        return position;
      });
    }
  };
  var mergeBlocks = function (rootNode, forward, block1, block2) {
    return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  };
  var $_4yurvx3djh8lywu4 = { mergeBlocks: mergeBlocks };

  var backspaceDelete = function (editor, forward) {
    var position;
    var rootNode = $_cgttw3zjh8lywdq.fromDom(editor.getBody());
    position = $_bmbex333jh8lywru.read(rootNode.dom(), forward, editor.selection.getRng()).bind(function (blockBoundary) {
      return $_4yurvx3djh8lywu4.mergeBlocks(rootNode, forward, blockBoundary.from().block(), blockBoundary.to().block());
    });
    position.each(function (pos) {
      editor.selection.setRng(pos.toRange());
    });
    return position.isSome();
  };
  var $_5jmwsv32jh8lywrr = { backspaceDelete: backspaceDelete };

  var deleteRangeMergeBlocks = function (rootNode, selection) {
    var rng = selection.getRng();
    return $_b8twwq26jh8lywmm.liftN([
      $_aj8isd34jh8lyws4.getParentBlock(rootNode, $_cgttw3zjh8lywdq.fromDom(rng.startContainer)),
      $_aj8isd34jh8lyws4.getParentBlock(rootNode, $_cgttw3zjh8lywdq.fromDom(rng.endContainer))
    ], function (block1, block2) {
      if ($_5f6gpb1djh8lywg5.eq(block1, block2) === false) {
        rng.deleteContents();
        $_4yurvx3djh8lywu4.mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
          selection.setRng(pos.toRange());
        });
        return true;
      } else {
        return false;
      }
    }).getOr(false);
  };
  var isRawNodeInTable = function (root, rawNode) {
    var node = $_cgttw3zjh8lywdq.fromDom(rawNode);
    var isRoot = $_eqpqvr6jh8lyw3s.curry($_5f6gpb1djh8lywg5.eq, root);
    return $_6hl03835jh8lywsm.ancestor(node, isTableCell, isRoot).isSome();
  };
  var isSelectionInTable = function (root, rng) {
    return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  };
  var isEverythingSelected = function (root, rng) {
    var noPrevious = $_9kvypj2cjh8lywnz.prevPosition(root.dom(), CaretPosition$1.fromRangeStart(rng)).isNone();
    var noNext = $_9kvypj2cjh8lywnz.nextPosition(root.dom(), CaretPosition$1.fromRangeEnd(rng)).isNone();
    return !isSelectionInTable(root, rng) && noPrevious && noNext;
  };
  var emptyEditor = function (editor) {
    editor.setContent('');
    editor.selection.setCursorLocation();
    return true;
  };
  var deleteRange = function (editor) {
    var rootNode = $_cgttw3zjh8lywdq.fromDom(editor.getBody());
    var rng = editor.selection.getRng();
    return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  };
  var backspaceDelete$1 = function (editor, forward) {
    return editor.selection.isCollapsed() ? false : deleteRange(editor);
  };
  var $_lcy1p3fjh8lywxx = { backspaceDelete: backspaceDelete$1 };

  var generate = function (cases) {
    if (!$_dp4g6d7jh8lyw3y.isArray(cases)) {
      throw new Error('cases must be an array');
    }
    if (cases.length === 0) {
      throw new Error('there must be at least one case');
    }
    var constructors = [];
    var adt = {};
    $_5wjzy24jh8lyw2t.each(cases, function (acase, count) {
      var keys = $_g63v2c13jh8lywej.keys(acase);
      if (keys.length !== 1) {
        throw new Error('one and only one name per case');
      }
      var key = keys[0];
      var value = acase[key];
      if (adt[key] !== undefined) {
        throw new Error('duplicate key detected:' + key);
      } else if (key === 'cata') {
        throw new Error('cannot have a case named cata (sorry)');
      } else if (!$_dp4g6d7jh8lyw3y.isArray(value)) {
        throw new Error('case arguments must be an array');
      }
      constructors.push(key);
      adt[key] = function () {
        var argLength = arguments.length;
        if (argLength !== value.length) {
          throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
        }
        var args = new Array(argLength);
        for (var i = 0; i < args.length; i++)
          args[i] = arguments[i];
        var match = function (branches) {
          var branchKeys = $_g63v2c13jh8lywej.keys(branches);
          if (constructors.length !== branchKeys.length) {
            throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
          }
          var allReqd = $_5wjzy24jh8lyw2t.forall(constructors, function (reqKey) {
            return $_5wjzy24jh8lyw2t.contains(branchKeys, reqKey);
          });
          if (!allReqd)
            throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
          return branches[key].apply(null, args);
        };
        return {
          fold: function () {
            if (arguments.length !== cases.length) {
              throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
            }
            var target = arguments[count];
            return target.apply(null, args);
          },
          match: match,
          log: function (label) {
            console.log(label, {
              constructors: constructors,
              constructor: key,
              params: args
            });
          }
        };
      };
    });
    return adt;
  };
  var $_1ml90g3ijh8lywyp = { generate: generate };

  var isCompoundElement = function (node) {
    return isTableCell($_cgttw3zjh8lywdq.fromDom(node)) || isListItem($_cgttw3zjh8lywdq.fromDom(node));
  };
  var DeleteAction = $_1ml90g3ijh8lywyp.generate([
    { remove: ['element'] },
    { moveToElement: ['element'] },
    { moveToPosition: ['position'] }
  ]);
  var isAtContentEditableBlockCaret = function (forward, from) {
    var elm = from.getNode(forward === false);
    var caretLocation = forward ? 'after' : 'before';
    return $_5oonaz1qjh8lywhz.isElement(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  };
  var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
    var inSameBlock = function (elm) {
      return isInline($_cgttw3zjh8lywdq.fromDom(elm)) && !isInSameBlock(from, to, root);
    };
    return getRelativeCefElm(!forward, from).fold(function () {
      return getRelativeCefElm(forward, to).fold($_eqpqvr6jh8lyw3s.constant(false), inSameBlock);
    }, inSameBlock);
  };
  var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
    var toCefElm = to.getNode(forward === false);
    return $_aj8isd34jh8lyws4.getParentBlock($_cgttw3zjh8lywdq.fromDom(root), $_cgttw3zjh8lywdq.fromDom(from.getNode())).map(function (blockElm) {
      return $_b1urh33ajh8lywts.isEmpty(blockElm) ? DeleteAction.remove(blockElm.dom()) : DeleteAction.moveToElement(toCefElm);
    }).orThunk(function () {
      return Option.some(DeleteAction.moveToElement(toCefElm));
    });
  };
  var findCefPosition = function (root, forward, from) {
    return $_9kvypj2cjh8lywnz.fromPosition(forward, root, from).bind(function (to) {
      if (isCompoundElement(to.getNode())) {
        return Option.none();
      } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
        return Option.none();
      } else if (forward && $_5oonaz1qjh8lywhz.isContentEditableFalse(to.getNode())) {
        return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
      } else if (forward === false && $_5oonaz1qjh8lywhz.isContentEditableFalse(to.getNode(true))) {
        return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
      } else if (forward && isAfterContentEditableFalse(from)) {
        return Option.some(DeleteAction.moveToPosition(to));
      } else if (forward === false && isBeforeContentEditableFalse(from)) {
        return Option.some(DeleteAction.moveToPosition(to));
      } else {
        return Option.none();
      }
    });
  };
  var getContentEditableBlockAction = function (forward, elm) {
    if (forward && $_5oonaz1qjh8lywhz.isContentEditableFalse(elm.nextSibling)) {
      return Option.some(DeleteAction.moveToElement(elm.nextSibling));
    } else if (forward === false && $_5oonaz1qjh8lywhz.isContentEditableFalse(elm.previousSibling)) {
      return Option.some(DeleteAction.moveToElement(elm.previousSibling));
    } else {
      return Option.none();
    }
  };
  var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
    return deleteAction.fold(function (elm) {
      return Option.some(DeleteAction.remove(elm));
    }, function (elm) {
      return Option.some(DeleteAction.moveToElement(elm));
    }, function (to) {
      if (isInSameBlock(from, to, root)) {
        return Option.none();
      } else {
        return Option.some(DeleteAction.moveToPosition(to));
      }
    });
  };
  var getContentEditableAction = function (root, forward, from) {
    if (isAtContentEditableBlockCaret(forward, from)) {
      return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
        return findCefPosition(root, forward, from);
      }, Option.some);
    } else {
      return findCefPosition(root, forward, from).bind(function (deleteAction) {
        return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
      });
    }
  };
  var read$1 = function (root, forward, rng) {
    var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
    var from = CaretPosition$1.fromRangeStart(normalizedRange);
    if (forward === false && isAfterContentEditableFalse(from)) {
      return Option.some(DeleteAction.remove(from.getNode(true)));
    } else if (forward && isBeforeContentEditableFalse(from)) {
      return Option.some(DeleteAction.remove(from.getNode()));
    } else {
      return getContentEditableAction(root, forward, from);
    }
  };

  var needsReposition = function (pos, elm) {
    var container = pos.container();
    var offset = pos.offset();
    return CaretPosition$1.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition$1.before(elm).offset();
  };
  var reposition = function (elm, pos) {
    return needsReposition(pos, elm) ? CaretPosition$1(pos.container(), pos.offset() - 1) : pos;
  };
  var beforeOrStartOf = function (node) {
    return $_5oonaz1qjh8lywhz.isText(node) ? CaretPosition$1(node, 0) : CaretPosition$1.before(node);
  };
  var afterOrEndOf = function (node) {
    return $_5oonaz1qjh8lywhz.isText(node) ? CaretPosition$1(node, node.data.length) : CaretPosition$1.after(node);
  };
  var getPreviousSiblingCaretPosition = function (elm) {
    if (isCaretCandidate(elm.previousSibling)) {
      return Option.some(afterOrEndOf(elm.previousSibling));
    } else {
      return elm.previousSibling ? $_9kvypj2cjh8lywnz.lastPositionIn(elm.previousSibling) : Option.none();
    }
  };
  var getNextSiblingCaretPosition = function (elm) {
    if (isCaretCandidate(elm.nextSibling)) {
      return Option.some(beforeOrStartOf(elm.nextSibling));
    } else {
      return elm.nextSibling ? $_9kvypj2cjh8lywnz.firstPositionIn(elm.nextSibling) : Option.none();
    }
  };
  var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
    var startPosition = CaretPosition$1.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
    return $_9kvypj2cjh8lywnz.prevPosition(rootElement, startPosition).fold(function () {
      return $_9kvypj2cjh8lywnz.nextPosition(rootElement, CaretPosition$1.after(elm));
    }, Option.some);
  };
  var findCaretPositionForwardsFromElm = function (rootElement, elm) {
    return $_9kvypj2cjh8lywnz.nextPosition(rootElement, CaretPosition$1.after(elm)).fold(function () {
      return $_9kvypj2cjh8lywnz.prevPosition(rootElement, CaretPosition$1.before(elm));
    }, Option.some);
  };
  var findCaretPositionBackwards = function (rootElement, elm) {
    return getPreviousSiblingCaretPosition(elm).orThunk(function () {
      return getNextSiblingCaretPosition(elm);
    }).orThunk(function () {
      return findCaretPositionBackwardsFromElm(rootElement, elm);
    });
  };
  var findCaretPositionForward = function (rootElement, elm) {
    return getNextSiblingCaretPosition(elm).orThunk(function () {
      return getPreviousSiblingCaretPosition(elm);
    }).orThunk(function () {
      return findCaretPositionForwardsFromElm(rootElement, elm);
    });
  };
  var findCaretPosition$1 = function (forward, rootElement, elm) {
    return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  };
  var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
    return findCaretPosition$1(forward, rootElement, elm).map($_eqpqvr6jh8lyw3s.curry(reposition, elm));
  };
  var setSelection = function (editor, forward, pos) {
    pos.fold(function () {
      editor.focus();
    }, function (pos) {
      editor.selection.setRng(pos.toRange(), forward);
    });
  };
  var eqRawNode = function (rawNode) {
    return function (elm) {
      return elm.dom() === rawNode;
    };
  };
  var isBlock$2 = function (editor, elm) {
    return elm && editor.schema.getBlockElements().hasOwnProperty($_7j1jt210jh8lywdx.name(elm));
  };
  var paddEmptyBlock = function (elm) {
    if ($_b1urh33ajh8lywts.isEmpty(elm)) {
      var br = $_cgttw3zjh8lywdq.fromHtml('<br data-mce-bogus="1">');
      $_bfmuql2ujh8lywr1.empty(elm);
      $_4m7u2e2kjh8lywpi.append(elm, br);
      return Option.some(CaretPosition$1.before(br.dom()));
    } else {
      return Option.none();
    }
  };
  var deleteNormalized = function (elm, afterDeletePosOpt) {
    return $_b8twwq26jh8lywmm.liftN([
      $_a43q0i17jh8lywfe.prevSibling(elm),
      $_a43q0i17jh8lywfe.nextSibling(elm),
      afterDeletePosOpt
    ], function (prev, next, afterDeletePos) {
      var offset;
      var prevNode = prev.dom();
      var nextNode = next.dom();
      if ($_5oonaz1qjh8lywhz.isText(prevNode) && $_5oonaz1qjh8lywhz.isText(nextNode)) {
        offset = prevNode.data.length;
        prevNode.appendData(nextNode.data);
        $_bfmuql2ujh8lywr1.remove(next);
        $_bfmuql2ujh8lywr1.remove(elm);
        if (afterDeletePos.container() === nextNode) {
          return CaretPosition$1(prevNode, offset);
        } else {
          return afterDeletePos;
        }
      } else {
        $_bfmuql2ujh8lywr1.remove(elm);
        return afterDeletePos;
      }
    }).orThunk(function () {
      $_bfmuql2ujh8lywr1.remove(elm);
      return afterDeletePosOpt;
    });
  };
  var deleteElement = function (editor, forward, elm) {
    var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom());
    var parentBlock = $_6hl03835jh8lywsm.ancestor(elm, $_eqpqvr6jh8lyw3s.curry(isBlock$2, editor), eqRawNode(editor.getBody()));
    var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos);
    if (editor.dom.isEmpty(editor.getBody())) {
      editor.setContent('');
      editor.selection.setCursorLocation();
    } else {
      parentBlock.bind(paddEmptyBlock).fold(function () {
        setSelection(editor, forward, normalizedAfterDeletePos);
      }, function (paddPos) {
        setSelection(editor, forward, Option.some(paddPos));
      });
    }
  };
  var $_1al0sh3jjh8lywyv = { deleteElement: deleteElement };

  var deleteElement$1 = function (editor, forward) {
    return function (element) {
      editor._selectionOverrides.hideFakeCaret();
      $_1al0sh3jjh8lywyv.deleteElement(editor, forward, $_cgttw3zjh8lywdq.fromDom(element));
      return true;
    };
  };
  var moveToElement = function (editor, forward) {
    return function (element) {
      var pos = forward ? CaretPosition$1.before(element) : CaretPosition$1.after(element);
      editor.selection.setRng(pos.toRange());
      return true;
    };
  };
  var moveToPosition = function (editor) {
    return function (pos) {
      editor.selection.setRng(pos.toRange());
      return true;
    };
  };
  var backspaceDeleteCaret = function (editor, forward) {
    var result = read$1(editor.getBody(), forward, editor.selection.getRng()).map(function (deleteAction) {
      return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
    });
    return result.getOr(false);
  };
  var deleteOffscreenSelection = function (rootElement) {
    $_5wjzy24jh8lyw2t.each($_eebxu2gjh8lywp3.descendants(rootElement, '.mce-offscreen-selection'), $_bfmuql2ujh8lywr1.remove);
  };
  var backspaceDeleteRange = function (editor, forward) {
    var selectedElement = editor.selection.getNode();
    if ($_5oonaz1qjh8lywhz.isContentEditableFalse(selectedElement)) {
      deleteOffscreenSelection($_cgttw3zjh8lywdq.fromDom(editor.getBody()));
      $_1al0sh3jjh8lywyv.deleteElement(editor, forward, $_cgttw3zjh8lywdq.fromDom(editor.selection.getNode()));
      $_aj8isd34jh8lyws4.paddEmptyBody(editor);
      return true;
    } else {
      return false;
    }
  };
  var getContentEditableRoot = function (root, node) {
    while (node && node !== root) {
      if ($_5oonaz1qjh8lywhz.isContentEditableTrue(node) || $_5oonaz1qjh8lywhz.isContentEditableFalse(node)) {
        return node;
      }
      node = node.parentNode;
    }
    return null;
  };
  var paddEmptyElement = function (editor) {
    var br;
    var ceRoot = getContentEditableRoot(editor.getBody(), editor.selection.getNode());
    if ($_5oonaz1qjh8lywhz.isContentEditableTrue(ceRoot) && editor.dom.isBlock(ceRoot) && editor.dom.isEmpty(ceRoot)) {
      br = editor.dom.create('br', { 'data-mce-bogus': '1' });
      editor.dom.setHTML(ceRoot, '');
      ceRoot.appendChild(br);
      editor.selection.setRng(CaretPosition$1.before(br).toRange());
    }
    return true;
  };
  var backspaceDelete$2 = function (editor, forward) {
    if (editor.selection.isCollapsed()) {
      return backspaceDeleteCaret(editor, forward);
    } else {
      return backspaceDeleteRange(editor, forward);
    }
  };
  var $_ar80r13gjh8lywy7 = {
    backspaceDelete: backspaceDelete$2,
    paddEmptyElement: paddEmptyElement
  };

  var isText$8 = $_5oonaz1qjh8lywhz.isText;
  var startsWithCaretContainer$1 = function (node) {
    return isText$8(node) && node.data[0] === $_d383mr21jh8lywlv.ZWSP;
  };
  var endsWithCaretContainer$1 = function (node) {
    return isText$8(node) && node.data[node.data.length - 1] === $_d383mr21jh8lywlv.ZWSP;
  };
  var createZwsp = function (node) {
    return node.ownerDocument.createTextNode($_d383mr21jh8lywlv.ZWSP);
  };
  var insertBefore$1 = function (node) {
    if (isText$8(node.previousSibling)) {
      if (endsWithCaretContainer$1(node.previousSibling)) {
        return node.previousSibling;
      } else {
        node.previousSibling.appendData($_d383mr21jh8lywlv.ZWSP);
        return node.previousSibling;
      }
    } else if (isText$8(node)) {
      if (startsWithCaretContainer$1(node)) {
        return node;
      } else {
        node.insertData(0, $_d383mr21jh8lywlv.ZWSP);
        return node;
      }
    } else {
      var newNode = createZwsp(node);
      node.parentNode.insertBefore(newNode, node);
      return newNode;
    }
  };
  var insertAfter$1 = function (node) {
    if (isText$8(node.nextSibling)) {
      if (startsWithCaretContainer$1(node.nextSibling)) {
        return node.nextSibling;
      } else {
        node.nextSibling.insertData(0, $_d383mr21jh8lywlv.ZWSP);
        return node.nextSibling;
      }
    } else if (isText$8(node)) {
      if (endsWithCaretContainer$1(node)) {
        return node;
      } else {
        node.appendData($_d383mr21jh8lywlv.ZWSP);
        return node;
      }
    } else {
      var newNode = createZwsp(node);
      if (node.nextSibling) {
        node.parentNode.insertBefore(newNode, node.nextSibling);
      } else {
        node.parentNode.appendChild(newNode);
      }
      return newNode;
    }
  };
  var insertInline$1 = function (before, node) {
    return before ? insertBefore$1(node) : insertAfter$1(node);
  };
  var insertInlineBefore = $_eqpqvr6jh8lyw3s.curry(insertInline$1, true);
  var insertInlineAfter = $_eqpqvr6jh8lyw3s.curry(insertInline$1, false);

  var insertInlinePos = function (pos, before) {
    if ($_5oonaz1qjh8lywhz.isText(pos.container())) {
      return insertInline$1(before, pos.container());
    } else {
      return insertInline$1(before, pos.getNode());
    }
  };
  var isPosCaretContainer = function (pos, caret) {
    var caretNode = caret.get();
    return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  };
  var renderCaret = function (caret, location) {
    return location.fold(function (element) {
      $_9nl16f2ajh8lywne.remove(caret.get());
      var text = insertInlineBefore(element);
      caret.set(text);
      return Option.some(CaretPosition$1(text, text.length - 1));
    }, function (element) {
      return $_9kvypj2cjh8lywnz.firstPositionIn(element).map(function (pos) {
        if (!isPosCaretContainer(pos, caret)) {
          $_9nl16f2ajh8lywne.remove(caret.get());
          var text = insertInlinePos(pos, true);
          caret.set(text);
          return CaretPosition$1(text, 1);
        } else {
          return CaretPosition$1(caret.get(), 1);
        }
      });
    }, function (element) {
      return $_9kvypj2cjh8lywnz.lastPositionIn(element).map(function (pos) {
        if (!isPosCaretContainer(pos, caret)) {
          $_9nl16f2ajh8lywne.remove(caret.get());
          var text = insertInlinePos(pos, false);
          caret.set(text);
          return CaretPosition$1(text, text.length - 1);
        } else {
          return CaretPosition$1(caret.get(), caret.get().length - 1);
        }
      });
    }, function (element) {
      $_9nl16f2ajh8lywne.remove(caret.get());
      var text = insertInlineAfter(element);
      caret.set(text);
      return Option.some(CaretPosition$1(text, 1));
    });
  };
  var $_biul8i3ljh8lywzl = { renderCaret: renderCaret };

  var evaluateUntil = function (fns, args) {
    for (var i = 0; i < fns.length; i++) {
      var result = fns[i].apply(null, args);
      if (result.isSome()) {
        return result;
      }
    }
    return Option.none();
  };
  var $_7r5om73ojh8lyx09 = { evaluateUntil: evaluateUntil };

  var Location = $_1ml90g3ijh8lywyp.generate([
    { before: ['element'] },
    { start: ['element'] },
    { end: ['element'] },
    { after: ['element'] }
  ]);
  var rescope = function (rootNode, node) {
    var parentBlock = getParentBlock(node, rootNode);
    return parentBlock ? parentBlock : rootNode;
  };
  var before$3 = function (isInlineTarget, rootNode, pos) {
    var nPos = $_231v7s37jh8lywt3.normalizeForwards(pos);
    var scope = rescope(rootNode, nPos.container());
    return $_231v7s37jh8lywt3.findRootInline(isInlineTarget, scope, nPos).fold(function () {
      return $_9kvypj2cjh8lywnz.nextPosition(scope, nPos).bind($_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.findRootInline, isInlineTarget, scope)).map(function (inline) {
        return Location.before(inline);
      });
    }, Option.none);
  };
  var isNotInsideFormatCaretContainer = function (rootNode, elm) {
    return getParentCaretContainer(rootNode, elm) === null;
  };
  var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
    return $_231v7s37jh8lywt3.findRootInline(isInlineTarget, rootNode, pos).filter($_eqpqvr6jh8lyw3s.curry(isNotInsideFormatCaretContainer, rootNode));
  };
  var start = function (isInlineTarget, rootNode, pos) {
    var nPos = $_231v7s37jh8lywt3.normalizeBackwards(pos);
    return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
      var prevPos = $_9kvypj2cjh8lywnz.prevPosition(inline, nPos);
      return prevPos.isNone() ? Option.some(Location.start(inline)) : Option.none();
    });
  };
  var end = function (isInlineTarget, rootNode, pos) {
    var nPos = $_231v7s37jh8lywt3.normalizeForwards(pos);
    return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
      var nextPos = $_9kvypj2cjh8lywnz.nextPosition(inline, nPos);
      return nextPos.isNone() ? Option.some(Location.end(inline)) : Option.none();
    });
  };
  var after$3 = function (isInlineTarget, rootNode, pos) {
    var nPos = $_231v7s37jh8lywt3.normalizeBackwards(pos);
    var scope = rescope(rootNode, nPos.container());
    return $_231v7s37jh8lywt3.findRootInline(isInlineTarget, scope, nPos).fold(function () {
      return $_9kvypj2cjh8lywnz.prevPosition(scope, nPos).bind($_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.findRootInline, isInlineTarget, scope)).map(function (inline) {
        return Location.after(inline);
      });
    }, Option.none);
  };
  var isValidLocation = function (location) {
    return $_231v7s37jh8lywt3.isRtl(getElement(location)) === false;
  };
  var readLocation = function (isInlineTarget, rootNode, pos) {
    var location = $_7r5om73ojh8lyx09.evaluateUntil([
      before$3,
      start,
      end,
      after$3
    ], [
      isInlineTarget,
      rootNode,
      pos
    ]);
    return location.filter(isValidLocation);
  };
  var getElement = function (location) {
    return location.fold($_eqpqvr6jh8lyw3s.identity, $_eqpqvr6jh8lyw3s.identity, $_eqpqvr6jh8lyw3s.identity, $_eqpqvr6jh8lyw3s.identity);
  };
  var getName = function (location) {
    return location.fold($_eqpqvr6jh8lyw3s.constant('before'), $_eqpqvr6jh8lyw3s.constant('start'), $_eqpqvr6jh8lyw3s.constant('end'), $_eqpqvr6jh8lyw3s.constant('after'));
  };
  var outside = function (location) {
    return location.fold(Location.before, Location.before, Location.after, Location.after);
  };
  var inside = function (location) {
    return location.fold(Location.start, Location.start, Location.end, Location.end);
  };
  var isEq = function (location1, location2) {
    return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  };
  var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
    return $_b8twwq26jh8lywmm.liftN([
      $_231v7s37jh8lywt3.findRootInline(isInlineTarget, rootNode, from),
      $_231v7s37jh8lywt3.findRootInline(isInlineTarget, rootNode, to)
    ], function (fromInline, toInline) {
      if (fromInline !== toInline && $_231v7s37jh8lywt3.hasSameParentBlock(rootNode, fromInline, toInline)) {
        return Location.after(forward ? fromInline : toInline);
      } else {
        return location;
      }
    }).getOr(location);
  };
  var skipNoMovement = function (fromLocation, toLocation) {
    return fromLocation.fold($_eqpqvr6jh8lyw3s.constant(true), function (fromLocation) {
      return !isEq(fromLocation, toLocation);
    });
  };
  var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
    var from = $_231v7s37jh8lywt3.normalizePosition(forward, pos);
    var to = $_9kvypj2cjh8lywnz.fromPosition(forward, rootNode, from).map($_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.normalizePosition, forward));
    var location = to.fold(function () {
      return fromLocation.map(outside);
    }, function (to) {
      return readLocation(isInlineTarget, rootNode, to).map($_eqpqvr6jh8lyw3s.curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter($_eqpqvr6jh8lyw3s.curry(skipNoMovement, fromLocation));
    });
    return location.filter(isValidLocation);
  };
  var findLocationSimple = function (forward, location) {
    if (forward) {
      return location.fold($_eqpqvr6jh8lyw3s.compose(Option.some, Location.start), Option.none, $_eqpqvr6jh8lyw3s.compose(Option.some, Location.after), Option.none);
    } else {
      return location.fold(Option.none, $_eqpqvr6jh8lyw3s.compose(Option.some, Location.before), Option.none, $_eqpqvr6jh8lyw3s.compose(Option.some, Location.end));
    }
  };
  var findLocation = function (forward, isInlineTarget, rootNode, pos) {
    var from = $_231v7s37jh8lywt3.normalizePosition(forward, pos);
    var fromLocation = readLocation(isInlineTarget, rootNode, from);
    return readLocation(isInlineTarget, rootNode, from).bind($_eqpqvr6jh8lyw3s.curry(findLocationSimple, forward)).orThunk(function () {
      return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
    });
  };
  var $_6kjy7r3njh8lywzz = {
    readLocation: readLocation,
    findLocation: findLocation,
    prevLocation: $_eqpqvr6jh8lyw3s.curry(findLocation, false),
    nextLocation: $_eqpqvr6jh8lyw3s.curry(findLocation, true),
    getElement: getElement,
    outside: outside,
    inside: inside
  };

  var hasSelectionModifyApi = function (editor) {
    return $_dp4g6d7jh8lyw3y.isFunction(editor.selection.getSel().modify);
  };
  var moveRel = function (forward, selection, pos) {
    var delta = forward ? 1 : -1;
    selection.setRng(CaretPosition$1(pos.container(), pos.offset() + delta).toRange());
    selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
    return true;
  };
  var moveByWord = function (forward, editor) {
    var rng = editor.selection.getRng();
    var pos = forward ? CaretPosition$1.fromRangeEnd(rng) : CaretPosition$1.fromRangeStart(rng);
    if (!hasSelectionModifyApi(editor)) {
      return false;
    } else if (forward && isBeforeInline(pos)) {
      return moveRel(true, editor.selection, pos);
    } else if (!forward && isAfterInline(pos)) {
      return moveRel(false, editor.selection, pos);
    } else {
      return false;
    }
  };
  var $_d48vbn3qjh8lyx0k = {
    hasSelectionModifyApi: hasSelectionModifyApi,
    moveByWord: moveByWord
  };

  var setCaretPosition = function (editor, pos) {
    var rng = editor.dom.createRng();
    rng.setStart(pos.container(), pos.offset());
    rng.setEnd(pos.container(), pos.offset());
    editor.selection.setRng(rng);
  };
  var isFeatureEnabled = function (editor) {
    return editor.settings.inline_boundaries !== false;
  };
  var setSelected = function (state, elm) {
    if (state) {
      elm.setAttribute('data-mce-selected', 'inline-boundary');
    } else {
      elm.removeAttribute('data-mce-selected');
    }
  };
  var renderCaretLocation = function (editor, caret, location) {
    return $_biul8i3ljh8lywzl.renderCaret(caret, location).map(function (pos) {
      setCaretPosition(editor, pos);
      return location;
    });
  };
  var findLocation$1 = function (editor, caret, forward) {
    var rootNode = editor.getBody();
    var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
    var isInlineTarget = $_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.isInlineTarget, editor);
    var location = $_6kjy7r3njh8lywzz.findLocation(forward, isInlineTarget, rootNode, from);
    return location.bind(function (location) {
      return renderCaretLocation(editor, caret, location);
    });
  };
  var toggleInlines = function (isInlineTarget, dom, elms) {
    var selectedInlines = $_5wjzy24jh8lyw2t.filter(dom.select('*[data-mce-selected="inline-boundary"]'), isInlineTarget);
    var targetInlines = $_5wjzy24jh8lyw2t.filter(elms, isInlineTarget);
    $_5wjzy24jh8lyw2t.each($_5wjzy24jh8lyw2t.difference(selectedInlines, targetInlines), $_eqpqvr6jh8lyw3s.curry(setSelected, false));
    $_5wjzy24jh8lyw2t.each($_5wjzy24jh8lyw2t.difference(targetInlines, selectedInlines), $_eqpqvr6jh8lyw3s.curry(setSelected, true));
  };
  var safeRemoveCaretContainer = function (editor, caret) {
    if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
      var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
      if (CaretPosition$1.isTextPosition(pos) && $_231v7s37jh8lywt3.isAtZwsp(pos) === false) {
        setCaretPosition(editor, $_9nl16f2ajh8lywne.removeAndReposition(caret.get(), pos));
        caret.set(null);
      }
    }
  };
  var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
    if (editor.selection.isCollapsed()) {
      var inlines = $_5wjzy24jh8lyw2t.filter(elms, isInlineTarget);
      $_5wjzy24jh8lyw2t.each(inlines, function (inline) {
        var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
        $_6kjy7r3njh8lywzz.readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
          return renderCaretLocation(editor, caret, location);
        });
      });
    }
  };
  var move = function (editor, caret, forward) {
    return function () {
      return isFeatureEnabled(editor) ? findLocation$1(editor, caret, forward).isSome() : false;
    };
  };
  var moveWord = function (forward, editor, caret) {
    return function () {
      return isFeatureEnabled(editor) ? $_d48vbn3qjh8lyx0k.moveByWord(forward, editor) : false;
    };
  };
  var setupSelectedState = function (editor) {
    var caret = Cell(null);
    var isInlineTarget = $_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.isInlineTarget, editor);
    editor.on('NodeChange', function (e) {
      if (isFeatureEnabled(editor)) {
        toggleInlines(isInlineTarget, editor.dom, e.parents);
        safeRemoveCaretContainer(editor, caret);
        renderInsideInlineCaret(isInlineTarget, editor, caret, e.parents);
      }
    });
    return caret;
  };
  var moveNextWord = $_eqpqvr6jh8lyw3s.curry(moveWord, true);
  var movePrevWord = $_eqpqvr6jh8lyw3s.curry(moveWord, false);
  var $_65xx7w3pjh8lyx0d = {
    move: move,
    moveNextWord: moveNextWord,
    movePrevWord: movePrevWord,
    setupSelectedState: setupSelectedState,
    setCaretPosition: setCaretPosition
  };

  var isFeatureEnabled$1 = function (editor) {
    return editor.settings.inline_boundaries !== false;
  };
  var rangeFromPositions = function (from, to) {
    var range = document.createRange();
    range.setStart(from.container(), from.offset());
    range.setEnd(to.container(), to.offset());
    return range;
  };
  var hasOnlyTwoOrLessPositionsLeft = function (elm) {
    return $_b8twwq26jh8lywmm.liftN([
      $_9kvypj2cjh8lywnz.firstPositionIn(elm),
      $_9kvypj2cjh8lywnz.lastPositionIn(elm)
    ], function (firstPos, lastPos) {
      var normalizedFirstPos = $_231v7s37jh8lywt3.normalizePosition(true, firstPos);
      var normalizedLastPos = $_231v7s37jh8lywt3.normalizePosition(false, lastPos);
      return $_9kvypj2cjh8lywnz.nextPosition(elm, normalizedFirstPos).map(function (pos) {
        return pos.isEqual(normalizedLastPos);
      }).getOr(true);
    }).getOr(true);
  };
  var setCaretLocation = function (editor, caret) {
    return function (location) {
      return $_biul8i3ljh8lywzl.renderCaret(caret, location).map(function (pos) {
        $_65xx7w3pjh8lyx0d.setCaretPosition(editor, pos);
        return true;
      }).getOr(false);
    };
  };
  var deleteFromTo = function (editor, caret, from, to) {
    var rootNode = editor.getBody();
    var isInlineTarget = $_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.isInlineTarget, editor);
    editor.undoManager.ignore(function () {
      editor.selection.setRng(rangeFromPositions(from, to));
      editor.execCommand('Delete');
      $_6kjy7r3njh8lywzz.readLocation(isInlineTarget, rootNode, CaretPosition$1.fromRangeStart(editor.selection.getRng())).map($_6kjy7r3njh8lywzz.inside).map(setCaretLocation(editor, caret));
    });
    editor.nodeChanged();
  };
  var rescope$1 = function (rootNode, node) {
    var parentBlock = getParentBlock(node, rootNode);
    return parentBlock ? parentBlock : rootNode;
  };
  var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
    var rootNode = rescope$1(editor.getBody(), from.container());
    var isInlineTarget = $_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.isInlineTarget, editor);
    var fromLocation = $_6kjy7r3njh8lywzz.readLocation(isInlineTarget, rootNode, from);
    return fromLocation.bind(function (location) {
      if (forward) {
        return location.fold($_eqpqvr6jh8lyw3s.constant(Option.some($_6kjy7r3njh8lywzz.inside(location))), Option.none, $_eqpqvr6jh8lyw3s.constant(Option.some($_6kjy7r3njh8lywzz.outside(location))), Option.none);
      } else {
        return location.fold(Option.none, $_eqpqvr6jh8lyw3s.constant(Option.some($_6kjy7r3njh8lywzz.outside(location))), Option.none, $_eqpqvr6jh8lyw3s.constant(Option.some($_6kjy7r3njh8lywzz.inside(location))));
      }
    }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
      var toPosition = $_9kvypj2cjh8lywnz.navigate(forward, rootNode, from);
      var toLocation = toPosition.bind(function (pos) {
        return $_6kjy7r3njh8lywzz.readLocation(isInlineTarget, rootNode, pos);
      });
      if (fromLocation.isSome() && toLocation.isSome()) {
        return $_231v7s37jh8lywt3.findRootInline(isInlineTarget, rootNode, from).map(function (elm) {
          if (hasOnlyTwoOrLessPositionsLeft(elm)) {
            $_1al0sh3jjh8lywyv.deleteElement(editor, forward, $_cgttw3zjh8lywdq.fromDom(elm));
            return true;
          } else {
            return false;
          }
        }).getOr(false);
      } else {
        return toLocation.bind(function (_) {
          return toPosition.map(function (to) {
            if (forward) {
              deleteFromTo(editor, caret, from, to);
            } else {
              deleteFromTo(editor, caret, to, from);
            }
            return true;
          });
        }).getOr(false);
      }
    });
  };
  var backspaceDelete$3 = function (editor, caret, forward) {
    if (editor.selection.isCollapsed() && isFeatureEnabled$1(editor)) {
      var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
      return backspaceDeleteCollapsed(editor, caret, forward, from);
    }
    return false;
  };
  var $_ej9d8d3kjh8lywzc = { backspaceDelete: backspaceDelete$3 };

  var tableCellRng = $_4jz0ce18jh8lywft.immutable('start', 'end');
  var tableSelection = $_4jz0ce18jh8lywft.immutable('rng', 'table', 'cells');
  var deleteAction = $_1ml90g3ijh8lywyp.generate([
    { removeTable: ['element'] },
    { emptyCells: ['cells'] }
  ]);
  var isRootFromElement = function (root) {
    return $_eqpqvr6jh8lyw3s.curry($_5f6gpb1djh8lywg5.eq, root);
  };
  var getClosestCell$1 = function (container, isRoot) {
    return $_7sg18r3cjh8lywu1.closest($_cgttw3zjh8lywdq.fromDom(container), 'td,th', isRoot);
  };
  var getClosestTable = function (cell, isRoot) {
    return $_7sg18r3cjh8lywu1.ancestor(cell, 'table', isRoot);
  };
  var isExpandedCellRng = function (cellRng) {
    return $_5f6gpb1djh8lywg5.eq(cellRng.start(), cellRng.end()) === false;
  };
  var getTableFromCellRng = function (cellRng, isRoot) {
    return getClosestTable(cellRng.start(), isRoot).bind(function (startParentTable) {
      return getClosestTable(cellRng.end(), isRoot).bind(function (endParentTable) {
        return $_5f6gpb1djh8lywg5.eq(startParentTable, endParentTable) ? Option.some(startParentTable) : Option.none();
      });
    });
  };
  var getTableCells = function (table) {
    return $_eebxu2gjh8lywp3.descendants(table, 'td,th');
  };
  var getCellRangeFromStartTable = function (cellRng, isRoot) {
    return getClosestTable(cellRng.start(), isRoot).bind(function (table) {
      return $_5wjzy24jh8lyw2t.last(getTableCells(table)).map(function (endCell) {
        return tableCellRng(cellRng.start(), endCell);
      });
    });
  };
  var partialSelection = function (isRoot, rng) {
    var startCell = getClosestCell$1(rng.startContainer, isRoot);
    var endCell = getClosestCell$1(rng.endContainer, isRoot);
    return rng.collapsed ? Option.none() : $_b8twwq26jh8lywmm.liftN([
      startCell,
      endCell
    ], tableCellRng).fold(function () {
      return startCell.fold(function () {
        return endCell.bind(function (endCell) {
          return getClosestTable(endCell, isRoot).bind(function (table) {
            return $_5wjzy24jh8lyw2t.head(getTableCells(table)).map(function (startCell) {
              return tableCellRng(startCell, endCell);
            });
          });
        });
      }, function (startCell) {
        return getClosestTable(startCell, isRoot).bind(function (table) {
          return $_5wjzy24jh8lyw2t.last(getTableCells(table)).map(function (endCell) {
            return tableCellRng(startCell, endCell);
          });
        });
      });
    }, function (cellRng) {
      return isWithinSameTable(isRoot, cellRng) ? Option.none() : getCellRangeFromStartTable(cellRng, isRoot);
    });
  };
  var isWithinSameTable = function (isRoot, cellRng) {
    return getTableFromCellRng(cellRng, isRoot).isSome();
  };
  var getCellRng = function (rng, isRoot) {
    var startCell = getClosestCell$1(rng.startContainer, isRoot);
    var endCell = getClosestCell$1(rng.endContainer, isRoot);
    return $_b8twwq26jh8lywmm.liftN([
      startCell,
      endCell
    ], tableCellRng).filter(isExpandedCellRng).filter(function (cellRng) {
      return isWithinSameTable(isRoot, cellRng);
    }).orThunk(function () {
      return partialSelection(isRoot, rng);
    });
  };
  var getTableSelectionFromCellRng = function (cellRng, isRoot) {
    return getTableFromCellRng(cellRng, isRoot).map(function (table) {
      return tableSelection(cellRng, table, getTableCells(table));
    });
  };
  var getTableSelectionFromRng = function (root, rng) {
    var isRoot = isRootFromElement(root);
    return getCellRng(rng, isRoot).bind(function (cellRng) {
      return getTableSelectionFromCellRng(cellRng, isRoot);
    });
  };
  var getCellIndex = function (cells, cell) {
    return $_5wjzy24jh8lyw2t.findIndex(cells, function (x) {
      return $_5f6gpb1djh8lywg5.eq(x, cell);
    });
  };
  var getSelectedCells = function (tableSelection) {
    return $_b8twwq26jh8lywmm.liftN([
      getCellIndex(tableSelection.cells(), tableSelection.rng().start()),
      getCellIndex(tableSelection.cells(), tableSelection.rng().end())
    ], function (startIndex, endIndex) {
      return tableSelection.cells().slice(startIndex, endIndex + 1);
    });
  };
  var getAction = function (tableSelection) {
    return getSelectedCells(tableSelection).map(function (selected) {
      var cells = tableSelection.cells();
      return selected.length === cells.length ? deleteAction.removeTable(tableSelection.table()) : deleteAction.emptyCells(selected);
    });
  };
  var getActionFromCells = function (cells) {
    return deleteAction.emptyCells(cells);
  };
  var getActionFromRange = function (root, rng) {
    return getTableSelectionFromRng(root, rng).bind(getAction);
  };
  var $_g0m0zq3sjh8lyx10 = {
    getActionFromRange: getActionFromRange,
    getActionFromCells: getActionFromCells
  };

  var getRanges = function (selection) {
    var ranges = [];
    if (selection) {
      for (var i = 0; i < selection.rangeCount; i++) {
        ranges.push(selection.getRangeAt(i));
      }
    }
    return ranges;
  };
  var getSelectedNodes = function (ranges) {
    return $_5wjzy24jh8lyw2t.bind(ranges, function (range) {
      var node = getSelectedNode(range);
      return node ? [$_cgttw3zjh8lywdq.fromDom(node)] : [];
    });
  };
  var hasMultipleRanges = function (selection) {
    return getRanges(selection).length > 1;
  };
  var $_d1o8uj3ujh8lyx1u = {
    getRanges: getRanges,
    getSelectedNodes: getSelectedNodes,
    hasMultipleRanges: hasMultipleRanges
  };

  var getCellsFromRanges = function (ranges) {
    return $_5wjzy24jh8lyw2t.filter($_d1o8uj3ujh8lyx1u.getSelectedNodes(ranges), isTableCell);
  };
  var getCellsFromElement = function (elm) {
    var selectedCells = $_eebxu2gjh8lywp3.descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
    return selectedCells;
  };
  var getCellsFromElementOrRanges = function (ranges, element) {
    var selectedCells = getCellsFromElement(element);
    var rangeCells = getCellsFromRanges(ranges);
    return selectedCells.length > 0 ? selectedCells : rangeCells;
  };
  var getCellsFromEditor = function (editor) {
    return getCellsFromElementOrRanges($_d1o8uj3ujh8lyx1u.getRanges(editor.selection.getSel()), $_cgttw3zjh8lywdq.fromDom(editor.getBody()));
  };
  var $_bwjtq63tjh8lyx1g = {
    getCellsFromRanges: getCellsFromRanges,
    getCellsFromElement: getCellsFromElement,
    getCellsFromElementOrRanges: getCellsFromElementOrRanges,
    getCellsFromEditor: getCellsFromEditor
  };

  var emptyCells = function (editor, cells) {
    $_5wjzy24jh8lyw2t.each(cells, $_2bvsfb2tjh8lywqo.fillWithPaddingBr);
    editor.selection.setCursorLocation(cells[0].dom(), 0);
    return true;
  };
  var deleteTableElement = function (editor, table) {
    $_1al0sh3jjh8lywyv.deleteElement(editor, false, table);
    return true;
  };
  var deleteCellRange = function (editor, rootElm, rng) {
    return $_g0m0zq3sjh8lyx10.getActionFromRange(rootElm, rng).map(function (action) {
      return action.fold($_eqpqvr6jh8lyw3s.curry(deleteTableElement, editor), $_eqpqvr6jh8lyw3s.curry(emptyCells, editor));
    });
  };
  var deleteCaptionRange = function (editor, caption) {
    return emptyElement(editor, caption);
  };
  var deleteTableRange = function (editor, rootElm, rng, startElm) {
    return getParentCaption(rootElm, startElm).fold(function () {
      return deleteCellRange(editor, rootElm, rng);
    }, function (caption) {
      return deleteCaptionRange(editor, caption);
    }).getOr(false);
  };
  var deleteRange$1 = function (editor, startElm) {
    var rootNode = $_cgttw3zjh8lywdq.fromDom(editor.getBody());
    var rng = editor.selection.getRng();
    var selectedCells = $_bwjtq63tjh8lyx1g.getCellsFromEditor(editor);
    return selectedCells.length !== 0 ? emptyCells(editor, selectedCells) : deleteTableRange(editor, rootNode, rng, startElm);
  };
  var getParentCell = function (rootElm, elm) {
    return $_5wjzy24jh8lyw2t.find($_dyxtub3ejh8lywxq.parentsAndSelf(elm, rootElm), isTableCell);
  };
  var getParentCaption = function (rootElm, elm) {
    return $_5wjzy24jh8lyw2t.find($_dyxtub3ejh8lywxq.parentsAndSelf(elm, rootElm), function (elm) {
      return $_7j1jt210jh8lywdx.name(elm) === 'caption';
    });
  };
  var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
    return $_9kvypj2cjh8lywnz.navigate(forward, editor.getBody(), from).bind(function (to) {
      return getParentCell(rootElm, $_cgttw3zjh8lywdq.fromDom(to.getNode())).map(function (toCell) {
        return $_5f6gpb1djh8lywg5.eq(toCell, fromCell) === false;
      });
    });
  };
  var emptyElement = function (editor, elm) {
    $_2bvsfb2tjh8lywqo.fillWithPaddingBr(elm);
    editor.selection.setCursorLocation(elm.dom(), 0);
    return Option.some(true);
  };
  var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
    return $_9kvypj2cjh8lywnz.firstPositionIn(fromCaption.dom()).bind(function (first) {
      return $_9kvypj2cjh8lywnz.lastPositionIn(fromCaption.dom()).map(function (last) {
        return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
      });
    }).getOr(true);
  };
  var emptyCaretCaption = function (editor, elm) {
    return emptyElement(editor, elm);
  };
  var validateCaretCaption = function (rootElm, fromCaption, to) {
    return getParentCaption(rootElm, $_cgttw3zjh8lywdq.fromDom(to.getNode())).map(function (toCaption) {
      return $_5f6gpb1djh8lywg5.eq(toCaption, fromCaption) === false;
    });
  };
  var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
    return $_9kvypj2cjh8lywnz.navigate(forward, editor.getBody(), from).bind(function (to) {
      return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
    }).or(Option.some(true));
  };
  var deleteCaretCells = function (editor, forward, rootElm, startElm) {
    var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
    return getParentCell(rootElm, startElm).bind(function (fromCell) {
      return $_b1urh33ajh8lywts.isEmpty(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
    });
  };
  var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
    var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
    return $_b1urh33ajh8lywts.isEmpty(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  };
  var deleteCaret = function (editor, forward, startElm) {
    var rootElm = $_cgttw3zjh8lywdq.fromDom(editor.getBody());
    return getParentCaption(rootElm, startElm).fold(function () {
      return deleteCaretCells(editor, forward, rootElm, startElm);
    }, function (fromCaption) {
      return deleteCaretCaption(editor, forward, rootElm, fromCaption);
    }).getOr(false);
  };
  var backspaceDelete$4 = function (editor, forward) {
    var startElm = $_cgttw3zjh8lywdq.fromDom(editor.selection.getStart(true));
    var cells = $_bwjtq63tjh8lyx1g.getCellsFromEditor(editor);
    return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret(editor, forward, startElm) : deleteRange$1(editor, startElm);
  };
  var $_746feo3rjh8lyx0o = { backspaceDelete: backspaceDelete$4 };

  var nativeCommand = function (editor, command) {
    editor.getDoc().execCommand(command, false, null);
  };
  var deleteCommand = function (editor) {
    if ($_ar80r13gjh8lywy7.backspaceDelete(editor, false)) {
      return;
    } else if ($_ej9d8d3kjh8lywzc.backspaceDelete(editor, false)) {
      return;
    } else if ($_5jmwsv32jh8lywrr.backspaceDelete(editor, false)) {
      return;
    } else if ($_746feo3rjh8lyx0o.backspaceDelete(editor)) {
      return;
    } else if ($_lcy1p3fjh8lywxx.backspaceDelete(editor, false)) {
      return;
    } else {
      nativeCommand(editor, 'Delete');
      $_aj8isd34jh8lyws4.paddEmptyBody(editor);
    }
  };
  var forwardDeleteCommand = function (editor) {
    if ($_ar80r13gjh8lywy7.backspaceDelete(editor, true)) {
      return;
    } else if ($_ej9d8d3kjh8lywzc.backspaceDelete(editor, true)) {
      return;
    } else if ($_5jmwsv32jh8lywrr.backspaceDelete(editor, true)) {
      return;
    } else if ($_746feo3rjh8lyx0o.backspaceDelete(editor)) {
      return;
    } else if ($_lcy1p3fjh8lywxx.backspaceDelete(editor, true)) {
      return;
    } else {
      nativeCommand(editor, 'ForwardDelete');
    }
  };
  var $_fmagiy31jh8lywrp = {
    deleteCommand: deleteCommand,
    forwardDeleteCommand: forwardDeleteCommand
  };

  var getSpecifiedFontProp = function (propName, rootElm, elm) {
    var getProperty = function (elm) {
      return $_36knnd12jh8lywe1.getRaw(elm, propName);
    };
    var isRoot = function (elm) {
      return $_5f6gpb1djh8lywg5.eq($_cgttw3zjh8lywdq.fromDom(rootElm), elm);
    };
    return $_6hl03835jh8lywsm.closest($_cgttw3zjh8lywdq.fromDom(elm), function (elm) {
      return getProperty(elm).isSome();
    }, isRoot).bind(getProperty);
  };
  var round$1 = function (number, precision) {
    var factor = Math.pow(10, precision);
    return Math.round(number * factor) / factor;
  };
  var toPt = function (fontSize, precision) {
    if (/[0-9.]+px$/.test(fontSize)) {
      return round$1(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
    }
    return fontSize;
  };
  var normalizeFontFamily = function (fontFamily) {
    return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  };
  var getComputedFontProp = function (propName, elm) {
    return Option.from(DOMUtils$1.DOM.getStyle(elm, propName, true));
  };
  var getFontProp = function (propName) {
    return function (rootElm, elm) {
      return Option.from(elm).map($_cgttw3zjh8lywdq.fromDom).filter($_7j1jt210jh8lywdx.isElement).bind(function (element) {
        return getSpecifiedFontProp(propName, rootElm, element.dom()).or(getComputedFontProp(propName, element.dom()));
      }).getOr('');
    };
  };
  var $_9wj7cv3wjh8lyx23 = {
    getFontSize: getFontProp('font-size'),
    getFontFamily: $_eqpqvr6jh8lyw3s.compose(normalizeFontFamily, getFontProp('font-family')),
    toPt: toPt
  };

  var findFirstCaretElement = function (editor) {
    return $_9kvypj2cjh8lywnz.firstPositionIn(editor.getBody()).map(function (caret) {
      var container = caret.container();
      return $_5oonaz1qjh8lywhz.isText(container) ? container.parentNode : container;
    });
  };
  var isRangeAtStartOfNode = function (rng, root) {
    return rng.startContainer === root && rng.startOffset === 0;
  };
  var getCaretElement = function (editor) {
    return Option.from(editor.selection.getRng()).bind(function (rng) {
      var root = editor.getBody();
      return isRangeAtStartOfNode(rng, root) ? Option.none() : Option.from(editor.selection.getStart(true));
    });
  };
  var fromFontSizeNumber = function (editor, value) {
    if (/^[0-9\.]+$/.test(value)) {
      var fontSizeNumber = parseInt(value, 10);
      if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
        var fontSizes = $_66vr6g2jjh8lywpf.getFontStyleValues(editor);
        var fontClasses = $_66vr6g2jjh8lywpf.getFontSizeClasses(editor);
        if (fontClasses) {
          return fontClasses[fontSizeNumber - 1] || value;
        } else {
          return fontSizes[fontSizeNumber - 1] || value;
        }
      } else {
        return value;
      }
    } else {
      return value;
    }
  };
  var fontNameAction = function (editor, value) {
    editor.formatter.toggle('fontname', { value: fromFontSizeNumber(editor, value) });
    editor.nodeChanged();
  };
  var fontNameQuery = function (editor) {
    return getCaretElement(editor).fold(function () {
      return findFirstCaretElement(editor).map(function (caretElement) {
        return $_9wj7cv3wjh8lyx23.getFontFamily(editor.getBody(), caretElement);
      }).getOr('');
    }, function (caretElement) {
      return $_9wj7cv3wjh8lyx23.getFontFamily(editor.getBody(), caretElement);
    });
  };
  var fontSizeAction = function (editor, value) {
    editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
    editor.nodeChanged();
  };
  var fontSizeQuery = function (editor) {
    return getCaretElement(editor).fold(function () {
      return findFirstCaretElement(editor).map(function (caretElement) {
        return $_9wj7cv3wjh8lyx23.getFontSize(editor.getBody(), caretElement);
      }).getOr('');
    }, function (caretElement) {
      return $_9wj7cv3wjh8lyx23.getFontSize(editor.getBody(), caretElement);
    });
  };

  var isEq$1 = function (rng1, rng2) {
    return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  };
  var $_aayq8q3zjh8lyx2z = { isEq: isEq$1 };

  var findParent = function (node, rootNode, predicate) {
    while (node && node !== rootNode) {
      if (predicate(node)) {
        return node;
      }
      node = node.parentNode;
    }
    return null;
  };
  var hasParent = function (node, rootNode, predicate) {
    return findParent(node, rootNode, predicate) !== null;
  };
  var hasParentWithName = function (node, rootNode, name) {
    return hasParent(node, rootNode, function (node) {
      return node.nodeName === name;
    });
  };
  var isTable$2 = function (node) {
    return node && node.nodeName === 'TABLE';
  };
  var isTableCell$3 = function (node) {
    return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  };
  var isCeFalseCaretContainer = function (node, rootNode) {
    return isCaretContainer(node) && hasParent(node, rootNode, isCaretNode) === false;
  };
  var hasBrBeforeAfter = function (dom, node, left) {
    var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
    while (node = walker[left ? 'prev' : 'next']()) {
      if ($_5oonaz1qjh8lywhz.isBr(node)) {
        return true;
      }
    }
  };
  var isPrevNode = function (node, name) {
    return node.previousSibling && node.previousSibling.nodeName === name;
  };
  var hasContentEditableFalseParent = function (body, node) {
    while (node && node !== body) {
      if ($_5oonaz1qjh8lywhz.isContentEditableFalse(node)) {
        return true;
      }
      node = node.parentNode;
    }
    return false;
  };
  var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
    var walker, lastInlineElement, parentBlockContainer;
    var body = dom.getRoot();
    var node;
    var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
    parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
    if (left && $_5oonaz1qjh8lywhz.isBr(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
      return Option.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
    }
    walker = new TreeWalker(startNode, parentBlockContainer);
    while (node = walker[left ? 'prev' : 'next']()) {
      if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
        return Option.none();
      }
      if ($_5oonaz1qjh8lywhz.isText(node) && node.nodeValue.length > 0) {
        if (hasParentWithName(node, body, 'A') === false) {
          return Option.some(CaretPosition(node, left ? node.nodeValue.length : 0));
        }
        return Option.none();
      }
      if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
        return Option.none();
      }
      lastInlineElement = node;
    }
    if (collapsed && lastInlineElement) {
      return Option.some(CaretPosition(lastInlineElement, 0));
    }
    return Option.none();
  };
  var normalizeEndPoint = function (dom, collapsed, start, rng) {
    var container, offset, walker;
    var body = dom.getRoot();
    var node, nonEmptyElementsMap;
    var directionLeft, isAfterNode, normalized = false;
    container = rng[(start ? 'start' : 'end') + 'Container'];
    offset = rng[(start ? 'start' : 'end') + 'Offset'];
    isAfterNode = $_5oonaz1qjh8lywhz.isElement(container) && offset === container.childNodes.length;
    nonEmptyElementsMap = dom.schema.getNonEmptyElements();
    directionLeft = start;
    if (isCaretContainer(container)) {
      return Option.none();
    }
    if ($_5oonaz1qjh8lywhz.isElement(container) && offset > container.childNodes.length - 1) {
      directionLeft = false;
    }
    if ($_5oonaz1qjh8lywhz.isDocument(container)) {
      container = body;
      offset = 0;
    }
    if (container === body) {
      if (directionLeft) {
        node = container.childNodes[offset > 0 ? offset - 1 : 0];
        if (node) {
          if (isCaretContainer(node)) {
            return Option.none();
          }
          if (nonEmptyElementsMap[node.nodeName] || isTable$2(node)) {
            return Option.none();
          }
        }
      }
      if (container.hasChildNodes()) {
        offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
        container = container.childNodes[offset];
        offset = $_5oonaz1qjh8lywhz.isText(container) && isAfterNode ? container.data.length : 0;
        if (!collapsed && container === body.lastChild && isTable$2(container)) {
          return Option.none();
        }
        if (hasContentEditableFalseParent(body, container) || isCaretContainer(container)) {
          return Option.none();
        }
        if (container.hasChildNodes() && isTable$2(container) === false) {
          node = container;
          walker = new TreeWalker(container, body);
          do {
            if ($_5oonaz1qjh8lywhz.isContentEditableFalse(node) || isCaretContainer(node)) {
              normalized = false;
              break;
            }
            if ($_5oonaz1qjh8lywhz.isText(node) && node.nodeValue.length > 0) {
              offset = directionLeft ? 0 : node.nodeValue.length;
              container = node;
              normalized = true;
              break;
            }
            if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$3(node)) {
              offset = dom.nodeIndex(node);
              container = node.parentNode;
              if (!directionLeft) {
                offset++;
              }
              normalized = true;
              break;
            }
          } while (node = directionLeft ? walker.next() : walker.prev());
        }
      }
    }
    if (collapsed) {
      if ($_5oonaz1qjh8lywhz.isText(container) && offset === 0) {
        findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
          container = pos.container();
          offset = pos.offset();
          normalized = true;
        });
      }
      if ($_5oonaz1qjh8lywhz.isElement(container)) {
        node = container.childNodes[offset];
        if (!node) {
          node = container.childNodes[offset - 1];
        }
        if (node && $_5oonaz1qjh8lywhz.isBr(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
          findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
            container = pos.container();
            offset = pos.offset();
            normalized = true;
          });
        }
      }
    }
    if (directionLeft && !collapsed && $_5oonaz1qjh8lywhz.isText(container) && offset === container.nodeValue.length) {
      findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
        container = pos.container();
        offset = pos.offset();
        normalized = true;
      });
    }
    return normalized ? Option.some(CaretPosition(container, offset)) : Option.none();
  };
  var normalize$1 = function (dom, rng) {
    var collapsed = rng.collapsed, normRng = rng.cloneRange();
    var startPos = CaretPosition.fromRangeStart(rng);
    normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
      if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
        normRng.setStart(pos.container(), pos.offset());
      }
    });
    if (!collapsed) {
      normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
        normRng.setEnd(pos.container(), pos.offset());
      });
    }
    if (collapsed) {
      normRng.collapse(true);
    }
    return $_aayq8q3zjh8lyx2z.isEq(rng, normRng) ? Option.none() : Option.some(normRng);
  };
  var $_4v2pn63yjh8lyx2s = { normalize: normalize$1 };

  var hasRightSideContent = function (schema, container, parentBlock) {
    var walker = new TreeWalker(container, parentBlock);
    var node;
    var nonEmptyElementsMap = schema.getNonEmptyElements();
    while (node = walker.next()) {
      if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
        return true;
      }
    }
  };
  var scrollToBr = function (dom, selection, brElm) {
    var marker = dom.create('span', {}, '&nbsp;');
    brElm.parentNode.insertBefore(marker, brElm);
    selection.scrollIntoView(marker);
    dom.remove(marker);
  };
  var moveSelectionToBr = function (dom, selection, brElm, extraBr) {
    var rng = dom.createRng();
    if (!extraBr) {
      rng.setStartAfter(brElm);
      rng.setEndAfter(brElm);
    } else {
      rng.setStartBefore(brElm);
      rng.setEndBefore(brElm);
    }
    selection.setRng(rng);
  };
  var insertBrAtCaret = function (editor, evt) {
    var selection = editor.selection, dom = editor.dom;
    var brElm, extraBr;
    var rng = selection.getRng();
    $_4v2pn63yjh8lyx2s.normalize(dom, rng).each(function (normRng) {
      rng.setStart(normRng.startContainer, normRng.startOffset);
      rng.setEnd(normRng.endContainer, normRng.endOffset);
    });
    var offset = rng.startOffset;
    var container = rng.startContainer;
    if (container.nodeType === 1 && container.hasChildNodes()) {
      var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
      container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
      if (isAfterLastNodeInContainer && container.nodeType === 3) {
        offset = container.nodeValue.length;
      } else {
        offset = 0;
      }
    }
    var parentBlock = dom.getParent(container, dom.isBlock);
    var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
    var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
    var isControlKey = evt && evt.ctrlKey;
    if (containerBlockName === 'LI' && !isControlKey) {
      parentBlock = containerBlock;
    }
    if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
      if (!hasRightSideContent(editor.schema, container, parentBlock)) {
        brElm = dom.create('br');
        rng.insertNode(brElm);
        rng.setStartAfter(brElm);
        rng.setEndAfter(brElm);
        extraBr = true;
      }
    }
    brElm = dom.create('br');
    rng.insertNode(brElm);
    scrollToBr(dom, selection, brElm);
    moveSelectionToBr(dom, selection, brElm, extraBr);
    editor.undoManager.add();
  };
  var insertBrBefore = function (editor, inline) {
    var br = $_cgttw3zjh8lywdq.fromTag('br');
    $_4m7u2e2kjh8lywpi.before($_cgttw3zjh8lywdq.fromDom(inline), br);
    editor.undoManager.add();
  };
  var insertBrAfter = function (editor, inline) {
    if (!hasBrAfter(editor.getBody(), inline)) {
      $_4m7u2e2kjh8lywpi.after($_cgttw3zjh8lywdq.fromDom(inline), $_cgttw3zjh8lywdq.fromTag('br'));
    }
    var br = $_cgttw3zjh8lywdq.fromTag('br');
    $_4m7u2e2kjh8lywpi.after($_cgttw3zjh8lywdq.fromDom(inline), br);
    scrollToBr(editor.dom, editor.selection, br.dom());
    moveSelectionToBr(editor.dom, editor.selection, br.dom(), false);
    editor.undoManager.add();
  };
  var isBeforeBr = function (pos) {
    return $_5oonaz1qjh8lywhz.isBr(pos.getNode());
  };
  var hasBrAfter = function (rootNode, startNode) {
    if (isBeforeBr(CaretPosition$1.after(startNode))) {
      return true;
    } else {
      return $_9kvypj2cjh8lywnz.nextPosition(rootNode, CaretPosition$1.after(startNode)).map(function (pos) {
        return $_5oonaz1qjh8lywhz.isBr(pos.getNode());
      }).getOr(false);
    }
  };
  var isAnchorLink = function (elm) {
    return elm && elm.nodeName === 'A' && 'href' in elm;
  };
  var isInsideAnchor = function (location) {
    return location.fold($_eqpqvr6jh8lyw3s.constant(false), isAnchorLink, isAnchorLink, $_eqpqvr6jh8lyw3s.constant(false));
  };
  var readInlineAnchorLocation = function (editor) {
    var isInlineTarget = $_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.isInlineTarget, editor);
    var position = CaretPosition$1.fromRangeStart(editor.selection.getRng());
    return $_6kjy7r3njh8lywzz.readLocation(isInlineTarget, editor.getBody(), position).filter(isInsideAnchor);
  };
  var insertBrOutsideAnchor = function (editor, location) {
    location.fold($_eqpqvr6jh8lyw3s.noop, $_eqpqvr6jh8lyw3s.curry(insertBrBefore, editor), $_eqpqvr6jh8lyw3s.curry(insertBrAfter, editor), $_eqpqvr6jh8lyw3s.noop);
  };
  var insert = function (editor, evt) {
    var anchorLocation = readInlineAnchorLocation(editor);
    if (anchorLocation.isSome()) {
      anchorLocation.each($_eqpqvr6jh8lyw3s.curry(insertBrOutsideAnchor, editor));
    } else {
      insertBrAtCaret(editor, evt);
    }
  };
  var $_cg4dz53xjh8lyx2g = { insert: insert };

  var adt = $_1ml90g3ijh8lywyp.generate([
    { 'before': ['element'] },
    {
      'on': [
        'element',
        'offset'
      ]
    },
    { after: ['element'] }
  ]);
  var cata = function (subject, onBefore, onOn, onAfter) {
    return subject.fold(onBefore, onOn, onAfter);
  };
  var getStart = function (situ) {
    return situ.fold($_eqpqvr6jh8lyw3s.identity, $_eqpqvr6jh8lyw3s.identity, $_eqpqvr6jh8lyw3s.identity);
  };
  var $_fn8a2o42jh8lyx3r = {
    before: adt.before,
    on: adt.on,
    after: adt.after,
    cata: cata,
    getStart: getStart
  };

  var type$1 = $_1ml90g3ijh8lywyp.generate([
    { domRange: ['rng'] },
    {
      relative: [
        'startSitu',
        'finishSitu'
      ]
    },
    {
      exact: [
        'start',
        'soffset',
        'finish',
        'foffset'
      ]
    }
  ]);
  var range$1 = $_4jz0ce18jh8lywft.immutable('start', 'soffset', 'finish', 'foffset');
  var exactFromRange = function (simRange) {
    return type$1.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  };
  var getStart$1 = function (selection) {
    return selection.match({
      domRange: function (rng) {
        return $_cgttw3zjh8lywdq.fromDom(rng.startContainer);
      },
      relative: function (startSitu, finishSitu) {
        return $_fn8a2o42jh8lyx3r.getStart(startSitu);
      },
      exact: function (start, soffset, finish, foffset) {
        return start;
      }
    });
  };
  var getWin = function (selection) {
    var start = getStart$1(selection);
    return $_a43q0i17jh8lywfe.defaultView(start);
  };
  var $_bx4foa41jh8lyx3f = {
    domRange: type$1.domRange,
    relative: type$1.relative,
    exact: type$1.exact,
    exactFromRange: exactFromRange,
    range: range$1,
    getWin: getWin
  };

  var browser$3 = $_9hkktfnjh8lywc6.detect().browser;
  var clamp = function (offset, element) {
    var max = $_7j1jt210jh8lywdx.isText(element) ? $_lh5l42wjh8lywr8.get(element).length : $_a43q0i17jh8lywfe.children(element).length + 1;
    if (offset > max) {
      return max;
    } else if (offset < 0) {
      return 0;
    }
    return offset;
  };
  var normalizeRng = function (rng) {
    return $_bx4foa41jh8lyx3f.range(rng.start(), clamp(rng.soffset(), rng.start()), rng.finish(), clamp(rng.foffset(), rng.finish()));
  };
  var isOrContains = function (root, elm) {
    return $_5f6gpb1djh8lywg5.contains(root, elm) || $_5f6gpb1djh8lywg5.eq(root, elm);
  };
  var isRngInRoot = function (root) {
    return function (rng) {
      return isOrContains(root, rng.start()) && isOrContains(root, rng.finish());
    };
  };
  var shouldStore = function (editor) {
    return editor.inline === true || browser$3.isIE();
  };
  var nativeRangeToSelectionRange = function (r) {
    return $_bx4foa41jh8lyx3f.range($_cgttw3zjh8lywdq.fromDom(r.startContainer), r.startOffset, $_cgttw3zjh8lywdq.fromDom(r.endContainer), r.endOffset);
  };
  var readRange = function (win) {
    var selection = win.getSelection();
    var rng = !selection || selection.rangeCount === 0 ? Option.none() : Option.from(selection.getRangeAt(0));
    return rng.map(nativeRangeToSelectionRange);
  };
  var getBookmark$2 = function (root) {
    var win = $_a43q0i17jh8lywfe.defaultView(root);
    return readRange(win.dom()).filter(isRngInRoot(root));
  };
  var validate = function (root, bookmark) {
    return Option.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  };
  var bookmarkToNativeRng = function (bookmark) {
    var rng = document.createRange();
    try {
      rng.setStart(bookmark.start().dom(), bookmark.soffset());
      rng.setEnd(bookmark.finish().dom(), bookmark.foffset());
      return Option.some(rng);
    } catch (_) {
      return Option.none();
    }
  };
  var store = function (editor) {
    var newBookmark = shouldStore(editor) ? getBookmark$2($_cgttw3zjh8lywdq.fromDom(editor.getBody())) : Option.none();
    editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  };
  var storeNative = function (editor, rng) {
    var root = $_cgttw3zjh8lywdq.fromDom(editor.getBody());
    var range = shouldStore(editor) ? Option.from(rng) : Option.none();
    var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
    editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  };
  var getRng = function (editor) {
    var bookmark = editor.bookmark ? editor.bookmark : Option.none();
    return bookmark.bind($_eqpqvr6jh8lyw3s.curry(validate, $_cgttw3zjh8lywdq.fromDom(editor.getBody()))).bind(bookmarkToNativeRng);
  };
  var restore = function (editor) {
    getRng(editor).each(function (rng) {
      editor.selection.setRng(rng);
    });
  };
  var $_eqs11m40jh8lyx31 = {
    store: store,
    storeNative: storeNative,
    readRange: readRange,
    restore: restore,
    getRng: getRng,
    getBookmark: getBookmark$2,
    validate: validate
  };

  var indentElement = function (dom, command, useMargin, value, unit, element) {
    if (dom.getContentEditable(element) === 'false') {
      return;
    }
    if (element.nodeName !== 'LI') {
      var indentStyleName = useMargin ? 'margin' : 'padding';
      indentStyleName = element.nodeName === 'TABLE' ? 'margin' : indentStyleName;
      indentStyleName += dom.getStyle(element, 'direction', true) === 'rtl' ? 'Right' : 'Left';
      if (command === 'outdent') {
        var styleValue = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - value);
        dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
      } else {
        var styleValue = parseInt(element.style[indentStyleName] || 0, 10) + value + unit;
        dom.setStyle(element, indentStyleName, styleValue);
      }
    }
  };
  var handle = function (editor, command) {
    var settings = editor.settings, dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
    var indentUnit = /[a-z%]+$/i.exec(settings.indentation)[0];
    var indentValue = parseInt(settings.indentation, 10);
    var useMargin = editor.getParam('indent_use_margin', false);
    if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
      if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) {
        formatter.apply('div');
      }
      $_5wjzy24jh8lyw2t.each(selection.getSelectedBlocks(), function (element) {
        return indentElement(dom, command, useMargin, indentValue, indentUnit, element);
      });
    }
  };

  var each$9 = $_ahowuxkjh8lywbj.each;
  var extend$2 = $_ahowuxkjh8lywbj.extend;
  var map$2 = $_ahowuxkjh8lywbj.map;
  var inArray$2 = $_ahowuxkjh8lywbj.inArray;
  function EditorCommands (editor) {
    var dom, selection, formatter;
    var commands = {
      state: {},
      exec: {},
      value: {}
    };
    var settings = editor.settings, bookmark;
    editor.on('PreInit', function () {
      dom = editor.dom;
      selection = editor.selection;
      settings = editor.settings;
      formatter = editor.formatter;
    });
    var execCommand = function (command, ui, value, args) {
      var func, customCommand, state = false;
      if (editor.removed) {
        return;
      }
      if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
        editor.focus();
      } else {
        $_eqs11m40jh8lyx31.restore(editor);
      }
      args = editor.fire('BeforeExecCommand', {
        command: command,
        ui: ui,
        value: value
      });
      if (args.isDefaultPrevented()) {
        return false;
      }
      customCommand = command.toLowerCase();
      if (func = commands.exec[customCommand]) {
        func(customCommand, ui, value);
        editor.fire('ExecCommand', {
          command: command,
          ui: ui,
          value: value
        });
        return true;
      }
      each$9(editor.plugins, function (p) {
        if (p.execCommand && p.execCommand(command, ui, value)) {
          editor.fire('ExecCommand', {
            command: command,
            ui: ui,
            value: value
          });
          state = true;
          return false;
        }
      });
      if (state) {
        return state;
      }
      if (editor.theme && editor.theme.execCommand && editor.theme.execCommand(command, ui, value)) {
        editor.fire('ExecCommand', {
          command: command,
          ui: ui,
          value: value
        });
        return true;
      }
      try {
        state = editor.getDoc().execCommand(command, ui, value);
      } catch (ex) {
      }
      if (state) {
        editor.fire('ExecCommand', {
          command: command,
          ui: ui,
          value: value
        });
        return true;
      }
      return false;
    };
    var queryCommandState = function (command) {
      var func;
      if (editor.quirks.isHidden() || editor.removed) {
        return;
      }
      command = command.toLowerCase();
      if (func = commands.state[command]) {
        return func(command);
      }
      try {
        return editor.getDoc().queryCommandState(command);
      } catch (ex) {
      }
      return false;
    };
    var queryCommandValue = function (command) {
      var func;
      if (editor.quirks.isHidden() || editor.removed) {
        return;
      }
      command = command.toLowerCase();
      if (func = commands.value[command]) {
        return func(command);
      }
      try {
        return editor.getDoc().queryCommandValue(command);
      } catch (ex) {
      }
    };
    var addCommands = function (commandList, type) {
      type = type || 'exec';
      each$9(commandList, function (callback, command) {
        each$9(command.toLowerCase().split(','), function (command) {
          commands[type][command] = callback;
        });
      });
    };
    var addCommand = function (command, callback, scope) {
      command = command.toLowerCase();
      commands.exec[command] = function (command, ui, value, args) {
        return callback.call(scope || editor, ui, value, args);
      };
    };
    var queryCommandSupported = function (command) {
      command = command.toLowerCase();
      if (commands.exec[command]) {
        return true;
      }
      try {
        return editor.getDoc().queryCommandSupported(command);
      } catch (ex) {
      }
      return false;
    };
    var addQueryStateHandler = function (command, callback, scope) {
      command = command.toLowerCase();
      commands.state[command] = function () {
        return callback.call(scope || editor);
      };
    };
    var addQueryValueHandler = function (command, callback, scope) {
      command = command.toLowerCase();
      commands.value[command] = function () {
        return callback.call(scope || editor);
      };
    };
    var hasCustomCommand = function (command) {
      command = command.toLowerCase();
      return !!commands.exec[command];
    };
    extend$2(this, {
      execCommand: execCommand,
      queryCommandState: queryCommandState,
      queryCommandValue: queryCommandValue,
      queryCommandSupported: queryCommandSupported,
      addCommands: addCommands,
      addCommand: addCommand,
      addQueryStateHandler: addQueryStateHandler,
      addQueryValueHandler: addQueryValueHandler,
      hasCustomCommand: hasCustomCommand
    });
    var execNativeCommand = function (command, ui, value) {
      if (ui === undefined) {
        ui = false;
      }
      if (value === undefined) {
        value = null;
      }
      return editor.getDoc().execCommand(command, ui, value);
    };
    var isFormatMatch = function (name) {
      return formatter.match(name);
    };
    var toggleFormat = function (name, value) {
      formatter.toggle(name, value ? { value: value } : undefined);
      editor.nodeChanged();
    };
    var storeSelection = function (type) {
      bookmark = selection.getBookmark(type);
    };
    var restoreSelection = function () {
      selection.moveToBookmark(bookmark);
    };
    addCommands({
      'mceResetDesignMode,mceBeginUndoLevel': function () {
      },
      'mceEndUndoLevel,mceAddUndoLevel': function () {
        editor.undoManager.add();
      },
      'Cut,Copy,Paste': function (command) {
        var doc = editor.getDoc();
        var failed;
        try {
          execNativeCommand(command);
        } catch (ex) {
          failed = true;
        }
        if (command === 'paste' && !doc.queryCommandEnabled(command)) {
          failed = true;
        }
        if (failed || !doc.queryCommandSupported(command)) {
          var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
          if ($_9bpim8ajh8lyw68.mac) {
            msg = msg.replace(/Ctrl\+/g, '\u2318+');
          }
          editor.notificationManager.open({
            text: msg,
            type: 'error'
          });
        }
      },
      'unlink': function () {
        if (selection.isCollapsed()) {
          var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
          if (elm) {
            editor.dom.remove(elm, true);
          }
          return;
        }
        formatter.remove('link');
      },
      'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
        var align = command.substring(7);
        if (align === 'full') {
          align = 'justify';
        }
        each$9('left,center,right,justify'.split(','), function (name) {
          if (align !== name) {
            formatter.remove('align' + name);
          }
        });
        if (align !== 'none') {
          toggleFormat('align' + align);
        }
      },
      'InsertUnorderedList,InsertOrderedList': function (command) {
        var listElm, listParent;
        execNativeCommand(command);
        listElm = dom.getParent(selection.getNode(), 'ol,ul');
        if (listElm) {
          listParent = listElm.parentNode;
          if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
            storeSelection();
            dom.split(listParent, listElm);
            restoreSelection();
          }
        }
      },
      'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
        toggleFormat(command);
      },
      'ForeColor,HiliteColor': function (command, ui, value) {
        toggleFormat(command, value);
      },
      'FontName': function (command, ui, value) {
        fontNameAction(editor, value);
      },
      'FontSize': function (command, ui, value) {
        fontSizeAction(editor, value);
      },
      'RemoveFormat': function (command) {
        formatter.remove(command);
      },
      'mceBlockQuote': function () {
        toggleFormat('blockquote');
      },
      'FormatBlock': function (command, ui, value) {
        return toggleFormat(value || 'p');
      },
      'mceCleanup': function () {
        var bookmark = selection.getBookmark();
        editor.setContent(editor.getContent());
        selection.moveToBookmark(bookmark);
      },
      'mceRemoveNode': function (command, ui, value) {
        var node = value || selection.getNode();
        if (node !== editor.getBody()) {
          storeSelection();
          editor.dom.remove(node, true);
          restoreSelection();
        }
      },
      'mceSelectNodeDepth': function (command, ui, value) {
        var counter = 0;
        dom.getParent(selection.getNode(), function (node) {
          if (node.nodeType === 1 && counter++ === value) {
            selection.select(node);
            return false;
          }
        }, editor.getBody());
      },
      'mceSelectNode': function (command, ui, value) {
        selection.select(value);
      },
      'mceInsertContent': function (command, ui, value) {
        $_13xltl1wjh8lywkr.insertAtCaret(editor, value);
      },
      'mceInsertRawHTML': function (command, ui, value) {
        var content = editor.getContent();
        selection.setContent('tiny_mce_marker');
        editor.setContent(content.replace(/tiny_mce_marker/g, function () {
          return value;
        }));
      },
      'mceToggleFormat': function (command, ui, value) {
        toggleFormat(value);
      },
      'mceSetContent': function (command, ui, value) {
        editor.setContent(value);
      },
      'Indent,Outdent': function (command) {
        handle(editor, command);
      },
      'mceRepaint': function () {
      },
      'InsertHorizontalRule': function () {
        editor.execCommand('mceInsertContent', false, '<hr />');
      },
      'mceToggleVisualAid': function () {
        editor.hasVisual = !editor.hasVisual;
        editor.addVisual();
      },
      'mceReplaceContent': function (command, ui, value) {
        editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({ format: 'text' })));
      },
      'mceInsertLink': function (command, ui, value) {
        var anchor;
        if (typeof value === 'string') {
          value = { href: value };
        }
        anchor = dom.getParent(selection.getNode(), 'a');
        value.href = value.href.replace(' ', '%20');
        if (!anchor || !value.href) {
          formatter.remove('link');
        }
        if (value.href) {
          formatter.apply('link', value, anchor);
        }
      },
      'selectAll': function () {
        var editingHost = dom.getParent(selection.getStart(), $_5oonaz1qjh8lywhz.isContentEditableTrue);
        if (editingHost) {
          var rng = dom.createRng();
          rng.selectNodeContents(editingHost);
          selection.setRng(rng);
        }
      },
      'delete': function () {
        $_fmagiy31jh8lywrp.deleteCommand(editor);
      },
      'forwardDelete': function () {
        $_fmagiy31jh8lywrp.forwardDeleteCommand(editor);
      },
      'mceNewDocument': function () {
        editor.setContent('');
      },
      'InsertLineBreak': function (command, ui, value) {
        $_cg4dz53xjh8lyx2g.insert(editor, value);
        return true;
      }
    });
    var alignStates = function (name) {
      return function () {
        var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks();
        var matches = map$2(nodes, function (node) {
          return !!formatter.matchNode(node, name);
        });
        return inArray$2(matches, true) !== -1;
      };
    };
    addCommands({
      'JustifyLeft': alignStates('alignleft'),
      'JustifyCenter': alignStates('aligncenter'),
      'JustifyRight': alignStates('alignright'),
      'JustifyFull': alignStates('alignjustify'),
      'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
        return isFormatMatch(command);
      },
      'mceBlockQuote': function () {
        return isFormatMatch('blockquote');
      },
      'Outdent': function () {
        var node;
        if (settings.inline_styles) {
          if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
            return true;
          }
          if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
            return true;
          }
        }
        return queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || !settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE');
      },
      'InsertUnorderedList,InsertOrderedList': function (command) {
        var list = dom.getParent(selection.getNode(), 'ul,ol');
        return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
      }
    }, 'state');
    addCommands({
      Undo: function () {
        editor.undoManager.undo();
      },
      Redo: function () {
        editor.undoManager.redo();
      }
    });
    addQueryValueHandler('FontName', function () {
      return fontNameQuery(editor);
    }, this);
    addQueryValueHandler('FontSize', function () {
      return fontSizeQuery(editor);
    }, this);
  }

  var nativeEvents = $_ahowuxkjh8lywbj.makeMap('focus blur focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy selectionchange ' + 'mouseout mouseenter mouseleave wheel keydown keypress keyup input contextmenu dragstart dragend dragover ' + 'draggesture dragdrop drop drag submit ' + 'compositionstart compositionend compositionupdate touchstart touchmove touchend', ' ');
  var Dispatcher = function (settings) {
    var self = this;
    var scope, bindings = {}, toggleEvent;
    var returnFalse = function () {
      return false;
    };
    var returnTrue = function () {
      return true;
    };
    settings = settings || {};
    scope = settings.scope || self;
    toggleEvent = settings.toggleEvent || returnFalse;
    var fire = function (name, args) {
      var handlers, i, l, callback;
      name = name.toLowerCase();
      args = args || {};
      args.type = name;
      if (!args.target) {
        args.target = scope;
      }
      if (!args.preventDefault) {
        args.preventDefault = function () {
          args.isDefaultPrevented = returnTrue;
        };
        args.stopPropagation = function () {
          args.isPropagationStopped = returnTrue;
        };
        args.stopImmediatePropagation = function () {
          args.isImmediatePropagationStopped = returnTrue;
        };
        args.isDefaultPrevented = returnFalse;
        args.isPropagationStopped = returnFalse;
        args.isImmediatePropagationStopped = returnFalse;
      }
      if (settings.beforeFire) {
        settings.beforeFire(args);
      }
      handlers = bindings[name];
      if (handlers) {
        for (i = 0, l = handlers.length; i < l; i++) {
          callback = handlers[i];
          if (callback.once) {
            off(name, callback.func);
          }
          if (args.isImmediatePropagationStopped()) {
            args.stopPropagation();
            return args;
          }
          if (callback.func.call(scope, args) === false) {
            args.preventDefault();
            return args;
          }
        }
      }
      return args;
    };
    var on = function (name, callback, prepend, extra) {
      var handlers, names, i;
      if (callback === false) {
        callback = returnFalse;
      }
      if (callback) {
        callback = { func: callback };
        if (extra) {
          $_ahowuxkjh8lywbj.extend(callback, extra);
        }
        names = name.toLowerCase().split(' ');
        i = names.length;
        while (i--) {
          name = names[i];
          handlers = bindings[name];
          if (!handlers) {
            handlers = bindings[name] = [];
            toggleEvent(name, true);
          }
          if (prepend) {
            handlers.unshift(callback);
          } else {
            handlers.push(callback);
          }
        }
      }
      return self;
    };
    var off = function (name, callback) {
      var i, handlers, bindingName, names, hi;
      if (name) {
        names = name.toLowerCase().split(' ');
        i = names.length;
        while (i--) {
          name = names[i];
          handlers = bindings[name];
          if (!name) {
            for (bindingName in bindings) {
              toggleEvent(bindingName, false);
              delete bindings[bindingName];
            }
            return self;
          }
          if (handlers) {
            if (!callback) {
              handlers.length = 0;
            } else {
              hi = handlers.length;
              while (hi--) {
                if (handlers[hi].func === callback) {
                  handlers = handlers.slice(0, hi).concat(handlers.slice(hi + 1));
                  bindings[name] = handlers;
                }
              }
            }
            if (!handlers.length) {
              toggleEvent(name, false);
              delete bindings[name];
            }
          }
        }
      } else {
        for (name in bindings) {
          toggleEvent(name, false);
        }
        bindings = {};
      }
      return self;
    };
    var once = function (name, callback, prepend) {
      return on(name, callback, prepend, { once: true });
    };
    var has = function (name) {
      name = name.toLowerCase();
      return !(!bindings[name] || bindings[name].length === 0);
    };
    self.fire = fire;
    self.on = on;
    self.off = off;
    self.once = once;
    self.has = has;
  };
  Dispatcher.isNative = function (name) {
    return !!nativeEvents[name.toLowerCase()];
  };

  var getEventDispatcher = function (obj) {
    if (!obj._eventDispatcher) {
      obj._eventDispatcher = new Dispatcher({
        scope: obj,
        toggleEvent: function (name, state) {
          if (Dispatcher.isNative(name) && obj.toggleNativeEvent) {
            obj.toggleNativeEvent(name, state);
          }
        }
      });
    }
    return obj._eventDispatcher;
  };
  var $_fuzxjg45jh8lyx45 = {
    fire: function (name, args, bubble) {
      var self = this;
      if (self.removed && name !== 'remove') {
        return args;
      }
      args = getEventDispatcher(self).fire(name, args, bubble);
      if (bubble !== false && self.parent) {
        var parent_1 = self.parent();
        while (parent_1 && !args.isPropagationStopped()) {
          parent_1.fire(name, args, false);
          parent_1 = parent_1.parent();
        }
      }
      return args;
    },
    on: function (name, callback, prepend) {
      return getEventDispatcher(this).on(name, callback, prepend);
    },
    off: function (name, callback) {
      return getEventDispatcher(this).off(name, callback);
    },
    once: function (name, callback) {
      return getEventDispatcher(this).once(name, callback);
    },
    hasEventListeners: function (name) {
      return getEventDispatcher(this).has(name);
    }
  };

  function Toggler (turnOff, turnOn, initial) {
    var active = initial || false;
    var on = function () {
      turnOn();
      active = true;
    };
    var off = function () {
      turnOff();
      active = false;
    };
    var toggle = function () {
      var f = active ? off : on;
      f();
    };
    var isOn = function () {
      return active;
    };
    return {
      on: on,
      off: off,
      toggle: toggle,
      isOn: isOn
    };
  }

  var read$2 = function (element, attr) {
    var value = $_3da62i14jh8lyweo.get(element, attr);
    return value === undefined || value === '' ? [] : value.split(' ');
  };
  var add = function (element, attr, id) {
    var old = read$2(element, attr);
    var nu = old.concat([id]);
    $_3da62i14jh8lyweo.set(element, attr, nu.join(' '));
  };
  var remove$4 = function (element, attr, id) {
    var nu = $_5wjzy24jh8lyw2t.filter(read$2(element, attr), function (v) {
      return v !== id;
    });
    if (nu.length > 0)
      $_3da62i14jh8lyweo.set(element, attr, nu.join(' '));
    else
      $_3da62i14jh8lyweo.remove(element, attr);
  };
  var $_5xj9rq4bjh8lyx4m = {
    read: read$2,
    add: add,
    remove: remove$4
  };

  var supports = function (element) {
    return element.dom().classList !== undefined;
  };
  var get$4 = function (element) {
    return $_5xj9rq4bjh8lyx4m.read(element, 'class');
  };
  var add$1 = function (element, clazz) {
    return $_5xj9rq4bjh8lyx4m.add(element, 'class', clazz);
  };
  var remove$5 = function (element, clazz) {
    return $_5xj9rq4bjh8lyx4m.remove(element, 'class', clazz);
  };
  var toggle = function (element, clazz) {
    if ($_5wjzy24jh8lyw2t.contains(get$4(element), clazz)) {
      remove$5(element, clazz);
    } else {
      add$1(element, clazz);
    }
  };
  var $_eprb6o4ajh8lyx4j = {
    get: get$4,
    add: add$1,
    remove: remove$5,
    toggle: toggle,
    supports: supports
  };

  var add$2 = function (element, clazz) {
    if ($_eprb6o4ajh8lyx4j.supports(element))
      element.dom().classList.add(clazz);
    else
      $_eprb6o4ajh8lyx4j.add(element, clazz);
  };
  var cleanClass = function (element) {
    var classList = $_eprb6o4ajh8lyx4j.supports(element) ? element.dom().classList : $_eprb6o4ajh8lyx4j.get(element);
    if (classList.length === 0) {
      $_3da62i14jh8lyweo.remove(element, 'class');
    }
  };
  var remove$6 = function (element, clazz) {
    if ($_eprb6o4ajh8lyx4j.supports(element)) {
      var classList = element.dom().classList;
      classList.remove(clazz);
    } else
      $_eprb6o4ajh8lyx4j.remove(element, clazz);
    cleanClass(element);
  };
  var toggle$1 = function (element, clazz) {
    return $_eprb6o4ajh8lyx4j.supports(element) ? element.dom().classList.toggle(clazz) : $_eprb6o4ajh8lyx4j.toggle(element, clazz);
  };
  var toggler = function (element, clazz) {
    var hasClasslist = $_eprb6o4ajh8lyx4j.supports(element);
    var classList = element.dom().classList;
    var off = function () {
      if (hasClasslist)
        classList.remove(clazz);
      else
        $_eprb6o4ajh8lyx4j.remove(element, clazz);
    };
    var on = function () {
      if (hasClasslist)
        classList.add(clazz);
      else
        $_eprb6o4ajh8lyx4j.add(element, clazz);
    };
    return Toggler(off, on, has$1(element, clazz));
  };
  var has$1 = function (element, clazz) {
    return $_eprb6o4ajh8lyx4j.supports(element) && element.dom().classList.contains(clazz);
  };
  var $_6hv60f48jh8lyx4g = {
    add: add$2,
    remove: remove$6,
    toggle: toggle$1,
    toggler: toggler,
    has: has$1
  };

  var firePreProcess = function (editor, args) {
    return editor.fire('PreProcess', args);
  };
  var firePostProcess = function (editor, args) {
    return editor.fire('PostProcess', args);
  };
  var fireRemove = function (editor) {
    return editor.fire('remove');
  };
  var fireSwitchMode = function (editor, mode) {
    return editor.fire('SwitchMode', { mode: mode });
  };
  var fireObjectResizeStart = function (editor, target, width, height) {
    editor.fire('ObjectResizeStart', {
      target: target,
      width: width,
      height: height
    });
  };
  var fireObjectResized = function (editor, target, width, height) {
    editor.fire('ObjectResized', {
      target: target,
      width: width,
      height: height
    });
  };
  var $_a4fgrn4cjh8lyx4q = {
    firePreProcess: firePreProcess,
    firePostProcess: firePostProcess,
    fireRemove: fireRemove,
    fireSwitchMode: fireSwitchMode,
    fireObjectResizeStart: fireObjectResizeStart,
    fireObjectResized: fireObjectResized
  };

  var setEditorCommandState = function (editor, cmd, state) {
    try {
      editor.getDoc().execCommand(cmd, false, state);
    } catch (ex) {
    }
  };
  var toggleClass = function (elm, cls, state) {
    if ($_6hv60f48jh8lyx4g.has(elm, cls) && state === false) {
      $_6hv60f48jh8lyx4g.remove(elm, cls);
    } else if (state) {
      $_6hv60f48jh8lyx4g.add(elm, cls);
    }
  };
  var toggleReadOnly = function (editor, state) {
    toggleClass($_cgttw3zjh8lywdq.fromDom(editor.getBody()), 'mce-content-readonly', state);
    if (state) {
      editor.selection.controlSelection.hideResizeRect();
      editor.readonly = true;
      editor.getBody().contentEditable = 'false';
    } else {
      editor.readonly = false;
      editor.getBody().contentEditable = 'true';
      setEditorCommandState(editor, 'StyleWithCSS', false);
      setEditorCommandState(editor, 'enableInlineTableEditing', false);
      setEditorCommandState(editor, 'enableObjectResizing', false);
      editor.focus();
      editor.nodeChanged();
    }
  };
  var setMode = function (editor, mode) {
    if (mode === getMode(editor)) {
      return;
    }
    if (editor.initialized) {
      toggleReadOnly(editor, mode === 'readonly');
    } else {
      editor.on('init', function () {
        toggleReadOnly(editor, mode === 'readonly');
      });
    }
    $_a4fgrn4cjh8lyx4q.fireSwitchMode(editor, mode);
  };
  var getMode = function (editor) {
    return editor.readonly ? 'readonly' : 'design';
  };
  var isReadOnly = function (editor) {
    return editor.readonly === true;
  };

  var DOM$1 = DOMUtils$1.DOM;
  var customEventRootDelegates;
  var getEventTarget = function (editor, eventName) {
    if (eventName === 'selectionchange') {
      return editor.getDoc();
    }
    if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
      return editor.getDoc().documentElement;
    }
    if (editor.settings.event_root) {
      if (!editor.eventRoot) {
        editor.eventRoot = DOM$1.select(editor.settings.event_root)[0];
      }
      return editor.eventRoot;
    }
    return editor.getBody();
  };
  var isListening = function (editor) {
    return !editor.hidden && !editor.readonly;
  };
  var fireEvent = function (editor, eventName, e) {
    if (isListening(editor)) {
      editor.fire(eventName, e);
    } else if (isReadOnly(editor)) {
      e.preventDefault();
    }
  };
  var bindEventDelegate = function (editor, eventName) {
    var eventRootElm, delegate;
    if (!editor.delegates) {
      editor.delegates = {};
    }
    if (editor.delegates[eventName] || editor.removed) {
      return;
    }
    eventRootElm = getEventTarget(editor, eventName);
    if (editor.settings.event_root) {
      if (!customEventRootDelegates) {
        customEventRootDelegates = {};
        editor.editorManager.on('removeEditor', function () {
          var name;
          if (!editor.editorManager.activeEditor) {
            if (customEventRootDelegates) {
              for (name in customEventRootDelegates) {
                editor.dom.unbind(getEventTarget(editor, name));
              }
              customEventRootDelegates = null;
            }
          }
        });
      }
      if (customEventRootDelegates[eventName]) {
        return;
      }
      delegate = function (e) {
        var target = e.target;
        var editors = editor.editorManager.get();
        var i = editors.length;
        while (i--) {
          var body = editors[i].getBody();
          if (body === target || DOM$1.isChildOf(target, body)) {
            fireEvent(editors[i], eventName, e);
          }
        }
      };
      customEventRootDelegates[eventName] = delegate;
      DOM$1.bind(eventRootElm, eventName, delegate);
    } else {
      delegate = function (e) {
        fireEvent(editor, eventName, e);
      };
      DOM$1.bind(eventRootElm, eventName, delegate);
      editor.delegates[eventName] = delegate;
    }
  };
  var EditorObservable = {
    bindPendingEventDelegates: function () {
      var self = this;
      $_ahowuxkjh8lywbj.each(self._pendingNativeEvents, function (name) {
        bindEventDelegate(self, name);
      });
    },
    toggleNativeEvent: function (name, state) {
      var self = this;
      if (name === 'focus' || name === 'blur') {
        return;
      }
      if (state) {
        if (self.initialized) {
          bindEventDelegate(self, name);
        } else {
          if (!self._pendingNativeEvents) {
            self._pendingNativeEvents = [name];
          } else {
            self._pendingNativeEvents.push(name);
          }
        }
      } else if (self.initialized) {
        self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
        delete self.delegates[name];
      }
    },
    unbindAllNativeEvents: function () {
      var self = this;
      var body = self.getBody();
      var dom = self.dom;
      var name;
      if (self.delegates) {
        for (name in self.delegates) {
          self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
        }
        delete self.delegates;
      }
      if (!self.inline && body && dom) {
        body.onload = null;
        dom.unbind(self.getWin());
        dom.unbind(self.getDoc());
      }
      if (dom) {
        dom.unbind(body);
        dom.unbind(self.getContainer());
      }
    }
  };
  EditorObservable = $_ahowuxkjh8lywbj.extend({}, $_fuzxjg45jh8lyx45, EditorObservable);
  var EditorObservable$1 = EditorObservable;

  var each$10 = $_ahowuxkjh8lywbj.each;
  var explode$2 = $_ahowuxkjh8lywbj.explode;
  var keyCodeLookup = {
    f9: 120,
    f10: 121,
    f11: 122
  };
  var modifierNames = $_ahowuxkjh8lywbj.makeMap('alt,ctrl,shift,meta,access');
  function Shortcuts (editor) {
    var self = this;
    var shortcuts = {};
    var pendingPatterns = [];
    var parseShortcut = function (pattern) {
      var id, key;
      var shortcut = {};
      each$10(explode$2(pattern, '+'), function (value) {
        if (value in modifierNames) {
          shortcut[value] = true;
        } else {
          if (/^[0-9]{2,}$/.test(value)) {
            shortcut.keyCode = parseInt(value, 10);
          } else {
            shortcut.charCode = value.charCodeAt(0);
            shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
          }
        }
      });
      id = [shortcut.keyCode];
      for (key in modifierNames) {
        if (shortcut[key]) {
          id.push(key);
        } else {
          shortcut[key] = false;
        }
      }
      shortcut.id = id.join(',');
      if (shortcut.access) {
        shortcut.alt = true;
        if ($_9bpim8ajh8lyw68.mac) {
          shortcut.ctrl = true;
        } else {
          shortcut.shift = true;
        }
      }
      if (shortcut.meta) {
        if ($_9bpim8ajh8lyw68.mac) {
          shortcut.meta = true;
        } else {
          shortcut.ctrl = true;
          shortcut.meta = false;
        }
      }
      return shortcut;
    };
    var createShortcut = function (pattern, desc, cmdFunc, scope) {
      var shortcuts;
      shortcuts = $_ahowuxkjh8lywbj.map(explode$2(pattern, '>'), parseShortcut);
      shortcuts[shortcuts.length - 1] = $_ahowuxkjh8lywbj.extend(shortcuts[shortcuts.length - 1], {
        func: cmdFunc,
        scope: scope || editor
      });
      return $_ahowuxkjh8lywbj.extend(shortcuts[0], {
        desc: editor.translate(desc),
        subpatterns: shortcuts.slice(1)
      });
    };
    var hasModifier = function (e) {
      return e.altKey || e.ctrlKey || e.metaKey;
    };
    var isFunctionKey = function (e) {
      return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
    };
    var matchShortcut = function (e, shortcut) {
      if (!shortcut) {
        return false;
      }
      if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
        return false;
      }
      if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
        return false;
      }
      if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
        e.preventDefault();
        return true;
      }
      return false;
    };
    var executeShortcutAction = function (shortcut) {
      return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
    };
    editor.on('keyup keypress keydown', function (e) {
      if ((hasModifier(e) || isFunctionKey(e)) && !e.isDefaultPrevented()) {
        each$10(shortcuts, function (shortcut) {
          if (matchShortcut(e, shortcut)) {
            pendingPatterns = shortcut.subpatterns.slice(0);
            if (e.type === 'keydown') {
              executeShortcutAction(shortcut);
            }
            return true;
          }
        });
        if (matchShortcut(e, pendingPatterns[0])) {
          if (pendingPatterns.length === 1) {
            if (e.type === 'keydown') {
              executeShortcutAction(pendingPatterns[0]);
            }
          }
          pendingPatterns.shift();
        }
      }
    });
    self.add = function (pattern, desc, cmdFunc, scope) {
      var cmd;
      cmd = cmdFunc;
      if (typeof cmdFunc === 'string') {
        cmdFunc = function () {
          editor.execCommand(cmd, false, null);
        };
      } else if ($_ahowuxkjh8lywbj.isArray(cmd)) {
        cmdFunc = function () {
          editor.execCommand(cmd[0], cmd[1], cmd[2]);
        };
      }
      each$10(explode$2($_ahowuxkjh8lywbj.trim(pattern.toLowerCase())), function (pattern) {
        var shortcut = createShortcut(pattern, desc, cmdFunc, scope);
        shortcuts[shortcut.id] = shortcut;
      });
      return true;
    };
    self.remove = function (pattern) {
      var shortcut = createShortcut(pattern);
      if (shortcuts[shortcut.id]) {
        delete shortcuts[shortcut.id];
        return true;
      }
      return false;
    };
  }

  var any$1 = function (predicate) {
    return $_6hl03835jh8lywsm.first(predicate).isSome();
  };
  var ancestor$3 = function (scope, predicate, isRoot) {
    return $_6hl03835jh8lywsm.ancestor(scope, predicate, isRoot).isSome();
  };
  var closest$3 = function (scope, predicate, isRoot) {
    return $_6hl03835jh8lywsm.closest(scope, predicate, isRoot).isSome();
  };
  var sibling$4 = function (scope, predicate) {
    return $_6hl03835jh8lywsm.sibling(scope, predicate).isSome();
  };
  var child$4 = function (scope, predicate) {
    return $_6hl03835jh8lywsm.child(scope, predicate).isSome();
  };
  var descendant$3 = function (scope, predicate) {
    return $_6hl03835jh8lywsm.descendant(scope, predicate).isSome();
  };
  var $_1jfttr4gjh8lyx5b = {
    any: any$1,
    ancestor: ancestor$3,
    closest: closest$3,
    sibling: sibling$4,
    child: child$4,
    descendant: descendant$3
  };

  var focus = function (element) {
    element.dom().focus();
  };
  var blur = function (element) {
    element.dom().blur();
  };
  var hasFocus = function (element) {
    var doc = $_a43q0i17jh8lywfe.owner(element).dom();
    return element.dom() === doc.activeElement;
  };
  var active = function (_doc) {
    var doc = _doc !== undefined ? _doc.dom() : document;
    return Option.from(doc.activeElement).map($_cgttw3zjh8lywdq.fromDom);
  };
  var focusInside = function (element) {
    var doc = $_a43q0i17jh8lywfe.owner(element);
    var inside = active(doc).filter(function (a) {
      return $_1jfttr4gjh8lyx5b.closest(a, $_eqpqvr6jh8lyw3s.curry($_5f6gpb1djh8lywg5.eq, element));
    });
    inside.fold(function () {
      focus(element);
    }, $_eqpqvr6jh8lyw3s.noop);
  };
  var search = function (element) {
    return active($_a43q0i17jh8lywfe.owner(element)).filter(function (e) {
      return element.dom().contains(e.dom());
    });
  };
  var $_717ku14fjh8lyx55 = {
    hasFocus: hasFocus,
    focus: focus,
    blur: blur,
    active: active,
    search: search,
    focusInside: focusInside
  };

  var getContentEditableHost = function (editor, node) {
    return editor.dom.getParent(node, function (node) {
      return editor.dom.getContentEditable(node) === 'true';
    });
  };
  var getCollapsedNode = function (rng) {
    return rng.collapsed ? Option.from(getNode(rng.startContainer, rng.startOffset)).map($_cgttw3zjh8lywdq.fromDom) : Option.none();
  };
  var getFocusInElement = function (root, rng) {
    return getCollapsedNode(rng).bind(function (node) {
      if (isTableSection(node)) {
        return Option.some(node);
      } else if ($_5f6gpb1djh8lywg5.contains(root, node) === false) {
        return Option.some(root);
      } else {
        return Option.none();
      }
    });
  };
  var normalizeSelection = function (editor, rng) {
    getFocusInElement($_cgttw3zjh8lywdq.fromDom(editor.getBody()), rng).bind(function (elm) {
      return $_9kvypj2cjh8lywnz.firstPositionIn(elm.dom());
    }).fold(function () {
      editor.selection.normalize();
      return;
    }, function (caretPos) {
      return editor.selection.setRng(caretPos.toRange());
    });
  };
  var focusBody = function (body) {
    if (body.setActive) {
      try {
        body.setActive();
      } catch (ex) {
        body.focus();
      }
    } else {
      body.focus();
    }
  };
  var hasElementFocus = function (elm) {
    return $_717ku14fjh8lyx55.hasFocus(elm) || $_717ku14fjh8lyx55.search(elm).isSome();
  };
  var hasIframeFocus = function (editor) {
    return editor.iframeElement && $_717ku14fjh8lyx55.hasFocus($_cgttw3zjh8lywdq.fromDom(editor.iframeElement));
  };
  var hasInlineFocus = function (editor) {
    var rawBody = editor.getBody();
    return rawBody && hasElementFocus($_cgttw3zjh8lywdq.fromDom(rawBody));
  };
  var hasFocus$1 = function (editor) {
    return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  };
  var focusEditor = function (editor) {
    var selection = editor.selection, contentEditable = editor.settings.content_editable;
    var body = editor.getBody();
    var rng = selection.getRng();
    editor.quirks.refreshContentEditable();
    var contentEditableHost = getContentEditableHost(editor, selection.getNode());
    if (editor.$.contains(body, contentEditableHost)) {
      focusBody(contentEditableHost);
      normalizeSelection(editor, rng);
      activateEditor(editor);
      return;
    }
    if (editor.bookmark !== undefined && hasFocus$1(editor) === false) {
      $_eqs11m40jh8lyx31.getRng(editor).each(function (bookmarkRng) {
        editor.selection.setRng(bookmarkRng);
        rng = bookmarkRng;
      });
    }
    if (!contentEditable) {
      if (!$_9bpim8ajh8lyw68.opera) {
        focusBody(body);
      }
      editor.getWin().focus();
    }
    if ($_9bpim8ajh8lyw68.gecko || contentEditable) {
      focusBody(body);
      normalizeSelection(editor, rng);
    }
    activateEditor(editor);
  };
  var activateEditor = function (editor) {
    return editor.editorManager.setActive(editor);
  };
  var focus$1 = function (editor, skipFocus) {
    if (editor.removed) {
      return;
    }
    skipFocus ? activateEditor(editor) : focusEditor(editor);
  };
  var $_cnu79r4ejh8lyx4x = {
    focus: focus$1,
    hasFocus: hasFocus$1
  };

  var getProp = function (propName, elm) {
    var rawElm = elm.dom();
    return rawElm[propName];
  };
  var getComputedSizeProp = function (propName, elm) {
    return parseInt($_36knnd12jh8lywe1.get(elm, propName), 10);
  };
  var getClientWidth = $_eqpqvr6jh8lyw3s.curry(getProp, 'clientWidth');
  var getClientHeight = $_eqpqvr6jh8lyw3s.curry(getProp, 'clientHeight');
  var getMarginTop = $_eqpqvr6jh8lyw3s.curry(getComputedSizeProp, 'margin-top');
  var getMarginLeft = $_eqpqvr6jh8lyw3s.curry(getComputedSizeProp, 'margin-left');
  var getBoundingClientRect$1 = function (elm) {
    return elm.dom().getBoundingClientRect();
  };
  var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
    var clientWidth = getClientWidth(bodyElm);
    var clientHeight = getClientHeight(bodyElm);
    return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  };
  var transpose = function (inline, elm, clientX, clientY) {
    var clientRect = getBoundingClientRect$1(elm);
    var deltaX = inline ? clientRect.left + elm.dom().clientLeft + getMarginLeft(elm) : 0;
    var deltaY = inline ? clientRect.top + elm.dom().clientTop + getMarginTop(elm) : 0;
    var x = clientX - deltaX;
    var y = clientY - deltaY;
    return {
      x: x,
      y: y
    };
  };
  var isXYInContentArea = function (editor, clientX, clientY) {
    var bodyElm = $_cgttw3zjh8lywdq.fromDom(editor.getBody());
    var targetElm = editor.inline ? bodyElm : $_a43q0i17jh8lywfe.documentElement(bodyElm);
    var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
    return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  };
  var fromDomSafe = function (node) {
    return Option.from(node).map($_cgttw3zjh8lywdq.fromDom);
  };
  var isEditorAttachedToDom = function (editor) {
    var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
    return fromDomSafe(rawContainer).map(function (container) {
      return $_5f6gpb1djh8lywg5.contains($_a43q0i17jh8lywfe.owner(container), container);
    }).getOr(false);
  };
  var $_7f1iw94jjh8lyx60 = {
    isXYInContentArea: isXYInContentArea,
    isEditorAttachedToDom: isEditorAttachedToDom
  };

  function NotificationManagerImpl () {
    var unimplemented = function () {
      throw new Error('Theme did not provide a NotificationManager implementation.');
    };
    return {
      open: unimplemented,
      close: unimplemented,
      reposition: unimplemented,
      getArgs: unimplemented
    };
  }

  function NotificationManager (editor) {
    var notifications = [];
    var getImplementation = function () {
      var theme = editor.theme;
      return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
    };
    var getTopNotification = function () {
      return Option.from(notifications[0]);
    };
    var isEqual = function (a, b) {
      return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
    };
    var reposition = function () {
      if (notifications.length > 0) {
        getImplementation().reposition(notifications);
      }
    };
    var addNotification = function (notification) {
      notifications.push(notification);
    };
    var closeNotification = function (notification) {
      $_5wjzy24jh8lyw2t.findIndex(notifications, function (otherNotification) {
        return otherNotification === notification;
      }).each(function (index) {
        notifications.splice(index, 1);
      });
    };
    var open = function (args) {
      if (editor.removed || !$_7f1iw94jjh8lyx60.isEditorAttachedToDom(editor)) {
        return;
      }
      return $_5wjzy24jh8lyw2t.find(notifications, function (notification) {
        return isEqual(getImplementation().getArgs(notification), args);
      }).getOrThunk(function () {
        editor.editorManager.setActive(editor);
        var notification = getImplementation().open(args, function () {
          closeNotification(notification);
          reposition();
        });
        addNotification(notification);
        reposition();
        return notification;
      });
    };
    var close = function () {
      getTopNotification().each(function (notification) {
        getImplementation().close(notification);
        closeNotification(notification);
        reposition();
      });
    };
    var getNotifications = function () {
      return notifications;
    };
    var registerEvents = function (editor) {
      editor.on('SkinLoaded', function () {
        var serviceMessage = editor.settings.service_message;
        if (serviceMessage) {
          open({
            text: serviceMessage,
            type: 'warning',
            timeout: 0,
            icon: ''
          });
        }
      });
      editor.on('ResizeEditor ResizeWindow', function () {
        $_8sy3pfhjh8lyw95.requestAnimationFrame(reposition);
      });
      editor.on('remove', function () {
        $_5wjzy24jh8lyw2t.each(notifications, function (notification) {
          getImplementation().close(notification);
        });
      });
    };
    registerEvents(editor);
    return {
      open: open,
      close: close,
      getNotifications: getNotifications
    };
  }

  function WindowManagerImpl () {
    var unimplemented = function () {
      throw new Error('Theme did not provide a WindowManager implementation.');
    };
    return {
      open: unimplemented,
      alert: unimplemented,
      confirm: unimplemented,
      close: unimplemented,
      getParams: unimplemented,
      setParams: unimplemented
    };
  }

  function WindowManager (editor) {
    var windows = [];
    var getImplementation = function () {
      var theme = editor.theme;
      return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
    };
    var funcBind = function (scope, f) {
      return function () {
        return f ? f.apply(scope, arguments) : undefined;
      };
    };
    var fireOpenEvent = function (win) {
      editor.fire('OpenWindow', { win: win });
    };
    var fireCloseEvent = function (win) {
      editor.fire('CloseWindow', { win: win });
    };
    var addWindow = function (win) {
      windows.push(win);
      fireOpenEvent(win);
    };
    var closeWindow = function (win) {
      $_5wjzy24jh8lyw2t.findIndex(windows, function (otherWindow) {
        return otherWindow === win;
      }).each(function (index) {
        windows.splice(index, 1);
        fireCloseEvent(win);
        if (windows.length === 0) {
          editor.focus();
        }
      });
    };
    var getTopWindow = function () {
      return Option.from(windows[windows.length - 1]);
    };
    var open = function (args, params) {
      editor.editorManager.setActive(editor);
      $_eqs11m40jh8lyx31.store(editor);
      var win = getImplementation().open(args, params, closeWindow);
      addWindow(win);
      return win;
    };
    var alert = function (message, callback, scope) {
      var win = getImplementation().alert(message, funcBind(scope ? scope : this, callback), closeWindow);
      addWindow(win);
    };
    var confirm = function (message, callback, scope) {
      var win = getImplementation().confirm(message, funcBind(scope ? scope : this, callback), closeWindow);
      addWindow(win);
    };
    var close = function () {
      getTopWindow().each(function (win) {
        getImplementation().close(win);
        closeWindow(win);
      });
    };
    var getParams = function () {
      return getTopWindow().map(getImplementation().getParams).getOr(null);
    };
    var setParams = function (params) {
      getTopWindow().each(function (win) {
        getImplementation().setParams(win, params);
      });
    };
    var getWindows = function () {
      return windows;
    };
    editor.on('remove', function () {
      $_5wjzy24jh8lyw2t.each(windows.slice(0), function (win) {
        getImplementation().close(win);
      });
    });
    return {
      windows: windows,
      open: open,
      alert: alert,
      confirm: confirm,
      close: close,
      getParams: getParams,
      setParams: setParams,
      getWindows: getWindows
    };
  }

  var PluginManager = AddOnManager.PluginManager;
  var resolvePluginName = function (targetUrl, suffix) {
    for (var name_1 in PluginManager.urls) {
      var matchUrl = PluginManager.urls[name_1] + '/plugin' + suffix + '.js';
      if (matchUrl === targetUrl) {
        return name_1;
      }
    }
    return null;
  };
  var pluginUrlToMessage = function (editor, url) {
    var plugin = resolvePluginName(url, editor.suffix);
    return plugin ? 'Failed to load plugin: ' + plugin + ' from url ' + url : 'Failed to load plugin url: ' + url;
  };
  var displayNotification = function (editor, message) {
    editor.notificationManager.open({
      type: 'error',
      text: message
    });
  };
  var displayError = function (editor, message) {
    if (editor._skinLoaded) {
      displayNotification(editor, message);
    } else {
      editor.on('SkinLoaded', function () {
        displayNotification(editor, message);
      });
    }
  };
  var uploadError = function (editor, message) {
    displayError(editor, 'Failed to upload image: ' + message);
  };
  var pluginLoadError = function (editor, url) {
    displayError(editor, pluginUrlToMessage(editor, url));
  };
  var initError = function (message) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var console = window.console;
    if (console) {
      if (console.error) {
        console.error.apply(console, arguments);
      } else {
        console.log.apply(console, arguments);
      }
    }
  };
  var $_5vy074njh8lyx6h = {
    pluginLoadError: pluginLoadError,
    uploadError: uploadError,
    displayError: displayError,
    initError: initError
  };

  var PluginManager$1 = AddOnManager.PluginManager;

  var ThemeManager = AddOnManager.ThemeManager;

  function XMLHttpRequest () {
    var f = $_99xmy7cjh8lyw6k.getOrDie('XMLHttpRequest');
    return new f();
  }

  function Uploader (uploadStatus, settings) {
    var pendingPromises = {};
    var pathJoin = function (path1, path2) {
      if (path1) {
        return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
      }
      return path2;
    };
    var defaultHandler = function (blobInfo, success, failure, progress) {
      var xhr, formData;
      xhr = new XMLHttpRequest();
      xhr.open('POST', settings.url);
      xhr.withCredentials = settings.credentials;
      xhr.upload.onprogress = function (e) {
        progress(e.loaded / e.total * 100);
      };
      xhr.onerror = function () {
        failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
      };
      xhr.onload = function () {
        var json;
        if (xhr.status < 200 || xhr.status >= 300) {
          failure('HTTP Error: ' + xhr.status);
          return;
        }
        json = JSON.parse(xhr.responseText);
        if (!json || typeof json.location !== 'string') {
          failure('Invalid JSON: ' + xhr.responseText);
          return;
        }
        success(pathJoin(settings.basePath, json.location));
      };
      formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());
      xhr.send(formData);
    };
    var noUpload = function () {
      return new promiseObj(function (resolve) {
        resolve([]);
      });
    };
    var handlerSuccess = function (blobInfo, url) {
      return {
        url: url,
        blobInfo: blobInfo,
        status: true
      };
    };
    var handlerFailure = function (blobInfo, error) {
      return {
        url: '',
        blobInfo: blobInfo,
        status: false,
        error: error
      };
    };
    var resolvePending = function (blobUri, result) {
      $_ahowuxkjh8lywbj.each(pendingPromises[blobUri], function (resolve) {
        resolve(result);
      });
      delete pendingPromises[blobUri];
    };
    var uploadBlobInfo = function (blobInfo, handler, openNotification) {
      uploadStatus.markPending(blobInfo.blobUri());
      return new promiseObj(function (resolve) {
        var notification, progress;
        var noop = function () {
        };
        try {
          var closeNotification_1 = function () {
            if (notification) {
              notification.close();
              progress = noop;
            }
          };
          var success = function (url) {
            closeNotification_1();
            uploadStatus.markUploaded(blobInfo.blobUri(), url);
            resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
            resolve(handlerSuccess(blobInfo, url));
          };
          var failure = function (error) {
            closeNotification_1();
            uploadStatus.removeFailed(blobInfo.blobUri());
            resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error));
            resolve(handlerFailure(blobInfo, error));
          };
          progress = function (percent) {
            if (percent < 0 || percent > 100) {
              return;
            }
            if (!notification) {
              notification = openNotification();
            }
            notification.progressBar.value(percent);
          };
          handler(blobInfo, success, failure, progress);
        } catch (ex) {
          resolve(handlerFailure(blobInfo, ex.message));
        }
      });
    };
    var isDefaultHandler = function (handler) {
      return handler === defaultHandler;
    };
    var pendingUploadBlobInfo = function (blobInfo) {
      var blobUri = blobInfo.blobUri();
      return new promiseObj(function (resolve) {
        pendingPromises[blobUri] = pendingPromises[blobUri] || [];
        pendingPromises[blobUri].push(resolve);
      });
    };
    var uploadBlobs = function (blobInfos, openNotification) {
      blobInfos = $_ahowuxkjh8lywbj.grep(blobInfos, function (blobInfo) {
        return !uploadStatus.isUploaded(blobInfo.blobUri());
      });
      return promiseObj.all($_ahowuxkjh8lywbj.map(blobInfos, function (blobInfo) {
        return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
      }));
    };
    var upload = function (blobInfos, openNotification) {
      return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
    };
    settings = $_ahowuxkjh8lywbj.extend({
      credentials: false,
      handler: defaultHandler
    }, settings);
    return { upload: upload };
  }

  function Blob (parts, properties) {
    var f = $_99xmy7cjh8lyw6k.getOrDie('Blob');
    return new f(parts, properties);
  }

  function FileReader () {
    var f = $_99xmy7cjh8lyw6k.getOrDie('FileReader');
    return new f();
  }

  function Uint8Array (arr) {
    var f = $_99xmy7cjh8lyw6k.getOrDie('Uint8Array');
    return new f(arr);
  }

  var requestAnimationFrame$1 = function (callback) {
    var f = $_99xmy7cjh8lyw6k.getOrDie('requestAnimationFrame');
    f(callback);
  };
  var atob = function (base64) {
    var f = $_99xmy7cjh8lyw6k.getOrDie('atob');
    return f(base64);
  };
  var $_bfbm2n50jh8lyx88 = {
    atob: atob,
    requestAnimationFrame: requestAnimationFrame$1
  };

  var blobUriToBlob = function (url) {
    return new promiseObj(function (resolve, reject) {
      var rejectWithError = function () {
        reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
      };
      try {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            rejectWithError();
          }
        };
        xhr.onerror = rejectWithError;
        xhr.send();
      } catch (ex) {
        rejectWithError();
      }
    });
  };
  var parseDataUri = function (uri) {
    var type, matches;
    uri = decodeURIComponent(uri).split(',');
    matches = /data:([^;]+)/.exec(uri[0]);
    if (matches) {
      type = matches[1];
    }
    return {
      type: type,
      data: uri[1]
    };
  };
  var dataUriToBlob = function (uri) {
    return new promiseObj(function (resolve) {
      var str, arr, i;
      uri = parseDataUri(uri);
      try {
        str = $_bfbm2n50jh8lyx88.atob(uri.data);
      } catch (e) {
        resolve(new Blob([]));
        return;
      }
      arr = new Uint8Array(str.length);
      for (i = 0; i < arr.length; i++) {
        arr[i] = str.charCodeAt(i);
      }
      resolve(new Blob([arr], { type: uri.type }));
    });
  };
  var uriToBlob = function (url) {
    if (url.indexOf('blob:') === 0) {
      return blobUriToBlob(url);
    }
    if (url.indexOf('data:') === 0) {
      return dataUriToBlob(url);
    }
    return null;
  };
  var blobToDataUri = function (blob) {
    return new promiseObj(function (resolve) {
      var reader = new FileReader();
      reader.onloadend = function () {
        resolve(reader.result);
      };
      reader.readAsDataURL(blob);
    });
  };
  var $_ap7oid4wjh8lyx7y = {
    uriToBlob: uriToBlob,
    blobToDataUri: blobToDataUri,
    parseDataUri: parseDataUri
  };

  var count = 0;
  var uniqueId = function (prefix) {
    return (prefix || 'blobid') + count++;
  };
  var imageToBlobInfo = function (blobCache, img, resolve, reject) {
    var base64, blobInfo;
    if (img.src.indexOf('blob:') === 0) {
      blobInfo = blobCache.getByUri(img.src);
      if (blobInfo) {
        resolve({
          image: img,
          blobInfo: blobInfo
        });
      } else {
        $_ap7oid4wjh8lyx7y.uriToBlob(img.src).then(function (blob) {
          $_ap7oid4wjh8lyx7y.blobToDataUri(blob).then(function (dataUri) {
            base64 = $_ap7oid4wjh8lyx7y.parseDataUri(dataUri).data;
            blobInfo = blobCache.create(uniqueId(), blob, base64);
            blobCache.add(blobInfo);
            resolve({
              image: img,
              blobInfo: blobInfo
            });
          });
        }, function (err) {
          reject(err);
        });
      }
      return;
    }
    base64 = $_ap7oid4wjh8lyx7y.parseDataUri(img.src).data;
    blobInfo = blobCache.findFirst(function (cachedBlobInfo) {
      return cachedBlobInfo.base64() === base64;
    });
    if (blobInfo) {
      resolve({
        image: img,
        blobInfo: blobInfo
      });
    } else {
      $_ap7oid4wjh8lyx7y.uriToBlob(img.src).then(function (blob) {
        blobInfo = blobCache.create(uniqueId(), blob, base64);
        blobCache.add(blobInfo);
        resolve({
          image: img,
          blobInfo: blobInfo
        });
      }, function (err) {
        reject(err);
      });
    }
  };
  var getAllImages = function (elm) {
    return elm ? elm.getElementsByTagName('img') : [];
  };
  function ImageScanner (uploadStatus, blobCache) {
    var cachedPromises = {};
    var findAll = function (elm, predicate) {
      var images;
      if (!predicate) {
        predicate = $_8aqzj925jh8lywmj.constant(true);
      }
      images = $_9tjm51ljh8lywbq.filter(getAllImages(elm), function (img) {
        var src = img.src;
        if (!$_9bpim8ajh8lyw68.fileApi) {
          return false;
        }
        if (img.hasAttribute('data-mce-bogus')) {
          return false;
        }
        if (img.hasAttribute('data-mce-placeholder')) {
          return false;
        }
        if (!src || src === $_9bpim8ajh8lyw68.transparentSrc) {
          return false;
        }
        if (src.indexOf('blob:') === 0) {
          return !uploadStatus.isUploaded(src);
        }
        if (src.indexOf('data:') === 0) {
          return predicate(img);
        }
        return false;
      });
      var promises = $_9tjm51ljh8lywbq.map(images, function (img) {
        if (cachedPromises[img.src]) {
          return new promiseObj(function (resolve) {
            cachedPromises[img.src].then(function (imageInfo) {
              if (typeof imageInfo === 'string') {
                return imageInfo;
              }
              resolve({
                image: img,
                blobInfo: imageInfo.blobInfo
              });
            });
          });
        }
        var newPromise = new promiseObj(function (resolve, reject) {
          imageToBlobInfo(blobCache, img, resolve, reject);
        }).then(function (result) {
          delete cachedPromises[result.image.src];
          return result;
        }).catch(function (error) {
          delete cachedPromises[img.src];
          return error;
        });
        cachedPromises[img.src] = newPromise;
        return newPromise;
      });
      return promiseObj.all(promises);
    };
    return { findAll: findAll };
  }

  var count$1 = 0;
  var seed = function () {
    var rnd = function () {
      return Math.round(Math.random() * 4294967295).toString(36);
    };
    var now = new Date().getTime();
    return 's' + now.toString(36) + rnd() + rnd() + rnd();
  };
  var uuid = function (prefix) {
    return prefix + count$1++ + seed();
  };
  var $_co2y7g52jh8lyx8f = { uuid: uuid };

  function BlobCache () {
    var cache = [];
    var constant = $_8aqzj925jh8lywmj.constant;
    var mimeToExt = function (mime) {
      var mimes = {
        'image/jpeg': 'jpg',
        'image/jpg': 'jpg',
        'image/gif': 'gif',
        'image/png': 'png'
      };
      return mimes[mime.toLowerCase()] || 'dat';
    };
    var create = function (o, blob, base64, filename) {
      return typeof o === 'object' ? toBlobInfo(o) : toBlobInfo({
        id: o,
        name: filename,
        blob: blob,
        base64: base64
      });
    };
    var toBlobInfo = function (o) {
      var id, name;
      if (!o.blob || !o.base64) {
        throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
      }
      id = o.id || $_co2y7g52jh8lyx8f.uuid('blobid');
      name = o.name || id;
      return {
        id: constant(id),
        name: constant(name),
        filename: constant(name + '.' + mimeToExt(o.blob.type)),
        blob: constant(o.blob),
        base64: constant(o.base64),
        blobUri: constant(o.blobUri || $_ge0pt0bjh8lyw6g.createObjectURL(o.blob)),
        uri: constant(o.uri)
      };
    };
    var add = function (blobInfo) {
      if (!get(blobInfo.id())) {
        cache.push(blobInfo);
      }
    };
    var get = function (id) {
      return findFirst(function (cachedBlobInfo) {
        return cachedBlobInfo.id() === id;
      });
    };
    var findFirst = function (predicate) {
      return $_9tjm51ljh8lywbq.filter(cache, predicate)[0];
    };
    var getByUri = function (blobUri) {
      return findFirst(function (blobInfo) {
        return blobInfo.blobUri() === blobUri;
      });
    };
    var removeByUri = function (blobUri) {
      cache = $_9tjm51ljh8lywbq.filter(cache, function (blobInfo) {
        if (blobInfo.blobUri() === blobUri) {
          $_ge0pt0bjh8lyw6g.revokeObjectURL(blobInfo.blobUri());
          return false;
        }
        return true;
      });
    };
    var destroy = function () {
      $_9tjm51ljh8lywbq.each(cache, function (cachedBlobInfo) {
        $_ge0pt0bjh8lyw6g.revokeObjectURL(cachedBlobInfo.blobUri());
      });
      cache = [];
    };
    return {
      create: create,
      add: add,
      get: get,
      getByUri: getByUri,
      findFirst: findFirst,
      removeByUri: removeByUri,
      destroy: destroy
    };
  }

  function UploadStatus () {
    var PENDING = 1, UPLOADED = 2;
    var blobUriStatuses = {};
    var createStatus = function (status, resultUri) {
      return {
        status: status,
        resultUri: resultUri
      };
    };
    var hasBlobUri = function (blobUri) {
      return blobUri in blobUriStatuses;
    };
    var getResultUri = function (blobUri) {
      var result = blobUriStatuses[blobUri];
      return result ? result.resultUri : null;
    };
    var isPending = function (blobUri) {
      return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
    };
    var isUploaded = function (blobUri) {
      return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
    };
    var markPending = function (blobUri) {
      blobUriStatuses[blobUri] = createStatus(PENDING, null);
    };
    var markUploaded = function (blobUri, resultUri) {
      blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
    };
    var removeFailed = function (blobUri) {
      delete blobUriStatuses[blobUri];
    };
    var destroy = function () {
      blobUriStatuses = {};
    };
    return {
      hasBlobUri: hasBlobUri,
      getResultUri: getResultUri,
      isPending: isPending,
      isUploaded: isUploaded,
      markPending: markPending,
      markUploaded: markUploaded,
      removeFailed: removeFailed,
      destroy: destroy
    };
  }

  function EditorUpload (editor) {
    var blobCache = BlobCache();
    var uploader, imageScanner;
    var settings = editor.settings;
    var uploadStatus = UploadStatus();
    var aliveGuard = function (callback) {
      return function (result) {
        if (editor.selection) {
          return callback(result);
        }
        return [];
      };
    };
    var cacheInvalidator = function () {
      return '?' + new Date().getTime();
    };
    var replaceString = function (content, search, replace) {
      var index = 0;
      do {
        index = content.indexOf(search, index);
        if (index !== -1) {
          content = content.substring(0, index) + replace + content.substr(index + search.length);
          index += replace.length - search.length + 1;
        }
      } while (index !== -1);
      return content;
    };
    var replaceImageUrl = function (content, targetUrl, replacementUrl) {
      content = replaceString(content, 'src="' + targetUrl + '"', 'src="' + replacementUrl + '"');
      content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
      return content;
    };
    var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
      $_9tjm51ljh8lywbq.each(editor.undoManager.data, function (level) {
        if (level.type === 'fragmented') {
          level.fragments = $_9tjm51ljh8lywbq.map(level.fragments, function (fragment) {
            return replaceImageUrl(fragment, targetUrl, replacementUrl);
          });
        } else {
          level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
        }
      });
    };
    var openNotification = function () {
      return editor.notificationManager.open({
        text: editor.translate('Image uploading...'),
        type: 'info',
        timeout: -1,
        progressBar: true
      });
    };
    var replaceImageUri = function (image, resultUri) {
      blobCache.removeByUri(image.src);
      replaceUrlInUndoStack(image.src, resultUri);
      editor.$(image).attr({
        'src': settings.images_reuse_filename ? resultUri + cacheInvalidator() : resultUri,
        'data-mce-src': editor.convertURL(resultUri, 'src')
      });
    };
    var uploadImages = function (callback) {
      if (!uploader) {
        uploader = Uploader(uploadStatus, {
          url: settings.images_upload_url,
          basePath: settings.images_upload_base_path,
          credentials: settings.images_upload_credentials,
          handler: settings.images_upload_handler
        });
      }
      return scanForImages().then(aliveGuard(function (imageInfos) {
        var blobInfos;
        blobInfos = $_9tjm51ljh8lywbq.map(imageInfos, function (imageInfo) {
          return imageInfo.blobInfo;
        });
        return uploader.upload(blobInfos, openNotification).then(aliveGuard(function (result) {
          var filteredResult = $_9tjm51ljh8lywbq.map(result, function (uploadInfo, index) {
            var image = imageInfos[index].image;
            if (uploadInfo.status && editor.settings.images_replace_blob_uris !== false) {
              replaceImageUri(image, uploadInfo.url);
            } else if (uploadInfo.error) {
              $_5vy074njh8lyx6h.uploadError(editor, uploadInfo.error);
            }
            return {
              element: image,
              status: uploadInfo.status
            };
          });
          if (callback) {
            callback(filteredResult);
          }
          return filteredResult;
        }));
      }));
    };
    var uploadImagesAuto = function (callback) {
      if (settings.automatic_uploads !== false) {
        return uploadImages(callback);
      }
    };
    var isValidDataUriImage = function (imgElm) {
      return settings.images_dataimg_filter ? settings.images_dataimg_filter(imgElm) : true;
    };
    var scanForImages = function () {
      if (!imageScanner) {
        imageScanner = ImageScanner(uploadStatus, blobCache);
      }
      return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
        result = $_9tjm51ljh8lywbq.filter(result, function (resultItem) {
          if (typeof resultItem === 'string') {
            $_5vy074njh8lyx6h.displayError(editor, resultItem);
            return false;
          }
          return true;
        });
        $_9tjm51ljh8lywbq.each(result, function (resultItem) {
          replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
          resultItem.image.src = resultItem.blobInfo.blobUri();
          resultItem.image.removeAttribute('data-mce-src');
        });
        return result;
      }));
    };
    var destroy = function () {
      blobCache.destroy();
      uploadStatus.destroy();
      imageScanner = uploader = null;
    };
    var replaceBlobUris = function (content) {
      return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
        var resultUri = uploadStatus.getResultUri(blobUri);
        if (resultUri) {
          return 'src="' + resultUri + '"';
        }
        var blobInfo = blobCache.getByUri(blobUri);
        if (!blobInfo) {
          blobInfo = $_9tjm51ljh8lywbq.reduce(editor.editorManager.get(), function (result, editor) {
            return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
          }, null);
        }
        if (blobInfo) {
          return 'src="data:' + blobInfo.blob().type + ';base64,' + blobInfo.base64() + '"';
        }
        return match;
      });
    };
    editor.on('setContent', function () {
      if (editor.settings.automatic_uploads !== false) {
        uploadImagesAuto();
      } else {
        scanForImages();
      }
    });
    editor.on('RawSaveContent', function (e) {
      e.content = replaceBlobUris(e.content);
    });
    editor.on('getContent', function (e) {
      if (e.source_view || e.format === 'raw') {
        return;
      }
      e.content = replaceBlobUris(e.content);
    });
    editor.on('PostRender', function () {
      editor.parser.addNodeFilter('img', function (images) {
        $_9tjm51ljh8lywbq.each(images, function (img) {
          var src = img.attr('src');
          if (blobCache.getByUri(src)) {
            return;
          }
          var resultUri = uploadStatus.getResultUri(src);
          if (resultUri) {
            img.attr('src', resultUri);
          }
        });
      });
    });
    return {
      blobCache: blobCache,
      uploadImages: uploadImages,
      uploadImagesAuto: uploadImagesAuto,
      scanForImages: scanForImages,
      destroy: destroy
    };
  }

  var isBlockElement = function (blockElements, node) {
    return blockElements.hasOwnProperty(node.nodeName);
  };
  var isValidTarget = function (blockElements, node) {
    if ($_5oonaz1qjh8lywhz.isText(node)) {
      return true;
    } else if ($_5oonaz1qjh8lywhz.isElement(node)) {
      return !isBlockElement(blockElements, node) && !$_eyp5ec2njh8lywpo.isBookmarkNode(node);
    } else {
      return false;
    }
  };
  var hasBlockParent = function (blockElements, root, node) {
    return $_5wjzy24jh8lyw2t.exists($_dyxtub3ejh8lywxq.parents($_cgttw3zjh8lywdq.fromDom(node), $_cgttw3zjh8lywdq.fromDom(root)), function (elm) {
      return isBlockElement(blockElements, elm.dom());
    });
  };
  var shouldRemoveTextNode = function (blockElements, node) {
    if ($_5oonaz1qjh8lywhz.isText(node)) {
      if (node.nodeValue.length === 0) {
        return true;
      } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
        return true;
      }
    }
    return false;
  };
  var addRootBlocks = function (editor) {
    var settings = editor.settings, dom = editor.dom, selection = editor.selection;
    var schema = editor.schema, blockElements = schema.getBlockElements();
    var node = selection.getStart();
    var rootNode = editor.getBody();
    var rng;
    var startContainer, startOffset, endContainer, endOffset, rootBlockNode;
    var tempNode, wrapped, restoreSelection;
    var rootNodeName, forcedRootBlock;
    forcedRootBlock = settings.forced_root_block;
    if (!node || !$_5oonaz1qjh8lywhz.isElement(node) || !forcedRootBlock) {
      return;
    }
    rootNodeName = rootNode.nodeName.toLowerCase();
    if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
      return;
    }
    rng = selection.getRng();
    startContainer = rng.startContainer;
    startOffset = rng.startOffset;
    endContainer = rng.endContainer;
    endOffset = rng.endOffset;
    restoreSelection = $_cnu79r4ejh8lyx4x.hasFocus(editor);
    node = rootNode.firstChild;
    while (node) {
      if (isValidTarget(blockElements, node)) {
        if (shouldRemoveTextNode(blockElements, node)) {
          tempNode = node;
          node = node.nextSibling;
          dom.remove(tempNode);
          continue;
        }
        if (!rootBlockNode) {
          rootBlockNode = dom.create(forcedRootBlock, editor.settings.forced_root_block_attrs);
          node.parentNode.insertBefore(rootBlockNode, node);
          wrapped = true;
        }
        tempNode = node;
        node = node.nextSibling;
        rootBlockNode.appendChild(tempNode);
      } else {
        rootBlockNode = null;
        node = node.nextSibling;
      }
    }
    if (wrapped && restoreSelection) {
      rng.setStart(startContainer, startOffset);
      rng.setEnd(endContainer, endOffset);
      selection.setRng(rng);
      editor.nodeChanged();
    }
  };
  var setup = function (editor) {
    if (editor.settings.forced_root_block) {
      editor.on('NodeChange', $_eqpqvr6jh8lyw3s.curry(addRootBlocks, editor));
    }
  };
  var $_85z7kh54jh8lyx8j = { setup: setup };

  var getStartNode = function (rng) {
    var sc = rng.startContainer, so = rng.startOffset;
    if ($_5oonaz1qjh8lywhz.isText(sc)) {
      return so === 0 ? Option.some($_cgttw3zjh8lywdq.fromDom(sc)) : Option.none();
    } else {
      return Option.from(sc.childNodes[so]).map($_cgttw3zjh8lywdq.fromDom);
    }
  };
  var getEndNode = function (rng) {
    var ec = rng.endContainer, eo = rng.endOffset;
    if ($_5oonaz1qjh8lywhz.isText(ec)) {
      return eo === ec.data.length ? Option.some($_cgttw3zjh8lywdq.fromDom(ec)) : Option.none();
    } else {
      return Option.from(ec.childNodes[eo - 1]).map($_cgttw3zjh8lywdq.fromDom);
    }
  };
  var getFirstChildren = function (node) {
    return $_a43q0i17jh8lywfe.firstChild(node).fold($_eqpqvr6jh8lyw3s.constant([node]), function (child) {
      return [node].concat(getFirstChildren(child));
    });
  };
  var getLastChildren$1 = function (node) {
    return $_a43q0i17jh8lywfe.lastChild(node).fold($_eqpqvr6jh8lyw3s.constant([node]), function (child) {
      if ($_7j1jt210jh8lywdx.name(child) === 'br') {
        return $_a43q0i17jh8lywfe.prevSibling(child).map(function (sibling) {
          return [node].concat(getLastChildren$1(sibling));
        }).getOr([]);
      } else {
        return [node].concat(getLastChildren$1(child));
      }
    });
  };
  var hasAllContentsSelected = function (elm, rng) {
    return $_b8twwq26jh8lywmm.liftN([
      getStartNode(rng),
      getEndNode(rng)
    ], function (startNode, endNode) {
      var start = $_5wjzy24jh8lyw2t.find(getFirstChildren(elm), $_eqpqvr6jh8lyw3s.curry($_5f6gpb1djh8lywg5.eq, startNode));
      var end = $_5wjzy24jh8lyw2t.find(getLastChildren$1(elm), $_eqpqvr6jh8lyw3s.curry($_5f6gpb1djh8lywg5.eq, endNode));
      return start.isSome() && end.isSome();
    }).getOr(false);
  };
  var moveEndPoint$1 = function (dom, rng, node, start) {
    var root = node, walker = new TreeWalker(node, root);
    var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
    do {
      if (node.nodeType === 3 && $_ahowuxkjh8lywbj.trim(node.nodeValue).length !== 0) {
        if (start) {
          rng.setStart(node, 0);
        } else {
          rng.setEnd(node, node.nodeValue.length);
        }
        return;
      }
      if (nonEmptyElementsMap[node.nodeName] && !/^(TD|TH)$/.test(node.nodeName)) {
        if (start) {
          rng.setStartBefore(node);
        } else {
          if (node.nodeName === 'BR') {
            rng.setEndBefore(node);
          } else {
            rng.setEndAfter(node);
          }
        }
        return;
      }
      if ($_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie < 11 && dom.isBlock(node) && dom.isEmpty(node)) {
        if (start) {
          rng.setStart(node, 0);
        } else {
          rng.setEnd(node, 0);
        }
        return;
      }
    } while (node = start ? walker.next() : walker.prev());
    if (root.nodeName === 'BODY') {
      if (start) {
        rng.setStart(root, 0);
      } else {
        rng.setEnd(root, root.childNodes.length);
      }
    }
  };
  var hasAnyRanges = function (editor) {
    var sel = editor.selection.getSel();
    return sel && sel.rangeCount > 0;
  };

  function NodeChange (editor) {
    var lastRng, lastPath = [];
    var isSameElementPath = function (startElm) {
      var i, currentPath;
      currentPath = editor.$(startElm).parentsUntil(editor.getBody()).add(startElm);
      if (currentPath.length === lastPath.length) {
        for (i = currentPath.length; i >= 0; i--) {
          if (currentPath[i] !== lastPath[i]) {
            break;
          }
        }
        if (i === -1) {
          lastPath = currentPath;
          return true;
        }
      }
      lastPath = currentPath;
      return false;
    };
    if (!('onselectionchange' in editor.getDoc())) {
      editor.on('NodeChange Click MouseUp KeyUp Focus', function (e) {
        var nativeRng, fakeRng;
        nativeRng = editor.selection.getRng();
        fakeRng = {
          startContainer: nativeRng.startContainer,
          startOffset: nativeRng.startOffset,
          endContainer: nativeRng.endContainer,
          endOffset: nativeRng.endOffset
        };
        if (e.type === 'nodechange' || !$_aayq8q3zjh8lyx2z.isEq(fakeRng, lastRng)) {
          editor.fire('SelectionChange');
        }
        lastRng = fakeRng;
      });
    }
    editor.on('contextmenu', function () {
      editor.fire('SelectionChange');
    });
    editor.on('SelectionChange', function () {
      var startElm = editor.selection.getStart(true);
      if (!startElm || !$_9bpim8ajh8lyw68.range && editor.selection.isCollapsed()) {
        return;
      }
      if (hasAnyRanges(editor) && !isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
        editor.nodeChanged({ selectionChange: true });
      }
    });
    editor.on('MouseUp', function (e) {
      if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
        if (editor.selection.getNode().nodeName === 'IMG') {
          $_8sy3pfhjh8lyw95.setEditorTimeout(editor, function () {
            editor.nodeChanged();
          });
        } else {
          editor.nodeChanged();
        }
      }
    });
    this.nodeChanged = function (args) {
      var selection = editor.selection;
      var node, parents, root;
      if (editor.initialized && selection && !editor.settings.disable_nodechange && !editor.readonly) {
        root = editor.getBody();
        node = selection.getStart(true) || root;
        if (node.ownerDocument !== editor.getDoc() || !editor.dom.isChildOf(node, root)) {
          node = root;
        }
        parents = [];
        editor.dom.getParent(node, function (node) {
          if (node === root) {
            return true;
          }
          parents.push(node);
        });
        args = args || {};
        args.element = node;
        args.parents = parents;
        editor.fire('NodeChange', args);
      }
    };
  }

  var getAbsolutePosition = function (elm) {
    var doc, docElem, win, clientRect;
    clientRect = elm.getBoundingClientRect();
    doc = elm.ownerDocument;
    docElem = doc.documentElement;
    win = doc.defaultView;
    return {
      top: clientRect.top + win.pageYOffset - docElem.clientTop,
      left: clientRect.left + win.pageXOffset - docElem.clientLeft
    };
  };
  var getBodyPosition = function (editor) {
    return editor.inline ? getAbsolutePosition(editor.getBody()) : {
      left: 0,
      top: 0
    };
  };
  var getScrollPosition = function (editor) {
    var body = editor.getBody();
    return editor.inline ? {
      left: body.scrollLeft,
      top: body.scrollTop
    } : {
      left: 0,
      top: 0
    };
  };
  var getBodyScroll = function (editor) {
    var body = editor.getBody(), docElm = editor.getDoc().documentElement;
    var inlineScroll = {
      left: body.scrollLeft,
      top: body.scrollTop
    };
    var iframeScroll = {
      left: body.scrollLeft || docElm.scrollLeft,
      top: body.scrollTop || docElm.scrollTop
    };
    return editor.inline ? inlineScroll : iframeScroll;
  };
  var getMousePosition = function (editor, event) {
    if (event.target.ownerDocument !== editor.getDoc()) {
      var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
      var scrollPosition = getBodyScroll(editor);
      return {
        left: event.pageX - iframePosition.left + scrollPosition.left,
        top: event.pageY - iframePosition.top + scrollPosition.top
      };
    }
    return {
      left: event.pageX,
      top: event.pageY
    };
  };
  var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
    return {
      pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
      pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
    };
  };
  var calc = function (editor, event) {
    return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  };
  var $_car16w59jh8lyxa8 = { calc: calc };

  var isContentEditableFalse$7 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var isContentEditableTrue$4 = $_5oonaz1qjh8lywhz.isContentEditableTrue;
  var isDraggable = function (rootElm, elm) {
    return isContentEditableFalse$7(elm) && elm !== rootElm;
  };
  var isValidDropTarget = function (editor, targetElement, dragElement) {
    if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
      return false;
    }
    if (isContentEditableFalse$7(targetElement)) {
      return false;
    }
    return true;
  };
  var cloneElement = function (elm) {
    var cloneElm = elm.cloneNode(true);
    cloneElm.removeAttribute('data-mce-selected');
    return cloneElm;
  };
  var createGhost = function (editor, elm, width, height) {
    var clonedElm = elm.cloneNode(true);
    editor.dom.setStyles(clonedElm, {
      width: width,
      height: height
    });
    editor.dom.setAttrib(clonedElm, 'data-mce-selected', null);
    var ghostElm = editor.dom.create('div', {
      'class': 'mce-drag-container',
      'data-mce-bogus': 'all',
      'unselectable': 'on',
      'contenteditable': 'false'
    });
    editor.dom.setStyles(ghostElm, {
      position: 'absolute',
      opacity: 0.5,
      overflow: 'hidden',
      border: 0,
      padding: 0,
      margin: 0,
      width: width,
      height: height
    });
    editor.dom.setStyles(clonedElm, {
      margin: 0,
      boxSizing: 'border-box'
    });
    ghostElm.appendChild(clonedElm);
    return ghostElm;
  };
  var appendGhostToBody = function (ghostElm, bodyElm) {
    if (ghostElm.parentNode !== bodyElm) {
      bodyElm.appendChild(ghostElm);
    }
  };
  var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
    var overflowX = 0, overflowY = 0;
    ghostElm.style.left = position.pageX + 'px';
    ghostElm.style.top = position.pageY + 'px';
    if (position.pageX + width > maxX) {
      overflowX = position.pageX + width - maxX;
    }
    if (position.pageY + height > maxY) {
      overflowY = position.pageY + height - maxY;
    }
    ghostElm.style.width = width - overflowX + 'px';
    ghostElm.style.height = height - overflowY + 'px';
  };
  var removeElement = function (elm) {
    if (elm && elm.parentNode) {
      elm.parentNode.removeChild(elm);
    }
  };
  var isLeftMouseButtonPressed = function (e) {
    return e.button === 0;
  };
  var hasDraggableElement = function (state) {
    return state.element;
  };
  var applyRelPos = function (state, position) {
    return {
      pageX: position.pageX - state.relX,
      pageY: position.pageY + 5
    };
  };
  var start$1 = function (state, editor) {
    return function (e) {
      if (isLeftMouseButtonPressed(e)) {
        var ceElm = $_9tjm51ljh8lywbq.find(editor.dom.getParents(e.target), $_8aqzj925jh8lywmj.or(isContentEditableFalse$7, isContentEditableTrue$4));
        if (isDraggable(editor.getBody(), ceElm)) {
          var elmPos = editor.dom.getPos(ceElm);
          var bodyElm = editor.getBody();
          var docElm = editor.getDoc().documentElement;
          state.element = ceElm;
          state.screenX = e.screenX;
          state.screenY = e.screenY;
          state.maxX = (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2;
          state.maxY = (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2;
          state.relX = e.pageX - elmPos.x;
          state.relY = e.pageY - elmPos.y;
          state.width = ceElm.offsetWidth;
          state.height = ceElm.offsetHeight;
          state.ghost = createGhost(editor, ceElm, state.width, state.height);
        }
      }
    };
  };
  var move$1 = function (state, editor) {
    var throttledPlaceCaretAt = $_8sy3pfhjh8lyw95.throttle(function (clientX, clientY) {
      editor._selectionOverrides.hideFakeCaret();
      editor.selection.placeCaretAt(clientX, clientY);
    }, 0);
    return function (e) {
      var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
      if (hasDraggableElement(state) && !state.dragging && movement > 10) {
        var args = editor.fire('dragstart', { target: state.element });
        if (args.isDefaultPrevented()) {
          return;
        }
        state.dragging = true;
        editor.focus();
      }
      if (state.dragging) {
        var targetPos = applyRelPos(state, $_car16w59jh8lyxa8.calc(editor, e));
        appendGhostToBody(state.ghost, editor.getBody());
        moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
        throttledPlaceCaretAt(e.clientX, e.clientY);
      }
    };
  };
  var getRawTarget = function (selection) {
    var rng = selection.getSel().getRangeAt(0);
    var startContainer = rng.startContainer;
    return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  };
  var drop = function (state, editor) {
    return function (e) {
      if (state.dragging) {
        if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
          var targetClone_1 = cloneElement(state.element);
          var args = editor.fire('drop', {
            targetClone: targetClone_1,
            clientX: e.clientX,
            clientY: e.clientY
          });
          if (!args.isDefaultPrevented()) {
            targetClone_1 = args.targetClone;
            editor.undoManager.transact(function () {
              removeElement(state.element);
              editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
              editor._selectionOverrides.hideFakeCaret();
            });
          }
        }
      }
      removeDragState(state);
    };
  };
  var stop = function (state, editor) {
    return function () {
      if (state.dragging) {
        editor.fire('dragend');
      }
      removeDragState(state);
    };
  };
  var removeDragState = function (state) {
    state.dragging = false;
    state.element = null;
    removeElement(state.ghost);
  };
  var bindFakeDragEvents = function (editor) {
    var state = {};
    var pageDom, dragStartHandler, dragHandler, dropHandler, dragEndHandler, rootDocument;
    pageDom = DOMUtils$1.DOM;
    rootDocument = document;
    dragStartHandler = start$1(state, editor);
    dragHandler = move$1(state, editor);
    dropHandler = drop(state, editor);
    dragEndHandler = stop(state, editor);
    editor.on('mousedown', dragStartHandler);
    editor.on('mousemove', dragHandler);
    editor.on('mouseup', dropHandler);
    pageDom.bind(rootDocument, 'mousemove', dragHandler);
    pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
    editor.on('remove', function () {
      pageDom.unbind(rootDocument, 'mousemove', dragHandler);
      pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
    });
  };
  var blockIeDrop = function (editor) {
    editor.on('drop', function (e) {
      var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
      if (isContentEditableFalse$7(realTarget) || isContentEditableFalse$7(editor.dom.getContentEditableParent(realTarget))) {
        e.preventDefault();
      }
    });
  };
  var init = function (editor) {
    bindFakeDragEvents(editor);
    blockIeDrop(editor);
  };
  var $_8bbr0a58jh8lyxa1 = { init: init };

  var getNodeClientRects = function (node) {
    var toArrayWithNode = function (clientRects) {
      return $_9tjm51ljh8lywbq.map(clientRects, function (clientRect) {
        clientRect = clone$1(clientRect);
        clientRect.node = node;
        return clientRect;
      });
    };
    if ($_5oonaz1qjh8lywhz.isElement(node)) {
      return toArrayWithNode(node.getClientRects());
    }
    if ($_5oonaz1qjh8lywhz.isText(node)) {
      var rng = node.ownerDocument.createRange();
      rng.setStart(node, 0);
      rng.setEnd(node, node.data.length);
      return toArrayWithNode(rng.getClientRects());
    }
  };
  var getClientRects = function (node) {
    return $_9tjm51ljh8lywbq.reduce(node, function (result, node) {
      return result.concat(getNodeClientRects(node));
    }, []);
  };

  var VDirection;
  (function (VDirection) {
    VDirection[VDirection['Up'] = -1] = 'Up';
    VDirection[VDirection['Down'] = 1] = 'Down';
  }(VDirection || (VDirection = {})));
  var findUntil = function (direction, root, predicateFn, node) {
    while (node = findNode(node, direction, isEditableCaretCandidate, root)) {
      if (predicateFn(node)) {
        return;
      }
    }
  };
  var walkUntil = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
    var line = 0, node;
    var result = [];
    var targetClientRect;
    var add = function (node) {
      var i, clientRect, clientRects;
      clientRects = getClientRects([node]);
      if (direction === -1) {
        clientRects = clientRects.reverse();
      }
      for (i = 0; i < clientRects.length; i++) {
        clientRect = clientRects[i];
        if (isBeflowFn(clientRect, targetClientRect)) {
          continue;
        }
        if (result.length > 0 && isAboveFn(clientRect, $_9tjm51ljh8lywbq.last(result))) {
          line++;
        }
        clientRect.line = line;
        if (predicateFn(clientRect)) {
          return true;
        }
        result.push(clientRect);
      }
    };
    targetClientRect = $_9tjm51ljh8lywbq.last(caretPosition.getClientRects());
    if (!targetClientRect) {
      return result;
    }
    node = caretPosition.getNode();
    add(node);
    findUntil(direction, root, add, node);
    return result;
  };
  var aboveLineNumber = function (lineNumber, clientRect) {
    return clientRect.line > lineNumber;
  };
  var isLineNumber = function (lineNumber, clientRect) {
    return clientRect.line === lineNumber;
  };
  var upUntil = $_eqpqvr6jh8lyw3s.curry(walkUntil, VDirection.Up, isAbove, isBelow);
  var downUntil = $_eqpqvr6jh8lyw3s.curry(walkUntil, VDirection.Down, isBelow, isAbove);
  var positionsUntil = function (direction, root, predicateFn, node) {
    var caretWalker = CaretWalker(root);
    var walkFn, isBelowFn, isAboveFn, caretPosition;
    var result = [];
    var line = 0, clientRect, targetClientRect;
    var getClientRect = function (caretPosition) {
      if (direction === 1) {
        return $_9tjm51ljh8lywbq.last(caretPosition.getClientRects());
      }
      return $_9tjm51ljh8lywbq.last(caretPosition.getClientRects());
    };
    if (direction === 1) {
      walkFn = caretWalker.next;
      isBelowFn = isBelow;
      isAboveFn = isAbove;
      caretPosition = CaretPosition$1.after(node);
    } else {
      walkFn = caretWalker.prev;
      isBelowFn = isAbove;
      isAboveFn = isBelow;
      caretPosition = CaretPosition$1.before(node);
    }
    targetClientRect = getClientRect(caretPosition);
    do {
      if (!caretPosition.isVisible()) {
        continue;
      }
      clientRect = getClientRect(caretPosition);
      if (isAboveFn(clientRect, targetClientRect)) {
        continue;
      }
      if (result.length > 0 && isBelowFn(clientRect, $_9tjm51ljh8lywbq.last(result))) {
        line++;
      }
      clientRect = clone$1(clientRect);
      clientRect.position = caretPosition;
      clientRect.line = line;
      if (predicateFn(clientRect)) {
        return result;
      }
      result.push(clientRect);
    } while (caretPosition = walkFn(caretPosition));
    return result;
  };
  var isAboveLine = function (lineNumber) {
    return function (clientRect) {
      return aboveLineNumber(lineNumber, clientRect);
    };
  };
  var isLine = function (lineNumber) {
    return function (clientRect) {
      return isLineNumber(lineNumber, clientRect);
    };
  };

  var isContentEditableFalse$8 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var findNode$1 = findNode;
  var distanceToRectLeft = function (clientRect, clientX) {
    return Math.abs(clientRect.left - clientX);
  };
  var distanceToRectRight = function (clientRect, clientX) {
    return Math.abs(clientRect.right - clientX);
  };
  var isInside = function (clientX, clientRect) {
    return clientX >= clientRect.left && clientX <= clientRect.right;
  };
  var findClosestClientRect = function (clientRects, clientX) {
    return $_9tjm51ljh8lywbq.reduce(clientRects, function (oldClientRect, clientRect) {
      var oldDistance, newDistance;
      oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
      newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
      if (isInside(clientX, clientRect)) {
        return clientRect;
      }
      if (isInside(clientX, oldClientRect)) {
        return oldClientRect;
      }
      if (newDistance === oldDistance && isContentEditableFalse$8(clientRect.node)) {
        return clientRect;
      }
      if (newDistance < oldDistance) {
        return clientRect;
      }
      return oldClientRect;
    });
  };
  var walkUntil$1 = function (direction, root, predicateFn, node) {
    while (node = findNode$1(node, direction, isEditableCaretCandidate, root)) {
      if (predicateFn(node)) {
        return;
      }
    }
  };
  var findLineNodeRects = function (root, targetNodeRect) {
    var clientRects = [];
    var collect = function (checkPosFn, node) {
      var lineRects;
      lineRects = $_9tjm51ljh8lywbq.filter(getClientRects([node]), function (clientRect) {
        return !checkPosFn(clientRect, targetNodeRect);
      });
      clientRects = clientRects.concat(lineRects);
      return lineRects.length === 0;
    };
    clientRects.push(targetNodeRect);
    walkUntil$1(VDirection.Up, root, $_eqpqvr6jh8lyw3s.curry(collect, isAbove), targetNodeRect.node);
    walkUntil$1(VDirection.Down, root, $_eqpqvr6jh8lyw3s.curry(collect, isBelow), targetNodeRect.node);
    return clientRects;
  };
  var getFakeCaretTargets = function (root) {
    return $_9tjm51ljh8lywbq.filter($_9tjm51ljh8lywbq.toArray(root.getElementsByTagName('*')), isFakeCaretTarget);
  };
  var caretInfo = function (clientRect, clientX) {
    return {
      node: clientRect.node,
      before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
    };
  };
  var closestCaret = function (root, clientX, clientY) {
    var closestNodeRect;
    var contentEditableFalseNodeRects = getClientRects(getFakeCaretTargets(root));
    var targetNodeRects = $_9tjm51ljh8lywbq.filter(contentEditableFalseNodeRects, function (rect) {
      return clientY >= rect.top && clientY <= rect.bottom;
    });
    closestNodeRect = findClosestClientRect(targetNodeRects, clientX);
    if (closestNodeRect) {
      closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect), clientX);
      if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
        return caretInfo(closestNodeRect, clientX);
      }
    }
    return null;
  };

  var isXYWithinRange = function (clientX, clientY, range) {
    if (range.collapsed) {
      return false;
    }
    return $_5wjzy24jh8lyw2t.foldl(range.getClientRects(), function (state, rect) {
      return state || containsXY(rect, clientX, clientY);
    }, false);
  };
  var $_3kj84i5djh8lyxan = { isXYWithinRange: isXYWithinRange };

  var adaptable = function (fn, rate) {
    var timer = null;
    var args = null;
    var cancel = function () {
      if (timer !== null) {
        clearTimeout(timer);
        timer = null;
        args = null;
      }
    };
    var throttle = function () {
      args = arguments;
      if (timer === null) {
        timer = setTimeout(function () {
          fn.apply(null, args);
          timer = null;
          args = null;
        }, rate);
      }
    };
    return {
      cancel: cancel,
      throttle: throttle
    };
  };
  var first$3 = function (fn, rate) {
    var timer = null;
    var cancel = function () {
      if (timer !== null) {
        clearTimeout(timer);
        timer = null;
      }
    };
    var throttle = function () {
      var args = arguments;
      if (timer === null) {
        timer = setTimeout(function () {
          fn.apply(null, args);
          timer = null;
          args = null;
        }, rate);
      }
    };
    return {
      cancel: cancel,
      throttle: throttle
    };
  };
  var last$3 = function (fn, rate) {
    var timer = null;
    var cancel = function () {
      if (timer !== null) {
        clearTimeout(timer);
        timer = null;
      }
    };
    var throttle = function () {
      var args = arguments;
      if (timer !== null)
        clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(null, args);
        timer = null;
        args = null;
      }, rate);
    };
    return {
      cancel: cancel,
      throttle: throttle
    };
  };
  var $_de600j5fjh8lyxas = {
    adaptable: adaptable,
    first: first$3,
    last: last$3
  };

  var setup$1 = function (editor) {
    var renderFocusCaret = $_de600j5fjh8lyxas.first(function () {
      if (!editor.removed) {
        var rng = editor.selection.getRng();
        if (rng.collapsed) {
          var caretRange = renderRangeCaret(editor, editor.selection.getRng(), false);
          editor.selection.setRng(caretRange);
        }
      }
    }, 0);
    editor.on('focus', function () {
      renderFocusCaret.throttle();
    });
    editor.on('blur', function () {
      renderFocusCaret.cancel();
    });
  };
  var $_plloj5ejh8lyxap = { setup: setup$1 };

  var $_6lsk4i5gjh8lyxau = {
    BACKSPACE: 8,
    DELETE: 46,
    DOWN: 40,
    ENTER: 13,
    LEFT: 37,
    RIGHT: 39,
    SPACEBAR: 32,
    TAB: 9,
    UP: 38,
    modifierPressed: function (e) {
      return e.shiftKey || e.ctrlKey || e.altKey || this.metaKeyPressed(e);
    },
    metaKeyPressed: function (e) {
      return $_9bpim8ajh8lyw68.mac ? e.metaKey : e.ctrlKey && !e.altKey;
    }
  };

  var isContentEditableTrue$5 = $_5oonaz1qjh8lywhz.isContentEditableTrue;
  var isContentEditableFalse$9 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var isAfterContentEditableFalse$1 = isAfterContentEditableFalse;
  var isBeforeContentEditableFalse$1 = isBeforeContentEditableFalse;
  var getContentEditableRoot$1 = function (editor, node) {
    var root = editor.getBody();
    while (node && node !== root) {
      if (isContentEditableTrue$5(node) || isContentEditableFalse$9(node)) {
        return node;
      }
      node = node.parentNode;
    }
    return null;
  };
  var SelectionOverrides = function (editor) {
    var isBlock = function (node) {
      return editor.dom.isBlock(node);
    };
    var rootNode = editor.getBody();
    var fakeCaret = FakeCaret(editor.getBody(), isBlock, function () {
      return $_cnu79r4ejh8lyx4x.hasFocus(editor);
    });
    var realSelectionId = 'sel-' + editor.dom.uniqueId();
    var selectedContentEditableNode;
    var isFakeSelectionElement = function (elm) {
      return editor.dom.hasClass(elm, 'mce-offscreen-selection');
    };
    var getRealSelectionElement = function () {
      var container = editor.dom.get(realSelectionId);
      return container ? container.getElementsByTagName('*')[0] : container;
    };
    var setRange = function (range) {
      if (range) {
        editor.selection.setRng(range);
      }
    };
    var getRange = function () {
      return editor.selection.getRng();
    };
    var showCaret$$1 = function (direction, node, before, scrollIntoView) {
      if (scrollIntoView === void 0) {
        scrollIntoView = true;
      }
      var e;
      e = editor.fire('ShowCaret', {
        target: node,
        direction: direction,
        before: before
      });
      if (e.isDefaultPrevented()) {
        return null;
      }
      if (scrollIntoView) {
        editor.selection.scrollIntoView(node, direction === -1);
      }
      return fakeCaret.show(before, node);
    };
    var getNormalizedRangeEndPoint$$1 = function (direction, range) {
      range = normalizeRange(direction, rootNode, range);
      if (direction === -1) {
        return CaretPosition$1.fromRangeStart(range);
      }
      return CaretPosition$1.fromRangeEnd(range);
    };
    var showBlockCaretContainer = function (blockCaretContainer) {
      if (blockCaretContainer.hasAttribute('data-mce-caret')) {
        showCaretContainerBlock(blockCaretContainer);
        setRange(getRange());
        editor.selection.scrollIntoView(blockCaretContainer[0]);
      }
    };
    var registerEvents = function () {
      editor.on('mouseup', function (e) {
        var range = getRange();
        if (range.collapsed && $_7f1iw94jjh8lyx60.isXYInContentArea(editor, e.clientX, e.clientY)) {
          setRange(renderCaretAtRange(editor, range, false));
        }
      });
      editor.on('click', function (e) {
        var contentEditableRoot;
        contentEditableRoot = getContentEditableRoot$1(editor, e.target);
        if (contentEditableRoot) {
          if (isContentEditableFalse$9(contentEditableRoot)) {
            e.preventDefault();
            editor.focus();
          }
          if (isContentEditableTrue$5(contentEditableRoot)) {
            if (editor.dom.isChildOf(contentEditableRoot, editor.selection.getNode())) {
              removeContentEditableSelection();
            }
          }
        }
      });
      editor.on('blur NewBlock', function () {
        removeContentEditableSelection();
      });
      editor.on('ResizeWindow FullscreenStateChanged', function () {
        return fakeCaret.reposition();
      });
      var handleTouchSelect = function (editor) {
        var moved = false;
        editor.on('touchstart', function () {
          moved = false;
        });
        editor.on('touchmove', function () {
          moved = true;
        });
        editor.on('touchend', function (e) {
          var contentEditableRoot = getContentEditableRoot$1(editor, e.target);
          if (isContentEditableFalse$9(contentEditableRoot)) {
            if (!moved) {
              e.preventDefault();
              setContentEditableSelection(selectNode(editor, contentEditableRoot));
            }
          }
        });
      };
      var hasNormalCaretPosition = function (elm) {
        var caretWalker = CaretWalker(elm);
        if (!elm.firstChild) {
          return false;
        }
        var startPos = CaretPosition$1.before(elm.firstChild);
        var newPos = caretWalker.next(startPos);
        return newPos && !isBeforeContentEditableFalse$1(newPos) && !isAfterContentEditableFalse$1(newPos);
      };
      var isInSameBlock$$1 = function (node1, node2) {
        var block1 = editor.dom.getParent(node1, editor.dom.isBlock);
        var block2 = editor.dom.getParent(node2, editor.dom.isBlock);
        return block1 === block2;
      };
      var hasBetterMouseTarget = function (targetNode, caretNode) {
        var targetBlock = editor.dom.getParent(targetNode, editor.dom.isBlock);
        var caretBlock = editor.dom.getParent(caretNode, editor.dom.isBlock);
        if (targetBlock && editor.dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse$9(getContentEditableRoot$1(editor, targetBlock)) === false) {
          return true;
        }
        return targetBlock && !isInSameBlock$$1(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
      };
      handleTouchSelect(editor);
      editor.on('mousedown', function (e) {
        var contentEditableRoot;
        var targetElm = e.target;
        if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !editor.dom.isChildOf(targetElm, rootNode)) {
          return;
        }
        if ($_7f1iw94jjh8lyx60.isXYInContentArea(editor, e.clientX, e.clientY) === false) {
          return;
        }
        contentEditableRoot = getContentEditableRoot$1(editor, targetElm);
        if (contentEditableRoot) {
          if (isContentEditableFalse$9(contentEditableRoot)) {
            e.preventDefault();
            setContentEditableSelection(selectNode(editor, contentEditableRoot));
          } else {
            removeContentEditableSelection();
            if (!(isContentEditableTrue$5(contentEditableRoot) && e.shiftKey) && !$_3kj84i5djh8lyxan.isXYWithinRange(e.clientX, e.clientY, editor.selection.getRng())) {
              hideFakeCaret();
              editor.selection.placeCaretAt(e.clientX, e.clientY);
            }
          }
        } else if (isFakeCaretTarget(targetElm) === false) {
          removeContentEditableSelection();
          hideFakeCaret();
          var caretInfo = closestCaret(rootNode, e.clientX, e.clientY);
          if (caretInfo) {
            if (!hasBetterMouseTarget(e.target, caretInfo.node)) {
              e.preventDefault();
              var range = showCaret$$1(1, caretInfo.node, caretInfo.before, false);
              editor.getBody().focus();
              setRange(range);
            }
          }
        }
      });
      editor.on('keypress', function (e) {
        if ($_6lsk4i5gjh8lyxau.modifierPressed(e)) {
          return;
        }
        switch (e.keyCode) {
        default:
          if (isContentEditableFalse$9(editor.selection.getNode())) {
            e.preventDefault();
          }
          break;
        }
      });
      editor.on('getSelectionRange', function (e) {
        var rng = e.range;
        if (selectedContentEditableNode) {
          if (!selectedContentEditableNode.parentNode) {
            selectedContentEditableNode = null;
            return;
          }
          rng = rng.cloneRange();
          rng.selectNode(selectedContentEditableNode);
          e.range = rng;
        }
      });
      editor.on('setSelectionRange', function (e) {
        var rng;
        rng = setContentEditableSelection(e.range, e.forward);
        if (rng) {
          e.range = rng;
        }
      });
      editor.on('AfterSetSelectionRange', function (e) {
        var rng = e.range;
        if (!isRangeInCaretContainer(rng)) {
          hideFakeCaret();
        }
        if (!isFakeSelectionElement(rng.startContainer.parentNode)) {
          removeContentEditableSelection();
        }
      });
      editor.on('copy', function (e) {
        var clipboardData = e.clipboardData;
        if (!e.isDefaultPrevented() && e.clipboardData && !$_9bpim8ajh8lyw68.ie) {
          var realSelectionElement = getRealSelectionElement();
          if (realSelectionElement) {
            e.preventDefault();
            clipboardData.clearData();
            clipboardData.setData('text/html', realSelectionElement.outerHTML);
            clipboardData.setData('text/plain', realSelectionElement.outerText);
          }
        }
      });
      $_8bbr0a58jh8lyxa1.init(editor);
      $_plloj5ejh8lyxap.setup(editor);
    };
    var addCss = function () {
      var styles = editor.contentStyles, rootClass = '.mce-content-body';
      styles.push(fakeCaret.getCss());
      styles.push(rootClass + ' .mce-offscreen-selection {' + 'position: absolute;' + 'left: -9999999999px;' + 'max-width: 1000000px;' + '}' + rootClass + ' *[contentEditable=false] {' + 'cursor: default;' + '}' + rootClass + ' *[contentEditable=true] {' + 'cursor: text;' + '}');
    };
    var isWithinCaretContainer = function (node) {
      return isCaretContainer(node) || startsWithCaretContainer(node) || endsWithCaretContainer(node);
    };
    var isRangeInCaretContainer = function (rng) {
      return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
    };
    var setContentEditableSelection = function (range, forward) {
      var node;
      var $ = editor.$;
      var dom = editor.dom;
      var $realSelectionContainer, sel, startContainer, startOffset, endOffset, e, caretPosition, targetClone, origTargetClone;
      if (!range) {
        return null;
      }
      if (range.collapsed) {
        if (!isRangeInCaretContainer(range)) {
          if (forward === false) {
            caretPosition = getNormalizedRangeEndPoint$$1(-1, range);
            if (isFakeCaretTarget(caretPosition.getNode(true))) {
              return showCaret$$1(-1, caretPosition.getNode(true), false, false);
            }
            if (isFakeCaretTarget(caretPosition.getNode())) {
              return showCaret$$1(-1, caretPosition.getNode(), !caretPosition.isAtEnd(), false);
            }
          } else {
            caretPosition = getNormalizedRangeEndPoint$$1(1, range);
            if (isFakeCaretTarget(caretPosition.getNode())) {
              return showCaret$$1(1, caretPosition.getNode(), !caretPosition.isAtEnd(), false);
            }
            if (isFakeCaretTarget(caretPosition.getNode(true))) {
              return showCaret$$1(1, caretPosition.getNode(true), false, false);
            }
          }
        }
        return null;
      }
      startContainer = range.startContainer;
      startOffset = range.startOffset;
      endOffset = range.endOffset;
      if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse$9(startContainer.parentNode)) {
        startContainer = startContainer.parentNode;
        startOffset = dom.nodeIndex(startContainer);
        startContainer = startContainer.parentNode;
      }
      if (startContainer.nodeType !== 1) {
        return null;
      }
      if (endOffset === startOffset + 1) {
        node = startContainer.childNodes[startOffset];
      }
      if (!isContentEditableFalse$9(node)) {
        return null;
      }
      targetClone = origTargetClone = node.cloneNode(true);
      e = editor.fire('ObjectSelected', {
        target: node,
        targetClone: targetClone
      });
      if (e.isDefaultPrevented()) {
        return null;
      }
      $realSelectionContainer = $_7sg18r3cjh8lywu1.descendant($_cgttw3zjh8lywdq.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
        return $([]);
      }, function (elm) {
        return $([elm.dom()]);
      });
      targetClone = e.targetClone;
      if ($realSelectionContainer.length === 0) {
        $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
        $realSelectionContainer.appendTo(editor.getBody());
      }
      range = editor.dom.createRng();
      if (targetClone === origTargetClone && $_9bpim8ajh8lyw68.ie) {
        $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
        range.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
        range.setEndAfter(targetClone);
      } else {
        $realSelectionContainer.empty().append('\xA0').append(targetClone).append('\xA0');
        range.setStart($realSelectionContainer[0].firstChild, 1);
        range.setEnd($realSelectionContainer[0].lastChild, 0);
      }
      $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
      $realSelectionContainer[0].focus();
      sel = editor.selection.getSel();
      sel.removeAllRanges();
      sel.addRange(range);
      $_5wjzy24jh8lyw2t.each($_eebxu2gjh8lywp3.descendants($_cgttw3zjh8lywdq.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
        $_3da62i14jh8lyweo.remove(elm, 'data-mce-selected');
      });
      node.setAttribute('data-mce-selected', '1');
      selectedContentEditableNode = node;
      hideFakeCaret();
      return range;
    };
    var removeContentEditableSelection = function () {
      if (selectedContentEditableNode) {
        selectedContentEditableNode.removeAttribute('data-mce-selected');
      }
      $_7sg18r3cjh8lywu1.descendant($_cgttw3zjh8lywdq.fromDom(editor.getBody()), '#' + realSelectionId).each($_bfmuql2ujh8lywr1.remove);
      selectedContentEditableNode = null;
    };
    var destroy = function () {
      fakeCaret.destroy();
      selectedContentEditableNode = null;
    };
    var hideFakeCaret = function () {
      fakeCaret.hide();
    };
    if ($_9bpim8ajh8lyw68.ceFalse) {
      registerEvents();
      addCss();
    }
    return {
      showCaret: showCaret$$1,
      showBlockCaretContainer: showBlockCaretContainer,
      hideFakeCaret: hideFakeCaret,
      destroy: destroy
    };
  };

  var isValidPrefixAttrName = function (name) {
    return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  };
  var trimComments = function (text) {
    return text.replace(/<!--|-->/g, '');
  };
  var isInvalidUri = function (settings, uri) {
    if (settings.allow_html_data_urls) {
      return false;
    } else if (/^data:image\//i.test(uri)) {
      return settings.allow_svg_data_urls === false && /^data:image\/svg\+xml/i.test(uri);
    } else {
      return /^data:/i.test(uri);
    }
  };
  var findEndTagIndex = function (schema, html, startIndex) {
    var count = 1, index, matches, tokenRegExp, shortEndedElements;
    shortEndedElements = schema.getShortEndedElements();
    tokenRegExp = /<([!?\/])?([A-Za-z0-9\-_\:\.]+)((?:\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\/|\s+)>/g;
    tokenRegExp.lastIndex = index = startIndex;
    while (matches = tokenRegExp.exec(html)) {
      index = tokenRegExp.lastIndex;
      if (matches[1] === '/') {
        count--;
      } else if (!matches[1]) {
        if (matches[2] in shortEndedElements) {
          continue;
        }
        count++;
      }
      if (count === 0) {
        break;
      }
    }
    return index;
  };
  function SaxParser(settings, schema) {
    if (schema === void 0) {
      schema = Schema();
    }
    var noop = function () {
    };
    settings = settings || {};
    if (settings.fix_self_closing !== false) {
      settings.fix_self_closing = true;
    }
    var comment = settings.comment ? settings.comment : noop;
    var cdata = settings.cdata ? settings.cdata : noop;
    var text = settings.text ? settings.text : noop;
    var start = settings.start ? settings.start : noop;
    var end = settings.end ? settings.end : noop;
    var pi = settings.pi ? settings.pi : noop;
    var doctype = settings.doctype ? settings.doctype : noop;
    var parse = function (html) {
      var matches, index = 0, value, endRegExp;
      var stack = [];
      var attrList, i, textData, name;
      var isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded;
      var validate, elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
      var attributesRequired, attributesDefault, attributesForced, processHtml;
      var anyAttributesRequired, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0;
      var decode = $_gex7a11rjh8lywi4.decode;
      var fixSelfClosing;
      var filteredUrlAttrs = $_ahowuxkjh8lywbj.makeMap('src,href,data,background,formaction,poster,xlink:href');
      var scriptUriRegExp = /((java|vb)script|mhtml):/i;
      var processEndTag = function (name) {
        var pos, i;
        pos = stack.length;
        while (pos--) {
          if (stack[pos].name === name) {
            break;
          }
        }
        if (pos >= 0) {
          for (i = stack.length - 1; i >= pos; i--) {
            name = stack[i];
            if (name.valid) {
              end(name.name);
            }
          }
          stack.length = pos;
        }
      };
      var parseAttribute = function (match, name, value, val2, val3) {
        var attrRule, i;
        var trimRegExp = /[\s\u0000-\u001F]+/g;
        name = name.toLowerCase();
        value = name in fillAttrsMap ? name : decode(value || val2 || val3 || '');
        if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
          attrRule = validAttributesMap[name];
          if (!attrRule && validAttributePatterns) {
            i = validAttributePatterns.length;
            while (i--) {
              attrRule = validAttributePatterns[i];
              if (attrRule.pattern.test(name)) {
                break;
              }
            }
            if (i === -1) {
              attrRule = null;
            }
          }
          if (!attrRule) {
            return;
          }
          if (attrRule.validValues && !(value in attrRule.validValues)) {
            return;
          }
        }
        if (filteredUrlAttrs[name] && !settings.allow_script_urls) {
          var uri = value.replace(trimRegExp, '');
          try {
            uri = decodeURIComponent(uri);
          } catch (ex) {
            uri = unescape(uri);
          }
          if (scriptUriRegExp.test(uri)) {
            return;
          }
          if (isInvalidUri(settings, uri)) {
            return;
          }
        }
        if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
          return;
        }
        attrList.map[name] = value;
        attrList.push({
          name: name,
          value: value
        });
      };
      tokenRegExp = new RegExp('<(?:' + '(?:!--([\\w\\W]*?)-->)|' + '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + '(?:!DOCTYPE([\\w\\W]*?)>)|' + '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + '(?:\\/([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)>)|' + '(?:([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/|\\s+)>)' + ')', 'g');
      attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
      shortEndedElements = schema.getShortEndedElements();
      selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
      fillAttrsMap = schema.getBoolAttrs();
      validate = settings.validate;
      removeInternalElements = settings.remove_internals;
      fixSelfClosing = settings.fix_self_closing;
      specialElements = schema.getSpecialElements();
      processHtml = html + '>';
      while (matches = tokenRegExp.exec(processHtml)) {
        if (index < matches.index) {
          text(decode(html.substr(index, matches.index - index)));
        }
        if (value = matches[6]) {
          value = value.toLowerCase();
          if (value.charAt(0) === ':') {
            value = value.substr(1);
          }
          processEndTag(value);
        } else if (value = matches[7]) {
          if (matches.index + matches[0].length > html.length) {
            text(decode(html.substr(matches.index)));
            index = matches.index + matches[0].length;
            continue;
          }
          value = value.toLowerCase();
          if (value.charAt(0) === ':') {
            value = value.substr(1);
          }
          isShortEnded = value in shortEndedElements;
          if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
            processEndTag(value);
          }
          if (!validate || (elementRule = schema.getElementRule(value))) {
            isValidElement = true;
            if (validate) {
              validAttributesMap = elementRule.attributes;
              validAttributePatterns = elementRule.attributePatterns;
            }
            if (attribsValue = matches[8]) {
              isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
              if (isInternalElement && removeInternalElements) {
                isValidElement = false;
              }
              attrList = [];
              attrList.map = {};
              attribsValue.replace(attrRegExp, parseAttribute);
            } else {
              attrList = [];
              attrList.map = {};
            }
            if (validate && !isInternalElement) {
              attributesRequired = elementRule.attributesRequired;
              attributesDefault = elementRule.attributesDefault;
              attributesForced = elementRule.attributesForced;
              anyAttributesRequired = elementRule.removeEmptyAttrs;
              if (anyAttributesRequired && !attrList.length) {
                isValidElement = false;
              }
              if (attributesForced) {
                i = attributesForced.length;
                while (i--) {
                  attr = attributesForced[i];
                  name = attr.name;
                  attrValue = attr.value;
                  if (attrValue === '{$uid}') {
                    attrValue = 'mce_' + idCount++;
                  }
                  attrList.map[name] = attrValue;
                  attrList.push({
                    name: name,
                    value: attrValue
                  });
                }
              }
              if (attributesDefault) {
                i = attributesDefault.length;
                while (i--) {
                  attr = attributesDefault[i];
                  name = attr.name;
                  if (!(name in attrList.map)) {
                    attrValue = attr.value;
                    if (attrValue === '{$uid}') {
                      attrValue = 'mce_' + idCount++;
                    }
                    attrList.map[name] = attrValue;
                    attrList.push({
                      name: name,
                      value: attrValue
                    });
                  }
                }
              }
              if (attributesRequired) {
                i = attributesRequired.length;
                while (i--) {
                  if (attributesRequired[i] in attrList.map) {
                    break;
                  }
                }
                if (i === -1) {
                  isValidElement = false;
                }
              }
              if (attr = attrList.map['data-mce-bogus']) {
                if (attr === 'all') {
                  index = findEndTagIndex(schema, html, tokenRegExp.lastIndex);
                  tokenRegExp.lastIndex = index;
                  continue;
                }
                isValidElement = false;
              }
            }
            if (isValidElement) {
              start(value, attrList, isShortEnded);
            }
          } else {
            isValidElement = false;
          }
          if (endRegExp = specialElements[value]) {
            endRegExp.lastIndex = index = matches.index + matches[0].length;
            if (matches = endRegExp.exec(html)) {
              if (isValidElement) {
                textData = html.substr(index, matches.index - index);
              }
              index = matches.index + matches[0].length;
            } else {
              textData = html.substr(index);
              index = html.length;
            }
            if (isValidElement) {
              if (textData.length > 0) {
                text(textData, true);
              }
              end(value);
            }
            tokenRegExp.lastIndex = index;
            continue;
          }
          if (!isShortEnded) {
            if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
              stack.push({
                name: value,
                valid: isValidElement
              });
            } else if (isValidElement) {
              end(value);
            }
          }
        } else if (value = matches[1]) {
          if (value.charAt(0) === '>') {
            value = ' ' + value;
          }
          if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
            value = ' ' + value;
          }
          comment(value);
        } else if (value = matches[2]) {
          cdata(trimComments(value));
        } else if (value = matches[3]) {
          doctype(value);
        } else if (value = matches[4]) {
          pi(value, matches[5]);
        }
        index = matches.index + matches[0].length;
      }
      if (index < html.length) {
        text(decode(html.substr(index)));
      }
      for (i = stack.length - 1; i >= 0; i--) {
        value = stack[i];
        if (value.valid) {
          end(value.name);
        }
      }
    };
    return { parse: parse };
  }
  (function (SaxParser) {
    SaxParser.findEndTag = findEndTagIndex;
  }(SaxParser || (SaxParser = {})));
  var SaxParser$1 = SaxParser;

  var trimHtml = function (tempAttrs, html) {
    var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
    return html.replace(trimContentRegExp, '');
  };
  var trimInternal = function (serializer, html) {
    var content = html;
    var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
    var endTagIndex, index, matchLength, matches, shortEndedElements;
    var schema = serializer.schema;
    content = trimHtml(serializer.getTempAttrs(), content);
    shortEndedElements = schema.getShortEndedElements();
    while (matches = bogusAllRegExp.exec(content)) {
      index = bogusAllRegExp.lastIndex;
      matchLength = matches[0].length;
      if (shortEndedElements[matches[1]]) {
        endTagIndex = index;
      } else {
        endTagIndex = SaxParser$1.findEndTag(schema, content, index);
      }
      content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
      bogusAllRegExp.lastIndex = index - matchLength;
    }
    return $_d383mr21jh8lywlv.trim(content);
  };
  var trimExternal = trimInternal;
  var $_8lol015jjh8lyxbf = {
    trimExternal: trimExternal,
    trimInternal: trimInternal
  };

  var KEEP = 0;
  var INSERT = 1;
  var DELETE = 2;
  var diff = function (left, right) {
    var size = left.length + right.length + 2;
    var vDown = new Array(size);
    var vUp = new Array(size);
    var snake = function (start, end, diag) {
      return {
        start: start,
        end: end,
        diag: diag
      };
    };
    var buildScript = function (start1, end1, start2, end2, script) {
      var middle = getMiddleSnake(start1, end1, start2, end2);
      if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
        var i = start1;
        var j = start2;
        while (i < end1 || j < end2) {
          if (i < end1 && j < end2 && left[i] === right[j]) {
            script.push([
              KEEP,
              left[i]
            ]);
            ++i;
            ++j;
          } else {
            if (end1 - start1 > end2 - start2) {
              script.push([
                DELETE,
                left[i]
              ]);
              ++i;
            } else {
              script.push([
                INSERT,
                right[j]
              ]);
              ++j;
            }
          }
        }
      } else {
        buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
        for (var i2 = middle.start; i2 < middle.end; ++i2) {
          script.push([
            KEEP,
            left[i2]
          ]);
        }
        buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
      }
    };
    var buildSnake = function (start, diag, end1, end2) {
      var end = start;
      while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
        ++end;
      }
      return snake(start, end, diag);
    };
    var getMiddleSnake = function (start1, end1, start2, end2) {
      var m = end1 - start1;
      var n = end2 - start2;
      if (m === 0 || n === 0) {
        return null;
      }
      var delta = m - n;
      var sum = n + m;
      var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
      vDown[1 + offset] = start1;
      vUp[1 + offset] = end1 + 1;
      var d, k, i, x, y;
      for (d = 0; d <= offset; ++d) {
        for (k = -d; k <= d; k += 2) {
          i = k + offset;
          if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
            vDown[i] = vDown[i + 1];
          } else {
            vDown[i] = vDown[i - 1] + 1;
          }
          x = vDown[i];
          y = x - start1 + start2 - k;
          while (x < end1 && y < end2 && left[x] === right[y]) {
            vDown[i] = ++x;
            ++y;
          }
          if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
            if (vUp[i - delta] <= vDown[i]) {
              return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
            }
          }
        }
        for (k = delta - d; k <= delta + d; k += 2) {
          i = k + offset - delta;
          if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
            vUp[i] = vUp[i + 1] - 1;
          } else {
            vUp[i] = vUp[i - 1];
          }
          x = vUp[i] - 1;
          y = x - start1 + start2 - k;
          while (x >= start1 && y >= start2 && left[x] === right[y]) {
            vUp[i] = x--;
            y--;
          }
          if (delta % 2 === 0 && -d <= k && k <= d) {
            if (vUp[i] <= vDown[i + delta]) {
              return buildSnake(vUp[i], k + start1 - start2, end1, end2);
            }
          }
        }
      }
    };
    var script = [];
    buildScript(0, left.length, 0, right.length, script);
    return script;
  };
  var $_5dhayi5mjh8lyxc5 = {
    KEEP: KEEP,
    DELETE: DELETE,
    INSERT: INSERT,
    diff: diff
  };

  var getOuterHtml = function (elm) {
    if ($_5oonaz1qjh8lywhz.isElement(elm)) {
      return elm.outerHTML;
    } else if ($_5oonaz1qjh8lywhz.isText(elm)) {
      return $_gex7a11rjh8lywi4.encodeRaw(elm.data, false);
    } else if ($_5oonaz1qjh8lywhz.isComment(elm)) {
      return '<!--' + elm.data + '-->';
    }
    return '';
  };
  var createFragment$1 = function (html) {
    var frag, node, container;
    container = document.createElement('div');
    frag = document.createDocumentFragment();
    if (html) {
      container.innerHTML = html;
    }
    while (node = container.firstChild) {
      frag.appendChild(node);
    }
    return frag;
  };
  var insertAt = function (elm, html, index) {
    var fragment = createFragment$1(html);
    if (elm.hasChildNodes() && index < elm.childNodes.length) {
      var target = elm.childNodes[index];
      target.parentNode.insertBefore(fragment, target);
    } else {
      elm.appendChild(fragment);
    }
  };
  var removeAt = function (elm, index) {
    if (elm.hasChildNodes() && index < elm.childNodes.length) {
      var target = elm.childNodes[index];
      target.parentNode.removeChild(target);
    }
  };
  var applyDiff = function (diff, elm) {
    var index = 0;
    $_9tjm51ljh8lywbq.each(diff, function (action) {
      if (action[0] === $_5dhayi5mjh8lyxc5.KEEP) {
        index++;
      } else if (action[0] === $_5dhayi5mjh8lyxc5.INSERT) {
        insertAt(elm, action[1], index);
        index++;
      } else if (action[0] === $_5dhayi5mjh8lyxc5.DELETE) {
        removeAt(elm, index);
      }
    });
  };
  var read$3 = function (elm) {
    return $_9tjm51ljh8lywbq.filter($_9tjm51ljh8lywbq.map(elm.childNodes, getOuterHtml), function (item) {
      return item.length > 0;
    });
  };
  var write = function (fragments, elm) {
    var currentFragments = $_9tjm51ljh8lywbq.map(elm.childNodes, getOuterHtml);
    applyDiff($_5dhayi5mjh8lyxc5.diff(currentFragments, fragments), elm);
    return elm;
  };
  var $_9x5cnf5ljh8lyxc2 = {
    read: read$3,
    write: write
  };

  var fromHtml$1 = function (html, scope) {
    var doc = scope || document;
    var div = doc.createElement('div');
    div.innerHTML = html;
    return $_a43q0i17jh8lywfe.children($_cgttw3zjh8lywdq.fromDom(div));
  };
  var fromTags = function (tags, scope) {
    return $_5wjzy24jh8lyw2t.map(tags, function (x) {
      return $_cgttw3zjh8lywdq.fromTag(x, scope);
    });
  };
  var fromText$1 = function (texts, scope) {
    return $_5wjzy24jh8lyw2t.map(texts, function (x) {
      return $_cgttw3zjh8lywdq.fromText(x, scope);
    });
  };
  var fromDom$1 = function (nodes) {
    return $_5wjzy24jh8lyw2t.map(nodes, $_cgttw3zjh8lywdq.fromDom);
  };
  var $_egn65r5ojh8lyxcb = {
    fromHtml: fromHtml$1,
    fromTags: fromTags,
    fromText: fromText$1,
    fromDom: fromDom$1
  };

  var get$5 = function (element) {
    return element.dom().innerHTML;
  };
  var set$3 = function (element, content) {
    var owner = $_a43q0i17jh8lywfe.owner(element);
    var docDom = owner.dom();
    var fragment = $_cgttw3zjh8lywdq.fromDom(docDom.createDocumentFragment());
    var contentElements = $_egn65r5ojh8lyxcb.fromHtml(content, docDom);
    $_9hl8mu2vjh8lywr4.append(fragment, contentElements);
    $_bfmuql2ujh8lywr1.empty(element);
    $_4m7u2e2kjh8lywpi.append(element, fragment);
  };
  var getOuter = function (element) {
    var container = $_cgttw3zjh8lywdq.fromTag('div');
    var clone = $_cgttw3zjh8lywdq.fromDom(element.dom().cloneNode(true));
    $_4m7u2e2kjh8lywpi.append(container, clone);
    return get$5(container);
  };
  var $_cxg0x95njh8lyxc9 = {
    get: get$5,
    set: set$3,
    getOuter: getOuter
  };

  var undoLevelDocument = Cell(Option.none());
  var lazyTempDocument = function () {
    return undoLevelDocument.get().getOrThunk(function () {
      var doc = document.implementation.createHTMLDocument('undo');
      undoLevelDocument.set(Option.some(doc));
      return doc;
    });
  };
  var hasIframes = function (html) {
    return html.indexOf('</iframe>') !== -1;
  };
  var createFragmentedLevel = function (fragments) {
    return {
      type: 'fragmented',
      fragments: fragments,
      content: '',
      bookmark: null,
      beforeBookmark: null
    };
  };
  var createCompleteLevel = function (content) {
    return {
      type: 'complete',
      fragments: null,
      content: content,
      bookmark: null,
      beforeBookmark: null
    };
  };
  var createFromEditor = function (editor) {
    var fragments, content, trimmedFragments;
    fragments = $_9x5cnf5ljh8lyxc2.read(editor.getBody());
    trimmedFragments = $_5wjzy24jh8lyw2t.bind(fragments, function (html) {
      var trimmed = $_8lol015jjh8lyxbf.trimInternal(editor.serializer, html);
      return trimmed.length > 0 ? [trimmed] : [];
    });
    content = trimmedFragments.join('');
    return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  };
  var applyToEditor = function (editor, level, before) {
    if (level.type === 'fragmented') {
      $_9x5cnf5ljh8lyxc2.write(level.fragments, editor.getBody());
    } else {
      editor.setContent(level.content, { format: 'raw' });
    }
    editor.selection.moveToBookmark(before ? level.beforeBookmark : level.bookmark);
  };
  var getLevelContent = function (level) {
    return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  };
  var getCleanLevelContent = function (level) {
    var elm = $_cgttw3zjh8lywdq.fromTag('body', lazyTempDocument());
    $_cxg0x95njh8lyxc9.set(elm, getLevelContent(level));
    $_5wjzy24jh8lyw2t.each($_eebxu2gjh8lywp3.descendants(elm, '*[data-mce-bogus]'), $_bfmuql2ujh8lywr1.unwrap);
    return $_cxg0x95njh8lyxc9.get(elm);
  };
  var hasEqualContent = function (level1, level2) {
    return getLevelContent(level1) === getLevelContent(level2);
  };
  var hasEqualCleanedContent = function (level1, level2) {
    return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  };
  var isEq$2 = function (level1, level2) {
    if (!level1 || !level2) {
      return false;
    } else if (hasEqualContent(level1, level2)) {
      return true;
    } else {
      return hasEqualCleanedContent(level1, level2);
    }
  };
  var $_dxjj465ijh8lyxb4 = {
    createFragmentedLevel: createFragmentedLevel,
    createCompleteLevel: createCompleteLevel,
    createFromEditor: createFromEditor,
    applyToEditor: applyToEditor,
    isEq: isEq$2
  };

  function UndoManager (editor) {
    var self = this, index = 0, data = [], beforeBookmark, isFirstTypedCharacter, locks = 0;
    var isUnlocked = function () {
      return locks === 0;
    };
    var setTyping = function (typing) {
      if (isUnlocked()) {
        self.typing = typing;
      }
    };
    var setDirty = function (state) {
      editor.setDirty(state);
    };
    var addNonTypingUndoLevel = function (e) {
      setTyping(false);
      self.add({}, e);
    };
    var endTyping = function () {
      if (self.typing) {
        setTyping(false);
        self.add();
      }
    };
    editor.on('init', function () {
      self.add();
    });
    editor.on('BeforeExecCommand', function (e) {
      var cmd = e.command;
      if (cmd !== 'Undo' && cmd !== 'Redo' && cmd !== 'mceRepaint') {
        endTyping();
        self.beforeChange();
      }
    });
    editor.on('ExecCommand', function (e) {
      var cmd = e.command;
      if (cmd !== 'Undo' && cmd !== 'Redo' && cmd !== 'mceRepaint') {
        addNonTypingUndoLevel(e);
      }
    });
    editor.on('ObjectResizeStart Cut', function () {
      self.beforeChange();
    });
    editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
    editor.on('DragEnd', addNonTypingUndoLevel);
    editor.on('KeyUp', function (e) {
      var keyCode = e.keyCode;
      if (e.isDefaultPrevented()) {
        return;
      }
      if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
        addNonTypingUndoLevel();
        editor.nodeChanged();
      }
      if (keyCode === 46 || keyCode === 8) {
        editor.nodeChanged();
      }
      if (isFirstTypedCharacter && self.typing && $_dxjj465ijh8lyxb4.isEq($_dxjj465ijh8lyxb4.createFromEditor(editor), data[0]) === false) {
        if (editor.isDirty() === false) {
          setDirty(true);
          editor.fire('change', {
            level: data[0],
            lastLevel: null
          });
        }
        editor.fire('TypingUndo');
        isFirstTypedCharacter = false;
        editor.nodeChanged();
      }
    });
    editor.on('KeyDown', function (e) {
      var keyCode = e.keyCode;
      if (e.isDefaultPrevented()) {
        return;
      }
      if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
        if (self.typing) {
          addNonTypingUndoLevel(e);
        }
        return;
      }
      var modKey = e.ctrlKey && !e.altKey || e.metaKey;
      if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !self.typing && !modKey) {
        self.beforeChange();
        setTyping(true);
        self.add({}, e);
        isFirstTypedCharacter = true;
      }
    });
    editor.on('MouseDown', function (e) {
      if (self.typing) {
        addNonTypingUndoLevel(e);
      }
    });
    var isInsertReplacementText = function (event) {
      return event.inputType === 'insertReplacementText';
    };
    var isInsertTextDataNull = function (event) {
      return event.inputType === 'insertText' && event.data === null;
    };
    editor.on('input', function (e) {
      if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e))) {
        addNonTypingUndoLevel(e);
      }
    });
    editor.addShortcut('meta+z', '', 'Undo');
    editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
    editor.on('AddUndo Undo Redo ClearUndos', function (e) {
      if (!e.isDefaultPrevented()) {
        editor.nodeChanged();
      }
    });
    self = {
      data: data,
      typing: false,
      beforeChange: function () {
        if (isUnlocked()) {
          beforeBookmark = $_8b82yg2ojh8lywpq.getUndoBookmark(editor.selection);
        }
      },
      add: function (level, event) {
        var i;
        var settings = editor.settings;
        var lastLevel, currentLevel;
        currentLevel = $_dxjj465ijh8lyxb4.createFromEditor(editor);
        level = level || {};
        level = $_ahowuxkjh8lywbj.extend(level, currentLevel);
        if (isUnlocked() === false || editor.removed) {
          return null;
        }
        lastLevel = data[index];
        if (editor.fire('BeforeAddUndo', {
            level: level,
            lastLevel: lastLevel,
            originalEvent: event
          }).isDefaultPrevented()) {
          return null;
        }
        if (lastLevel && $_dxjj465ijh8lyxb4.isEq(lastLevel, level)) {
          return null;
        }
        if (data[index]) {
          data[index].beforeBookmark = beforeBookmark;
        }
        if (settings.custom_undo_redo_levels) {
          if (data.length > settings.custom_undo_redo_levels) {
            for (i = 0; i < data.length - 1; i++) {
              data[i] = data[i + 1];
            }
            data.length--;
            index = data.length;
          }
        }
        level.bookmark = $_8b82yg2ojh8lywpq.getUndoBookmark(editor.selection);
        if (index < data.length - 1) {
          data.length = index + 1;
        }
        data.push(level);
        index = data.length - 1;
        var args = {
          level: level,
          lastLevel: lastLevel,
          originalEvent: event
        };
        editor.fire('AddUndo', args);
        if (index > 0) {
          setDirty(true);
          editor.fire('change', args);
        }
        return level;
      },
      undo: function () {
        var level;
        if (self.typing) {
          self.add();
          self.typing = false;
          setTyping(false);
        }
        if (index > 0) {
          level = data[--index];
          $_dxjj465ijh8lyxb4.applyToEditor(editor, level, true);
          setDirty(true);
          editor.fire('undo', { level: level });
        }
        return level;
      },
      redo: function () {
        var level;
        if (index < data.length - 1) {
          level = data[++index];
          $_dxjj465ijh8lyxb4.applyToEditor(editor, level, false);
          setDirty(true);
          editor.fire('redo', { level: level });
        }
        return level;
      },
      clear: function () {
        data = [];
        index = 0;
        self.typing = false;
        self.data = data;
        editor.fire('ClearUndos');
      },
      hasUndo: function () {
        return index > 0 || self.typing && data[0] && !$_dxjj465ijh8lyxb4.isEq($_dxjj465ijh8lyxb4.createFromEditor(editor), data[0]);
      },
      hasRedo: function () {
        return index < data.length - 1 && !self.typing;
      },
      transact: function (callback) {
        endTyping();
        self.beforeChange();
        self.ignore(callback);
        return self.add();
      },
      ignore: function (callback) {
        try {
          locks++;
          callback();
        } finally {
          locks--;
        }
      },
      extra: function (callback1, callback2) {
        var lastLevel, bookmark;
        if (self.transact(callback1)) {
          bookmark = data[index].bookmark;
          lastLevel = data[index - 1];
          $_dxjj465ijh8lyxb4.applyToEditor(editor, lastLevel, true);
          if (self.transact(callback2)) {
            data[index - 1].beforeBookmark = bookmark;
          }
        }
      }
    };
    return self;
  }

  var isInlineBlock = function (node) {
    return node && /^(IMG)$/.test(node.nodeName);
  };
  var moveStart = function (dom, selection, rng) {
    var offset = rng.startOffset;
    var container = rng.startContainer, walker, node, nodes;
    if (rng.startContainer === rng.endContainer) {
      if (isInlineBlock(rng.startContainer.childNodes[rng.startOffset])) {
        return;
      }
    }
    if (container.nodeType === 1) {
      nodes = container.childNodes;
      if (offset < nodes.length) {
        container = nodes[offset];
        walker = new TreeWalker(container, dom.getParent(container, dom.isBlock));
      } else {
        container = nodes[nodes.length - 1];
        walker = new TreeWalker(container, dom.getParent(container, dom.isBlock));
        walker.next(true);
      }
      for (node = walker.current(); node; node = walker.next()) {
        if (node.nodeType === 3 && !isWhiteSpaceNode(node)) {
          rng.setStart(node, 0);
          selection.setRng(rng);
          return;
        }
      }
    }
  };
  var getNonWhiteSpaceSibling = function (node, next, inc) {
    if (node) {
      next = next ? 'nextSibling' : 'previousSibling';
      for (node = inc ? node : node[next]; node; node = node[next]) {
        if (node.nodeType === 1 || !isWhiteSpaceNode(node)) {
          return node;
        }
      }
    }
  };
  var isTextBlock$1 = function (editor, name) {
    if (name.nodeType) {
      name = name.nodeName;
    }
    return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  };
  var isValid = function (ed, parent, child) {
    return ed.schema.isValidChild(parent, child);
  };
  var isWhiteSpaceNode = function (node) {
    return node && node.nodeType === 3 && /^([\t \r\n]+|)$/.test(node.nodeValue);
  };
  var replaceVars = function (value, vars) {
    if (typeof value !== 'string') {
      value = value(vars);
    } else if (vars) {
      value = value.replace(/%(\w+)/g, function (str, name) {
        return vars[name] || str;
      });
    }
    return value;
  };
  var isEq$3 = function (str1, str2) {
    str1 = str1 || '';
    str2 = str2 || '';
    str1 = '' + (str1.nodeName || str1);
    str2 = '' + (str2.nodeName || str2);
    return str1.toLowerCase() === str2.toLowerCase();
  };
  var normalizeStyleValue = function (dom, value, name) {
    if (name === 'color' || name === 'backgroundColor') {
      value = dom.toHex(value);
    }
    if (name === 'fontWeight' && value === 700) {
      value = 'bold';
    }
    if (name === 'fontFamily') {
      value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
    }
    return '' + value;
  };
  var getStyle = function (dom, node, name) {
    return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  };
  var getTextDecoration = function (dom, node) {
    var decoration;
    dom.getParent(node, function (n) {
      decoration = dom.getStyle(n, 'text-decoration');
      return decoration && decoration !== 'none';
    });
    return decoration;
  };
  var getParents$1 = function (dom, node, selector) {
    return dom.getParents(node, selector, dom.getRoot());
  };
  var $_dodtof5tjh8lyxdh = {
    isInlineBlock: isInlineBlock,
    moveStart: moveStart,
    getNonWhiteSpaceSibling: getNonWhiteSpaceSibling,
    isTextBlock: isTextBlock$1,
    isValid: isValid,
    isWhiteSpaceNode: isWhiteSpaceNode,
    replaceVars: replaceVars,
    isEq: isEq$3,
    normalizeStyleValue: normalizeStyleValue,
    getStyle: getStyle,
    getTextDecoration: getTextDecoration,
    getParents: getParents$1
  };

  var isBookmarkNode$2 = $_eyp5ec2njh8lywpo.isBookmarkNode;
  var getParents$2 = $_dodtof5tjh8lyxdh.getParents;
  var isWhiteSpaceNode$1 = $_dodtof5tjh8lyxdh.isWhiteSpaceNode;
  var isTextBlock$2 = $_dodtof5tjh8lyxdh.isTextBlock;
  var findLeaf = function (node, offset) {
    if (typeof offset === 'undefined') {
      offset = node.nodeType === 3 ? node.length : node.childNodes.length;
    }
    while (node && node.hasChildNodes()) {
      node = node.childNodes[offset];
      if (node) {
        offset = node.nodeType === 3 ? node.length : node.childNodes.length;
      }
    }
    return {
      node: node,
      offset: offset
    };
  };
  var excludeTrailingWhitespace = function (endContainer, endOffset) {
    var leaf = findLeaf(endContainer, endOffset);
    if (leaf.node) {
      while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling) {
        leaf = findLeaf(leaf.node.previousSibling);
      }
      if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 && leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') {
        if (leaf.offset > 1) {
          endContainer = leaf.node;
          endContainer.splitText(leaf.offset - 1);
        }
      }
    }
    return endContainer;
  };
  var isBogusBr = function (node) {
    return node.nodeName === 'BR' && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  };
  var findParentContentEditable = function (dom, node) {
    var parent = node;
    while (parent) {
      if (parent.nodeType === 1 && dom.getContentEditable(parent)) {
        return dom.getContentEditable(parent) === 'false' ? parent : node;
      }
      parent = parent.parentNode;
    }
    return node;
  };
  var findSpace = function (start, remove, node, offset) {
    var pos, pos2;
    var str = node.nodeValue;
    if (typeof offset === 'undefined') {
      offset = start ? str.length : 0;
    }
    if (start) {
      pos = str.lastIndexOf(' ', offset);
      pos2 = str.lastIndexOf('\xA0', offset);
      pos = pos > pos2 ? pos : pos2;
      if (pos !== -1 && !remove) {
        pos++;
      }
    } else {
      pos = str.indexOf(' ', offset);
      pos2 = str.indexOf('\xA0', offset);
      pos = pos !== -1 && (pos2 === -1 || pos < pos2) ? pos : pos2;
    }
    return pos;
  };
  var findWordEndPoint = function (dom, body, container, offset, start, remove) {
    var walker, node, pos, lastTextNode;
    if (container.nodeType === 3) {
      pos = findSpace(start, remove, container, offset);
      if (pos !== -1) {
        return {
          container: container,
          offset: pos
        };
      }
      lastTextNode = container;
    }
    walker = new TreeWalker(container, dom.getParent(container, dom.isBlock) || body);
    while (node = walker[start ? 'prev' : 'next']()) {
      if (node.nodeType === 3) {
        lastTextNode = node;
        pos = findSpace(start, remove, node);
        if (pos !== -1) {
          return {
            container: node,
            offset: pos
          };
        }
      } else if (dom.isBlock(node)) {
        break;
      }
    }
    if (lastTextNode) {
      if (start) {
        offset = 0;
      } else {
        offset = lastTextNode.length;
      }
      return {
        container: lastTextNode,
        offset: offset
      };
    }
  };
  var findSelectorEndPoint = function (dom, format, rng, container, siblingName) {
    var parents, i, y, curFormat;
    if (container.nodeType === 3 && container.nodeValue.length === 0 && container[siblingName]) {
      container = container[siblingName];
    }
    parents = getParents$2(dom, container);
    for (i = 0; i < parents.length; i++) {
      for (y = 0; y < format.length; y++) {
        curFormat = format[y];
        if ('collapsed' in curFormat && curFormat.collapsed !== rng.collapsed) {
          continue;
        }
        if (dom.is(parents[i], curFormat.selector)) {
          return parents[i];
        }
      }
    }
    return container;
  };
  var findBlockEndPoint = function (editor, format, container, siblingName) {
    var node;
    var dom = editor.dom;
    var root = dom.getRoot();
    if (!format[0].wrapper) {
      node = dom.getParent(container, format[0].block, root);
    }
    if (!node) {
      var scopeRoot = dom.getParent(container, 'LI,TD,TH');
      node = dom.getParent(container.nodeType === 3 ? container.parentNode : container, function (node) {
        return node !== root && isTextBlock$2(editor, node);
      }, scopeRoot);
    }
    if (node && format[0].wrapper) {
      node = getParents$2(dom, node, 'ul,ol').reverse()[0] || node;
    }
    if (!node) {
      node = container;
      while (node[siblingName] && !dom.isBlock(node[siblingName])) {
        node = node[siblingName];
        if ($_dodtof5tjh8lyxdh.isEq(node, 'br')) {
          break;
        }
      }
    }
    return node || container;
  };
  var findParentContainer = function (dom, format, startContainer, startOffset, endContainer, endOffset, start) {
    var container, parent, sibling, siblingName, root;
    container = parent = start ? startContainer : endContainer;
    siblingName = start ? 'previousSibling' : 'nextSibling';
    root = dom.getRoot();
    if (container.nodeType === 3 && !isWhiteSpaceNode$1(container)) {
      if (start ? startOffset > 0 : endOffset < container.nodeValue.length) {
        return container;
      }
    }
    while (true) {
      if (!format[0].block_expand && dom.isBlock(parent)) {
        return parent;
      }
      for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
        if (!isBookmarkNode$2(sibling) && !isWhiteSpaceNode$1(sibling) && !isBogusBr(sibling)) {
          return parent;
        }
      }
      if (parent === root || parent.parentNode === root) {
        container = parent;
        break;
      }
      parent = parent.parentNode;
    }
    return container;
  };
  var expandRng = function (editor, rng, format, remove) {
    var endPoint, startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
    var dom = editor.dom;
    if (startContainer.nodeType === 1 && startContainer.hasChildNodes()) {
      startContainer = getNode(startContainer, startOffset);
      if (startContainer.nodeType === 3) {
        startOffset = 0;
      }
    }
    if (endContainer.nodeType === 1 && endContainer.hasChildNodes()) {
      endContainer = getNode(endContainer, rng.collapsed ? endOffset : endOffset - 1);
      if (endContainer.nodeType === 3) {
        endOffset = endContainer.nodeValue.length;
      }
    }
    startContainer = findParentContentEditable(dom, startContainer);
    endContainer = findParentContentEditable(dom, endContainer);
    if (isBookmarkNode$2(startContainer.parentNode) || isBookmarkNode$2(startContainer)) {
      startContainer = isBookmarkNode$2(startContainer) ? startContainer : startContainer.parentNode;
      startContainer = startContainer.nextSibling || startContainer;
      if (startContainer.nodeType === 3) {
        startOffset = 0;
      }
    }
    if (isBookmarkNode$2(endContainer.parentNode) || isBookmarkNode$2(endContainer)) {
      endContainer = isBookmarkNode$2(endContainer) ? endContainer : endContainer.parentNode;
      endContainer = endContainer.previousSibling || endContainer;
      if (endContainer.nodeType === 3) {
        endOffset = endContainer.length;
      }
    }
    if (format[0].inline) {
      if (rng.collapsed) {
        endPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, remove);
        if (endPoint) {
          startContainer = endPoint.container;
          startOffset = endPoint.offset;
        }
        endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, remove);
        if (endPoint) {
          endContainer = endPoint.container;
          endOffset = endPoint.offset;
        }
      }
      endContainer = remove ? endContainer : excludeTrailingWhitespace(endContainer, endOffset);
    }
    if (format[0].inline || format[0].block_expand) {
      if (!format[0].inline || (startContainer.nodeType !== 3 || startOffset === 0)) {
        startContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, true);
      }
      if (!format[0].inline || (endContainer.nodeType !== 3 || endOffset === endContainer.nodeValue.length)) {
        endContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, false);
      }
    }
    if (format[0].selector && format[0].expand !== false && !format[0].inline) {
      startContainer = findSelectorEndPoint(dom, format, rng, startContainer, 'previousSibling');
      endContainer = findSelectorEndPoint(dom, format, rng, endContainer, 'nextSibling');
    }
    if (format[0].block || format[0].selector) {
      startContainer = findBlockEndPoint(editor, format, startContainer, 'previousSibling');
      endContainer = findBlockEndPoint(editor, format, endContainer, 'nextSibling');
      if (format[0].block) {
        if (!dom.isBlock(startContainer)) {
          startContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, true);
        }
        if (!dom.isBlock(endContainer)) {
          endContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, false);
        }
      }
    }
    if (startContainer.nodeType === 1) {
      startOffset = dom.nodeIndex(startContainer);
      startContainer = startContainer.parentNode;
    }
    if (endContainer.nodeType === 1) {
      endOffset = dom.nodeIndex(endContainer) + 1;
      endContainer = endContainer.parentNode;
    }
    return {
      startContainer: startContainer,
      startOffset: startOffset,
      endContainer: endContainer,
      endOffset: endOffset
    };
  };
  var $_fryklb5sjh8lyxd9 = { expandRng: expandRng };

  var isEq$4 = $_dodtof5tjh8lyxdh.isEq;
  var matchesUnInheritedFormatSelector = function (ed, node, name) {
    var formatList = ed.formatter.get(name);
    if (formatList) {
      for (var i = 0; i < formatList.length; i++) {
        if (formatList[i].inherit === false && ed.dom.is(node, formatList[i].selector)) {
          return true;
        }
      }
    }
    return false;
  };
  var matchParents = function (editor, node, name, vars) {
    var root = editor.dom.getRoot();
    if (node === root) {
      return false;
    }
    node = editor.dom.getParent(node, function (node) {
      if (matchesUnInheritedFormatSelector(editor, node, name)) {
        return true;
      }
      return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
    });
    return matchNode(editor, node, name, vars);
  };
  var matchName = function (dom, node, format) {
    if (isEq$4(node, format.inline)) {
      return true;
    }
    if (isEq$4(node, format.block)) {
      return true;
    }
    if (format.selector) {
      return node.nodeType === 1 && dom.is(node, format.selector);
    }
  };
  var matchItems = function (dom, node, format, itemName, similar, vars) {
    var key, value;
    var items = format[itemName];
    var i;
    if (format.onmatch) {
      return format.onmatch(node, format, itemName);
    }
    if (items) {
      if (typeof items.length === 'undefined') {
        for (key in items) {
          if (items.hasOwnProperty(key)) {
            if (itemName === 'attributes') {
              value = dom.getAttrib(node, key);
            } else {
              value = $_dodtof5tjh8lyxdh.getStyle(dom, node, key);
            }
            if (similar && !value && !format.exact) {
              return;
            }
            if ((!similar || format.exact) && !isEq$4(value, $_dodtof5tjh8lyxdh.normalizeStyleValue(dom, $_dodtof5tjh8lyxdh.replaceVars(items[key], vars), key))) {
              return;
            }
          }
        }
      } else {
        for (i = 0; i < items.length; i++) {
          if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : $_dodtof5tjh8lyxdh.getStyle(dom, node, items[i])) {
            return format;
          }
        }
      }
    }
    return format;
  };
  var matchNode = function (ed, node, name, vars, similar) {
    var formatList = ed.formatter.get(name);
    var format, i, x, classes;
    var dom = ed.dom;
    if (formatList && node) {
      for (i = 0; i < formatList.length; i++) {
        format = formatList[i];
        if (matchName(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
          if (classes = format.classes) {
            for (x = 0; x < classes.length; x++) {
              if (!ed.dom.hasClass(node, classes[x])) {
                return;
              }
            }
          }
          return format;
        }
      }
    }
  };
  var match = function (editor, name, vars, node) {
    var startNode;
    if (node) {
      return matchParents(editor, node, name, vars);
    }
    node = editor.selection.getNode();
    if (matchParents(editor, node, name, vars)) {
      return true;
    }
    startNode = editor.selection.getStart();
    if (startNode !== node) {
      if (matchParents(editor, startNode, name, vars)) {
        return true;
      }
    }
    return false;
  };
  var matchAll = function (editor, names, vars) {
    var startElement;
    var matchedFormatNames = [];
    var checkedMap = {};
    startElement = editor.selection.getStart();
    editor.dom.getParent(startElement, function (node) {
      var i, name;
      for (i = 0; i < names.length; i++) {
        name = names[i];
        if (!checkedMap[name] && matchNode(editor, node, name, vars)) {
          checkedMap[name] = true;
          matchedFormatNames.push(name);
        }
      }
    }, editor.dom.getRoot());
    return matchedFormatNames;
  };
  var canApply = function (editor, name) {
    var formatList = editor.formatter.get(name);
    var startNode, parents, i, x, selector;
    var dom = editor.dom;
    if (formatList) {
      startNode = editor.selection.getStart();
      parents = $_dodtof5tjh8lyxdh.getParents(dom, startNode);
      for (x = formatList.length - 1; x >= 0; x--) {
        selector = formatList[x].selector;
        if (!selector || formatList[x].defaultBlock) {
          return true;
        }
        for (i = parents.length - 1; i >= 0; i--) {
          if (dom.is(parents[i], selector)) {
            return true;
          }
        }
      }
    }
    return false;
  };
  var $_8qd8fq5ujh8lyxdx = {
    matchNode: matchNode,
    matchName: matchName,
    match: match,
    matchAll: matchAll,
    canApply: canApply,
    matchesUnInheritedFormatSelector: matchesUnInheritedFormatSelector
  };

  var splitText = function (node, offset) {
    return node.splitText(offset);
  };
  var split$1 = function (rng) {
    var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
    if (startContainer === endContainer && $_5oonaz1qjh8lywhz.isText(startContainer)) {
      if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
        endContainer = splitText(startContainer, startOffset);
        startContainer = endContainer.previousSibling;
        if (endOffset > startOffset) {
          endOffset = endOffset - startOffset;
          startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
          endOffset = endContainer.nodeValue.length;
          startOffset = 0;
        } else {
          endOffset = 0;
        }
      }
    } else {
      if ($_5oonaz1qjh8lywhz.isText(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
        startContainer = splitText(startContainer, startOffset);
        startOffset = 0;
      }
      if ($_5oonaz1qjh8lywhz.isText(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
        endContainer = splitText(endContainer, endOffset).previousSibling;
        endOffset = endContainer.nodeValue.length;
      }
    }
    return {
      startContainer: startContainer,
      startOffset: startOffset,
      endContainer: endContainer,
      endOffset: endOffset
    };
  };
  var $_5hrcpr5vjh8lyxe2 = { split: split$1 };

  var ZWSP$1 = $_d383mr21jh8lywlv.ZWSP;
  var CARET_ID$1 = '_mce_caret';
  var importNode = function (ownerDocument, node) {
    return ownerDocument.importNode(node, true);
  };
  var getEmptyCaretContainers = function (node) {
    var nodes = [];
    while (node) {
      if (node.nodeType === 3 && node.nodeValue !== ZWSP$1 || node.childNodes.length > 1) {
        return [];
      }
      if (node.nodeType === 1) {
        nodes.push(node);
      }
      node = node.firstChild;
    }
    return nodes;
  };
  var isCaretContainerEmpty = function (node) {
    return getEmptyCaretContainers(node).length > 0;
  };
  var findFirstTextNode = function (node) {
    var walker;
    if (node) {
      walker = new TreeWalker(node, node);
      for (node = walker.current(); node; node = walker.next()) {
        if (node.nodeType === 3) {
          return node;
        }
      }
    }
    return null;
  };
  var createCaretContainer = function (fill) {
    var caretContainer = $_cgttw3zjh8lywdq.fromTag('span');
    $_3da62i14jh8lyweo.setAll(caretContainer, {
      'id': CARET_ID$1,
      'data-mce-bogus': '1',
      'data-mce-type': 'format-caret'
    });
    if (fill) {
      $_4m7u2e2kjh8lywpi.append(caretContainer, $_cgttw3zjh8lywdq.fromText(ZWSP$1));
    }
    return caretContainer;
  };
  var trimZwspFromCaretContainer = function (caretContainerNode) {
    var textNode = findFirstTextNode(caretContainerNode);
    if (textNode && textNode.nodeValue.charAt(0) === ZWSP$1) {
      textNode.deleteData(0, 1);
    }
    return textNode;
  };
  var removeCaretContainerNode = function (dom, selection, node, moveCaret) {
    var rng, block, textNode;
    rng = selection.getRng(true);
    block = dom.getParent(node, dom.isBlock);
    if (isCaretContainerEmpty(node)) {
      if (moveCaret !== false) {
        rng.setStartBefore(node);
        rng.setEndBefore(node);
      }
      dom.remove(node);
    } else {
      textNode = trimZwspFromCaretContainer(node);
      if (rng.startContainer === textNode && rng.startOffset > 0) {
        rng.setStart(textNode, rng.startOffset - 1);
      }
      if (rng.endContainer === textNode && rng.endOffset > 0) {
        rng.setEnd(textNode, rng.endOffset - 1);
      }
      dom.remove(node, true);
    }
    if (block && dom.isEmpty(block)) {
      $_2bvsfb2tjh8lywqo.fillWithPaddingBr($_cgttw3zjh8lywdq.fromDom(block));
    }
    selection.setRng(rng);
  };
  var removeCaretContainer = function (body, dom, selection, node, moveCaret) {
    if (!node) {
      node = getParentCaretContainer(body, selection.getStart());
      if (!node) {
        while (node = dom.get(CARET_ID$1)) {
          removeCaretContainerNode(dom, selection, node, false);
        }
      }
    } else {
      removeCaretContainerNode(dom, selection, node, moveCaret);
    }
  };
  var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
    var dom = editor.dom, block = dom.getParent(formatNode, $_8aqzj925jh8lywmj.curry($_dodtof5tjh8lyxdh.isTextBlock, editor));
    if (block && dom.isEmpty(block)) {
      formatNode.parentNode.replaceChild(caretContainer, formatNode);
    } else {
      $_2bvsfb2tjh8lywqo.removeTrailingBr($_cgttw3zjh8lywdq.fromDom(formatNode));
      if (dom.isEmpty(formatNode)) {
        formatNode.parentNode.replaceChild(caretContainer, formatNode);
      } else {
        dom.insertAfter(caretContainer, formatNode);
      }
    }
  };
  var appendNode = function (parentNode, node) {
    parentNode.appendChild(node);
    return node;
  };
  var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
    var innerMostFormatNode = $_5wjzy24jh8lyw2t.foldr(formatNodes, function (parentNode, formatNode) {
      return appendNode(parentNode, formatNode.cloneNode(false));
    }, caretContainer);
    return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP$1));
  };
  var applyCaretFormat = function (editor, name, vars) {
    var rng, caretContainer, textNode, offset, bookmark, container, text;
    var selection = editor.selection;
    rng = selection.getRng(true);
    offset = rng.startOffset;
    container = rng.startContainer;
    text = container.nodeValue;
    caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
    if (caretContainer) {
      textNode = findFirstTextNode(caretContainer);
    }
    var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
    if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
      bookmark = selection.getBookmark();
      rng.collapse(true);
      rng = $_fryklb5sjh8lyxd9.expandRng(editor, rng, editor.formatter.get(name));
      rng = $_5hrcpr5vjh8lyxe2.split(rng);
      editor.formatter.apply(name, vars, rng);
      selection.moveToBookmark(bookmark);
    } else {
      if (!caretContainer || textNode.nodeValue !== ZWSP$1) {
        caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom());
        textNode = caretContainer.firstChild;
        rng.insertNode(caretContainer);
        offset = 1;
        editor.formatter.apply(name, vars, caretContainer);
      } else {
        editor.formatter.apply(name, vars, caretContainer);
      }
      selection.setCursorLocation(textNode, offset);
    }
  };
  var removeCaretFormat = function (editor, name, vars, similar) {
    var dom = editor.dom, selection = editor.selection;
    var container, offset, bookmark;
    var hasContentAfter, node, formatNode;
    var parents = [], rng = selection.getRng();
    var caretContainer;
    container = rng.startContainer;
    offset = rng.startOffset;
    node = container;
    if (container.nodeType === 3) {
      if (offset !== container.nodeValue.length) {
        hasContentAfter = true;
      }
      node = node.parentNode;
    }
    while (node) {
      if ($_8qd8fq5ujh8lyxdx.matchNode(editor, node, name, vars, similar)) {
        formatNode = node;
        break;
      }
      if (node.nextSibling) {
        hasContentAfter = true;
      }
      parents.push(node);
      node = node.parentNode;
    }
    if (!formatNode) {
      return;
    }
    if (hasContentAfter) {
      bookmark = selection.getBookmark();
      rng.collapse(true);
      var expandedRng = $_fryklb5sjh8lyxd9.expandRng(editor, rng, editor.formatter.get(name), true);
      expandedRng = $_5hrcpr5vjh8lyxe2.split(expandedRng);
      editor.formatter.remove(name, vars, expandedRng);
      selection.moveToBookmark(bookmark);
    } else {
      caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
      var newCaretContainer = createCaretContainer(false).dom();
      var caretNode = insertFormatNodesIntoCaretContainer(parents, newCaretContainer);
      if (caretContainer) {
        insertCaretContainerNode(editor, newCaretContainer, caretContainer);
      } else {
        insertCaretContainerNode(editor, newCaretContainer, formatNode);
      }
      removeCaretContainerNode(dom, selection, caretContainer, false);
      selection.setCursorLocation(caretNode, 1);
      if (dom.isEmpty(formatNode)) {
        dom.remove(formatNode);
      }
    }
  };
  var disableCaretContainer = function (body, dom, selection, keyCode) {
    removeCaretContainer(body, dom, selection, null, false);
    if (keyCode === 8 && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP$1) {
      removeCaretContainer(body, dom, selection, getParentCaretContainer(body, selection.getStart()));
    }
    if (keyCode === 37 || keyCode === 39) {
      removeCaretContainer(body, dom, selection, getParentCaretContainer(body, selection.getStart()));
    }
  };
  var setup$2 = function (editor) {
    var dom = editor.dom, selection = editor.selection;
    var body = editor.getBody();
    editor.on('mouseup keydown', function (e) {
      disableCaretContainer(body, dom, selection, e.keyCode);
    });
  };
  var replaceWithCaretFormat = function (targetNode, formatNodes) {
    var caretContainer = createCaretContainer(false);
    var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom());
    $_4m7u2e2kjh8lywpi.before($_cgttw3zjh8lywdq.fromDom(targetNode), caretContainer);
    $_bfmuql2ujh8lywr1.remove($_cgttw3zjh8lywdq.fromDom(targetNode));
    return CaretPosition$1(innerMost, 0);
  };
  var isFormatElement = function (editor, element) {
    var inlineElements = editor.schema.getTextInlineElements();
    return inlineElements.hasOwnProperty($_7j1jt210jh8lywdx.name(element)) && !isCaretNode(element.dom()) && !$_5oonaz1qjh8lywhz.isBogus(element.dom());
  };

  var postProcessHooks = {};
  var filter$2 = $_9tjm51ljh8lywbq.filter;
  var each$11 = $_9tjm51ljh8lywbq.each;
  var addPostProcessHook = function (name, hook) {
    var hooks = postProcessHooks[name];
    if (!hooks) {
      postProcessHooks[name] = hooks = [];
    }
    postProcessHooks[name].push(hook);
  };
  var postProcess = function (name, editor) {
    each$11(postProcessHooks[name], function (hook) {
      hook(editor);
    });
  };
  addPostProcessHook('pre', function (editor) {
    var rng = editor.selection.getRng();
    var isPre, blocks;
    var hasPreSibling = function (pre) {
      return isPre(pre.previousSibling) && $_9tjm51ljh8lywbq.indexOf(blocks, pre.previousSibling) !== -1;
    };
    var joinPre = function (pre1, pre2) {
      DomQuery(pre2).remove();
      DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
    };
    isPre = $_5oonaz1qjh8lywhz.matchNodeNames('pre');
    if (!rng.collapsed) {
      blocks = editor.selection.getSelectedBlocks();
      each$11(filter$2(filter$2(blocks, isPre), hasPreSibling), function (pre) {
        joinPre(pre.previousSibling, pre);
      });
    }
  });
  var $_78e03d5wjh8lyxe4 = { postProcess: postProcess };

  var each$12 = $_ahowuxkjh8lywbj.each;
  var getEndChild = function (container, index) {
    var childNodes = container.childNodes;
    index--;
    if (index > childNodes.length - 1) {
      index = childNodes.length - 1;
    } else if (index < 0) {
      index = 0;
    }
    return childNodes[index] || container;
  };
  var walk$2 = function (dom, rng, callback) {
    var startContainer = rng.startContainer;
    var startOffset = rng.startOffset;
    var endContainer = rng.endContainer;
    var endOffset = rng.endOffset;
    var ancestor;
    var startPoint;
    var endPoint;
    var node;
    var parent;
    var siblings;
    var nodes;
    nodes = dom.select('td[data-mce-selected],th[data-mce-selected]');
    if (nodes.length > 0) {
      each$12(nodes, function (node) {
        callback([node]);
      });
      return;
    }
    var exclude = function (nodes) {
      var node;
      node = nodes[0];
      if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) {
        nodes.splice(0, 1);
      }
      node = nodes[nodes.length - 1];
      if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) {
        nodes.splice(nodes.length - 1, 1);
      }
      return nodes;
    };
    var collectSiblings = function (node, name, endNode) {
      var siblings = [];
      for (; node && node !== endNode; node = node[name]) {
        siblings.push(node);
      }
      return siblings;
    };
    var findEndPoint = function (node, root) {
      do {
        if (node.parentNode === root) {
          return node;
        }
        node = node.parentNode;
      } while (node);
    };
    var walkBoundary = function (startNode, endNode, next) {
      var siblingName = next ? 'nextSibling' : 'previousSibling';
      for (node = startNode, parent = node.parentNode; node && node !== endNode; node = parent) {
        parent = node.parentNode;
        siblings = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
        if (siblings.length) {
          if (!next) {
            siblings.reverse();
          }
          callback(exclude(siblings));
        }
      }
    };
    if (startContainer.nodeType === 1 && startContainer.hasChildNodes()) {
      startContainer = startContainer.childNodes[startOffset];
    }
    if (endContainer.nodeType === 1 && endContainer.hasChildNodes()) {
      endContainer = getEndChild(endContainer, endOffset);
    }
    if (startContainer === endContainer) {
      return callback(exclude([startContainer]));
    }
    ancestor = dom.findCommonAncestor(startContainer, endContainer);
    for (node = startContainer; node; node = node.parentNode) {
      if (node === endContainer) {
        return walkBoundary(startContainer, ancestor, true);
      }
      if (node === ancestor) {
        break;
      }
    }
    for (node = endContainer; node; node = node.parentNode) {
      if (node === startContainer) {
        return walkBoundary(endContainer, ancestor);
      }
      if (node === ancestor) {
        break;
      }
    }
    startPoint = findEndPoint(startContainer, ancestor) || startContainer;
    endPoint = findEndPoint(endContainer, ancestor) || endContainer;
    walkBoundary(startContainer, startPoint, true);
    siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
    if (siblings.length) {
      callback(exclude(siblings));
    }
    walkBoundary(endContainer, endPoint);
  };
  var $_90itx05zjh8lyxeq = { walk: walk$2 };

  var MCE_ATTR_RE = /^(src|href|style)$/;
  var each$13 = $_ahowuxkjh8lywbj.each;
  var isEq$5 = $_dodtof5tjh8lyxdh.isEq;
  var isTableCell$4 = function (node) {
    return /^(TH|TD)$/.test(node.nodeName);
  };
  var getContainer = function (ed, rng, start) {
    var container, offset, lastIdx;
    container = rng[start ? 'startContainer' : 'endContainer'];
    offset = rng[start ? 'startOffset' : 'endOffset'];
    if ($_5oonaz1qjh8lywhz.isElement(container)) {
      lastIdx = container.childNodes.length - 1;
      if (!start && offset) {
        offset--;
      }
      container = container.childNodes[offset > lastIdx ? lastIdx : offset];
    }
    if ($_5oonaz1qjh8lywhz.isText(container) && start && offset >= container.nodeValue.length) {
      container = new TreeWalker(container, ed.getBody()).next() || container;
    }
    if ($_5oonaz1qjh8lywhz.isText(container) && !start && offset === 0) {
      container = new TreeWalker(container, ed.getBody()).prev() || container;
    }
    return container;
  };
  var wrap$2 = function (dom, node, name, attrs) {
    var wrapper = dom.create(name, attrs);
    node.parentNode.insertBefore(wrapper, node);
    wrapper.appendChild(node);
    return wrapper;
  };
  var matchName$1 = function (dom, node, format) {
    if (isEq$5(node, format.inline)) {
      return true;
    }
    if (isEq$5(node, format.block)) {
      return true;
    }
    if (format.selector) {
      return $_5oonaz1qjh8lywhz.isElement(node) && dom.is(node, format.selector);
    }
  };
  var isColorFormatAndAnchor = function (node, format) {
    return format.links && node.tagName === 'A';
  };
  var find$4 = function (dom, node, next, inc) {
    node = $_dodtof5tjh8lyxdh.getNonWhiteSpaceSibling(node, next, inc);
    return !node || (node.nodeName === 'BR' || dom.isBlock(node));
  };
  var removeNode$1 = function (ed, node, format) {
    var parentNode = node.parentNode;
    var rootBlockElm;
    var dom = ed.dom, forcedRootBlock = ed.settings.forced_root_block;
    if (format.block) {
      if (!forcedRootBlock) {
        if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
          if (!find$4(dom, node, false) && !find$4(dom, node.firstChild, true, 1)) {
            node.insertBefore(dom.create('br'), node.firstChild);
          }
          if (!find$4(dom, node, true) && !find$4(dom, node.lastChild, false, 1)) {
            node.appendChild(dom.create('br'));
          }
        }
      } else {
        if (parentNode === dom.getRoot()) {
          if (!format.list_block || !isEq$5(node, format.list_block)) {
            each$13($_ahowuxkjh8lywbj.grep(node.childNodes), function (node) {
              if ($_dodtof5tjh8lyxdh.isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
                if (!rootBlockElm) {
                  rootBlockElm = wrap$2(dom, node, forcedRootBlock);
                  dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
                } else {
                  rootBlockElm.appendChild(node);
                }
              } else {
                rootBlockElm = 0;
              }
            });
          }
        }
      }
    }
    if (format.selector && format.inline && !isEq$5(format.inline, node)) {
      return;
    }
    dom.remove(node, 1);
  };
  var removeFormat = function (ed, format, vars, node, compareNode) {
    var i, attrs, stylesModified;
    var dom = ed.dom;
    if (!matchName$1(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
      return false;
    }
    if (format.remove !== 'all') {
      each$13(format.styles, function (value, name) {
        value = $_dodtof5tjh8lyxdh.normalizeStyleValue(dom, $_dodtof5tjh8lyxdh.replaceVars(value, vars), name);
        if (typeof name === 'number') {
          name = value;
          compareNode = 0;
        }
        if (format.remove_similar || (!compareNode || isEq$5($_dodtof5tjh8lyxdh.getStyle(dom, compareNode, name), value))) {
          dom.setStyle(node, name, '');
        }
        stylesModified = 1;
      });
      if (stylesModified && dom.getAttrib(node, 'style') === '') {
        node.removeAttribute('style');
        node.removeAttribute('data-mce-style');
      }
      each$13(format.attributes, function (value, name) {
        var valueOut;
        value = $_dodtof5tjh8lyxdh.replaceVars(value, vars);
        if (typeof name === 'number') {
          name = value;
          compareNode = 0;
        }
        if (!compareNode || isEq$5(dom.getAttrib(compareNode, name), value)) {
          if (name === 'class') {
            value = dom.getAttrib(node, name);
            if (value) {
              valueOut = '';
              each$13(value.split(/\s+/), function (cls) {
                if (/mce\-\w+/.test(cls)) {
                  valueOut += (valueOut ? ' ' : '') + cls;
                }
              });
              if (valueOut) {
                dom.setAttrib(node, name, valueOut);
                return;
              }
            }
          }
          if (name === 'class') {
            node.removeAttribute('className');
          }
          if (MCE_ATTR_RE.test(name)) {
            node.removeAttribute('data-mce-' + name);
          }
          node.removeAttribute(name);
        }
      });
      each$13(format.classes, function (value) {
        value = $_dodtof5tjh8lyxdh.replaceVars(value, vars);
        if (!compareNode || dom.hasClass(compareNode, value)) {
          dom.removeClass(node, value);
        }
      });
      attrs = dom.getAttribs(node);
      for (i = 0; i < attrs.length; i++) {
        var attrName = attrs[i].nodeName;
        if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
          return false;
        }
      }
    }
    if (format.remove !== 'none') {
      removeNode$1(ed, node, format);
      return true;
    }
  };
  var findFormatRoot = function (editor, container, name, vars, similar) {
    var formatRoot;
    each$13($_dodtof5tjh8lyxdh.getParents(editor.dom, container.parentNode).reverse(), function (parent) {
      var format;
      if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
        format = $_8qd8fq5ujh8lyxdx.matchNode(editor, parent, name, vars, similar);
        if (format && format.split !== false) {
          formatRoot = parent;
        }
      }
    });
    return formatRoot;
  };
  var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
    var parent, clone, lastClone, firstClone, i, formatRootParent;
    var dom = editor.dom;
    if (formatRoot) {
      formatRootParent = formatRoot.parentNode;
      for (parent = container.parentNode; parent && parent !== formatRootParent; parent = parent.parentNode) {
        clone = dom.clone(parent, false);
        for (i = 0; i < formatList.length; i++) {
          if (removeFormat(editor, formatList[i], vars, clone, clone)) {
            clone = 0;
            break;
          }
        }
        if (clone) {
          if (lastClone) {
            clone.appendChild(lastClone);
          }
          if (!firstClone) {
            firstClone = clone;
          }
          lastClone = clone;
        }
      }
      if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
        container = dom.split(formatRoot, container);
      }
      if (lastClone) {
        target.parentNode.insertBefore(lastClone, target);
        firstClone.appendChild(target);
      }
    }
    return container;
  };
  var remove$7 = function (ed, name, vars, node, similar) {
    var formatList = ed.formatter.get(name), format = formatList[0];
    var bookmark, rng, contentEditable = true;
    var dom = ed.dom;
    var selection = ed.selection;
    var splitToFormatRoot = function (container) {
      var formatRoot = findFormatRoot(ed, container, name, vars, similar);
      return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
    };
    var process = function (node) {
      var children, i, l, lastContentEditable, hasContentEditableState;
      if ($_5oonaz1qjh8lywhz.isElement(node) && dom.getContentEditable(node)) {
        lastContentEditable = contentEditable;
        contentEditable = dom.getContentEditable(node) === 'true';
        hasContentEditableState = true;
      }
      children = $_ahowuxkjh8lywbj.grep(node.childNodes);
      if (contentEditable && !hasContentEditableState) {
        for (i = 0, l = formatList.length; i < l; i++) {
          if (removeFormat(ed, formatList[i], vars, node, node)) {
            break;
          }
        }
      }
      if (format.deep) {
        if (children.length) {
          for (i = 0, l = children.length; i < l; i++) {
            process(children[i]);
          }
          if (hasContentEditableState) {
            contentEditable = lastContentEditable;
          }
        }
      }
    };
    var unwrap = function (start) {
      var node = dom.get(start ? '_start' : '_end');
      var out = node[start ? 'firstChild' : 'lastChild'];
      if ($_eyp5ec2njh8lywpo.isBookmarkNode(out)) {
        out = out[start ? 'firstChild' : 'lastChild'];
      }
      if ($_5oonaz1qjh8lywhz.isText(out) && out.data.length === 0) {
        out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
      }
      dom.remove(node, true);
      return out;
    };
    var removeRngStyle = function (rng) {
      var startContainer, endContainer;
      var commonAncestorContainer = rng.commonAncestorContainer;
      rng = $_fryklb5sjh8lyxd9.expandRng(ed, rng, formatList, true);
      if (format.split) {
        startContainer = getContainer(ed, rng, true);
        endContainer = getContainer(ed, rng);
        if (startContainer !== endContainer) {
          if (/^(TR|TH|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) {
            if (startContainer.nodeName === 'TR') {
              startContainer = startContainer.firstChild.firstChild || startContainer;
            } else {
              startContainer = startContainer.firstChild || startContainer;
            }
          }
          if (commonAncestorContainer && /^T(HEAD|BODY|FOOT|R)$/.test(commonAncestorContainer.nodeName) && isTableCell$4(endContainer) && endContainer.firstChild) {
            endContainer = endContainer.firstChild || endContainer;
          }
          if (dom.isChildOf(startContainer, endContainer) && startContainer !== endContainer && !dom.isBlock(endContainer) && !isTableCell$4(startContainer) && !isTableCell$4(endContainer)) {
            startContainer = wrap$2(dom, startContainer, 'span', {
              'id': '_start',
              'data-mce-type': 'bookmark'
            });
            splitToFormatRoot(startContainer);
            startContainer = unwrap(true);
            return;
          }
          startContainer = wrap$2(dom, startContainer, 'span', {
            'id': '_start',
            'data-mce-type': 'bookmark'
          });
          endContainer = wrap$2(dom, endContainer, 'span', {
            'id': '_end',
            'data-mce-type': 'bookmark'
          });
          splitToFormatRoot(startContainer);
          splitToFormatRoot(endContainer);
          startContainer = unwrap(true);
          endContainer = unwrap();
        } else {
          startContainer = endContainer = splitToFormatRoot(startContainer);
        }
        rng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
        rng.startOffset = dom.nodeIndex(startContainer);
        rng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
        rng.endOffset = dom.nodeIndex(endContainer) + 1;
      }
      $_90itx05zjh8lyxeq.walk(dom, rng, function (nodes) {
        each$13(nodes, function (node) {
          process(node);
          if ($_5oonaz1qjh8lywhz.isElement(node) && ed.dom.getStyle(node, 'text-decoration') === 'underline' && node.parentNode && $_dodtof5tjh8lyxdh.getTextDecoration(dom, node.parentNode) === 'underline') {
            removeFormat(ed, {
              deep: false,
              exact: true,
              inline: 'span',
              styles: { textDecoration: 'underline' }
            }, null, node);
          }
        });
      });
    };
    if (node) {
      if (node.nodeType) {
        rng = dom.createRng();
        rng.setStartBefore(node);
        rng.setEndAfter(node);
        removeRngStyle(rng);
      } else {
        removeRngStyle(node);
      }
      return;
    }
    if (dom.getContentEditable(selection.getNode()) === 'false') {
      node = selection.getNode();
      for (var i = 0, l = formatList.length; i < l; i++) {
        if (formatList[i].ceFalseOverride) {
          if (removeFormat(ed, formatList[i], vars, node, node)) {
            break;
          }
        }
      }
      return;
    }
    if (!selection.isCollapsed() || !format.inline || dom.select('td[data-mce-selected],th[data-mce-selected]').length) {
      bookmark = $_8b82yg2ojh8lywpq.getPersistentBookmark(ed.selection, true);
      removeRngStyle(selection.getRng());
      selection.moveToBookmark(bookmark);
      if (format.inline && $_8qd8fq5ujh8lyxdx.match(ed, name, vars, selection.getStart())) {
        $_dodtof5tjh8lyxdh.moveStart(dom, selection, selection.getRng());
      }
      ed.nodeChanged();
    } else {
      removeCaretFormat(ed, name, vars, similar);
    }
  };
  var $_7cys7h5yjh8lyxeg = {
    removeFormat: removeFormat,
    remove: remove$7
  };

  var each$14 = $_ahowuxkjh8lywbj.each;
  var isElementNode = function (node) {
    return node && node.nodeType === 1 && !$_eyp5ec2njh8lywpo.isBookmarkNode(node) && !isCaretNode(node) && !$_5oonaz1qjh8lywhz.isBogus(node);
  };
  var findElementSibling = function (node, siblingName) {
    var sibling;
    for (sibling = node; sibling; sibling = sibling[siblingName]) {
      if (sibling.nodeType === 3 && sibling.nodeValue.length !== 0) {
        return node;
      }
      if (sibling.nodeType === 1 && !$_eyp5ec2njh8lywpo.isBookmarkNode(sibling)) {
        return sibling;
      }
    }
    return node;
  };
  var mergeSiblingsNodes = function (dom, prev, next) {
    var sibling, tmpSibling;
    var elementUtils = new ElementUtils(dom);
    if (prev && next) {
      prev = findElementSibling(prev, 'previousSibling');
      next = findElementSibling(next, 'nextSibling');
      if (elementUtils.compare(prev, next)) {
        for (sibling = prev.nextSibling; sibling && sibling !== next;) {
          tmpSibling = sibling;
          sibling = sibling.nextSibling;
          prev.appendChild(tmpSibling);
        }
        dom.remove(next);
        $_ahowuxkjh8lywbj.each($_ahowuxkjh8lywbj.grep(next.childNodes), function (node) {
          prev.appendChild(node);
        });
        return prev;
      }
    }
    return next;
  };
  var processChildElements = function (node, filter, process) {
    each$14(node.childNodes, function (node) {
      if (isElementNode(node)) {
        if (filter(node)) {
          process(node);
        }
        if (node.hasChildNodes()) {
          processChildElements(node, filter, process);
        }
      }
    });
  };
  var hasStyle = function (dom, name) {
    return $_eqpqvr6jh8lyw3s.curry(function (name, node) {
      return !!(node && $_dodtof5tjh8lyxdh.getStyle(dom, node, name));
    }, name);
  };
  var applyStyle = function (dom, name, value) {
    return $_eqpqvr6jh8lyw3s.curry(function (name, value, node) {
      dom.setStyle(node, name, value);
      if (node.getAttribute('style') === '') {
        node.removeAttribute('style');
      }
      unwrapEmptySpan(dom, node);
    }, name, value);
  };
  var unwrapEmptySpan = function (dom, node) {
    if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
      dom.remove(node, true);
    }
  };
  var processUnderlineAndColor = function (dom, node) {
    var textDecoration;
    if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) {
      textDecoration = $_dodtof5tjh8lyxdh.getTextDecoration(dom, node.parentNode);
      if (dom.getStyle(node, 'color') && textDecoration) {
        dom.setStyle(node, 'text-decoration', textDecoration);
      } else if (dom.getStyle(node, 'text-decoration') === textDecoration) {
        dom.setStyle(node, 'text-decoration', null);
      }
    }
  };
  var mergeUnderlineAndColor = function (dom, format, vars, node) {
    if (format.styles.color || format.styles.textDecoration) {
      $_ahowuxkjh8lywbj.walk(node, $_eqpqvr6jh8lyw3s.curry(processUnderlineAndColor, dom), 'childNodes');
      processUnderlineAndColor(dom, node);
    }
  };
  var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
    if (format.styles && format.styles.backgroundColor) {
      processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', $_dodtof5tjh8lyxdh.replaceVars(format.styles.backgroundColor, vars)));
    }
  };
  var mergeSubSup = function (dom, format, vars, node) {
    if (format.inline === 'sub' || format.inline === 'sup') {
      processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
      dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
    }
  };
  var mergeSiblings = function (dom, format, vars, node) {
    if (node && format.merge_siblings !== false) {
      node = mergeSiblingsNodes(dom, $_dodtof5tjh8lyxdh.getNonWhiteSpaceSibling(node), node);
      node = mergeSiblingsNodes(dom, node, $_dodtof5tjh8lyxdh.getNonWhiteSpaceSibling(node, true));
    }
  };
  var clearChildStyles = function (dom, format, node) {
    if (format.clear_child_styles) {
      var selector = format.links ? '*:not(a)' : '*';
      each$14(dom.select(selector, node), function (node) {
        if (isElementNode(node)) {
          each$14(format.styles, function (value, name) {
            dom.setStyle(node, name, '');
          });
        }
      });
    }
  };
  var mergeWithChildren = function (editor, formatList, vars, node) {
    each$14(formatList, function (format) {
      each$14(editor.dom.select(format.inline, node), function (child) {
        if (!isElementNode(child)) {
          return;
        }
        $_7cys7h5yjh8lyxeg.removeFormat(editor, format, vars, child, format.exact ? child : null);
      });
      clearChildStyles(editor.dom, format, node);
    });
  };
  var mergeWithParents = function (editor, format, name, vars, node) {
    if ($_8qd8fq5ujh8lyxdx.matchNode(editor, node.parentNode, name, vars)) {
      if ($_7cys7h5yjh8lyxeg.removeFormat(editor, format, vars, node)) {
        return;
      }
    }
    if (format.merge_with_parents) {
      editor.dom.getParent(node.parentNode, function (parent) {
        if ($_8qd8fq5ujh8lyxdx.matchNode(editor, parent, name, vars)) {
          $_7cys7h5yjh8lyxeg.removeFormat(editor, format, vars, node);
          return true;
        }
      });
    }
  };
  var $_3fattg5xjh8lyxe7 = {
    mergeWithChildren: mergeWithChildren,
    mergeUnderlineAndColor: mergeUnderlineAndColor,
    mergeBackgroundColorAndFontSize: mergeBackgroundColorAndFontSize,
    mergeSubSup: mergeSubSup,
    mergeSiblings: mergeSiblings,
    mergeWithParents: mergeWithParents
  };

  var each$15 = $_ahowuxkjh8lywbj.each;
  var isElementNode$1 = function (node) {
    return node && node.nodeType === 1 && !$_eyp5ec2njh8lywpo.isBookmarkNode(node) && !isCaretNode(node) && !$_5oonaz1qjh8lywhz.isBogus(node);
  };
  var applyFormat = function (ed, name, vars, node) {
    var formatList = ed.formatter.get(name);
    var format = formatList[0];
    var bookmark, rng;
    var isCollapsed = !node && ed.selection.isCollapsed();
    var dom = ed.dom, selection = ed.selection;
    var setElementFormat = function (elm, fmt) {
      fmt = fmt || format;
      if (elm) {
        if (fmt.onformat) {
          fmt.onformat(elm, fmt, vars, node);
        }
        each$15(fmt.styles, function (value, name) {
          dom.setStyle(elm, name, $_dodtof5tjh8lyxdh.replaceVars(value, vars));
        });
        if (fmt.styles) {
          var styleVal = dom.getAttrib(elm, 'style');
          if (styleVal) {
            elm.setAttribute('data-mce-style', styleVal);
          }
        }
        each$15(fmt.attributes, function (value, name) {
          dom.setAttrib(elm, name, $_dodtof5tjh8lyxdh.replaceVars(value, vars));
        });
        each$15(fmt.classes, function (value) {
          value = $_dodtof5tjh8lyxdh.replaceVars(value, vars);
          if (!dom.hasClass(elm, value)) {
            dom.addClass(elm, value);
          }
        });
      }
    };
    var applyNodeStyle = function (formatList, node) {
      var found = false;
      if (!format.selector) {
        return false;
      }
      each$15(formatList, function (format) {
        if ('collapsed' in format && format.collapsed !== isCollapsed) {
          return;
        }
        if (dom.is(node, format.selector) && !isCaretNode(node)) {
          setElementFormat(node, format);
          found = true;
          return false;
        }
      });
      return found;
    };
    var applyRngStyle = function (dom, rng, bookmark, nodeSpecific) {
      var newWrappers = [];
      var wrapName, wrapElm, contentEditable = true;
      wrapName = format.inline || format.block;
      wrapElm = dom.create(wrapName);
      setElementFormat(wrapElm);
      $_90itx05zjh8lyxeq.walk(dom, rng, function (nodes) {
        var currentWrapElm;
        var process = function (node) {
          var nodeName, parentName, hasContentEditableState, lastContentEditable;
          lastContentEditable = contentEditable;
          nodeName = node.nodeName.toLowerCase();
          parentName = node.parentNode.nodeName.toLowerCase();
          if (node.nodeType === 1 && dom.getContentEditable(node)) {
            lastContentEditable = contentEditable;
            contentEditable = dom.getContentEditable(node) === 'true';
            hasContentEditableState = true;
          }
          if ($_dodtof5tjh8lyxdh.isEq(nodeName, 'br')) {
            currentWrapElm = 0;
            if (format.block) {
              dom.remove(node);
            }
            return;
          }
          if (format.wrapper && $_8qd8fq5ujh8lyxdx.matchNode(ed, node, name, vars)) {
            currentWrapElm = 0;
            return;
          }
          if (contentEditable && !hasContentEditableState && format.block && !format.wrapper && $_dodtof5tjh8lyxdh.isTextBlock(ed, nodeName) && $_dodtof5tjh8lyxdh.isValid(ed, parentName, wrapName)) {
            node = dom.rename(node, wrapName);
            setElementFormat(node);
            newWrappers.push(node);
            currentWrapElm = 0;
            return;
          }
          if (format.selector) {
            var found = applyNodeStyle(formatList, node);
            if (!format.inline || found) {
              currentWrapElm = 0;
              return;
            }
          }
          if (contentEditable && !hasContentEditableState && $_dodtof5tjh8lyxdh.isValid(ed, wrapName, nodeName) && $_dodtof5tjh8lyxdh.isValid(ed, parentName, wrapName) && !(!nodeSpecific && node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279) && !isCaretNode(node) && (!format.inline || !dom.isBlock(node))) {
            if (!currentWrapElm) {
              currentWrapElm = dom.clone(wrapElm, false);
              node.parentNode.insertBefore(currentWrapElm, node);
              newWrappers.push(currentWrapElm);
            }
            currentWrapElm.appendChild(node);
          } else {
            currentWrapElm = 0;
            each$15($_ahowuxkjh8lywbj.grep(node.childNodes), process);
            if (hasContentEditableState) {
              contentEditable = lastContentEditable;
            }
            currentWrapElm = 0;
          }
        };
        each$15(nodes, process);
      });
      if (format.links === true) {
        each$15(newWrappers, function (node) {
          var process = function (node) {
            if (node.nodeName === 'A') {
              setElementFormat(node, format);
            }
            each$15($_ahowuxkjh8lywbj.grep(node.childNodes), process);
          };
          process(node);
        });
      }
      each$15(newWrappers, function (node) {
        var childCount;
        var getChildCount = function (node) {
          var count = 0;
          each$15(node.childNodes, function (node) {
            if (!$_dodtof5tjh8lyxdh.isWhiteSpaceNode(node) && !$_eyp5ec2njh8lywpo.isBookmarkNode(node)) {
              count++;
            }
          });
          return count;
        };
        var getChildElementNode = function (root) {
          var child = false;
          each$15(root.childNodes, function (node) {
            if (isElementNode$1(node)) {
              child = node;
              return false;
            }
          });
          return child;
        };
        var mergeStyles = function (node) {
          var child, clone;
          child = getChildElementNode(node);
          if (child && !$_eyp5ec2njh8lywpo.isBookmarkNode(child) && $_8qd8fq5ujh8lyxdx.matchName(dom, child, format)) {
            clone = dom.clone(child, false);
            setElementFormat(clone);
            dom.replace(clone, node, true);
            dom.remove(child, 1);
          }
          return clone || node;
        };
        childCount = getChildCount(node);
        if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
          dom.remove(node, 1);
          return;
        }
        if (format.inline || format.wrapper) {
          if (!format.exact && childCount === 1) {
            node = mergeStyles(node);
          }
          $_3fattg5xjh8lyxe7.mergeWithChildren(ed, formatList, vars, node);
          $_3fattg5xjh8lyxe7.mergeWithParents(ed, format, name, vars, node);
          $_3fattg5xjh8lyxe7.mergeBackgroundColorAndFontSize(dom, format, vars, node);
          $_3fattg5xjh8lyxe7.mergeSubSup(dom, format, vars, node);
          $_3fattg5xjh8lyxe7.mergeSiblings(dom, format, vars, node);
        }
      });
    };
    if (dom.getContentEditable(selection.getNode()) === 'false') {
      node = selection.getNode();
      for (var i = 0, l = formatList.length; i < l; i++) {
        if (formatList[i].ceFalseOverride && dom.is(node, formatList[i].selector)) {
          setElementFormat(node, formatList[i]);
          return;
        }
      }
      return;
    }
    if (format) {
      if (node) {
        if (node.nodeType) {
          if (!applyNodeStyle(formatList, node)) {
            rng = dom.createRng();
            rng.setStartBefore(node);
            rng.setEndAfter(node);
            applyRngStyle(dom, $_fryklb5sjh8lyxd9.expandRng(ed, rng, formatList), null, true);
          }
        } else {
          applyRngStyle(dom, node, null, true);
        }
      } else {
        if (!isCollapsed || !format.inline || dom.select('td[data-mce-selected],th[data-mce-selected]').length) {
          var curSelNode = ed.selection.getNode();
          if (!ed.settings.forced_root_block && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
            applyFormat(ed, formatList[0].defaultBlock);
          }
          ed.selection.setRng($_cnbluh30jh8lywrn.normalize(ed.selection.getRng()));
          bookmark = $_8b82yg2ojh8lywpq.getPersistentBookmark(ed.selection, true);
          applyRngStyle(dom, $_fryklb5sjh8lyxd9.expandRng(ed, selection.getRng(), formatList), bookmark);
          if (format.styles) {
            $_3fattg5xjh8lyxe7.mergeUnderlineAndColor(dom, format, vars, curSelNode);
          }
          selection.moveToBookmark(bookmark);
          $_dodtof5tjh8lyxdh.moveStart(dom, selection, selection.getRng());
          ed.nodeChanged();
        } else {
          applyCaretFormat(ed, name, vars);
        }
      }
      $_78e03d5wjh8lyxe4.postProcess(name, ed);
    }
  };
  var $_36ocwe5qjh8lyxck = { applyFormat: applyFormat };

  var each$16 = $_ahowuxkjh8lywbj.each;
  var setup$3 = function (formatChangeData, editor) {
    var currentFormats = {};
    formatChangeData.set({});
    editor.on('NodeChange', function (e) {
      var parents = $_dodtof5tjh8lyxdh.getParents(editor.dom, e.element);
      var matchedFormats = {};
      parents = $_ahowuxkjh8lywbj.grep(parents, function (node) {
        return node.nodeType === 1 && !node.getAttribute('data-mce-bogus');
      });
      each$16(formatChangeData.get(), function (callbacks, format) {
        each$16(parents, function (node) {
          if (editor.formatter.matchNode(node, format, {}, callbacks.similar)) {
            if (!currentFormats[format]) {
              each$16(callbacks, function (callback) {
                callback(true, {
                  node: node,
                  format: format,
                  parents: parents
                });
              });
              currentFormats[format] = callbacks;
            }
            matchedFormats[format] = callbacks;
            return false;
          }
          if ($_8qd8fq5ujh8lyxdx.matchesUnInheritedFormatSelector(editor, node, format)) {
            return false;
          }
        });
      });
      each$16(currentFormats, function (callbacks, format) {
        if (!matchedFormats[format]) {
          delete currentFormats[format];
          each$16(callbacks, function (callback) {
            callback(false, {
              node: e.element,
              format: format,
              parents: parents
            });
          });
        }
      });
    });
  };
  var addListeners = function (formatChangeData, formats, callback, similar) {
    var formatChangeItems = formatChangeData.get();
    each$16(formats.split(','), function (format) {
      if (!formatChangeItems[format]) {
        formatChangeItems[format] = [];
        formatChangeItems[format].similar = similar;
      }
      formatChangeItems[format].push(callback);
    });
    formatChangeData.set(formatChangeItems);
  };
  var formatChanged = function (editor, formatChangeState, formats, callback, similar) {
    if (formatChangeState.get() === null) {
      setup$3(formatChangeState, editor);
    }
    addListeners(formatChangeState, formats, callback, similar);
  };
  var $_cpfal560jh8lyxeu = { formatChanged: formatChanged };

  var get$6 = function (dom) {
    var formats = {
      valigntop: [{
          selector: 'td,th',
          styles: { verticalAlign: 'top' }
        }],
      valignmiddle: [{
          selector: 'td,th',
          styles: { verticalAlign: 'middle' }
        }],
      valignbottom: [{
          selector: 'td,th',
          styles: { verticalAlign: 'bottom' }
        }],
      alignleft: [
        {
          selector: 'figure.image',
          collapsed: false,
          classes: 'align-left',
          ceFalseOverride: true,
          preview: 'font-family font-size'
        },
        {
          selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
          styles: { textAlign: 'left' },
          inherit: false,
          preview: false,
          defaultBlock: 'div'
        },
        {
          selector: 'img,table',
          collapsed: false,
          styles: { float: 'left' },
          preview: 'font-family font-size'
        }
      ],
      aligncenter: [
        {
          selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
          styles: { textAlign: 'center' },
          inherit: false,
          preview: 'font-family font-size',
          defaultBlock: 'div'
        },
        {
          selector: 'figure.image',
          collapsed: false,
          classes: 'align-center',
          ceFalseOverride: true,
          preview: 'font-family font-size'
        },
        {
          selector: 'img',
          collapsed: false,
          styles: {
            display: 'block',
            marginLeft: 'auto',
            marginRight: 'auto'
          },
          preview: false
        },
        {
          selector: 'table',
          collapsed: false,
          styles: {
            marginLeft: 'auto',
            marginRight: 'auto'
          },
          preview: 'font-family font-size'
        }
      ],
      alignright: [
        {
          selector: 'figure.image',
          collapsed: false,
          classes: 'align-right',
          ceFalseOverride: true,
          preview: 'font-family font-size'
        },
        {
          selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
          styles: { textAlign: 'right' },
          inherit: false,
          preview: 'font-family font-size',
          defaultBlock: 'div'
        },
        {
          selector: 'img,table',
          collapsed: false,
          styles: { float: 'right' },
          preview: 'font-family font-size'
        }
      ],
      alignjustify: [{
          selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
          styles: { textAlign: 'justify' },
          inherit: false,
          defaultBlock: 'div',
          preview: 'font-family font-size'
        }],
      bold: [
        {
          inline: 'strong',
          remove: 'all'
        },
        {
          inline: 'span',
          styles: { fontWeight: 'bold' }
        },
        {
          inline: 'b',
          remove: 'all'
        }
      ],
      italic: [
        {
          inline: 'em',
          remove: 'all'
        },
        {
          inline: 'span',
          styles: { fontStyle: 'italic' }
        },
        {
          inline: 'i',
          remove: 'all'
        }
      ],
      underline: [
        {
          inline: 'span',
          styles: { textDecoration: 'underline' },
          exact: true
        },
        {
          inline: 'u',
          remove: 'all'
        }
      ],
      strikethrough: [
        {
          inline: 'span',
          styles: { textDecoration: 'line-through' },
          exact: true
        },
        {
          inline: 'strike',
          remove: 'all'
        }
      ],
      forecolor: {
        inline: 'span',
        styles: { color: '%value' },
        links: true,
        remove_similar: true,
        clear_child_styles: true
      },
      hilitecolor: {
        inline: 'span',
        styles: { backgroundColor: '%value' },
        links: true,
        remove_similar: true,
        clear_child_styles: true
      },
      fontname: {
        inline: 'span',
        toggle: false,
        styles: { fontFamily: '%value' },
        clear_child_styles: true
      },
      fontsize: {
        inline: 'span',
        toggle: false,
        styles: { fontSize: '%value' },
        clear_child_styles: true
      },
      fontsize_class: {
        inline: 'span',
        attributes: { class: '%value' }
      },
      blockquote: {
        block: 'blockquote',
        wrapper: 1,
        remove: 'all'
      },
      subscript: { inline: 'sub' },
      superscript: { inline: 'sup' },
      code: { inline: 'code' },
      link: {
        inline: 'a',
        selector: 'a',
        remove: 'all',
        split: true,
        deep: true,
        onmatch: function () {
          return true;
        },
        onformat: function (elm, fmt, vars) {
          $_ahowuxkjh8lywbj.each(vars, function (value, key) {
            dom.setAttrib(elm, key, value);
          });
        }
      },
      removeformat: [
        {
          selector: 'b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins',
          remove: 'all',
          split: true,
          expand: false,
          block_expand: true,
          deep: true
        },
        {
          selector: 'span',
          attributes: [
            'style',
            'class'
          ],
          remove: 'empty',
          split: true,
          expand: false,
          deep: true
        },
        {
          selector: '*',
          attributes: [
            'style',
            'class'
          ],
          split: false,
          expand: false,
          deep: true
        }
      ]
    };
    $_ahowuxkjh8lywbj.each('p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp'.split(/\s/), function (name) {
      formats[name] = {
        block: name,
        remove: 'all'
      };
    });
    return formats;
  };
  var $_3zwfyl62jh8lyxez = { get: get$6 };

  function FormatRegistry (editor) {
    var formats = {};
    var get = function (name) {
      return name ? formats[name] : formats;
    };
    var register = function (name, format) {
      if (name) {
        if (typeof name !== 'string') {
          $_ahowuxkjh8lywbj.each(name, function (format, name) {
            register(name, format);
          });
        } else {
          format = format.length ? format : [format];
          $_ahowuxkjh8lywbj.each(format, function (format) {
            if (typeof format.deep === 'undefined') {
              format.deep = !format.selector;
            }
            if (typeof format.split === 'undefined') {
              format.split = !format.selector || format.inline;
            }
            if (typeof format.remove === 'undefined' && format.selector && !format.inline) {
              format.remove = 'none';
            }
            if (format.selector && format.inline) {
              format.mixed = true;
              format.block_expand = true;
            }
            if (typeof format.classes === 'string') {
              format.classes = format.classes.split(/\s+/);
            }
          });
          formats[name] = format;
        }
      }
    };
    var unregister = function (name) {
      if (name && formats[name]) {
        delete formats[name];
      }
      return formats;
    };
    register($_3zwfyl62jh8lyxez.get(editor.dom));
    register(editor.settings.formats);
    return {
      get: get,
      register: register,
      unregister: unregister
    };
  }

  var each$17 = $_ahowuxkjh8lywbj.each;
  var dom = DOMUtils$1.DOM;
  var parsedSelectorToHtml = function (ancestry, editor) {
    var elm, item, fragment;
    var schema = editor && editor.schema || Schema({});
    var decorate = function (elm, item) {
      if (item.classes.length) {
        dom.addClass(elm, item.classes.join(' '));
      }
      dom.setAttribs(elm, item.attrs);
    };
    var createElement = function (sItem) {
      var elm;
      item = typeof sItem === 'string' ? {
        name: sItem,
        classes: [],
        attrs: {}
      } : sItem;
      elm = dom.create(item.name);
      decorate(elm, item);
      return elm;
    };
    var getRequiredParent = function (elm, candidate) {
      var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
      var elmRule = schema.getElementRule(name);
      var parentsRequired = elmRule && elmRule.parentsRequired;
      if (parentsRequired && parentsRequired.length) {
        return candidate && $_ahowuxkjh8lywbj.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
      } else {
        return false;
      }
    };
    var wrapInHtml = function (elm, ancestry, siblings) {
      var parent, parentCandidate, parentRequired;
      var ancestor = ancestry.length > 0 && ancestry[0];
      var ancestorName = ancestor && ancestor.name;
      parentRequired = getRequiredParent(elm, ancestorName);
      if (parentRequired) {
        if (ancestorName === parentRequired) {
          parentCandidate = ancestry[0];
          ancestry = ancestry.slice(1);
        } else {
          parentCandidate = parentRequired;
        }
      } else if (ancestor) {
        parentCandidate = ancestry[0];
        ancestry = ancestry.slice(1);
      } else if (!siblings) {
        return elm;
      }
      if (parentCandidate) {
        parent = createElement(parentCandidate);
        parent.appendChild(elm);
      }
      if (siblings) {
        if (!parent) {
          parent = dom.create('div');
          parent.appendChild(elm);
        }
        $_ahowuxkjh8lywbj.each(siblings, function (sibling) {
          var siblingElm = createElement(sibling);
          parent.insertBefore(siblingElm, elm);
        });
      }
      return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
    };
    if (ancestry && ancestry.length) {
      item = ancestry[0];
      elm = createElement(item);
      fragment = dom.create('div');
      fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
      return fragment;
    } else {
      return '';
    }
  };
  var selectorToHtml = function (selector, editor) {
    return parsedSelectorToHtml(parseSelector(selector), editor);
  };
  var parseSelectorItem = function (item) {
    var tagName;
    var obj = {
      classes: [],
      attrs: {}
    };
    item = obj.selector = $_ahowuxkjh8lywbj.trim(item);
    if (item !== '*') {
      tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
        switch ($1) {
        case '#':
          obj.attrs.id = $2;
          break;
        case '.':
          obj.classes.push($2);
          break;
        case ':':
          if ($_ahowuxkjh8lywbj.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
            obj.attrs[$2] = $2;
          }
          break;
        }
        if ($3 === '[') {
          var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
          if (m) {
            obj.attrs[m[1]] = m[2];
          }
        }
        return '';
      });
    }
    obj.name = tagName || 'div';
    return obj;
  };
  var parseSelector = function (selector) {
    if (!selector || typeof selector !== 'string') {
      return [];
    }
    selector = selector.split(/\s*,\s*/)[0];
    selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
    return $_ahowuxkjh8lywbj.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
      var siblings = $_ahowuxkjh8lywbj.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
      var obj = siblings.pop();
      if (siblings.length) {
        obj.siblings = siblings;
      }
      return obj;
    }).reverse();
  };
  var getCssText = function (editor, format) {
    var name, previewFrag, previewElm, items;
    var previewCss = '', parentFontSize, previewStyles;
    previewStyles = editor.settings.preview_styles;
    if (previewStyles === false) {
      return '';
    }
    if (typeof previewStyles !== 'string') {
      previewStyles = 'font-family font-size font-weight font-style text-decoration ' + 'text-transform color background-color border border-radius outline text-shadow';
    }
    var removeVars = function (val) {
      return val.replace(/%(\w+)/g, '');
    };
    if (typeof format === 'string') {
      format = editor.formatter.get(format);
      if (!format) {
        return;
      }
      format = format[0];
    }
    if ('preview' in format) {
      previewStyles = format.preview;
      if (previewStyles === false) {
        return '';
      }
    }
    name = format.block || format.inline || 'span';
    items = parseSelector(format.selector);
    if (items.length) {
      if (!items[0].name) {
        items[0].name = name;
      }
      name = format.selector;
      previewFrag = parsedSelectorToHtml(items, editor);
    } else {
      previewFrag = parsedSelectorToHtml([name], editor);
    }
    previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
    each$17(format.styles, function (value, name) {
      value = removeVars(value);
      if (value) {
        dom.setStyle(previewElm, name, value);
      }
    });
    each$17(format.attributes, function (value, name) {
      value = removeVars(value);
      if (value) {
        dom.setAttrib(previewElm, name, value);
      }
    });
    each$17(format.classes, function (value) {
      value = removeVars(value);
      if (!dom.hasClass(previewElm, value)) {
        dom.addClass(previewElm, value);
      }
    });
    editor.fire('PreviewFormats');
    dom.setStyles(previewFrag, {
      position: 'absolute',
      left: -65535
    });
    editor.getBody().appendChild(previewFrag);
    parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
    parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
    each$17(previewStyles.split(' '), function (name) {
      var value = dom.getStyle(previewElm, name, true);
      if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
        value = dom.getStyle(editor.getBody(), name, true);
        if (dom.toHex(value).toLowerCase() === '#ffffff') {
          return;
        }
      }
      if (name === 'color') {
        if (dom.toHex(value).toLowerCase() === '#000000') {
          return;
        }
      }
      if (name === 'font-size') {
        if (/em|%$/.test(value)) {
          if (parentFontSize === 0) {
            return;
          }
          var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
          value = numValue * parentFontSize + 'px';
        }
      }
      if (name === 'border' && value) {
        previewCss += 'padding:0 2px;';
      }
      previewCss += name + ':' + value + ';';
    });
    editor.fire('AfterPreviewFormats');
    dom.remove(previewFrag);
    return previewCss;
  };
  var $_fwiqkm63jh8lyxf5 = {
    getCssText: getCssText,
    parseSelector: parseSelector,
    selectorToHtml: selectorToHtml
  };

  var toggle$2 = function (editor, formats, name, vars, node) {
    var fmt = formats.get(name);
    if ($_8qd8fq5ujh8lyxdx.match(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
      $_7cys7h5yjh8lyxeg.remove(editor, name, vars, node);
    } else {
      $_36ocwe5qjh8lyxck.applyFormat(editor, name, vars, node);
    }
  };
  var $_5bc2se64jh8lyxfc = { toggle: toggle$2 };

  var setup$4 = function (editor) {
    editor.addShortcut('meta+b', '', 'Bold');
    editor.addShortcut('meta+i', '', 'Italic');
    editor.addShortcut('meta+u', '', 'Underline');
    for (var i = 1; i <= 6; i++) {
      editor.addShortcut('access+' + i, '', [
        'FormatBlock',
        false,
        'h' + i
      ]);
    }
    editor.addShortcut('access+7', '', [
      'FormatBlock',
      false,
      'p'
    ]);
    editor.addShortcut('access+8', '', [
      'FormatBlock',
      false,
      'div'
    ]);
    editor.addShortcut('access+9', '', [
      'FormatBlock',
      false,
      'address'
    ]);
  };
  var $_3p946b65jh8lyxfe = { setup: setup$4 };

  function Formatter (editor) {
    var formats = FormatRegistry(editor);
    var formatChangeState = Cell(null);
    $_3p946b65jh8lyxfe.setup(editor);
    setup$2(editor);
    return {
      get: formats.get,
      register: formats.register,
      unregister: formats.unregister,
      apply: $_eqpqvr6jh8lyw3s.curry($_36ocwe5qjh8lyxck.applyFormat, editor),
      remove: $_eqpqvr6jh8lyw3s.curry($_7cys7h5yjh8lyxeg.remove, editor),
      toggle: $_eqpqvr6jh8lyw3s.curry($_5bc2se64jh8lyxfc.toggle, editor, formats),
      match: $_eqpqvr6jh8lyw3s.curry($_8qd8fq5ujh8lyxdx.match, editor),
      matchAll: $_eqpqvr6jh8lyw3s.curry($_8qd8fq5ujh8lyxdx.matchAll, editor),
      matchNode: $_eqpqvr6jh8lyw3s.curry($_8qd8fq5ujh8lyxdx.matchNode, editor),
      canApply: $_eqpqvr6jh8lyw3s.curry($_8qd8fq5ujh8lyxdx.canApply, editor),
      formatChanged: $_eqpqvr6jh8lyw3s.curry($_cpfal560jh8lyxeu.formatChanged, editor, formatChangeState),
      getCssText: $_eqpqvr6jh8lyw3s.curry($_fwiqkm63jh8lyxf5.getCssText, editor)
    };
  }

  var shallow = function (old, nu) {
    return nu;
  };
  var deep = function (old, nu) {
    var bothObjects = $_dp4g6d7jh8lyw3y.isObject(old) && $_dp4g6d7jh8lyw3y.isObject(nu);
    return bothObjects ? deepMerge(old, nu) : nu;
  };
  var baseMerge = function (merger) {
    return function () {
      var objects = new Array(arguments.length);
      for (var i = 0; i < objects.length; i++)
        objects[i] = arguments[i];
      if (objects.length === 0)
        throw new Error('Can\'t merge zero objects');
      var ret = {};
      for (var j = 0; j < objects.length; j++) {
        var curObject = objects[j];
        for (var key in curObject)
          if (curObject.hasOwnProperty(key)) {
            ret[key] = merger(ret[key], curObject[key]);
          }
      }
      return ret;
    };
  };
  var deepMerge = baseMerge(deep);
  var merge = baseMerge(shallow);
  var $_7ffry568jh8lyxfy = {
    deepMerge: deepMerge,
    merge: merge
  };

  var register = function (htmlParser, settings, dom) {
    htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
      var i = nodes.length, node;
      while (i--) {
        node = nodes[i];
        node.attr('tabindex', node.attributes.map['data-mce-tabindex']);
        node.attr(name, null);
      }
    });
    htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
      var i = nodes.length, node, value;
      var internalName = 'data-mce-' + name;
      var urlConverter = settings.url_converter;
      var urlConverterScope = settings.url_converter_scope;
      while (i--) {
        node = nodes[i];
        value = node.attributes.map[internalName];
        if (value !== undefined) {
          node.attr(name, value.length > 0 ? value : null);
          node.attr(internalName, null);
        } else {
          value = node.attributes.map[name];
          if (name === 'style') {
            value = dom.serializeStyle(dom.parseStyle(value), node.name);
          } else if (urlConverter) {
            value = urlConverter.call(urlConverterScope, value, name, node.name);
          }
          node.attr(name, value.length > 0 ? value : null);
        }
      }
    });
    htmlParser.addAttributeFilter('class', function (nodes) {
      var i = nodes.length, node, value;
      while (i--) {
        node = nodes[i];
        value = node.attr('class');
        if (value) {
          value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
          node.attr('class', value.length > 0 ? value : null);
        }
      }
    });
    htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
      var i = nodes.length, node;
      while (i--) {
        node = nodes[i];
        if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) {
          node.remove();
        }
      }
    });
    htmlParser.addNodeFilter('noscript', function (nodes) {
      var i = nodes.length, node;
      while (i--) {
        node = nodes[i].firstChild;
        if (node) {
          node.value = $_gex7a11rjh8lywi4.decode(node.value);
        }
      }
    });
    htmlParser.addNodeFilter('script,style', function (nodes, name) {
      var i = nodes.length, node, value, type;
      var trim = function (value) {
        return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n').replace(/^[\r\n]*|[\r\n]*$/g, '').replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '').replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
      };
      while (i--) {
        node = nodes[i];
        value = node.firstChild ? node.firstChild.value : '';
        if (name === 'script') {
          type = node.attr('type');
          if (type) {
            node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
          }
          if (settings.element_format === 'xhtml' && value.length > 0) {
            node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
          }
        } else {
          if (settings.element_format === 'xhtml' && value.length > 0) {
            node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
          }
        }
      }
    });
    htmlParser.addNodeFilter('#comment', function (nodes) {
      var i = nodes.length, node;
      while (i--) {
        node = nodes[i];
        if (node.value.indexOf('[CDATA[') === 0) {
          node.name = '#cdata';
          node.type = 4;
          node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, '');
        } else if (node.value.indexOf('mce:protected ') === 0) {
          node.name = '#text';
          node.type = 3;
          node.raw = true;
          node.value = unescape(node.value).substr(14);
        }
      }
    });
    htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
      var i = nodes.length, node;
      while (i--) {
        node = nodes[i];
        if (node.type === 7) {
          node.remove();
        } else if (node.type === 1) {
          if (name === 'input' && !('type' in node.attributes.map)) {
            node.attr('type', 'text');
          }
        }
      }
    });
    htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
      $_5wjzy24jh8lyw2t.each(nodes, function (node) {
        if (node.attr('data-mce-type') === 'format-caret') {
          if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
            node.remove();
          } else {
            node.unwrap();
          }
        }
      });
    });
    htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,' + 'data-mce-selected,data-mce-expando,' + 'data-mce-type,data-mce-resize', function (nodes, name) {
      var i = nodes.length;
      while (i--) {
        nodes[i].attr(name, null);
      }
    });
  };
  var trimTrailingBr = function (rootNode) {
    var brNode1, brNode2;
    var isBr = function (node) {
      return node && node.name === 'br';
    };
    brNode1 = rootNode.lastChild;
    if (isBr(brNode1)) {
      brNode2 = brNode1.prev;
      if (isBr(brNode2)) {
        brNode1.remove();
        brNode2.remove();
      }
    }
  };
  var $_834niu69jh8lyxg1 = {
    register: register,
    trimTrailingBr: trimTrailingBr
  };

  var preProcess = function (editor, node, args) {
    var impl, doc, oldDoc;
    var dom = editor.dom;
    node = node.cloneNode(true);
    impl = document.implementation;
    if (impl.createHTMLDocument) {
      doc = impl.createHTMLDocument('');
      $_ahowuxkjh8lywbj.each(node.nodeName === 'BODY' ? node.childNodes : [node], function (node) {
        doc.body.appendChild(doc.importNode(node, true));
      });
      if (node.nodeName !== 'BODY') {
        node = doc.body.firstChild;
      } else {
        node = doc.body;
      }
      oldDoc = dom.doc;
      dom.doc = doc;
    }
    $_a4fgrn4cjh8lyx4q.firePreProcess(editor, $_7ffry568jh8lyxfy.merge(args, { node: node }));
    if (oldDoc) {
      dom.doc = oldDoc;
    }
    return node;
  };
  var shouldFireEvent = function (editor, args) {
    return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  };
  var process = function (editor, node, args) {
    return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  };
  var $_gg1aca6ajh8lyxg7 = { process: process };

  var removeAttrs = function (node, names) {
    $_5wjzy24jh8lyw2t.each(names, function (name) {
      node.attr(name, null);
    });
  };
  var addFontToSpansFilter = function (domParser, styles, fontSizes) {
    domParser.addNodeFilter('font', function (nodes) {
      $_5wjzy24jh8lyw2t.each(nodes, function (node) {
        var props = styles.parse(node.attr('style'));
        var color = node.attr('color');
        var face = node.attr('face');
        var size = node.attr('size');
        if (color) {
          props.color = color;
        }
        if (face) {
          props['font-family'] = face;
        }
        if (size) {
          props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
        }
        node.name = 'span';
        node.attr('style', styles.serialize(props));
        removeAttrs(node, [
          'color',
          'face',
          'size'
        ]);
      });
    });
  };
  var addStrikeToSpanFilter = function (domParser, styles) {
    domParser.addNodeFilter('strike', function (nodes) {
      $_5wjzy24jh8lyw2t.each(nodes, function (node) {
        var props = styles.parse(node.attr('style'));
        props['text-decoration'] = 'line-through';
        node.name = 'span';
        node.attr('style', styles.serialize(props));
      });
    });
  };
  var addFilters = function (domParser, settings) {
    var styles = Styles();
    if (settings.convert_fonts_to_spans) {
      addFontToSpansFilter(domParser, styles, $_ahowuxkjh8lywbj.explode(settings.font_size_legacy_values));
    }
    addStrikeToSpanFilter(domParser, styles);
  };
  var register$1 = function (domParser, settings) {
    if (settings.inline_styles) {
      addFilters(domParser, settings);
    }
  };
  var $_9ewhzh6cjh8lyxgp = { register: register$1 };

  var whiteSpaceRegExp$3 = /^[ \t\r\n]*$/;
  var typeLookup = {
    '#text': 3,
    '#comment': 8,
    '#cdata': 4,
    '#pi': 7,
    '#doctype': 10,
    '#document-fragment': 11
  };
  var walk$3 = function (node, root, prev) {
    var sibling;
    var parent;
    var startName = prev ? 'lastChild' : 'firstChild';
    var siblingName = prev ? 'prev' : 'next';
    if (node[startName]) {
      return node[startName];
    }
    if (node !== root) {
      sibling = node[siblingName];
      if (sibling) {
        return sibling;
      }
      for (parent = node.parent; parent && parent !== root; parent = parent.parent) {
        sibling = parent[siblingName];
        if (sibling) {
          return sibling;
        }
      }
    }
  };
  var Node$2 = function () {
    function Node(name, type) {
      this.name = name;
      this.type = type;
      if (type === 1) {
        this.attributes = [];
        this.attributes.map = {};
      }
    }
    Node.create = function (name, attrs) {
      var node, attrName;
      node = new Node(name, typeLookup[name] || 1);
      if (attrs) {
        for (attrName in attrs) {
          node.attr(attrName, attrs[attrName]);
        }
      }
      return node;
    };
    Node.prototype.replace = function (node) {
      var self = this;
      if (node.parent) {
        node.remove();
      }
      self.insert(node, self);
      self.remove();
      return self;
    };
    Node.prototype.attr = function (name, value) {
      var self = this;
      var attrs, i;
      if (typeof name !== 'string') {
        for (i in name) {
          self.attr(i, name[i]);
        }
        return self;
      }
      if (attrs = self.attributes) {
        if (value !== undefined) {
          if (value === null) {
            if (name in attrs.map) {
              delete attrs.map[name];
              i = attrs.length;
              while (i--) {
                if (attrs[i].name === name) {
                  attrs = attrs.splice(i, 1);
                  return self;
                }
              }
            }
            return self;
          }
          if (name in attrs.map) {
            i = attrs.length;
            while (i--) {
              if (attrs[i].name === name) {
                attrs[i].value = value;
                break;
              }
            }
          } else {
            attrs.push({
              name: name,
              value: value
            });
          }
          attrs.map[name] = value;
          return self;
        }
        return attrs.map[name];
      }
    };
    Node.prototype.clone = function () {
      var self = this;
      var clone = new Node(self.name, self.type);
      var i, l, selfAttrs, selfAttr, cloneAttrs;
      if (selfAttrs = self.attributes) {
        cloneAttrs = [];
        cloneAttrs.map = {};
        for (i = 0, l = selfAttrs.length; i < l; i++) {
          selfAttr = selfAttrs[i];
          if (selfAttr.name !== 'id') {
            cloneAttrs[cloneAttrs.length] = {
              name: selfAttr.name,
              value: selfAttr.value
            };
            cloneAttrs.map[selfAttr.name] = selfAttr.value;
          }
        }
        clone.attributes = cloneAttrs;
      }
      clone.value = self.value;
      clone.shortEnded = self.shortEnded;
      return clone;
    };
    Node.prototype.wrap = function (wrapper) {
      var self = this;
      self.parent.insert(wrapper, self);
      wrapper.append(self);
      return self;
    };
    Node.prototype.unwrap = function () {
      var self = this;
      var node, next;
      for (node = self.firstChild; node;) {
        next = node.next;
        self.insert(node, self, true);
        node = next;
      }
      self.remove();
    };
    Node.prototype.remove = function () {
      var self = this, parent = self.parent, next = self.next, prev = self.prev;
      if (parent) {
        if (parent.firstChild === self) {
          parent.firstChild = next;
          if (next) {
            next.prev = null;
          }
        } else {
          prev.next = next;
        }
        if (parent.lastChild === self) {
          parent.lastChild = prev;
          if (prev) {
            prev.next = null;
          }
        } else {
          next.prev = prev;
        }
        self.parent = self.next = self.prev = null;
      }
      return self;
    };
    Node.prototype.append = function (node) {
      var self = this;
      var last;
      if (node.parent) {
        node.remove();
      }
      last = self.lastChild;
      if (last) {
        last.next = node;
        node.prev = last;
        self.lastChild = node;
      } else {
        self.lastChild = self.firstChild = node;
      }
      node.parent = self;
      return node;
    };
    Node.prototype.insert = function (node, refNode, before) {
      var parent;
      if (node.parent) {
        node.remove();
      }
      parent = refNode.parent || this;
      if (before) {
        if (refNode === parent.firstChild) {
          parent.firstChild = node;
        } else {
          refNode.prev.next = node;
        }
        node.prev = refNode.prev;
        node.next = refNode;
        refNode.prev = node;
      } else {
        if (refNode === parent.lastChild) {
          parent.lastChild = node;
        } else {
          refNode.next.prev = node;
        }
        node.next = refNode.next;
        node.prev = refNode;
        refNode.next = node;
      }
      node.parent = parent;
      return node;
    };
    Node.prototype.getAll = function (name) {
      var self = this;
      var node;
      var collection = [];
      for (node = self.firstChild; node; node = walk$3(node, self)) {
        if (node.name === name) {
          collection.push(node);
        }
      }
      return collection;
    };
    Node.prototype.empty = function () {
      var self = this;
      var nodes, i, node;
      if (self.firstChild) {
        nodes = [];
        for (node = self.firstChild; node; node = walk$3(node, self)) {
          nodes.push(node);
        }
        i = nodes.length;
        while (i--) {
          node = nodes[i];
          node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
        }
      }
      self.firstChild = self.lastChild = null;
      return self;
    };
    Node.prototype.isEmpty = function (elements, whitespace, predicate) {
      var self = this;
      var node = self.firstChild, i, name;
      whitespace = whitespace || {};
      if (node) {
        do {
          if (node.type === 1) {
            if (node.attributes.map['data-mce-bogus']) {
              continue;
            }
            if (elements[node.name]) {
              return false;
            }
            i = node.attributes.length;
            while (i--) {
              name = node.attributes[i].name;
              if (name === 'name' || name.indexOf('data-mce-bookmark') === 0) {
                return false;
              }
            }
          }
          if (node.type === 8) {
            return false;
          }
          if (node.type === 3 && !whiteSpaceRegExp$3.test(node.value)) {
            return false;
          }
          if (node.type === 3 && node.parent && whitespace[node.parent.name] && whiteSpaceRegExp$3.test(node.value)) {
            return false;
          }
          if (predicate && predicate(node)) {
            return false;
          }
        } while (node = walk$3(node, self));
      }
      return true;
    };
    Node.prototype.walk = function (prev) {
      return walk$3(this, null, prev);
    };
    return Node;
  }();

  var paddEmptyNode = function (settings, args, blockElements, node) {
    var brPreferred = settings.padd_empty_with_br || args.insert;
    if (brPreferred && blockElements[node.name]) {
      node.empty().append(new Node$2('br', 1)).shortEnded = true;
    } else {
      node.empty().append(new Node$2('#text', 3)).value = '\xA0';
    }
  };
  var isPaddedWithNbsp = function (node) {
    return hasOnlyChild(node, '#text') && node.firstChild.value === '\xA0';
  };
  var hasOnlyChild = function (node, name) {
    return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  };
  var isPadded = function (schema, node) {
    var rule = schema.getElementRule(node.name);
    return rule && rule.paddEmpty;
  };
  var isEmpty$2 = function (schema, nonEmptyElements, whitespaceElements, node) {
    return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
      return isPadded(schema, node);
    });
  };
  var isLineBreakNode = function (node, blockElements) {
    return node && (blockElements[node.name] || node.name === 'br');
  };

  var register$2 = function (parser, settings) {
    var schema = parser.schema;
    if (settings.remove_trailing_brs) {
      parser.addNodeFilter('br', function (nodes, _, args) {
        var i;
        var l = nodes.length;
        var node;
        var blockElements = $_ahowuxkjh8lywbj.extend({}, schema.getBlockElements());
        var nonEmptyElements = schema.getNonEmptyElements();
        var parent, lastParent, prev, prevName;
        var whiteSpaceElements = schema.getNonEmptyElements();
        var elementRule, textNode;
        blockElements.body = 1;
        for (i = 0; i < l; i++) {
          node = nodes[i];
          parent = node.parent;
          if (blockElements[node.parent.name] && node === parent.lastChild) {
            prev = node.prev;
            while (prev) {
              prevName = prev.name;
              if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
                if (prevName !== 'br') {
                  break;
                }
                if (prevName === 'br') {
                  node = null;
                  break;
                }
              }
              prev = prev.prev;
            }
            if (node) {
              node.remove();
              if (isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, parent)) {
                elementRule = schema.getElementRule(parent.name);
                if (elementRule) {
                  if (elementRule.removeEmpty) {
                    parent.remove();
                  } else if (elementRule.paddEmpty) {
                    paddEmptyNode(settings, args, blockElements, parent);
                  }
                }
              }
            }
          } else {
            lastParent = node;
            while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
              lastParent = parent;
              if (blockElements[parent.name]) {
                break;
              }
              parent = parent.parent;
            }
            if (lastParent === parent && settings.padd_empty_with_br !== true) {
              textNode = new Node$2('#text', 3);
              textNode.value = '\xA0';
              node.replace(textNode);
            }
          }
        }
      });
    }
    parser.addAttributeFilter('href', function (nodes) {
      var i = nodes.length, node;
      var appendRel = function (rel) {
        var parts = rel.split(' ').filter(function (p) {
          return p.length > 0;
        });
        return parts.concat(['noopener']).sort().join(' ');
      };
      var addNoOpener = function (rel) {
        var newRel = rel ? $_ahowuxkjh8lywbj.trim(rel) : '';
        if (!/\b(noopener)\b/g.test(newRel)) {
          return appendRel(newRel);
        } else {
          return newRel;
        }
      };
      if (!settings.allow_unsafe_link_target) {
        while (i--) {
          node = nodes[i];
          if (node.name === 'a' && node.attr('target') === '_blank') {
            node.attr('rel', addNoOpener(node.attr('rel')));
          }
        }
      }
    });
    if (!settings.allow_html_in_named_anchor) {
      parser.addAttributeFilter('id,name', function (nodes) {
        var i = nodes.length, sibling, prevSibling, parent, node;
        while (i--) {
          node = nodes[i];
          if (node.name === 'a' && node.firstChild && !node.attr('href')) {
            parent = node.parent;
            sibling = node.lastChild;
            do {
              prevSibling = sibling.prev;
              parent.insert(sibling, node);
              sibling = prevSibling;
            } while (sibling);
          }
        }
      });
    }
    if (settings.fix_list_elements) {
      parser.addNodeFilter('ul,ol', function (nodes) {
        var i = nodes.length, node, parentNode;
        while (i--) {
          node = nodes[i];
          parentNode = node.parent;
          if (parentNode.name === 'ul' || parentNode.name === 'ol') {
            if (node.prev && node.prev.name === 'li') {
              node.prev.append(node);
            } else {
              var li = new Node$2('li', 1);
              li.attr('style', 'list-style-type: none');
              node.wrap(li);
            }
          }
        }
      });
    }
    if (settings.validate && schema.getValidClasses()) {
      parser.addAttributeFilter('class', function (nodes) {
        var i = nodes.length, node, classList, ci, className, classValue;
        var validClasses = schema.getValidClasses();
        var validClassesMap, valid;
        while (i--) {
          node = nodes[i];
          classList = node.attr('class').split(' ');
          classValue = '';
          for (ci = 0; ci < classList.length; ci++) {
            className = classList[ci];
            valid = false;
            validClassesMap = validClasses['*'];
            if (validClassesMap && validClassesMap[className]) {
              valid = true;
            }
            validClassesMap = validClasses[node.name];
            if (!valid && validClassesMap && validClassesMap[className]) {
              valid = true;
            }
            if (valid) {
              if (classValue) {
                classValue += ' ';
              }
              classValue += className;
            }
          }
          if (!classValue.length) {
            classValue = null;
          }
          node.attr('class', classValue);
        }
      });
    }
  };

  var makeMap$4 = $_ahowuxkjh8lywbj.makeMap;
  var each$18 = $_ahowuxkjh8lywbj.each;
  var explode$3 = $_ahowuxkjh8lywbj.explode;
  var extend$3 = $_ahowuxkjh8lywbj.extend;
  function DomParser (settings, schema) {
    if (schema === void 0) {
      schema = Schema();
    }
    var nodeFilters = {};
    var attributeFilters = [];
    var matchedNodes = {};
    var matchedAttributes = {};
    settings = settings || {};
    settings.validate = 'validate' in settings ? settings.validate : true;
    settings.root_name = settings.root_name || 'body';
    var fixInvalidChildren = function (nodes) {
      var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i;
      var nonEmptyElements, whitespaceElements, nonSplitableElements, textBlockElements, specialElements, sibling, nextNode;
      nonSplitableElements = makeMap$4('tr,td,th,tbody,thead,tfoot,table');
      nonEmptyElements = schema.getNonEmptyElements();
      whitespaceElements = schema.getWhiteSpaceElements();
      textBlockElements = schema.getTextBlockElements();
      specialElements = schema.getSpecialElements();
      for (ni = 0; ni < nodes.length; ni++) {
        node = nodes[ni];
        if (!node.parent || node.fixed) {
          continue;
        }
        if (textBlockElements[node.name] && node.parent.name === 'li') {
          sibling = node.next;
          while (sibling) {
            if (textBlockElements[sibling.name]) {
              sibling.name = 'li';
              sibling.fixed = true;
              node.parent.insert(sibling, node.parent);
            } else {
              break;
            }
            sibling = sibling.next;
          }
          node.unwrap(node);
          continue;
        }
        parents = [node];
        for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent) {
          parents.push(parent);
        }
        if (parent && parents.length > 1) {
          parents.reverse();
          newParent = currentNode = filterNode(parents[0].clone());
          for (i = 0; i < parents.length - 1; i++) {
            if (schema.isValidChild(currentNode.name, parents[i].name)) {
              tempNode = filterNode(parents[i].clone());
              currentNode.append(tempNode);
            } else {
              tempNode = currentNode;
            }
            for (childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
              nextNode = childNode.next;
              tempNode.append(childNode);
              childNode = nextNode;
            }
            currentNode = tempNode;
          }
          if (!isEmpty$2(schema, nonEmptyElements, whitespaceElements, newParent)) {
            parent.insert(newParent, parents[0], true);
            parent.insert(node, newParent);
          } else {
            parent.insert(node, parents[0], true);
          }
          parent = parents[0];
          if (isEmpty$2(schema, nonEmptyElements, whitespaceElements, parent) || hasOnlyChild(parent, 'br')) {
            parent.empty().remove();
          }
        } else if (node.parent) {
          if (node.name === 'li') {
            sibling = node.prev;
            if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
              sibling.append(node);
              continue;
            }
            sibling = node.next;
            if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
              sibling.insert(node, sibling.firstChild, true);
              continue;
            }
            node.wrap(filterNode(new Node$2('ul', 1)));
            continue;
          }
          if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
            node.wrap(filterNode(new Node$2('div', 1)));
          } else {
            if (specialElements[node.name]) {
              node.empty().remove();
            } else {
              node.unwrap();
            }
          }
        }
      }
    };
    var filterNode = function (node) {
      var i, name, list;
      if (name in nodeFilters) {
        list = matchedNodes[name];
        if (list) {
          list.push(node);
        } else {
          matchedNodes[name] = [node];
        }
      }
      i = attributeFilters.length;
      while (i--) {
        name = attributeFilters[i].name;
        if (name in node.attributes.map) {
          list = matchedAttributes[name];
          if (list) {
            list.push(node);
          } else {
            matchedAttributes[name] = [node];
          }
        }
      }
      return node;
    };
    var addNodeFilter = function (name, callback) {
      each$18(explode$3(name), function (name) {
        var list = nodeFilters[name];
        if (!list) {
          nodeFilters[name] = list = [];
        }
        list.push(callback);
      });
    };
    var getNodeFilters = function () {
      var out = [];
      for (var name_1 in nodeFilters) {
        if (nodeFilters.hasOwnProperty(name_1)) {
          out.push({
            name: name_1,
            callbacks: nodeFilters[name_1]
          });
        }
      }
      return out;
    };
    var addAttributeFilter = function (name, callback) {
      each$18(explode$3(name), function (name) {
        var i;
        for (i = 0; i < attributeFilters.length; i++) {
          if (attributeFilters[i].name === name) {
            attributeFilters[i].callbacks.push(callback);
            return;
          }
        }
        attributeFilters.push({
          name: name,
          callbacks: [callback]
        });
      });
    };
    var getAttributeFilters = function () {
      return [].concat(attributeFilters);
    };
    var parse = function (html, args) {
      var parser, nodes, i, l, fi, fl, list, name;
      var blockElements;
      var invalidChildren = [];
      var isInWhiteSpacePreservedElement;
      var node;
      args = args || {};
      matchedNodes = {};
      matchedAttributes = {};
      blockElements = extend$3(makeMap$4('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
      var nonEmptyElements = schema.getNonEmptyElements();
      var children = schema.children;
      var validate = settings.validate;
      var rootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
      var whiteSpaceElements = schema.getWhiteSpaceElements();
      var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
      var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
      var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
      var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
      isInWhiteSpacePreservedElement = whiteSpaceElements.hasOwnProperty(args.context) || whiteSpaceElements.hasOwnProperty(settings.root_name);
      var addRootBlocks = function () {
        var node = rootNode.firstChild, next, rootBlockNode;
        var trim = function (rootBlockNode) {
          if (rootBlockNode) {
            node = rootBlockNode.firstChild;
            if (node && node.type === 3) {
              node.value = node.value.replace(startWhiteSpaceRegExp, '');
            }
            node = rootBlockNode.lastChild;
            if (node && node.type === 3) {
              node.value = node.value.replace(endWhiteSpaceRegExp, '');
            }
          }
        };
        if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
          return;
        }
        while (node) {
          next = node.next;
          if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
            if (!rootBlockNode) {
              rootBlockNode = createNode(rootBlockName, 1);
              rootBlockNode.attr(settings.forced_root_block_attrs);
              rootNode.insert(rootBlockNode, node);
              rootBlockNode.append(node);
            } else {
              rootBlockNode.append(node);
            }
          } else {
            trim(rootBlockNode);
            rootBlockNode = null;
          }
          node = next;
        }
        trim(rootBlockNode);
      };
      var createNode = function (name, type) {
        var node = new Node$2(name, type);
        var list;
        if (name in nodeFilters) {
          list = matchedNodes[name];
          if (list) {
            list.push(node);
          } else {
            matchedNodes[name] = [node];
          }
        }
        return node;
      };
      var removeWhitespaceBefore = function (node) {
        var textNode, textNodeNext, textVal, sibling;
        var blockElements = schema.getBlockElements();
        for (textNode = node.prev; textNode && textNode.type === 3;) {
          textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
          if (textVal.length > 0) {
            textNode.value = textVal;
            return;
          }
          textNodeNext = textNode.next;
          if (textNodeNext) {
            if (textNodeNext.type === 3 && textNodeNext.value.length) {
              textNode = textNode.prev;
              continue;
            }
            if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
              textNode = textNode.prev;
              continue;
            }
          }
          sibling = textNode.prev;
          textNode.remove();
          textNode = sibling;
        }
      };
      var cloneAndExcludeBlocks = function (input) {
        var name;
        var output = {};
        for (name in input) {
          if (name !== 'li' && name !== 'p') {
            output[name] = input[name];
          }
        }
        return output;
      };
      parser = SaxParser$1({
        validate: validate,
        allow_script_urls: settings.allow_script_urls,
        allow_conditional_comments: settings.allow_conditional_comments,
        self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
        cdata: function (text) {
          node.append(createNode('#cdata', 4)).value = text;
        },
        text: function (text, raw) {
          var textNode;
          if (!isInWhiteSpacePreservedElement) {
            text = text.replace(allWhiteSpaceRegExp, ' ');
            if (isLineBreakNode(node.lastChild, blockElements)) {
              text = text.replace(startWhiteSpaceRegExp, '');
            }
          }
          if (text.length !== 0) {
            textNode = createNode('#text', 3);
            textNode.raw = !!raw;
            node.append(textNode).value = text;
          }
        },
        comment: function (text) {
          node.append(createNode('#comment', 8)).value = text;
        },
        pi: function (name, text) {
          node.append(createNode(name, 7)).value = text;
          removeWhitespaceBefore(node);
        },
        doctype: function (text) {
          var newNode;
          newNode = node.append(createNode('#doctype', 10));
          newNode.value = text;
          removeWhitespaceBefore(node);
        },
        start: function (name, attrs, empty) {
          var newNode, attrFiltersLen, elementRule, attrName, parent;
          elementRule = validate ? schema.getElementRule(name) : {};
          if (elementRule) {
            newNode = createNode(elementRule.outputName || name, 1);
            newNode.attributes = attrs;
            newNode.shortEnded = empty;
            node.append(newNode);
            parent = children[node.name];
            if (parent && children[newNode.name] && !parent[newNode.name]) {
              invalidChildren.push(newNode);
            }
            attrFiltersLen = attributeFilters.length;
            while (attrFiltersLen--) {
              attrName = attributeFilters[attrFiltersLen].name;
              if (attrName in attrs.map) {
                list = matchedAttributes[attrName];
                if (list) {
                  list.push(newNode);
                } else {
                  matchedAttributes[attrName] = [newNode];
                }
              }
            }
            if (blockElements[name]) {
              removeWhitespaceBefore(newNode);
            }
            if (!empty) {
              node = newNode;
            }
            if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
              isInWhiteSpacePreservedElement = true;
            }
          }
        },
        end: function (name) {
          var textNode, elementRule, text, sibling, tempNode;
          elementRule = validate ? schema.getElementRule(name) : {};
          if (elementRule) {
            if (blockElements[name]) {
              if (!isInWhiteSpacePreservedElement) {
                textNode = node.firstChild;
                if (textNode && textNode.type === 3) {
                  text = textNode.value.replace(startWhiteSpaceRegExp, '');
                  if (text.length > 0) {
                    textNode.value = text;
                    textNode = textNode.next;
                  } else {
                    sibling = textNode.next;
                    textNode.remove();
                    textNode = sibling;
                    while (textNode && textNode.type === 3) {
                      text = textNode.value;
                      sibling = textNode.next;
                      if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                        textNode.remove();
                        textNode = sibling;
                      }
                      textNode = sibling;
                    }
                  }
                }
                textNode = node.lastChild;
                if (textNode && textNode.type === 3) {
                  text = textNode.value.replace(endWhiteSpaceRegExp, '');
                  if (text.length > 0) {
                    textNode.value = text;
                    textNode = textNode.prev;
                  } else {
                    sibling = textNode.prev;
                    textNode.remove();
                    textNode = sibling;
                    while (textNode && textNode.type === 3) {
                      text = textNode.value;
                      sibling = textNode.prev;
                      if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                        textNode.remove();
                        textNode = sibling;
                      }
                      textNode = sibling;
                    }
                  }
                }
              }
            }
            if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
              isInWhiteSpacePreservedElement = false;
            }
            if (elementRule.removeEmpty && isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node)) {
              if (!node.attributes.map.name && !node.attr('id')) {
                tempNode = node.parent;
                if (blockElements[node.name]) {
                  node.empty().remove();
                } else {
                  node.unwrap();
                }
                node = tempNode;
                return;
              }
            }
            if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node))) {
              paddEmptyNode(settings, args, blockElements, node);
            }
            node = node.parent;
          }
        }
      }, schema);
      var rootNode = node = new Node$2(args.context || settings.root_name, 11);
      parser.parse(html);
      if (validate && invalidChildren.length) {
        if (!args.context) {
          fixInvalidChildren(invalidChildren);
        } else {
          args.invalid = true;
        }
      }
      if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
        addRootBlocks();
      }
      if (!args.invalid) {
        for (name in matchedNodes) {
          list = nodeFilters[name];
          nodes = matchedNodes[name];
          fi = nodes.length;
          while (fi--) {
            if (!nodes[fi].parent) {
              nodes.splice(fi, 1);
            }
          }
          for (i = 0, l = list.length; i < l; i++) {
            list[i](nodes, name, args);
          }
        }
        for (i = 0, l = attributeFilters.length; i < l; i++) {
          list = attributeFilters[i];
          if (list.name in matchedAttributes) {
            nodes = matchedAttributes[list.name];
            fi = nodes.length;
            while (fi--) {
              if (!nodes[fi].parent) {
                nodes.splice(fi, 1);
              }
            }
            for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
              list.callbacks[fi](nodes, list.name, args);
            }
          }
        }
      }
      return rootNode;
    };
    var exports = {
      schema: schema,
      addAttributeFilter: addAttributeFilter,
      getAttributeFilters: getAttributeFilters,
      addNodeFilter: addNodeFilter,
      getNodeFilters: getNodeFilters,
      filterNode: filterNode,
      parse: parse
    };
    register$2(exports, settings);
    $_9ewhzh6cjh8lyxgp.register(exports, settings);
    return exports;
  }

  var addTempAttr = function (htmlParser, tempAttrs, name) {
    if ($_ahowuxkjh8lywbj.inArray(tempAttrs, name) === -1) {
      htmlParser.addAttributeFilter(name, function (nodes, name) {
        var i = nodes.length;
        while (i--) {
          nodes[i].attr(name, null);
        }
      });
      tempAttrs.push(name);
    }
  };
  var postProcess$1 = function (editor, args, content) {
    if (!args.no_events && editor) {
      var outArgs = $_a4fgrn4cjh8lyx4q.firePostProcess(editor, $_7ffry568jh8lyxfy.merge(args, { content: content }));
      return outArgs.content;
    } else {
      return content;
    }
  };
  var getHtmlFromNode = function (dom, node, args) {
    var html = $_d383mr21jh8lywlv.trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
    return args.selection || isWsPreserveElement($_cgttw3zjh8lywdq.fromDom(node)) ? html : $_ahowuxkjh8lywbj.trim(html);
  };
  var parseHtml = function (htmlParser, html, args) {
    var parserArgs = args.selection ? $_7ffry568jh8lyxfy.merge({ forced_root_block: false }, args) : args;
    var rootNode = htmlParser.parse(html, parserArgs);
    $_834niu69jh8lyxg1.trimTrailingBr(rootNode);
    return rootNode;
  };
  var serializeNode = function (settings, schema, node) {
    var htmlSerializer = HtmlSerializer(settings, schema);
    return htmlSerializer.serialize(node);
  };
  var toHtml = function (editor, settings, schema, rootNode, args) {
    var content = serializeNode(settings, schema, rootNode);
    return postProcess$1(editor, args, content);
  };
  function DomSerializer (settings, editor) {
    var dom, schema, htmlParser;
    var tempAttrs = ['data-mce-selected'];
    dom = editor && editor.dom ? editor.dom : DOMUtils$1.DOM;
    schema = editor && editor.schema ? editor.schema : Schema(settings);
    settings.entity_encoding = settings.entity_encoding || 'named';
    settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
    htmlParser = DomParser(settings, schema);
    $_834niu69jh8lyxg1.register(htmlParser, settings, dom);
    var serialize = function (node, parserArgs) {
      var args = $_7ffry568jh8lyxfy.merge({ format: 'html' }, parserArgs ? parserArgs : {});
      var targetNode = $_gg1aca6ajh8lyxg7.process(editor, node, args);
      var html = getHtmlFromNode(dom, targetNode, args);
      var rootNode = parseHtml(htmlParser, html, args);
      return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
    };
    return {
      schema: schema,
      addNodeFilter: htmlParser.addNodeFilter,
      addAttributeFilter: htmlParser.addAttributeFilter,
      serialize: serialize,
      addRules: function (rules) {
        schema.addValidElements(rules);
      },
      setRules: function (rules) {
        schema.setValidElements(rules);
      },
      addTempAttr: $_eqpqvr6jh8lyw3s.curry(addTempAttr, htmlParser, tempAttrs),
      getTempAttrs: function () {
        return tempAttrs;
      }
    };
  }

  function DomSerializer$1 (settings, editor) {
    var domSerializer = DomSerializer(settings, editor);
    return {
      schema: domSerializer.schema,
      addNodeFilter: domSerializer.addNodeFilter,
      addAttributeFilter: domSerializer.addAttributeFilter,
      serialize: domSerializer.serialize,
      addRules: domSerializer.addRules,
      setRules: domSerializer.setRules,
      addTempAttr: domSerializer.addTempAttr,
      getTempAttrs: domSerializer.getTempAttrs
    };
  }

  function BookmarkManager(selection) {
    return {
      getBookmark: $_eqpqvr6jh8lyw3s.curry($_eyp5ec2njh8lywpo.getBookmark, selection),
      moveToBookmark: $_eqpqvr6jh8lyw3s.curry($_eyp5ec2njh8lywpo.moveToBookmark, selection)
    };
  }
  (function (BookmarkManager) {
    BookmarkManager.isBookmarkNode = $_eyp5ec2njh8lywpo.isBookmarkNode;
  }(BookmarkManager || (BookmarkManager = {})));
  var BookmarkManager$1 = BookmarkManager;

  var isContentEditableFalse$10 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var isContentEditableTrue$6 = $_5oonaz1qjh8lywhz.isContentEditableTrue;
  var getContentEditableRoot$2 = function (root, node) {
    while (node && node !== root) {
      if (isContentEditableTrue$6(node) || isContentEditableFalse$10(node)) {
        return node;
      }
      node = node.parentNode;
    }
    return null;
  };
  var ControlSelection = function (selection, editor) {
    var dom = editor.dom, each = $_ahowuxkjh8lywbj.each;
    var selectedElm, selectedElmGhost, resizeHelper, resizeHandles, selectedHandle;
    var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
    var width, height;
    var editableDoc = editor.getDoc(), rootDocument = document;
    var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
    var startScrollWidth, startScrollHeight;
    resizeHandles = {
      nw: [
        0,
        0,
        -1,
        -1
      ],
      ne: [
        1,
        0,
        1,
        -1
      ],
      se: [
        1,
        1,
        1,
        1
      ],
      sw: [
        0,
        1,
        -1,
        1
      ]
    };
    var rootClass = '.mce-content-body';
    editor.contentStyles.push(rootClass + ' div.mce-resizehandle {' + 'position: absolute;' + 'border: 1px solid black;' + 'box-sizing: content-box;' + 'background: #FFF;' + 'width: 7px;' + 'height: 7px;' + 'z-index: 10000' + '}' + rootClass + ' .mce-resizehandle:hover {' + 'background: #000' + '}' + rootClass + ' img[data-mce-selected],' + rootClass + ' hr[data-mce-selected] {' + 'outline: 1px solid black;' + 'resize: none' + '}' + rootClass + ' .mce-clonedresizable {' + 'position: absolute;' + ($_9bpim8ajh8lyw68.gecko ? '' : 'outline: 1px dashed black;') + 'opacity: .5;' + 'filter: alpha(opacity=50);' + 'z-index: 10000' + '}' + rootClass + ' .mce-resize-helper {' + 'background: #555;' + 'background: rgba(0,0,0,0.75);' + 'border-radius: 3px;' + 'border: 1px;' + 'color: white;' + 'display: none;' + 'font-family: sans-serif;' + 'font-size: 12px;' + 'white-space: nowrap;' + 'line-height: 14px;' + 'margin: 5px 10px;' + 'padding: 5px;' + 'position: absolute;' + 'z-index: 10001' + '}');
    var isImage = function (elm) {
      return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
    };
    var isEventOnImageOutsideRange = function (evt, range) {
      return isImage(evt.target) && !$_3kj84i5djh8lyxan.isXYWithinRange(evt.clientX, evt.clientY, range);
    };
    var contextMenuSelectImage = function (evt) {
      var target = evt.target;
      if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
        evt.preventDefault();
        editor.selection.select(target);
      }
    };
    var getResizeTarget = function (elm) {
      return editor.dom.is(elm, 'figure.image') ? elm.querySelector('img') : elm;
    };
    var isResizable = function (elm) {
      var selector = editor.settings.object_resizing;
      if (selector === false || $_9bpim8ajh8lyw68.iOS) {
        return false;
      }
      if (typeof selector !== 'string') {
        selector = 'table,img,figure.image,div';
      }
      if (elm.getAttribute('data-mce-resize') === 'false') {
        return false;
      }
      if (elm === editor.getBody()) {
        return false;
      }
      return $_5h4ipt1fjh8lywgi.is($_cgttw3zjh8lywdq.fromDom(elm), selector);
    };
    var resizeGhostElement = function (e) {
      var deltaX, deltaY, proportional;
      var resizeHelperX, resizeHelperY;
      deltaX = e.screenX - startX;
      deltaY = e.screenY - startY;
      width = deltaX * selectedHandle[2] + startW;
      height = deltaY * selectedHandle[3] + startH;
      width = width < 5 ? 5 : width;
      height = height < 5 ? 5 : height;
      if (isImage(selectedElm) && editor.settings.resize_img_proportional !== false) {
        proportional = !$_6lsk4i5gjh8lyxau.modifierPressed(e);
      } else {
        proportional = $_6lsk4i5gjh8lyxau.modifierPressed(e) || isImage(selectedElm) && selectedHandle[2] * selectedHandle[3] !== 0;
      }
      if (proportional) {
        if (abs(deltaX) > abs(deltaY)) {
          height = round(width * ratio);
          width = round(height / ratio);
        } else {
          width = round(height / ratio);
          height = round(width * ratio);
        }
      }
      dom.setStyles(getResizeTarget(selectedElmGhost), {
        width: width,
        height: height
      });
      resizeHelperX = selectedHandle.startPos.x + deltaX;
      resizeHelperY = selectedHandle.startPos.y + deltaY;
      resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
      resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
      dom.setStyles(resizeHelper, {
        left: resizeHelperX,
        top: resizeHelperY,
        display: 'block'
      });
      resizeHelper.innerHTML = width + ' &times; ' + height;
      if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
        dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
      }
      if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
        dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
      }
      deltaX = rootElement.scrollWidth - startScrollWidth;
      deltaY = rootElement.scrollHeight - startScrollHeight;
      if (deltaX + deltaY !== 0) {
        dom.setStyles(resizeHelper, {
          left: resizeHelperX - deltaX,
          top: resizeHelperY - deltaY
        });
      }
      if (!resizeStarted) {
        $_a4fgrn4cjh8lyx4q.fireObjectResizeStart(editor, selectedElm, startW, startH);
        resizeStarted = true;
      }
    };
    var endGhostResize = function () {
      resizeStarted = false;
      var setSizeProp = function (name, value) {
        if (value) {
          if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) {
            dom.setStyle(getResizeTarget(selectedElm), name, value);
          } else {
            dom.setAttrib(getResizeTarget(selectedElm), name, value);
          }
        }
      };
      setSizeProp('width', width);
      setSizeProp('height', height);
      dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
      dom.unbind(editableDoc, 'mouseup', endGhostResize);
      if (rootDocument !== editableDoc) {
        dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
        dom.unbind(rootDocument, 'mouseup', endGhostResize);
      }
      dom.remove(selectedElmGhost);
      dom.remove(resizeHelper);
      showResizeRect(selectedElm);
      $_a4fgrn4cjh8lyx4q.fireObjectResized(editor, selectedElm, width, height);
      dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
      editor.nodeChanged();
    };
    var showResizeRect = function (targetElm) {
      var position, targetWidth, targetHeight, e, rect;
      hideResizeRect();
      unbindResizeHandleEvents();
      position = dom.getPos(targetElm, rootElement);
      selectedElmX = position.x;
      selectedElmY = position.y;
      rect = targetElm.getBoundingClientRect();
      targetWidth = rect.width || rect.right - rect.left;
      targetHeight = rect.height || rect.bottom - rect.top;
      if (selectedElm !== targetElm) {
        selectedElm = targetElm;
        width = height = 0;
      }
      e = editor.fire('ObjectSelected', { target: targetElm });
      if (isResizable(targetElm) && !e.isDefaultPrevented()) {
        each(resizeHandles, function (handle, name) {
          var handleElm;
          var startDrag = function (e) {
            startX = e.screenX;
            startY = e.screenY;
            startW = getResizeTarget(selectedElm).clientWidth;
            startH = getResizeTarget(selectedElm).clientHeight;
            ratio = startH / startW;
            selectedHandle = handle;
            handle.startPos = {
              x: targetWidth * handle[0] + selectedElmX,
              y: targetHeight * handle[1] + selectedElmY
            };
            startScrollWidth = rootElement.scrollWidth;
            startScrollHeight = rootElement.scrollHeight;
            selectedElmGhost = selectedElm.cloneNode(true);
            dom.addClass(selectedElmGhost, 'mce-clonedresizable');
            dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
            selectedElmGhost.contentEditable = false;
            selectedElmGhost.unSelectabe = true;
            dom.setStyles(selectedElmGhost, {
              left: selectedElmX,
              top: selectedElmY,
              margin: 0
            });
            selectedElmGhost.removeAttribute('data-mce-selected');
            rootElement.appendChild(selectedElmGhost);
            dom.bind(editableDoc, 'mousemove', resizeGhostElement);
            dom.bind(editableDoc, 'mouseup', endGhostResize);
            if (rootDocument !== editableDoc) {
              dom.bind(rootDocument, 'mousemove', resizeGhostElement);
              dom.bind(rootDocument, 'mouseup', endGhostResize);
            }
            resizeHelper = dom.add(rootElement, 'div', {
              'class': 'mce-resize-helper',
              'data-mce-bogus': 'all'
            }, startW + ' &times; ' + startH);
          };
          handleElm = dom.get('mceResizeHandle' + name);
          if (handleElm) {
            dom.remove(handleElm);
          }
          handleElm = dom.add(rootElement, 'div', {
            'id': 'mceResizeHandle' + name,
            'data-mce-bogus': 'all',
            'class': 'mce-resizehandle',
            'unselectable': true,
            'style': 'cursor:' + name + '-resize; margin:0; padding:0'
          });
          if ($_9bpim8ajh8lyw68.ie === 11) {
            handleElm.contentEditable = false;
          }
          dom.bind(handleElm, 'mousedown', function (e) {
            e.stopImmediatePropagation();
            e.preventDefault();
            startDrag(e);
          });
          handle.elm = handleElm;
          dom.setStyles(handleElm, {
            left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
            top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
          });
        });
      } else {
        hideResizeRect();
      }
      selectedElm.setAttribute('data-mce-selected', '1');
    };
    var hideResizeRect = function () {
      var name, handleElm;
      unbindResizeHandleEvents();
      if (selectedElm) {
        selectedElm.removeAttribute('data-mce-selected');
      }
      for (name in resizeHandles) {
        handleElm = dom.get('mceResizeHandle' + name);
        if (handleElm) {
          dom.unbind(handleElm);
          dom.remove(handleElm);
        }
      }
    };
    var updateResizeRect = function (e) {
      var startElm, controlElm;
      var isChildOrEqual = function (node, parent) {
        if (node) {
          do {
            if (node === parent) {
              return true;
            }
          } while (node = node.parentNode);
        }
      };
      if (resizeStarted || editor.removed) {
        return;
      }
      each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
        img.removeAttribute('data-mce-selected');
      });
      controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
      controlElm = dom.$(controlElm).closest('table,img,figure.image,hr')[0];
      if (isChildOrEqual(controlElm, rootElement)) {
        disableGeckoResize();
        startElm = selection.getStart(true);
        if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
          showResizeRect(controlElm);
          return;
        }
      }
      hideResizeRect();
    };
    var isWithinContentEditableFalse = function (elm) {
      return isContentEditableFalse$10(getContentEditableRoot$2(editor.getBody(), elm));
    };
    var unbindResizeHandleEvents = function () {
      for (var name_1 in resizeHandles) {
        var handle = resizeHandles[name_1];
        if (handle.elm) {
          dom.unbind(handle.elm);
          delete handle.elm;
        }
      }
    };
    var disableGeckoResize = function () {
      try {
        editor.getDoc().execCommand('enableObjectResizing', false, false);
      } catch (ex) {
      }
    };
    editor.on('init', function () {
      disableGeckoResize();
      if ($_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie >= 11) {
        editor.on('mousedown click', function (e) {
          var target = e.target, nodeName = target.nodeName;
          if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
            if (e.button !== 2) {
              editor.selection.select(target, nodeName === 'TABLE');
            }
            if (e.type === 'mousedown') {
              editor.nodeChanged();
            }
          }
        });
        editor.dom.bind(rootElement, 'mscontrolselect', function (e) {
          var delayedSelect = function (node) {
            $_8sy3pfhjh8lyw95.setEditorTimeout(editor, function () {
              editor.selection.select(node);
            });
          };
          if (isWithinContentEditableFalse(e.target)) {
            e.preventDefault();
            delayedSelect(e.target);
            return;
          }
          if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
            e.preventDefault();
            if (e.target.tagName === 'IMG') {
              delayedSelect(e.target);
            }
          }
        });
      }
      var throttledUpdateResizeRect = $_8sy3pfhjh8lyw95.throttle(function (e) {
        if (!editor.composing) {
          updateResizeRect(e);
        }
      });
      editor.on('nodechange ResizeEditor ResizeWindow drop FullscreenStateChanged', throttledUpdateResizeRect);
      editor.on('keyup compositionend', function (e) {
        if (selectedElm && selectedElm.nodeName === 'TABLE') {
          throttledUpdateResizeRect(e);
        }
      });
      editor.on('hide blur', hideResizeRect);
      editor.on('contextmenu', contextMenuSelectImage);
    });
    editor.on('remove', unbindResizeHandleEvents);
    var destroy = function () {
      selectedElm = selectedElmGhost = null;
    };
    return {
      isResizable: isResizable,
      showResizeRect: showResizeRect,
      hideResizeRect: hideResizeRect,
      updateResizeRect: updateResizeRect,
      destroy: destroy
    };
  };

  var hasCeProperty = function (node) {
    return $_5oonaz1qjh8lywhz.isContentEditableTrue(node) || $_5oonaz1qjh8lywhz.isContentEditableFalse(node);
  };
  var findParent$1 = function (node, rootNode, predicate) {
    while (node && node !== rootNode) {
      if (predicate(node)) {
        return node;
      }
      node = node.parentNode;
    }
    return null;
  };
  var findClosestIeRange = function (clientX, clientY, doc) {
    var element, rng, rects;
    element = doc.elementFromPoint(clientX, clientY);
    rng = doc.body.createTextRange();
    if (!element || element.tagName === 'HTML') {
      element = doc.body;
    }
    rng.moveToElementText(element);
    rects = $_ahowuxkjh8lywbj.toArray(rng.getClientRects());
    rects = rects.sort(function (a, b) {
      a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
      b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
      return a - b;
    });
    if (rects.length > 0) {
      clientY = (rects[0].bottom + rects[0].top) / 2;
      try {
        rng.moveToPoint(clientX, clientY);
        rng.collapse(true);
        return rng;
      } catch (ex) {
      }
    }
    return null;
  };
  var moveOutOfContentEditableFalse = function (rng, rootNode) {
    var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
    return $_5oonaz1qjh8lywhz.isContentEditableFalse(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
  };
  var fromPoint$1 = function (clientX, clientY, doc) {
    var rng, point;
    var pointDoc = doc;
    if (pointDoc.caretPositionFromPoint) {
      point = pointDoc.caretPositionFromPoint(clientX, clientY);
      if (point) {
        rng = doc.createRange();
        rng.setStart(point.offsetNode, point.offset);
        rng.collapse(true);
      }
    } else if (doc.caretRangeFromPoint) {
      rng = doc.caretRangeFromPoint(clientX, clientY);
    } else if (pointDoc.body.createTextRange) {
      rng = pointDoc.body.createTextRange();
      try {
        rng.moveToPoint(clientX, clientY);
        rng.collapse(true);
      } catch (ex) {
        rng = findClosestIeRange(clientX, clientY, doc);
      }
      return moveOutOfContentEditableFalse(rng, doc.body);
    }
    return rng;
  };
  var $_ct0ht56jjh8lyxif = { fromPoint: fromPoint$1 };

  var processRanges = function (editor, ranges) {
    return $_5wjzy24jh8lyw2t.map(ranges, function (range) {
      var evt = editor.fire('GetSelectionRange', { range: range });
      return evt.range !== range ? evt.range : range;
    });
  };
  var $_8o0eax6kjh8lyxii = { processRanges: processRanges };

  var clone$2 = function (original, deep) {
    return $_cgttw3zjh8lywdq.fromDom(original.dom().cloneNode(deep));
  };
  var shallow$1 = function (original) {
    return clone$2(original, false);
  };
  var deep$1 = function (original) {
    return clone$2(original, true);
  };
  var shallowAs = function (original, tag) {
    var nu = $_cgttw3zjh8lywdq.fromTag(tag);
    var attributes = $_3da62i14jh8lyweo.clone(original);
    $_3da62i14jh8lyweo.setAll(nu, attributes);
    return nu;
  };
  var copy$1 = function (original, tag) {
    var nu = shallowAs(original, tag);
    var cloneChildren = $_a43q0i17jh8lywfe.children(deep$1(original));
    $_9hl8mu2vjh8lywr4.append(nu, cloneChildren);
    return nu;
  };
  var mutate = function (original, tag) {
    var nu = shallowAs(original, tag);
    $_4m7u2e2kjh8lywpi.before(original, nu);
    var children = $_a43q0i17jh8lywfe.children(original);
    $_9hl8mu2vjh8lywr4.append(nu, children);
    $_bfmuql2ujh8lywr1.remove(original);
    return nu;
  };
  var $_azl0s66njh8lyxj4 = {
    shallow: shallow$1,
    shallowAs: shallowAs,
    deep: deep$1,
    copy: copy$1,
    mutate: mutate
  };

  var fromElements = function (elements, scope) {
    var doc = scope || document;
    var fragment = doc.createDocumentFragment();
    $_5wjzy24jh8lyw2t.each(elements, function (element) {
      fragment.appendChild(element.dom());
    });
    return $_cgttw3zjh8lywdq.fromDom(fragment);
  };
  var $_401op36ojh8lyxj6 = { fromElements: fromElements };

  var tableModel = $_4jz0ce18jh8lywft.immutable('element', 'width', 'rows');
  var tableRow = $_4jz0ce18jh8lywft.immutable('element', 'cells');
  var cellPosition = $_4jz0ce18jh8lywft.immutable('x', 'y');
  var getSpan = function (td, key) {
    var value = parseInt($_3da62i14jh8lyweo.get(td, key), 10);
    return isNaN(value) ? 1 : value;
  };
  var fillout = function (table, x, y, tr, td) {
    var rowspan = getSpan(td, 'rowspan');
    var colspan = getSpan(td, 'colspan');
    var rows = table.rows();
    for (var y2 = y; y2 < y + rowspan; y2++) {
      if (!rows[y2]) {
        rows[y2] = tableRow($_azl0s66njh8lyxj4.deep(tr), []);
      }
      for (var x2 = x; x2 < x + colspan; x2++) {
        var cells = rows[y2].cells();
        cells[x2] = y2 === y && x2 === x ? td : $_azl0s66njh8lyxj4.shallow(td);
      }
    }
  };
  var cellExists = function (table, x, y) {
    var rows = table.rows();
    var cells = rows[y] ? rows[y].cells() : [];
    return !!cells[x];
  };
  var skipCellsX = function (table, x, y) {
    while (cellExists(table, x, y)) {
      x++;
    }
    return x;
  };
  var getWidth = function (rows) {
    return $_5wjzy24jh8lyw2t.foldl(rows, function (acc, row) {
      return row.cells().length > acc ? row.cells().length : acc;
    }, 0);
  };
  var findElementPos = function (table, element) {
    var rows = table.rows();
    for (var y = 0; y < rows.length; y++) {
      var cells = rows[y].cells();
      for (var x = 0; x < cells.length; x++) {
        if ($_5f6gpb1djh8lywg5.eq(cells[x], element)) {
          return Option.some(cellPosition(x, y));
        }
      }
    }
    return Option.none();
  };
  var extractRows = function (table, sx, sy, ex, ey) {
    var newRows = [];
    var rows = table.rows();
    for (var y = sy; y <= ey; y++) {
      var cells = rows[y].cells();
      var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
      newRows.push(tableRow(rows[y].element(), slice));
    }
    return newRows;
  };
  var subTable = function (table, startPos, endPos) {
    var sx = startPos.x(), sy = startPos.y();
    var ex = endPos.x(), ey = endPos.y();
    var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
    return tableModel(table.element(), getWidth(newRows), newRows);
  };
  var createDomTable = function (table, rows) {
    var tableElement = $_azl0s66njh8lyxj4.shallow(table.element());
    var tableBody = $_cgttw3zjh8lywdq.fromTag('tbody');
    $_9hl8mu2vjh8lywr4.append(tableBody, rows);
    $_4m7u2e2kjh8lywpi.append(tableElement, tableBody);
    return tableElement;
  };
  var modelRowsToDomRows = function (table) {
    return $_5wjzy24jh8lyw2t.map(table.rows(), function (row) {
      var cells = $_5wjzy24jh8lyw2t.map(row.cells(), function (cell) {
        var td = $_azl0s66njh8lyxj4.deep(cell);
        $_3da62i14jh8lyweo.remove(td, 'colspan');
        $_3da62i14jh8lyweo.remove(td, 'rowspan');
        return td;
      });
      var tr = $_azl0s66njh8lyxj4.shallow(row.element());
      $_9hl8mu2vjh8lywr4.append(tr, cells);
      return tr;
    });
  };
  var fromDom$2 = function (tableElm) {
    var table = tableModel($_azl0s66njh8lyxj4.shallow(tableElm), 0, []);
    $_5wjzy24jh8lyw2t.each($_eebxu2gjh8lywp3.descendants(tableElm, 'tr'), function (tr, y) {
      $_5wjzy24jh8lyw2t.each($_eebxu2gjh8lywp3.descendants(tr, 'td,th'), function (td, x) {
        fillout(table, skipCellsX(table, x, y), y, tr, td);
      });
    });
    return tableModel(table.element(), getWidth(table.rows()), table.rows());
  };
  var toDom = function (table) {
    return createDomTable(table, modelRowsToDomRows(table));
  };
  var subsection = function (table, startElement, endElement) {
    return findElementPos(table, startElement).bind(function (startPos) {
      return findElementPos(table, endElement).map(function (endPos) {
        return subTable(table, startPos, endPos);
      });
    });
  };
  var $_fb3vwb6pjh8lyxjk = {
    fromDom: fromDom$2,
    toDom: toDom,
    subsection: subsection
  };

  var findParentListContainer = function (parents) {
    return $_5wjzy24jh8lyw2t.find(parents, function (elm) {
      return $_7j1jt210jh8lywdx.name(elm) === 'ul' || $_7j1jt210jh8lywdx.name(elm) === 'ol';
    });
  };
  var getFullySelectedListWrappers = function (parents, rng) {
    return $_5wjzy24jh8lyw2t.find(parents, function (elm) {
      return $_7j1jt210jh8lywdx.name(elm) === 'li' && hasAllContentsSelected(elm, rng);
    }).fold($_eqpqvr6jh8lyw3s.constant([]), function (li) {
      return findParentListContainer(parents).map(function (listCont) {
        return [
          $_cgttw3zjh8lywdq.fromTag('li'),
          $_cgttw3zjh8lywdq.fromTag($_7j1jt210jh8lywdx.name(listCont))
        ];
      }).getOr([]);
    });
  };
  var wrap$3 = function (innerElm, elms) {
    var wrapped = $_5wjzy24jh8lyw2t.foldl(elms, function (acc, elm) {
      $_4m7u2e2kjh8lywpi.append(elm, acc);
      return elm;
    }, innerElm);
    return elms.length > 0 ? $_401op36ojh8lyxj6.fromElements([wrapped]) : wrapped;
  };
  var directListWrappers = function (commonAnchorContainer) {
    if (isListItem(commonAnchorContainer)) {
      return $_a43q0i17jh8lywfe.parent(commonAnchorContainer).filter(isList).fold($_eqpqvr6jh8lyw3s.constant([]), function (listElm) {
        return [
          commonAnchorContainer,
          listElm
        ];
      });
    } else {
      return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
    }
  };
  var getWrapElements = function (rootNode, rng) {
    var commonAnchorContainer = $_cgttw3zjh8lywdq.fromDom(rng.commonAncestorContainer);
    var parents = $_dyxtub3ejh8lywxq.parentsAndSelf(commonAnchorContainer, rootNode);
    var wrapElements = $_5wjzy24jh8lyw2t.filter(parents, function (elm) {
      return isInline(elm) || isHeading(elm);
    });
    var listWrappers = getFullySelectedListWrappers(parents, rng);
    var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
    return $_5wjzy24jh8lyw2t.map(allWrappers, $_azl0s66njh8lyxj4.shallow);
  };
  var emptyFragment = function () {
    return $_401op36ojh8lyxj6.fromElements([]);
  };
  var getFragmentFromRange = function (rootNode, rng) {
    return wrap$3($_cgttw3zjh8lywdq.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  };
  var getParentTable = function (rootElm, cell) {
    return $_7sg18r3cjh8lywu1.ancestor(cell, 'table', $_eqpqvr6jh8lyw3s.curry($_5f6gpb1djh8lywg5.eq, rootElm));
  };
  var getTableFragment = function (rootNode, selectedTableCells) {
    return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
      var firstCell = selectedTableCells[0];
      var lastCell = selectedTableCells[selectedTableCells.length - 1];
      var fullTableModel = $_fb3vwb6pjh8lyxjk.fromDom(tableElm);
      return $_fb3vwb6pjh8lyxjk.subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
        return $_401op36ojh8lyxj6.fromElements([$_fb3vwb6pjh8lyxjk.toDom(sectionedTableModel)]);
      });
    }).getOrThunk(emptyFragment);
  };
  var getSelectionFragment = function (rootNode, ranges) {
    return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  };
  var read$4 = function (rootNode, ranges) {
    var selectedCells = $_bwjtq63tjh8lyx1g.getCellsFromElementOrRanges(ranges, rootNode);
    return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  };
  var $_7lffms6mjh8lyxip = { read: read$4 };

  var getContent = function (editor, args) {
    var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
    var sel = editor.selection.getSel();
    var fragment;
    var ranges = $_8o0eax6kjh8lyxii.processRanges(editor, $_d1o8uj3ujh8lyx1u.getRanges(sel));
    args = args || {};
    args.get = true;
    args.format = args.format || 'html';
    args.selection = true;
    args = editor.fire('BeforeGetContent', args);
    if (args.isDefaultPrevented()) {
      editor.fire('GetContent', args);
      return args.content;
    }
    if (args.format === 'text') {
      return editor.selection.isCollapsed() ? '' : $_d383mr21jh8lywlv.trim(rng.text || (sel.toString ? sel.toString() : ''));
    }
    if (rng.cloneContents) {
      fragment = args.contextual ? $_7lffms6mjh8lyxip.read($_cgttw3zjh8lywdq.fromDom(editor.getBody()), ranges).dom() : rng.cloneContents();
      if (fragment) {
        tmpElm.appendChild(fragment);
      }
    } else if (rng.item !== undefined || rng.htmlText !== undefined) {
      tmpElm.innerHTML = '<br>' + (rng.item ? rng.item(0).outerHTML : rng.htmlText);
      tmpElm.removeChild(tmpElm.firstChild);
    } else {
      tmpElm.innerHTML = rng.toString();
    }
    args.getInner = true;
    var content = editor.selection.serializer.serialize(tmpElm, args);
    if (args.format === 'tree') {
      return content;
    }
    args.content = editor.selection.isCollapsed() ? '' : content;
    editor.fire('GetContent', args);
    return args.content;
  };
  var $_dxvi8w6ljh8lyxik = { getContent: getContent };

  var setContent = function (editor, content, args) {
    var rng = editor.selection.getRng(), caretNode;
    var doc = editor.getDoc();
    var frag, temp;
    args = args || { format: 'html' };
    args.set = true;
    args.selection = true;
    args.content = content;
    if (!args.no_events) {
      args = editor.fire('BeforeSetContent', args);
      if (args.isDefaultPrevented()) {
        editor.fire('SetContent', args);
        return;
      }
    }
    content = args.content;
    if (rng.insertNode) {
      content += '<span id="__caret">_</span>';
      if (rng.startContainer === doc && rng.endContainer === doc) {
        doc.body.innerHTML = content;
      } else {
        rng.deleteContents();
        if (doc.body.childNodes.length === 0) {
          doc.body.innerHTML = content;
        } else {
          if (rng.createContextualFragment) {
            rng.insertNode(rng.createContextualFragment(content));
          } else {
            frag = doc.createDocumentFragment();
            temp = doc.createElement('div');
            frag.appendChild(temp);
            temp.outerHTML = content;
            rng.insertNode(frag);
          }
        }
      }
      caretNode = editor.dom.get('__caret');
      rng = doc.createRange();
      rng.setStartBefore(caretNode);
      rng.setEndBefore(caretNode);
      editor.selection.setRng(rng);
      editor.dom.remove('__caret');
      try {
        editor.selection.setRng(rng);
      } catch (ex) {
      }
    } else {
      if (rng.item) {
        doc.execCommand('Delete', false, null);
        rng = editor.getRng();
      }
      if (/^\s+/.test(content)) {
        rng.pasteHTML('<span id="__mce_tmp">_</span>' + content);
        editor.dom.remove('__mce_tmp');
      } else {
        rng.pasteHTML(content);
      }
    }
    if (!args.no_events) {
      editor.fire('SetContent', args);
    }
  };
  var $_8s2a5k6qjh8lyxk1 = { setContent: setContent };

  var getEndpointElement = function (root, rng, start, real, resolve) {
    var container = start ? rng.startContainer : rng.endContainer;
    var offset = start ? rng.startOffset : rng.endOffset;
    return Option.from(container).map($_cgttw3zjh8lywdq.fromDom).map(function (elm) {
      return !real || !rng.collapsed ? $_a43q0i17jh8lywfe.child(elm, resolve(elm, offset)).getOr(elm) : elm;
    }).bind(function (elm) {
      return $_7j1jt210jh8lywdx.isElement(elm) ? Option.some(elm) : $_a43q0i17jh8lywfe.parent(elm);
    }).map(function (elm) {
      return elm.dom();
    }).getOr(root);
  };
  var getStart$2 = function (root, rng, real) {
    return getEndpointElement(root, rng, true, real, function (elm, offset) {
      return Math.min($_a43q0i17jh8lywfe.childNodesCount(elm), offset);
    });
  };
  var getEnd = function (root, rng, real) {
    return getEndpointElement(root, rng, false, real, function (elm, offset) {
      return offset > 0 ? offset - 1 : offset;
    });
  };
  var skipEmptyTextNodes = function (node, forwards) {
    var orig = node;
    while (node && $_5oonaz1qjh8lywhz.isText(node) && node.length === 0) {
      node = forwards ? node.nextSibling : node.previousSibling;
    }
    return node || orig;
  };
  var getNode$1 = function (root, rng) {
    var elm, startContainer, endContainer, startOffset, endOffset;
    if (!rng) {
      return root;
    }
    startContainer = rng.startContainer;
    endContainer = rng.endContainer;
    startOffset = rng.startOffset;
    endOffset = rng.endOffset;
    elm = rng.commonAncestorContainer;
    if (!rng.collapsed) {
      if (startContainer === endContainer) {
        if (endOffset - startOffset < 2) {
          if (startContainer.hasChildNodes()) {
            elm = startContainer.childNodes[startOffset];
          }
        }
      }
      if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
        if (startContainer.length === startOffset) {
          startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
        } else {
          startContainer = startContainer.parentNode;
        }
        if (endOffset === 0) {
          endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
        } else {
          endContainer = endContainer.parentNode;
        }
        if (startContainer && startContainer === endContainer) {
          return startContainer;
        }
      }
    }
    if (elm && elm.nodeType === 3) {
      return elm.parentNode;
    }
    return elm;
  };
  var getSelectedBlocks = function (dom, rng, startElm, endElm) {
    var node, root;
    var selectedBlocks = [];
    root = dom.getRoot();
    startElm = dom.getParent(startElm || getStart$2(root, rng, false), dom.isBlock);
    endElm = dom.getParent(endElm || getEnd(root, rng, false), dom.isBlock);
    if (startElm && startElm !== root) {
      selectedBlocks.push(startElm);
    }
    if (startElm && endElm && startElm !== endElm) {
      node = startElm;
      var walker = new TreeWalker(startElm, root);
      while ((node = walker.next()) && node !== endElm) {
        if (dom.isBlock(node)) {
          selectedBlocks.push(node);
        }
      }
    }
    if (endElm && startElm !== endElm && endElm !== root) {
      selectedBlocks.push(endElm);
    }
    return selectedBlocks;
  };
  var select$1 = function (dom, node, content) {
    return Option.from(node).map(function (node) {
      var idx = dom.nodeIndex(node);
      var rng = dom.createRng();
      rng.setStart(node.parentNode, idx);
      rng.setEnd(node.parentNode, idx + 1);
      if (content) {
        moveEndPoint$1(dom, rng, node, true);
        moveEndPoint$1(dom, rng, node, false);
      }
      return rng;
    });
  };

  var each$19 = $_ahowuxkjh8lywbj.each;
  var isNativeIeSelection = function (rng) {
    return !!rng.select;
  };
  var isAttachedToDom = function (node) {
    return !!(node && node.ownerDocument) && $_5f6gpb1djh8lywg5.contains($_cgttw3zjh8lywdq.fromDom(node.ownerDocument), $_cgttw3zjh8lywdq.fromDom(node));
  };
  var isValidRange = function (rng) {
    if (!rng) {
      return false;
    } else if (isNativeIeSelection(rng)) {
      return true;
    } else {
      return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
    }
  };
  var Selection$1 = function (dom, win, serializer, editor) {
    var bookmarkManager, controlSelection;
    var selectedRange, explicitRange, selectorChangedData;
    var setCursorLocation = function (node, offset) {
      var rng = dom.createRng();
      if (!node) {
        moveEndPoint$1(dom, rng, editor.getBody(), true);
        setRng(rng);
      } else {
        rng.setStart(node, offset);
        rng.setEnd(node, offset);
        setRng(rng);
        collapse(false);
      }
    };
    var getContent = function (args) {
      return $_dxvi8w6ljh8lyxik.getContent(editor, args);
    };
    var setContent = function (content, args) {
      return $_8s2a5k6qjh8lyxk1.setContent(editor, content, args);
    };
    var getStart = function (real) {
      return getStart$2(editor.getBody(), getRng(), real);
    };
    var getEnd$$1 = function (real) {
      return getEnd(editor.getBody(), getRng(), real);
    };
    var getBookmark = function (type, normalized) {
      return bookmarkManager.getBookmark(type, normalized);
    };
    var moveToBookmark = function (bookmark) {
      return bookmarkManager.moveToBookmark(bookmark);
    };
    var select = function (node, content) {
      select$1(dom, node, content).each(setRng);
      return node;
    };
    var isCollapsed = function () {
      var rng = getRng(), sel = getSel();
      if (!rng || rng.item) {
        return false;
      }
      if (rng.compareEndPoints) {
        return rng.compareEndPoints('StartToEnd', rng) === 0;
      }
      return !sel || rng.collapsed;
    };
    var collapse = function (toStart) {
      var rng = getRng();
      rng.collapse(!!toStart);
      setRng(rng);
    };
    var getSel = function () {
      return win.getSelection ? win.getSelection() : win.document.selection;
    };
    var getRng = function () {
      var selection, rng, elm, doc;
      var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
        try {
          return sourceRange.compareBoundaryPoints(how, destinationRange);
        } catch (ex) {
          return -1;
        }
      };
      if (!win) {
        return null;
      }
      doc = win.document;
      if (typeof doc === 'undefined' || doc === null) {
        return null;
      }
      if (editor.bookmark !== undefined && $_cnu79r4ejh8lyx4x.hasFocus(editor) === false) {
        var bookmark = $_eqs11m40jh8lyx31.getRng(editor);
        if (bookmark.isSome()) {
          return bookmark.map(function (r) {
            return $_8o0eax6kjh8lyxii.processRanges(editor, [r])[0];
          }).getOr(doc.createRange());
        }
      }
      try {
        if (selection = getSel()) {
          if (selection.rangeCount > 0) {
            rng = selection.getRangeAt(0);
          } else {
            rng = selection.createRange ? selection.createRange() : doc.createRange();
          }
        }
      } catch (ex) {
      }
      rng = $_8o0eax6kjh8lyxii.processRanges(editor, [rng])[0];
      if (!rng) {
        rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
      }
      if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
        elm = dom.getRoot();
        rng.setStart(elm, 0);
        rng.setEnd(elm, 0);
      }
      if (selectedRange && explicitRange) {
        if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
          rng = explicitRange;
        } else {
          selectedRange = null;
          explicitRange = null;
        }
      }
      return rng;
    };
    var setRng = function (rng, forward) {
      var sel, node, evt;
      if (!isValidRange(rng)) {
        return;
      }
      var ieRange = isNativeIeSelection(rng) ? rng : null;
      if (ieRange) {
        explicitRange = null;
        try {
          ieRange.select();
        } catch (ex) {
        }
        return;
      }
      sel = getSel();
      evt = editor.fire('SetSelectionRange', {
        range: rng,
        forward: forward
      });
      rng = evt.range;
      if (sel) {
        explicitRange = rng;
        try {
          sel.removeAllRanges();
          sel.addRange(rng);
        } catch (ex) {
        }
        if (forward === false && sel.extend) {
          sel.collapse(rng.endContainer, rng.endOffset);
          sel.extend(rng.startContainer, rng.startOffset);
        }
        selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
      }
      if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !$_9bpim8ajh8lyw68.ie) {
        if (rng.endOffset - rng.startOffset < 2) {
          if (rng.startContainer.hasChildNodes()) {
            node = rng.startContainer.childNodes[rng.startOffset];
            if (node && node.tagName === 'IMG') {
              sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
              if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
                sel.setBaseAndExtent(node, 0, node, 1);
              }
            }
          }
        }
      }
      editor.fire('AfterSetSelectionRange', {
        range: rng,
        forward: forward
      });
    };
    var setNode = function (elm) {
      setContent(dom.getOuterHTML(elm));
      return elm;
    };
    var getNode = function () {
      return getNode$1(editor.getBody(), getRng());
    };
    var getSelectedBlocks$$1 = function (startElm, endElm) {
      return getSelectedBlocks(dom, getRng(), startElm, endElm);
    };
    var isForward = function () {
      var sel = getSel();
      var anchorRange, focusRange;
      if (!sel || !sel.anchorNode || !sel.focusNode) {
        return true;
      }
      anchorRange = dom.createRng();
      anchorRange.setStart(sel.anchorNode, sel.anchorOffset);
      anchorRange.collapse(true);
      focusRange = dom.createRng();
      focusRange.setStart(sel.focusNode, sel.focusOffset);
      focusRange.collapse(true);
      return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
    };
    var normalize = function () {
      var rng = getRng();
      var sel = getSel();
      if (!$_d1o8uj3ujh8lyx1u.hasMultipleRanges(sel) && hasAnyRanges(editor)) {
        var normRng = $_4v2pn63yjh8lyx2s.normalize(dom, rng);
        normRng.each(function (normRng) {
          setRng(normRng, isForward());
        });
        return normRng.getOr(rng);
      }
      return rng;
    };
    var selectorChanged = function (selector, callback) {
      var currentSelectors;
      if (!selectorChangedData) {
        selectorChangedData = {};
        currentSelectors = {};
        editor.on('NodeChange', function (e) {
          var node = e.element, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
          each$19(selectorChangedData, function (callbacks, selector) {
            each$19(parents, function (node) {
              if (dom.is(node, selector)) {
                if (!currentSelectors[selector]) {
                  each$19(callbacks, function (callback) {
                    callback(true, {
                      node: node,
                      selector: selector,
                      parents: parents
                    });
                  });
                  currentSelectors[selector] = callbacks;
                }
                matchedSelectors[selector] = callbacks;
                return false;
              }
            });
          });
          each$19(currentSelectors, function (callbacks, selector) {
            if (!matchedSelectors[selector]) {
              delete currentSelectors[selector];
              each$19(callbacks, function (callback) {
                callback(false, {
                  node: node,
                  selector: selector,
                  parents: parents
                });
              });
            }
          });
        });
      }
      if (!selectorChangedData[selector]) {
        selectorChangedData[selector] = [];
      }
      selectorChangedData[selector].push(callback);
      return exports;
    };
    var getScrollContainer = function () {
      var scrollContainer;
      var node = dom.getRoot();
      while (node && node.nodeName !== 'BODY') {
        if (node.scrollHeight > node.clientHeight) {
          scrollContainer = node;
          break;
        }
        node = node.parentNode;
      }
      return scrollContainer;
    };
    var scrollIntoView = function (elm, alignToTop) {
      return $_cosk3k2ijh8lywpa.scrollElementIntoView(editor, elm, alignToTop);
    };
    var placeCaretAt = function (clientX, clientY) {
      return setRng($_ct0ht56jjh8lyxif.fromPoint(clientX, clientY, editor.getDoc()));
    };
    var getBoundingClientRect = function () {
      var rng = getRng();
      return rng.collapsed ? CaretPosition$1.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
    };
    var destroy = function () {
      win = selectedRange = explicitRange = null;
      controlSelection.destroy();
    };
    var exports = {
      bookmarkManager: null,
      controlSelection: null,
      dom: dom,
      win: win,
      serializer: serializer,
      editor: editor,
      collapse: collapse,
      setCursorLocation: setCursorLocation,
      getContent: getContent,
      setContent: setContent,
      getBookmark: getBookmark,
      moveToBookmark: moveToBookmark,
      select: select,
      isCollapsed: isCollapsed,
      isForward: isForward,
      setNode: setNode,
      getNode: getNode,
      getSel: getSel,
      setRng: setRng,
      getRng: getRng,
      getStart: getStart,
      getEnd: getEnd$$1,
      getSelectedBlocks: getSelectedBlocks$$1,
      normalize: normalize,
      selectorChanged: selectorChanged,
      getScrollContainer: getScrollContainer,
      scrollIntoView: scrollIntoView,
      placeCaretAt: placeCaretAt,
      getBoundingClientRect: getBoundingClientRect,
      destroy: destroy
    };
    bookmarkManager = BookmarkManager$1(exports);
    controlSelection = ControlSelection(exports, editor);
    exports.bookmarkManager = bookmarkManager;
    exports.controlSelection = controlSelection;
    return exports;
  };

  var isContentEditableFalse$11 = $_5oonaz1qjh8lywhz.isContentEditableFalse;
  var getSelectedNode$1 = getSelectedNode;
  var isAfterContentEditableFalse$2 = isAfterContentEditableFalse;
  var isBeforeContentEditableFalse$2 = isBeforeContentEditableFalse;
  var getVisualCaretPosition = function (walkFn, caretPosition) {
    while (caretPosition = walkFn(caretPosition)) {
      if (caretPosition.isVisible()) {
        return caretPosition;
      }
    }
    return caretPosition;
  };
  var isMoveInsideSameBlock = function (from, to) {
    var inSameBlock = isInSameBlock(from, to);
    if (!inSameBlock && $_5oonaz1qjh8lywhz.isBr(from.getNode())) {
      return true;
    }
    return inSameBlock;
  };
  var moveToCeFalseHorizontally = function (direction, editor, getNextPosFn, range) {
    var node, caretPosition, peekCaretPosition, rangeIsInContainerBlock;
    var forwards = direction === HDirection.Forwards;
    var isBeforeContentEditableFalseFn = forwards ? isBeforeContentEditableFalse$2 : isAfterContentEditableFalse$2;
    if (!range.collapsed) {
      node = getSelectedNode$1(range);
      if (isContentEditableFalse$11(node)) {
        return showCaret(direction, editor, node, direction === HDirection.Backwards, true);
      }
    }
    rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
    caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
    if (isBeforeContentEditableFalseFn(caretPosition)) {
      return selectNode(editor, caretPosition.getNode(!forwards));
    }
    caretPosition = getNextPosFn(caretPosition);
    if (!caretPosition) {
      if (rangeIsInContainerBlock) {
        return range;
      }
      return null;
    }
    if (isBeforeContentEditableFalseFn(caretPosition)) {
      return showCaret(direction, editor, caretPosition.getNode(!forwards), forwards, true);
    }
    peekCaretPosition = getNextPosFn(caretPosition);
    if (isBeforeContentEditableFalseFn(peekCaretPosition)) {
      if (isMoveInsideSameBlock(caretPosition, peekCaretPosition)) {
        return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, true);
      }
    }
    if (rangeIsInContainerBlock) {
      return renderRangeCaret(editor, caretPosition.toRange(), true);
    }
    return null;
  };
  var moveToCeFalseVertically = function (direction, editor, walkerFn, range) {
    var caretPosition, linePositions, nextLinePositions;
    var closestNextLineRect, caretClientRect, clientX;
    var dist1, dist2, contentEditableFalseNode;
    contentEditableFalseNode = getSelectedNode$1(range);
    caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
    linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
    nextLinePositions = $_9tjm51ljh8lywbq.filter(linePositions, isLine(1));
    caretClientRect = $_9tjm51ljh8lywbq.last(caretPosition.getClientRects());
    if (isBeforeContentEditableFalse$2(caretPosition) || isBeforeTable(caretPosition)) {
      contentEditableFalseNode = caretPosition.getNode();
    }
    if (isAfterContentEditableFalse$2(caretPosition) || isAfterTable(caretPosition)) {
      contentEditableFalseNode = caretPosition.getNode(true);
    }
    if (!caretClientRect) {
      return null;
    }
    clientX = caretClientRect.left;
    closestNextLineRect = findClosestClientRect(nextLinePositions, clientX);
    if (closestNextLineRect) {
      if (isContentEditableFalse$11(closestNextLineRect.node)) {
        dist1 = Math.abs(clientX - closestNextLineRect.left);
        dist2 = Math.abs(clientX - closestNextLineRect.right);
        return showCaret(direction, editor, closestNextLineRect.node, dist1 < dist2, true);
      }
    }
    if (contentEditableFalseNode) {
      var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), contentEditableFalseNode);
      closestNextLineRect = findClosestClientRect($_9tjm51ljh8lywbq.filter(caretPositions, isLine(1)), clientX);
      if (closestNextLineRect) {
        return renderRangeCaret(editor, closestNextLineRect.position.toRange(), true);
      }
      closestNextLineRect = $_9tjm51ljh8lywbq.last($_9tjm51ljh8lywbq.filter(caretPositions, isLine(0)));
      if (closestNextLineRect) {
        return renderRangeCaret(editor, closestNextLineRect.position.toRange(), true);
      }
    }
  };
  var createTextBlock = function (editor) {
    var textBlock = editor.dom.create(editor.settings.forced_root_block);
    if (!$_9bpim8ajh8lyw68.ie || $_9bpim8ajh8lyw68.ie >= 11) {
      textBlock.innerHTML = '<br data-mce-bogus="1">';
    }
    return textBlock;
  };
  var exitPreBlock = function (editor, direction, range) {
    var pre, caretPos, newBlock;
    var caretWalker = CaretWalker(editor.getBody());
    var getNextVisualCaretPosition = $_8aqzj925jh8lywmj.curry(getVisualCaretPosition, caretWalker.next);
    var getPrevVisualCaretPosition = $_8aqzj925jh8lywmj.curry(getVisualCaretPosition, caretWalker.prev);
    if (range.collapsed && editor.settings.forced_root_block) {
      pre = editor.dom.getParent(range.startContainer, 'PRE');
      if (!pre) {
        return;
      }
      if (direction === 1) {
        caretPos = getNextVisualCaretPosition(CaretPosition$1.fromRangeStart(range));
      } else {
        caretPos = getPrevVisualCaretPosition(CaretPosition$1.fromRangeStart(range));
      }
      if (!caretPos) {
        newBlock = createTextBlock(editor);
        if (direction === 1) {
          editor.$(pre).after(newBlock);
        } else {
          editor.$(pre).before(newBlock);
        }
        editor.selection.select(newBlock, true);
        editor.selection.collapse();
      }
    }
  };
  var getHorizontalRange = function (editor, forward) {
    var caretWalker = CaretWalker(editor.getBody());
    var getNextVisualCaretPosition = $_8aqzj925jh8lywmj.curry(getVisualCaretPosition, caretWalker.next);
    var getPrevVisualCaretPosition = $_8aqzj925jh8lywmj.curry(getVisualCaretPosition, caretWalker.prev);
    var newRange;
    var direction = forward ? HDirection.Forwards : HDirection.Backwards;
    var getNextPosFn = forward ? getNextVisualCaretPosition : getPrevVisualCaretPosition;
    var range = editor.selection.getRng();
    newRange = moveToCeFalseHorizontally(direction, editor, getNextPosFn, range);
    if (newRange) {
      return newRange;
    }
    newRange = exitPreBlock(editor, direction, range);
    if (newRange) {
      return newRange;
    }
    return null;
  };
  var getVerticalRange = function (editor, down) {
    var newRange;
    var direction = down ? 1 : -1;
    var walkerFn = down ? downUntil : upUntil;
    var range = editor.selection.getRng();
    newRange = moveToCeFalseVertically(direction, editor, walkerFn, range);
    if (newRange) {
      return newRange;
    }
    newRange = exitPreBlock(editor, direction, range);
    if (newRange) {
      return newRange;
    }
    return null;
  };
  var moveH$1 = function (editor, forward) {
    return function () {
      var newRng = getHorizontalRange(editor, forward);
      if (newRng) {
        editor.selection.setRng(newRng);
        return true;
      } else {
        return false;
      }
    };
  };
  var moveV$1 = function (editor, down) {
    return function () {
      var newRng = getVerticalRange(editor, down);
      if (newRng) {
        editor.selection.setRng(newRng);
        return true;
      } else {
        return false;
      }
    };
  };

  var defaultPatterns = function (patterns) {
    return $_5wjzy24jh8lyw2t.map(patterns, function (pattern) {
      return $_7ffry568jh8lyxfy.merge({
        shiftKey: false,
        altKey: false,
        ctrlKey: false,
        metaKey: false,
        keyCode: 0,
        action: $_eqpqvr6jh8lyw3s.noop
      }, pattern);
    });
  };
  var matchesEvent = function (pattern, evt) {
    return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  };
  var match$1 = function (patterns, evt) {
    return $_5wjzy24jh8lyw2t.bind(defaultPatterns(patterns), function (pattern) {
      return matchesEvent(pattern, evt) ? [pattern] : [];
    });
  };
  var action = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = Array.prototype.slice.call(arguments, 1);
    return function () {
      return f.apply(null, args);
    };
  };
  var execute = function (patterns, evt) {
    return $_5wjzy24jh8lyw2t.find(match$1(patterns, evt), function (pattern) {
      return pattern.action();
    });
  };
  var $_8um8ta6vjh8lyxko = {
    match: match$1,
    action: action,
    execute: execute
  };

  var executeKeydownOverride = function (editor, caret, evt) {
    var os = $_9hkktfnjh8lywc6.detect().os;
    $_8um8ta6vjh8lyxko.execute([
      {
        keyCode: $_6lsk4i5gjh8lyxau.RIGHT,
        action: moveH$1(editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.LEFT,
        action: moveH$1(editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.UP,
        action: moveV$1(editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DOWN,
        action: moveV$1(editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.RIGHT,
        action: moveH(editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.LEFT,
        action: moveH(editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.UP,
        action: moveV(editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DOWN,
        action: moveV(editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.RIGHT,
        action: $_65xx7w3pjh8lyx0d.move(editor, caret, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.LEFT,
        action: $_65xx7w3pjh8lyx0d.move(editor, caret, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.RIGHT,
        ctrlKey: !os.isOSX(),
        altKey: os.isOSX(),
        action: $_65xx7w3pjh8lyx0d.moveNextWord(editor, caret)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.LEFT,
        ctrlKey: !os.isOSX(),
        altKey: os.isOSX(),
        action: $_65xx7w3pjh8lyx0d.movePrevWord(editor, caret)
      }
    ], evt).each(function (_) {
      evt.preventDefault();
    });
  };
  var setup$5 = function (editor, caret) {
    editor.on('keydown', function (evt) {
      if (evt.isDefaultPrevented() === false) {
        executeKeydownOverride(editor, caret, evt);
      }
    });
  };
  var $_8m3to56tjh8lyxkd = { setup: setup$5 };

  var getParentInlines = function (rootElm, startElm) {
    var parents = $_dyxtub3ejh8lywxq.parentsAndSelf(startElm, rootElm);
    return $_5wjzy24jh8lyw2t.findIndex(parents, isBlock).fold($_eqpqvr6jh8lyw3s.constant(parents), function (index) {
      return parents.slice(0, index);
    });
  };
  var hasOnlyOneChild$1 = function (elm) {
    return $_a43q0i17jh8lywfe.children(elm).length === 1;
  };
  var deleteLastPosition = function (forward, editor, target, parentInlines) {
    var isFormatElement$$1 = $_eqpqvr6jh8lyw3s.curry(isFormatElement, editor);
    var formatNodes = $_5wjzy24jh8lyw2t.map($_5wjzy24jh8lyw2t.filter(parentInlines, isFormatElement$$1), function (elm) {
      return elm.dom();
    });
    if (formatNodes.length === 0) {
      $_1al0sh3jjh8lywyv.deleteElement(editor, forward, target);
    } else {
      var pos = replaceWithCaretFormat(target.dom(), formatNodes);
      editor.selection.setRng(pos.toRange());
    }
  };
  var deleteCaret$1 = function (editor, forward) {
    var rootElm = $_cgttw3zjh8lywdq.fromDom(editor.getBody());
    var startElm = $_cgttw3zjh8lywdq.fromDom(editor.selection.getStart());
    var parentInlines = $_5wjzy24jh8lyw2t.filter(getParentInlines(rootElm, startElm), hasOnlyOneChild$1);
    return $_5wjzy24jh8lyw2t.last(parentInlines).map(function (target) {
      var fromPos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
      if ($_aj8isd34jh8lyws4.willDeleteLastPositionInElement(forward, fromPos, target.dom())) {
        deleteLastPosition(forward, editor, target, parentInlines);
        return true;
      } else {
        return false;
      }
    }).getOr(false);
  };
  var backspaceDelete$5 = function (editor, forward) {
    return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  };
  var $_vald86xjh8lyxkw = { backspaceDelete: backspaceDelete$5 };

  var executeKeydownOverride$1 = function (editor, caret, evt) {
    $_8um8ta6vjh8lyxko.execute([
      {
        keyCode: $_6lsk4i5gjh8lyxau.BACKSPACE,
        action: $_8um8ta6vjh8lyxko.action($_ar80r13gjh8lywy7.backspaceDelete, editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DELETE,
        action: $_8um8ta6vjh8lyxko.action($_ar80r13gjh8lywy7.backspaceDelete, editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.BACKSPACE,
        action: $_8um8ta6vjh8lyxko.action($_ej9d8d3kjh8lywzc.backspaceDelete, editor, caret, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DELETE,
        action: $_8um8ta6vjh8lyxko.action($_ej9d8d3kjh8lywzc.backspaceDelete, editor, caret, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.BACKSPACE,
        action: $_8um8ta6vjh8lyxko.action($_lcy1p3fjh8lywxx.backspaceDelete, editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DELETE,
        action: $_8um8ta6vjh8lyxko.action($_lcy1p3fjh8lywxx.backspaceDelete, editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.BACKSPACE,
        action: $_8um8ta6vjh8lyxko.action($_5jmwsv32jh8lywrr.backspaceDelete, editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DELETE,
        action: $_8um8ta6vjh8lyxko.action($_5jmwsv32jh8lywrr.backspaceDelete, editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.BACKSPACE,
        action: $_8um8ta6vjh8lyxko.action($_746feo3rjh8lyx0o.backspaceDelete, editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DELETE,
        action: $_8um8ta6vjh8lyxko.action($_746feo3rjh8lyx0o.backspaceDelete, editor, true)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.BACKSPACE,
        action: $_8um8ta6vjh8lyxko.action($_vald86xjh8lyxkw.backspaceDelete, editor, false)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DELETE,
        action: $_8um8ta6vjh8lyxko.action($_vald86xjh8lyxkw.backspaceDelete, editor, true)
      }
    ], evt).each(function (_) {
      evt.preventDefault();
    });
  };
  var executeKeyupOverride = function (editor, evt) {
    $_8um8ta6vjh8lyxko.execute([
      {
        keyCode: $_6lsk4i5gjh8lyxau.BACKSPACE,
        action: $_8um8ta6vjh8lyxko.action($_ar80r13gjh8lywy7.paddEmptyElement, editor)
      },
      {
        keyCode: $_6lsk4i5gjh8lyxau.DELETE,
        action: $_8um8ta6vjh8lyxko.action($_ar80r13gjh8lywy7.paddEmptyElement, editor)
      }
    ], evt);
  };
  var setup$6 = function (editor, caret) {
    editor.on('keydown', function (evt) {
      if (evt.isDefaultPrevented() === false) {
        executeKeydownOverride$1(editor, caret, evt);
      }
    });
    editor.on('keyup', function (evt) {
      if (evt.isDefaultPrevented() === false) {
        executeKeyupOverride(editor, evt);
      }
    });
  };
  var $_4ow4756wjh8lyxkt = { setup: setup$6 };

  var firstNonWhiteSpaceNodeSibling = function (node) {
    while (node) {
      if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
        return node;
      }
      node = node.nextSibling;
    }
  };
  var moveToCaretPosition = function (editor, root) {
    var walker, node, rng, lastNode = root, tempElm;
    var dom = editor.dom;
    var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
    if (!root) {
      return;
    }
    if (/^(LI|DT|DD)$/.test(root.nodeName)) {
      var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
      if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
        root.insertBefore(dom.doc.createTextNode('\xA0'), root.firstChild);
      }
    }
    rng = dom.createRng();
    root.normalize();
    if (root.hasChildNodes()) {
      walker = new TreeWalker(root, root);
      while (node = walker.current()) {
        if ($_5oonaz1qjh8lywhz.isText(node)) {
          rng.setStart(node, 0);
          rng.setEnd(node, 0);
          break;
        }
        if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
          rng.setStartBefore(node);
          rng.setEndBefore(node);
          break;
        }
        lastNode = node;
        node = walker.next();
      }
      if (!node) {
        rng.setStart(lastNode, 0);
        rng.setEnd(lastNode, 0);
      }
    } else {
      if ($_5oonaz1qjh8lywhz.isBr(root)) {
        if (root.nextSibling && dom.isBlock(root.nextSibling)) {
          rng.setStartBefore(root);
          rng.setEndBefore(root);
        } else {
          rng.setStartAfter(root);
          rng.setEndAfter(root);
        }
      } else {
        rng.setStart(root, 0);
        rng.setEnd(root, 0);
      }
    }
    editor.selection.setRng(rng);
    dom.remove(tempElm);
    editor.selection.scrollIntoView(root);
  };
  var getEditableRoot = function (dom, node) {
    var root = dom.getRoot();
    var parent, editableRoot;
    parent = node;
    while (parent !== root && dom.getContentEditable(parent) !== 'false') {
      if (dom.getContentEditable(parent) === 'true') {
        editableRoot = parent;
      }
      parent = parent.parentNode;
    }
    return parent !== root ? editableRoot : root;
  };
  var getParentBlock$2 = function (editor) {
    return Option.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  };
  var getParentBlockName = function (editor) {
    return getParentBlock$2(editor).fold($_eqpqvr6jh8lyw3s.constant(''), function (parentBlock) {
      return parentBlock.nodeName.toUpperCase();
    });
  };
  var isListItemParentBlock = function (editor) {
    return getParentBlock$2(editor).filter(function (elm) {
      return isListItem($_cgttw3zjh8lywdq.fromDom(elm));
    }).isSome();
  };
  var $_83wjn572jh8lyxlu = {
    moveToCaretPosition: moveToCaretPosition,
    getEditableRoot: getEditableRoot,
    getParentBlock: getParentBlock$2,
    getParentBlockName: getParentBlockName,
    isListItemParentBlock: isListItemParentBlock
  };

  var hasFirstChild = function (elm, name) {
    return elm.firstChild && elm.firstChild.nodeName === name;
  };
  var hasParent$1 = function (elm, parentName) {
    return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  };
  var isListBlock = function (elm) {
    return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  };
  var isNestedList = function (elm) {
    return isListBlock(elm) && isListBlock(elm.parentNode);
  };
  var getContainerBlock = function (containerBlock) {
    var containerBlockParent = containerBlock.parentNode;
    if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
      return containerBlockParent;
    }
    return containerBlock;
  };
  var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
    var node = containerBlock[first ? 'firstChild' : 'lastChild'];
    while (node) {
      if ($_5oonaz1qjh8lywhz.isElement(node)) {
        break;
      }
      node = node[first ? 'nextSibling' : 'previousSibling'];
    }
    return node === parentBlock;
  };
  var insert$1 = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
    var dom = editor.dom;
    var rng = editor.selection.getRng();
    if (containerBlock === editor.getBody()) {
      return;
    }
    if (isNestedList(containerBlock)) {
      newBlockName = 'LI';
    }
    var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
    if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
      if (hasParent$1(containerBlock, 'LI')) {
        dom.insertAfter(newBlock, getContainerBlock(containerBlock));
      } else {
        dom.replace(newBlock, containerBlock);
      }
    } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
      if (hasParent$1(containerBlock, 'LI')) {
        dom.insertAfter(newBlock, getContainerBlock(containerBlock));
        newBlock.appendChild(dom.doc.createTextNode(' '));
        newBlock.appendChild(containerBlock);
      } else {
        containerBlock.parentNode.insertBefore(newBlock, containerBlock);
      }
    } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
      dom.insertAfter(newBlock, getContainerBlock(containerBlock));
    } else {
      containerBlock = getContainerBlock(containerBlock);
      var tmpRng = rng.cloneRange();
      tmpRng.setStartAfter(parentBlock);
      tmpRng.setEndAfter(containerBlock);
      var fragment = tmpRng.extractContents();
      if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
        newBlock = fragment.firstChild;
        dom.insertAfter(fragment, containerBlock);
      } else {
        dom.insertAfter(fragment, containerBlock);
        dom.insertAfter(newBlock, containerBlock);
      }
    }
    dom.remove(parentBlock);
    $_83wjn572jh8lyxlu.moveToCaretPosition(editor, newBlock);
  };
  var $_5pzeb371jh8lyxlr = { insert: insert$1 };

  var isEmptyAnchor = function (elm) {
    return elm && elm.nodeName === 'A' && $_ahowuxkjh8lywbj.trim($_d383mr21jh8lywlv.trim(elm.innerText || elm.textContent)).length === 0;
  };
  var isTableCell$5 = function (node) {
    return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  };
  var emptyBlock = function (elm) {
    elm.innerHTML = '<br data-mce-bogus="1">';
  };
  var containerAndSiblingName = function (container, nodeName) {
    return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  };
  var canSplitBlock = function (dom, node) {
    return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  };
  var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
    var node = block;
    var firstChilds = [];
    var i;
    if (!node) {
      return;
    }
    while (node = node.firstChild) {
      if (dom.isBlock(node)) {
        return;
      }
      if ($_5oonaz1qjh8lywhz.isElement(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
        firstChilds.push(node);
      }
    }
    i = firstChilds.length;
    while (i--) {
      node = firstChilds[i];
      if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
        dom.remove(node);
      } else {
        if (isEmptyAnchor(node)) {
          dom.remove(node);
        }
      }
    }
  };
  var normalizeZwspOffset = function (start, container, offset) {
    if ($_5oonaz1qjh8lywhz.isText(container) === false) {
      return offset;
    } else if (start) {
      return offset === 1 && container.data.charAt(offset - 1) === $_d383mr21jh8lywlv.ZWSP ? 0 : offset;
    } else {
      return offset === container.data.length - 1 && container.data.charAt(offset) === $_d383mr21jh8lywlv.ZWSP ? container.data.length : offset;
    }
  };
  var includeZwspInRange = function (rng) {
    var newRng = rng.cloneRange();
    newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
    newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
    return newRng;
  };
  var trimLeadingLineBreaks = function (node) {
    do {
      if ($_5oonaz1qjh8lywhz.isText(node)) {
        node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
      }
      node = node.firstChild;
    } while (node);
  };
  var getEditableRoot$1 = function (dom, node) {
    var root = dom.getRoot();
    var parent, editableRoot;
    parent = node;
    while (parent !== root && dom.getContentEditable(parent) !== 'false') {
      if (dom.getContentEditable(parent) === 'true') {
        editableRoot = parent;
      }
      parent = parent.parentNode;
    }
    return parent !== root ? editableRoot : root;
  };
  var setForcedBlockAttrs = function (editor, node) {
    var forcedRootBlockName = $_66vr6g2jjh8lywpf.getForcedRootBlock(editor);
    if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
      editor.dom.setAttribs(node, $_66vr6g2jjh8lywpf.getForcedRootBlockAttrs(editor));
    }
  };
  var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
    var newBlock, parentBlock, startNode, node, next, rootBlockName;
    var blockName = newBlockName || 'P';
    var dom = editor.dom, editableRoot = getEditableRoot$1(dom, container);
    parentBlock = dom.getParent(container, dom.isBlock);
    if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
      parentBlock = parentBlock || editableRoot;
      if (parentBlock === editor.getBody() || isTableCell$5(parentBlock)) {
        rootBlockName = parentBlock.nodeName.toLowerCase();
      } else {
        rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
      }
      if (!parentBlock.hasChildNodes()) {
        newBlock = dom.create(blockName);
        setForcedBlockAttrs(editor, newBlock);
        parentBlock.appendChild(newBlock);
        rng.setStart(newBlock, 0);
        rng.setEnd(newBlock, 0);
        return newBlock;
      }
      node = container;
      while (node.parentNode !== parentBlock) {
        node = node.parentNode;
      }
      while (node && !dom.isBlock(node)) {
        startNode = node;
        node = node.previousSibling;
      }
      if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
        newBlock = dom.create(blockName);
        setForcedBlockAttrs(editor, newBlock);
        startNode.parentNode.insertBefore(newBlock, startNode);
        node = startNode;
        while (node && !dom.isBlock(node)) {
          next = node.nextSibling;
          newBlock.appendChild(node);
          node = next;
        }
        rng.setStart(container, offset);
        rng.setEnd(container, offset);
      }
    }
    return container;
  };
  var addBrToBlockIfNeeded = function (dom, block) {
    var lastChild;
    block.normalize();
    lastChild = block.lastChild;
    if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
      dom.add(block, 'br');
    }
  };
  var insert$2 = function (editor, evt) {
    var tmpRng, editableRoot, container, offset, parentBlock, shiftKey;
    var newBlock, fragment, containerBlock, parentBlockName, containerBlockName, newBlockName, isAfterLastNodeInContainer;
    var dom = editor.dom;
    var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
    var rng = editor.selection.getRng();
    var createNewBlock = function (name) {
      var node = container, block, clonedNode, caretNode;
      var textInlineElements = schema.getTextInlineElements();
      if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
        block = dom.create(name || newBlockName);
        setForcedBlockAttrs(editor, block);
      } else {
        block = parentBlock.cloneNode(false);
      }
      caretNode = block;
      if ($_66vr6g2jjh8lywpf.shouldKeepStyles(editor) === false) {
        dom.setAttrib(block, 'style', null);
        dom.setAttrib(block, 'class', null);
      } else {
        do {
          if (textInlineElements[node.nodeName]) {
            if (isCaretNode(node)) {
              continue;
            }
            clonedNode = node.cloneNode(false);
            dom.setAttrib(clonedNode, 'id', '');
            if (block.hasChildNodes()) {
              clonedNode.appendChild(block.firstChild);
              block.appendChild(clonedNode);
            } else {
              caretNode = clonedNode;
              block.appendChild(clonedNode);
            }
          }
        } while ((node = node.parentNode) && node !== editableRoot);
      }
      emptyBlock(caretNode);
      return block;
    };
    var isCaretAtStartOrEndOfBlock = function (start) {
      var walker, node, name, normalizedOffset;
      normalizedOffset = normalizeZwspOffset(start, container, offset);
      if ($_5oonaz1qjh8lywhz.isText(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
        return false;
      }
      if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
        return true;
      }
      if (start && $_5oonaz1qjh8lywhz.isElement(container) && container === parentBlock.firstChild) {
        return true;
      }
      if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
        return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
      }
      walker = new TreeWalker(container, parentBlock);
      if ($_5oonaz1qjh8lywhz.isText(container)) {
        if (start && normalizedOffset === 0) {
          walker.prev();
        } else if (!start && normalizedOffset === container.nodeValue.length) {
          walker.next();
        }
      }
      while (node = walker.current()) {
        if ($_5oonaz1qjh8lywhz.isElement(node)) {
          if (!node.getAttribute('data-mce-bogus')) {
            name = node.nodeName.toLowerCase();
            if (nonEmptyElementsMap[name] && name !== 'br') {
              return false;
            }
          }
        } else if ($_5oonaz1qjh8lywhz.isText(node) && !/^[ \t\r\n]*$/.test(node.nodeValue)) {
          return false;
        }
        if (start) {
          walker.prev();
        } else {
          walker.next();
        }
      }
      return true;
    };
    var insertNewBlockAfter = function () {
      if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
        newBlock = createNewBlock(newBlockName);
      } else {
        newBlock = createNewBlock();
      }
      if ($_66vr6g2jjh8lywpf.shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
        newBlock = dom.split(containerBlock, parentBlock);
      } else {
        dom.insertAfter(newBlock, parentBlock);
      }
      $_83wjn572jh8lyxlu.moveToCaretPosition(editor, newBlock);
    };
    $_4v2pn63yjh8lyx2s.normalize(dom, rng).each(function (normRng) {
      rng.setStart(normRng.startContainer, normRng.startOffset);
      rng.setEnd(normRng.endContainer, normRng.endOffset);
    });
    container = rng.startContainer;
    offset = rng.startOffset;
    newBlockName = $_66vr6g2jjh8lywpf.getForcedRootBlock(editor);
    shiftKey = evt.shiftKey;
    if ($_5oonaz1qjh8lywhz.isElement(container) && container.hasChildNodes()) {
      isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
      container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
      if (isAfterLastNodeInContainer && $_5oonaz1qjh8lywhz.isText(container)) {
        offset = container.nodeValue.length;
      } else {
        offset = 0;
      }
    }
    editableRoot = getEditableRoot$1(dom, container);
    if (!editableRoot) {
      return;
    }
    if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
      container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
    }
    parentBlock = dom.getParent(container, dom.isBlock);
    containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
    parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
    containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
    if (containerBlockName === 'LI' && !evt.ctrlKey) {
      parentBlock = containerBlock;
      containerBlock = containerBlock.parentNode;
      parentBlockName = containerBlockName;
    }
    if (/^(LI|DT|DD)$/.test(parentBlockName)) {
      if (dom.isEmpty(parentBlock)) {
        $_5pzeb371jh8lyxlr.insert(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
        return;
      }
    }
    if (newBlockName && parentBlock === editor.getBody()) {
      return;
    }
    newBlockName = newBlockName || 'P';
    if (isCaretContainerBlock(parentBlock)) {
      newBlock = showCaretContainerBlock(parentBlock);
      if (dom.isEmpty(parentBlock)) {
        emptyBlock(parentBlock);
      }
      $_83wjn572jh8lyxlu.moveToCaretPosition(editor, newBlock);
    } else if (isCaretAtStartOrEndOfBlock()) {
      insertNewBlockAfter();
    } else if (isCaretAtStartOrEndOfBlock(true)) {
      newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
      $_83wjn572jh8lyxlu.moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
    } else {
      tmpRng = includeZwspInRange(rng).cloneRange();
      tmpRng.setEndAfter(parentBlock);
      fragment = tmpRng.extractContents();
      trimLeadingLineBreaks(fragment);
      newBlock = fragment.firstChild;
      dom.insertAfter(fragment, parentBlock);
      trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
      addBrToBlockIfNeeded(dom, parentBlock);
      if (dom.isEmpty(parentBlock)) {
        emptyBlock(parentBlock);
      }
      newBlock.normalize();
      if (dom.isEmpty(newBlock)) {
        dom.remove(newBlock);
        insertNewBlockAfter();
      } else {
        $_83wjn572jh8lyxlu.moveToCaretPosition(editor, newBlock);
      }
    }
    dom.setAttrib(newBlock, 'id', '');
    editor.fire('NewBlock', { newBlock: newBlock });
  };
  var $_apcs0t70jh8lyxlh = { insert: insert$2 };

  var matchesSelector = function (editor, selector) {
    return $_83wjn572jh8lyxlu.getParentBlock(editor).filter(function (parentBlock) {
      return selector.length > 0 && $_5h4ipt1fjh8lywgi.is($_cgttw3zjh8lywdq.fromDom(parentBlock), selector);
    }).isSome();
  };
  var shouldInsertBr = function (editor) {
    return matchesSelector(editor, $_66vr6g2jjh8lywpf.getBrNewLineSelector(editor));
  };
  var shouldBlockNewLine = function (editor) {
    return matchesSelector(editor, $_66vr6g2jjh8lywpf.getNoNewLineSelector(editor));
  };
  var $_5mj33174jh8lyxm9 = {
    shouldInsertBr: shouldInsertBr,
    shouldBlockNewLine: shouldBlockNewLine
  };

  var newLineAction = $_1ml90g3ijh8lywyp.generate([
    { br: [] },
    { block: [] },
    { none: [] }
  ]);
  var shouldBlockNewLine$1 = function (editor, shiftKey) {
    return $_5mj33174jh8lyxm9.shouldBlockNewLine(editor);
  };
  var isBrMode = function (requiredState) {
    return function (editor, shiftKey) {
      var brMode = $_66vr6g2jjh8lywpf.getForcedRootBlock(editor) === '';
      return brMode === requiredState;
    };
  };
  var inListBlock = function (requiredState) {
    return function (editor, shiftKey) {
      return $_83wjn572jh8lyxlu.isListItemParentBlock(editor) === requiredState;
    };
  };
  var inBlock = function (blockName, requiredState) {
    return function (editor, shiftKey) {
      var state = $_83wjn572jh8lyxlu.getParentBlockName(editor) === blockName.toUpperCase();
      return state === requiredState;
    };
  };
  var inPreBlock = function (requiredState) {
    return inBlock('pre', requiredState);
  };
  var inSummaryBlock = function () {
    return inBlock('summary', true);
  };
  var shouldPutBrInPre$1 = function (requiredState) {
    return function (editor, shiftKey) {
      return $_66vr6g2jjh8lywpf.shouldPutBrInPre(editor) === requiredState;
    };
  };
  var inBrContext = function (editor, shiftKey) {
    return $_5mj33174jh8lyxm9.shouldInsertBr(editor);
  };
  var hasShiftKey = function (editor, shiftKey) {
    return shiftKey;
  };
  var canInsertIntoEditableRoot = function (editor) {
    var forcedRootBlock = $_66vr6g2jjh8lywpf.getForcedRootBlock(editor);
    var rootEditable = $_83wjn572jh8lyxlu.getEditableRoot(editor.dom, editor.selection.getStart());
    return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  };
  var match$2 = function (predicates, action) {
    return function (editor, shiftKey) {
      var isMatch = $_5wjzy24jh8lyw2t.foldl(predicates, function (res, p) {
        return res && p(editor, shiftKey);
      }, true);
      return isMatch ? Option.some(action) : Option.none();
    };
  };
  var getAction$1 = function (editor, evt) {
    return $_7r5om73ojh8lyx09.evaluateUntil([
      match$2([shouldBlockNewLine$1], newLineAction.none()),
      match$2([inSummaryBlock()], newLineAction.br()),
      match$2([
        inPreBlock(true),
        shouldPutBrInPre$1(false),
        hasShiftKey
      ], newLineAction.br()),
      match$2([
        inPreBlock(true),
        shouldPutBrInPre$1(false)
      ], newLineAction.block()),
      match$2([
        inPreBlock(true),
        shouldPutBrInPre$1(true),
        hasShiftKey
      ], newLineAction.block()),
      match$2([
        inPreBlock(true),
        shouldPutBrInPre$1(true)
      ], newLineAction.br()),
      match$2([
        inListBlock(true),
        hasShiftKey
      ], newLineAction.br()),
      match$2([inListBlock(true)], newLineAction.block()),
      match$2([
        isBrMode(true),
        hasShiftKey,
        canInsertIntoEditableRoot
      ], newLineAction.block()),
      match$2([isBrMode(true)], newLineAction.br()),
      match$2([inBrContext], newLineAction.br()),
      match$2([
        isBrMode(false),
        hasShiftKey
      ], newLineAction.br()),
      match$2([canInsertIntoEditableRoot], newLineAction.block())
    ], [
      editor,
      evt.shiftKey
    ]).getOr(newLineAction.none());
  };
  var $_efe7kj73jh8lyxm2 = { getAction: getAction$1 };

  var insert$3 = function (editor, evt) {
    $_efe7kj73jh8lyxm2.getAction(editor, evt).fold(function () {
      $_cg4dz53xjh8lyx2g.insert(editor, evt);
    }, function () {
      $_apcs0t70jh8lyxlh.insert(editor, evt);
    }, $_eqpqvr6jh8lyw3s.noop);
  };
  var $_5e167p6zjh8lyxlc = { insert: insert$3 };

  var endTypingLevel = function (undoManager) {
    if (undoManager.typing) {
      undoManager.typing = false;
      undoManager.add();
    }
  };
  var handleEnterKeyEvent = function (editor, event) {
    if (event.isDefaultPrevented()) {
      return;
    }
    event.preventDefault();
    endTypingLevel(editor.undoManager);
    editor.undoManager.transact(function () {
      if (editor.selection.isCollapsed() === false) {
        editor.execCommand('Delete');
      }
      $_5e167p6zjh8lyxlc.insert(editor, event);
    });
  };
  var setup$7 = function (editor) {
    editor.on('keydown', function (event) {
      if (event.keyCode === $_6lsk4i5gjh8lyxau.ENTER) {
        handleEnterKeyEvent(editor, event);
      }
    });
  };
  var $_5ff4w26yjh8lyxl3 = { setup: setup$7 };

  var isValidInsertPoint = function (location, caretPosition) {
    return isAtStartOrEnd(location) && $_5oonaz1qjh8lywhz.isText(caretPosition.container());
  };
  var insertNbspAtPosition = function (editor, caretPosition) {
    var container = caretPosition.container();
    var offset = caretPosition.offset();
    container.insertData(offset, '\xA0');
    editor.selection.setCursorLocation(container, offset + 1);
  };
  var insertAtLocation = function (editor, caretPosition, location) {
    if (isValidInsertPoint(location, caretPosition)) {
      insertNbspAtPosition(editor, caretPosition);
      return true;
    } else {
      return false;
    }
  };
  var insertAtCaret$2 = function (editor) {
    var isInlineTarget = $_eqpqvr6jh8lyw3s.curry($_231v7s37jh8lywt3.isInlineTarget, editor);
    var caretPosition = CaretPosition$1.fromRangeStart(editor.selection.getRng());
    var boundaryLocation = $_6kjy7r3njh8lywzz.readLocation(isInlineTarget, editor.getBody(), caretPosition);
    return boundaryLocation.map($_eqpqvr6jh8lyw3s.curry(insertAtLocation, editor, caretPosition)).getOr(false);
  };
  var isAtStartOrEnd = function (location) {
    return location.fold($_eqpqvr6jh8lyw3s.constant(false), $_eqpqvr6jh8lyw3s.constant(true), $_eqpqvr6jh8lyw3s.constant(true), $_eqpqvr6jh8lyw3s.constant(false));
  };
  var insertAtSelection = function (editor) {
    return editor.selection.isCollapsed() ? insertAtCaret$2(editor) : false;
  };
  var $_aptbve76jh8lyxme = { insertAtSelection: insertAtSelection };

  var executeKeydownOverride$2 = function (editor, evt) {
    $_8um8ta6vjh8lyxko.execute([{
        keyCode: $_6lsk4i5gjh8lyxau.SPACEBAR,
        action: $_8um8ta6vjh8lyxko.action($_aptbve76jh8lyxme.insertAtSelection, editor)
      }], evt).each(function (_) {
      evt.preventDefault();
    });
  };
  var setup$8 = function (editor) {
    editor.on('keydown', function (evt) {
      if (evt.isDefaultPrevented() === false) {
        executeKeydownOverride$2(editor, evt);
      }
    });
  };
  var $_50nb7z75jh8lyxmd = { setup: setup$8 };

  var findBlockCaretContainer = function (editor) {
    return $_7sg18r3cjh8lywu1.descendant($_cgttw3zjh8lywdq.fromDom(editor.getBody()), '*[data-mce-caret]').fold($_eqpqvr6jh8lyw3s.constant(null), function (elm) {
      return elm.dom();
    });
  };
  var removeIeControlRect = function (editor) {
    editor.selection.setRng(editor.selection.getRng());
  };
  var showBlockCaretContainer = function (editor, blockCaretContainer) {
    if (blockCaretContainer.hasAttribute('data-mce-caret')) {
      showCaretContainerBlock(blockCaretContainer);
      removeIeControlRect(editor);
      editor.selection.scrollIntoView(blockCaretContainer);
    }
  };
  var handleBlockContainer = function (editor, e) {
    var blockCaretContainer = findBlockCaretContainer(editor);
    if (!blockCaretContainer) {
      return;
    }
    if (e.type === 'compositionstart') {
      e.preventDefault();
      e.stopPropagation();
      showBlockCaretContainer(editor, blockCaretContainer);
      return;
    }
    if (hasContent(blockCaretContainer)) {
      showBlockCaretContainer(editor, blockCaretContainer);
      editor.undoManager.add();
    }
  };
  var setup$9 = function (editor) {
    editor.on('keyup compositionstart', $_eqpqvr6jh8lyw3s.curry(handleBlockContainer, editor));
  };
  var $_98x1lt77jh8lyxmi = { setup: setup$9 };

  var setup$10 = function (editor) {
    var caret = $_65xx7w3pjh8lyx0d.setupSelectedState(editor);
    $_98x1lt77jh8lyxmi.setup(editor);
    $_8m3to56tjh8lyxkd.setup(editor, caret);
    $_4ow4756wjh8lyxkt.setup(editor, caret);
    $_5ff4w26yjh8lyxl3.setup(editor);
    $_50nb7z75jh8lyxmd.setup(editor);
  };
  var $_btkj596sjh8lyxkc = { setup: setup$10 };

  function Quirks (editor) {
    var each = $_ahowuxkjh8lywbj.each;
    var BACKSPACE = $_6lsk4i5gjh8lyxau.BACKSPACE, DELETE = $_6lsk4i5gjh8lyxau.DELETE, dom = editor.dom, selection = editor.selection, settings = editor.settings, parser = editor.parser;
    var isGecko = $_9bpim8ajh8lyw68.gecko, isIE = $_9bpim8ajh8lyw68.ie, isWebKit = $_9bpim8ajh8lyw68.webkit;
    var mceInternalUrlPrefix = 'data:text/mce-internal,';
    var mceInternalDataType = isIE ? 'Text' : 'URL';
    var setEditorCommandState = function (cmd, state) {
      try {
        editor.getDoc().execCommand(cmd, false, state);
      } catch (ex) {
      }
    };
    var isDefaultPrevented = function (e) {
      return e.isDefaultPrevented();
    };
    var setMceInternalContent = function (e) {
      var selectionHtml, internalContent;
      if (e.dataTransfer) {
        if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
          selection.select(e.target);
        }
        selectionHtml = editor.selection.getContent();
        if (selectionHtml.length > 0) {
          internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
          e.dataTransfer.setData(mceInternalDataType, internalContent);
        }
      }
    };
    var getMceInternalContent = function (e) {
      var internalContent;
      if (e.dataTransfer) {
        internalContent = e.dataTransfer.getData(mceInternalDataType);
        if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
          internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
          return {
            id: unescape(internalContent[0]),
            html: unescape(internalContent[1])
          };
        }
      }
      return null;
    };
    var insertClipboardContents = function (content, internal) {
      if (editor.queryCommandSupported('mceInsertClipboardContent')) {
        editor.execCommand('mceInsertClipboardContent', false, {
          content: content,
          internal: internal
        });
      } else {
        editor.execCommand('mceInsertContent', false, content);
      }
    };
    var emptyEditorWhenDeleting = function () {
      var serializeRng = function (rng) {
        var body = dom.create('body');
        var contents = rng.cloneContents();
        body.appendChild(contents);
        return selection.serializer.serialize(body, { format: 'html' });
      };
      var allContentsSelected = function (rng) {
        var selection = serializeRng(rng);
        var allRng = dom.createRng();
        allRng.selectNode(editor.getBody());
        var allSelection = serializeRng(allRng);
        return selection === allSelection;
      };
      editor.on('keydown', function (e) {
        var keyCode = e.keyCode;
        var isCollapsed, body;
        if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
          isCollapsed = editor.selection.isCollapsed();
          body = editor.getBody();
          if (isCollapsed && !dom.isEmpty(body)) {
            return;
          }
          if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
            return;
          }
          e.preventDefault();
          editor.setContent('');
          if (body.firstChild && dom.isBlock(body.firstChild)) {
            editor.selection.setCursorLocation(body.firstChild, 0);
          } else {
            editor.selection.setCursorLocation(body, 0);
          }
          editor.nodeChanged();
        }
      });
    };
    var selectAll = function () {
      editor.shortcuts.add('meta+a', null, 'SelectAll');
    };
    var inputMethodFocus = function () {
      if (!editor.settings.content_editable) {
        dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
          var rng;
          if (e.target === editor.getDoc().documentElement) {
            rng = selection.getRng();
            editor.getBody().focus();
            if (e.type === 'mousedown') {
              if (isCaretContainer(rng.startContainer)) {
                return;
              }
              selection.placeCaretAt(e.clientX, e.clientY);
            } else {
              selection.setRng(rng);
            }
          }
        });
      }
    };
    var removeHrOnBackspace = function () {
      editor.on('keydown', function (e) {
        if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
          if (!editor.getBody().getElementsByTagName('hr').length) {
            return;
          }
          if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
            var node = selection.getNode();
            var previousSibling = node.previousSibling;
            if (node.nodeName === 'HR') {
              dom.remove(node);
              e.preventDefault();
              return;
            }
            if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
              dom.remove(previousSibling);
              e.preventDefault();
            }
          }
        }
      });
    };
    var focusBody = function () {
      if (!Range.prototype.getClientRects) {
        editor.on('mousedown', function (e) {
          if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
            var body_1 = editor.getBody();
            body_1.blur();
            $_8sy3pfhjh8lyw95.setEditorTimeout(editor, function () {
              body_1.focus();
            });
          }
        });
      }
    };
    var selectControlElements = function () {
      editor.on('click', function (e) {
        var target = e.target;
        if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
          e.preventDefault();
          editor.selection.select(target);
          editor.nodeChanged();
        }
        if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
          e.preventDefault();
          selection.select(target);
        }
      });
    };
    var removeStylesWhenDeletingAcrossBlockElements = function () {
      var getAttributeApplyFunction = function () {
        var template = dom.getAttribs(selection.getStart().cloneNode(false));
        return function () {
          var target = selection.getStart();
          if (target !== editor.getBody()) {
            dom.setAttrib(target, 'style', null);
            each(template, function (attr) {
              target.setAttributeNode(attr.cloneNode(true));
            });
          }
        };
      };
      var isSelectionAcrossElements = function () {
        return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
      };
      editor.on('keypress', function (e) {
        var applyAttributes;
        if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
          applyAttributes = getAttributeApplyFunction();
          editor.getDoc().execCommand('delete', false, null);
          applyAttributes();
          e.preventDefault();
          return false;
        }
      });
      dom.bind(editor.getDoc(), 'cut', function (e) {
        var applyAttributes;
        if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
          applyAttributes = getAttributeApplyFunction();
          $_8sy3pfhjh8lyw95.setEditorTimeout(editor, function () {
            applyAttributes();
          });
        }
      });
    };
    var disableBackspaceIntoATable = function () {
      editor.on('keydown', function (e) {
        if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
          if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
            var previousSibling = selection.getNode().previousSibling;
            if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
              e.preventDefault();
              return false;
            }
          }
        }
      });
    };
    var removeBlockQuoteOnBackSpace = function () {
      editor.on('keydown', function (e) {
        var rng, container, offset, root, parent;
        if (isDefaultPrevented(e) || e.keyCode !== $_6lsk4i5gjh8lyxau.BACKSPACE) {
          return;
        }
        rng = selection.getRng();
        container = rng.startContainer;
        offset = rng.startOffset;
        root = dom.getRoot();
        parent = container;
        if (!rng.collapsed || offset !== 0) {
          return;
        }
        while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
          parent = parent.parentNode;
        }
        if (parent.tagName === 'BLOCKQUOTE') {
          editor.formatter.toggle('blockquote', null, parent);
          rng = dom.createRng();
          rng.setStart(container, 0);
          rng.setEnd(container, 0);
          selection.setRng(rng);
        }
      });
    };
    var setGeckoEditingOptions = function () {
      var setOpts = function () {
        setEditorCommandState('StyleWithCSS', false);
        setEditorCommandState('enableInlineTableEditing', false);
        if (!settings.object_resizing) {
          setEditorCommandState('enableObjectResizing', false);
        }
      };
      if (!settings.readonly) {
        editor.on('BeforeExecCommand MouseDown', setOpts);
      }
    };
    var addBrAfterLastLinks = function () {
      var fixLinks = function () {
        each(dom.select('a'), function (node) {
          var parentNode = node.parentNode;
          var root = dom.getRoot();
          if (parentNode.lastChild === node) {
            while (parentNode && !dom.isBlock(parentNode)) {
              if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
                return;
              }
              parentNode = parentNode.parentNode;
            }
            dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
          }
        });
      };
      editor.on('SetContent ExecCommand', function (e) {
        if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
          fixLinks();
        }
      });
    };
    var setDefaultBlockType = function () {
      if (settings.forced_root_block) {
        editor.on('init', function () {
          setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block);
        });
      }
    };
    var normalizeSelection = function () {
      editor.on('keyup focusin mouseup', function (e) {
        if (!$_6lsk4i5gjh8lyxau.modifierPressed(e)) {
          selection.normalize();
        }
      }, true);
    };
    var showBrokenImageIcon = function () {
      editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
    };
    var restoreFocusOnKeyDown = function () {
      if (!editor.inline) {
        editor.on('keydown', function () {
          if (document.activeElement === document.body) {
            editor.getWin().focus();
          }
        });
      }
    };
    var bodyHeight = function () {
      if (!editor.inline) {
        editor.contentStyles.push('body {min-height: 150px}');
        editor.on('click', function (e) {
          var rng;
          if (e.target.nodeName === 'HTML') {
            if ($_9bpim8ajh8lyw68.ie > 11) {
              editor.getBody().focus();
              return;
            }
            rng = editor.selection.getRng();
            editor.getBody().focus();
            editor.selection.setRng(rng);
            editor.selection.normalize();
            editor.nodeChanged();
          }
        });
      }
    };
    var blockCmdArrowNavigation = function () {
      if ($_9bpim8ajh8lyw68.mac) {
        editor.on('keydown', function (e) {
          if ($_6lsk4i5gjh8lyxau.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
            e.preventDefault();
            editor.selection.getSel().modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
          }
        });
      }
    };
    var disableAutoUrlDetect = function () {
      setEditorCommandState('AutoUrlDetect', false);
    };
    var tapLinksAndImages = function () {
      editor.on('click', function (e) {
        var elm = e.target;
        do {
          if (elm.tagName === 'A') {
            e.preventDefault();
            return;
          }
        } while (elm = elm.parentNode);
      });
      editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
    };
    var blockFormSubmitInsideEditor = function () {
      editor.on('init', function () {
        editor.dom.bind(editor.getBody(), 'submit', function (e) {
          e.preventDefault();
        });
      });
    };
    var removeAppleInterchangeBrs = function () {
      parser.addNodeFilter('br', function (nodes) {
        var i = nodes.length;
        while (i--) {
          if (nodes[i].attr('class') === 'Apple-interchange-newline') {
            nodes[i].remove();
          }
        }
      });
    };
    var ieInternalDragAndDrop = function () {
      editor.on('dragstart', function (e) {
        setMceInternalContent(e);
      });
      editor.on('drop', function (e) {
        if (!isDefaultPrevented(e)) {
          var internalContent = getMceInternalContent(e);
          if (internalContent && internalContent.id !== editor.id) {
            e.preventDefault();
            var rng = $_ct0ht56jjh8lyxif.fromPoint(e.x, e.y, editor.getDoc());
            selection.setRng(rng);
            insertClipboardContents(internalContent.html, true);
          }
        }
      });
    };
    var refreshContentEditable = function () {
    };
    var isHidden = function () {
      var sel;
      if (!isGecko || editor.removed) {
        return 0;
      }
      sel = editor.selection.getSel();
      return !sel || !sel.rangeCount || sel.rangeCount === 0;
    };
    removeBlockQuoteOnBackSpace();
    emptyEditorWhenDeleting();
    if (!$_9bpim8ajh8lyw68.windowsPhone) {
      normalizeSelection();
    }
    if (isWebKit) {
      inputMethodFocus();
      selectControlElements();
      setDefaultBlockType();
      blockFormSubmitInsideEditor();
      disableBackspaceIntoATable();
      removeAppleInterchangeBrs();
      if ($_9bpim8ajh8lyw68.iOS) {
        restoreFocusOnKeyDown();
        bodyHeight();
        tapLinksAndImages();
      } else {
        selectAll();
      }
    }
    if ($_9bpim8ajh8lyw68.ie >= 11) {
      bodyHeight();
      disableBackspaceIntoATable();
    }
    if ($_9bpim8ajh8lyw68.ie) {
      selectAll();
      disableAutoUrlDetect();
      ieInternalDragAndDrop();
    }
    if (isGecko) {
      removeHrOnBackspace();
      focusBody();
      removeStylesWhenDeletingAcrossBlockElements();
      setGeckoEditingOptions();
      addBrAfterLastLinks();
      showBrokenImageIcon();
      blockCmdArrowNavigation();
      disableBackspaceIntoATable();
    }
    return {
      refreshContentEditable: refreshContentEditable,
      isHidden: isHidden
    };
  }

  var isTextBlockNode = function (node) {
    return $_5oonaz1qjh8lywhz.isElement(node) && isTextBlock($_cgttw3zjh8lywdq.fromDom(node));
  };
  var normalizeSelection$1 = function (editor) {
    var rng = editor.selection.getRng();
    var startPos = CaretPosition.fromRangeStart(rng);
    var endPos = CaretPosition.fromRangeEnd(rng);
    if (CaretPosition.isElementPosition(startPos)) {
      var container = startPos.container();
      if (isTextBlockNode(container)) {
        $_9kvypj2cjh8lywnz.firstPositionIn(container).each(function (pos) {
          return rng.setStart(pos.container(), pos.offset());
        });
      }
    }
    if (CaretPosition.isElementPosition(endPos)) {
      var container = startPos.container();
      if (isTextBlockNode(container)) {
        $_9kvypj2cjh8lywnz.lastPositionIn(container).each(function (pos) {
          return rng.setEnd(pos.container(), pos.offset());
        });
      }
    }
    editor.selection.setRng($_cnbluh30jh8lywrn.normalize(rng));
  };
  var setup$11 = function (editor) {
    editor.on('click', function (e) {
      if (e.detail === 3) {
        normalizeSelection$1(editor);
      }
    });
  };
  var $_1nhbc479jh8lyxn0 = { setup: setup$11 };

  var preventSummaryToggle = function (editor) {
    editor.on('click', function (e) {
      if (editor.dom.getParent(e.target, 'details')) {
        e.preventDefault();
      }
    });
  };
  var filterDetails = function (editor) {
    editor.parser.addNodeFilter('details', function (elms) {
      $_5wjzy24jh8lyw2t.each(elms, function (details) {
        details.attr('data-mce-open', details.attr('open'));
        details.attr('open', 'open');
      });
    });
    editor.serializer.addNodeFilter('details', function (elms) {
      $_5wjzy24jh8lyw2t.each(elms, function (details) {
        var open = details.attr('data-mce-open');
        details.attr('open', $_dp4g6d7jh8lyw3y.isString(open) ? open : null);
        details.attr('data-mce-open', null);
      });
    });
  };
  var setup$12 = function (editor) {
    preventSummaryToggle(editor);
    filterDetails(editor);
  };

  var DOM$2 = DOMUtils$1.DOM;
  var appendStyle = function (editor, text) {
    var head = $_cgttw3zjh8lywdq.fromDom(editor.getDoc().head);
    var tag = $_cgttw3zjh8lywdq.fromTag('style');
    $_3da62i14jh8lyweo.set(tag, 'type', 'text/css');
    $_4m7u2e2kjh8lywpi.append(tag, $_cgttw3zjh8lywdq.fromText(text));
    $_4m7u2e2kjh8lywpi.append(head, tag);
  };
  var createParser = function (editor) {
    var parser = DomParser(editor.settings, editor.schema);
    parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
      var i = nodes.length, node;
      var dom = editor.dom;
      var value, internalName;
      while (i--) {
        node = nodes[i];
        value = node.attr(name);
        internalName = 'data-mce-' + name;
        if (!node.attributes.map[internalName]) {
          if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
            continue;
          }
          if (name === 'style') {
            value = dom.serializeStyle(dom.parseStyle(value), node.name);
            if (!value.length) {
              value = null;
            }
            node.attr(internalName, value);
            node.attr(name, value);
          } else if (name === 'tabindex') {
            node.attr(internalName, value);
            node.attr(name, null);
          } else {
            node.attr(internalName, editor.convertURL(value, name, node.name));
          }
        }
      }
    });
    parser.addNodeFilter('script', function (nodes) {
      var i = nodes.length, node, type;
      while (i--) {
        node = nodes[i];
        type = node.attr('type') || 'no/type';
        if (type.indexOf('mce-') !== 0) {
          node.attr('type', 'mce-' + type);
        }
      }
    });
    parser.addNodeFilter('#cdata', function (nodes) {
      var i = nodes.length, node;
      while (i--) {
        node = nodes[i];
        node.type = 8;
        node.name = '#comment';
        node.value = '[CDATA[' + node.value + ']]';
      }
    });
    parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
      var i = nodes.length, node;
      var nonEmptyElements = editor.schema.getNonEmptyElements();
      while (i--) {
        node = nodes[i];
        if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
          node.append(new Node$2('br', 1)).shortEnded = true;
        }
      }
    });
    return parser;
  };
  var autoFocus = function (editor) {
    if (editor.settings.auto_focus) {
      $_8sy3pfhjh8lyw95.setEditorTimeout(editor, function () {
        var focusEditor;
        if (editor.settings.auto_focus === true) {
          focusEditor = editor;
        } else {
          focusEditor = editor.editorManager.get(editor.settings.auto_focus);
        }
        if (!focusEditor.destroyed) {
          focusEditor.focus();
        }
      }, 100);
    }
  };
  var initEditor = function (editor) {
    editor.bindPendingEventDelegates();
    editor.initialized = true;
    editor.fire('init');
    editor.focus(true);
    editor.nodeChanged({ initial: true });
    editor.execCallback('init_instance_callback', editor);
    autoFocus(editor);
  };
  var getStyleSheetLoader = function (editor) {
    return editor.inline ? DOM$2.styleSheetLoader : editor.dom.styleSheetLoader;
  };
  var initContentBody = function (editor, skipWrite) {
    var settings = editor.settings;
    var targetElm = editor.getElement();
    var doc = editor.getDoc(), body, contentCssText;
    if (!settings.inline) {
      editor.getElement().style.visibility = editor.orgVisibility;
    }
    if (!skipWrite && !settings.content_editable) {
      doc.open();
      doc.write(editor.iframeHTML);
      doc.close();
    }
    if (settings.content_editable) {
      editor.on('remove', function () {
        var bodyEl = this.getBody();
        DOM$2.removeClass(bodyEl, 'mce-content-body');
        DOM$2.removeClass(bodyEl, 'mce-edit-focus');
        DOM$2.setAttrib(bodyEl, 'contentEditable', null);
      });
      DOM$2.addClass(targetElm, 'mce-content-body');
      editor.contentDocument = doc = settings.content_document || document;
      editor.contentWindow = settings.content_window || window;
      editor.bodyElement = targetElm;
      settings.content_document = settings.content_window = null;
      settings.root_name = targetElm.nodeName.toLowerCase();
    }
    body = editor.getBody();
    body.disabled = true;
    editor.readonly = settings.readonly;
    if (!editor.readonly) {
      if (editor.inline && DOM$2.getStyle(body, 'position', true) === 'static') {
        body.style.position = 'relative';
      }
      body.contentEditable = editor.getParam('content_editable_state', true);
    }
    body.disabled = false;
    editor.editorUpload = EditorUpload(editor);
    editor.schema = Schema(settings);
    editor.dom = DOMUtils$1(doc, {
      keep_values: true,
      url_converter: editor.convertURL,
      url_converter_scope: editor,
      hex_colors: settings.force_hex_style_colors,
      class_filter: settings.class_filter,
      update_styles: true,
      root_element: editor.inline ? editor.getBody() : null,
      collect: settings.content_editable,
      schema: editor.schema,
      onSetAttrib: function (e) {
        editor.fire('SetAttrib', e);
      }
    });
    editor.parser = createParser(editor);
    editor.serializer = DomSerializer$1(settings, editor);
    editor.selection = Selection$1(editor.dom, editor.getWin(), editor.serializer, editor);
    editor.formatter = Formatter(editor);
    editor.undoManager = UndoManager(editor);
    editor._nodeChangeDispatcher = new NodeChange(editor);
    editor._selectionOverrides = SelectionOverrides(editor);
    setup$12(editor);
    $_1nhbc479jh8lyxn0.setup(editor);
    $_btkj596sjh8lyxkc.setup(editor);
    $_85z7kh54jh8lyx8j.setup(editor);
    editor.fire('PreInit');
    if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
      doc.body.spellcheck = false;
      DOM$2.setAttrib(body, 'spellcheck', 'false');
    }
    editor.quirks = Quirks(editor);
    editor.fire('PostRender');
    if (settings.directionality) {
      body.dir = settings.directionality;
    }
    if (settings.nowrap) {
      body.style.whiteSpace = 'nowrap';
    }
    if (settings.protect) {
      editor.on('BeforeSetContent', function (e) {
        $_ahowuxkjh8lywbj.each(settings.protect, function (pattern) {
          e.content = e.content.replace(pattern, function (str) {
            return '<!--mce:protected ' + escape(str) + '-->';
          });
        });
      });
    }
    editor.on('SetContent', function () {
      editor.addVisual(editor.getBody());
    });
    editor.load({
      initial: true,
      format: 'html'
    });
    editor.startContent = editor.getContent({ format: 'raw' });
    editor.on('compositionstart compositionend', function (e) {
      editor.composing = e.type === 'compositionstart';
    });
    if (editor.contentStyles.length > 0) {
      contentCssText = '';
      $_ahowuxkjh8lywbj.each(editor.contentStyles, function (style) {
        contentCssText += style + '\r\n';
      });
      editor.dom.addStyle(contentCssText);
    }
    getStyleSheetLoader(editor).loadAll(editor.contentCSS, function (_) {
      initEditor(editor);
    }, function (urls) {
      initEditor(editor);
    });
    if (settings.content_style) {
      appendStyle(editor, settings.content_style);
    }
  };
  var $_g84rjb4rjh8lyx6v = { initContentBody: initContentBody };

  var DOM$3 = DOMUtils$1.DOM;
  var relaxDomain = function (editor, ifr) {
    if (document.domain !== window.location.hostname && $_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie < 12) {
      var bodyUuid = $_co2y7g52jh8lyx8f.uuid('mce');
      editor[bodyUuid] = function () {
        $_g84rjb4rjh8lyx6v.initContentBody(editor);
      };
      var domainRelaxUrl = 'javascript:(function(){' + 'document.open();document.domain="' + document.domain + '";' + 'var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);' + 'document.close();ed.' + bodyUuid + '(true);})()';
      DOM$3.setAttrib(ifr, 'src', domainRelaxUrl);
      return true;
    }
    return false;
  };
  var normalizeHeight = function (height) {
    var normalizedHeight = typeof height === 'number' ? height + 'px' : height;
    return normalizedHeight ? normalizedHeight : '';
  };
  var createIframeElement = function (id, title, height, customAttrs) {
    var iframe = $_cgttw3zjh8lywdq.fromTag('iframe');
    $_3da62i14jh8lyweo.setAll(iframe, customAttrs);
    $_3da62i14jh8lyweo.setAll(iframe, {
      id: id + '_ifr',
      frameBorder: '0',
      allowTransparency: 'true',
      title: title
    });
    $_36knnd12jh8lywe1.setAll(iframe, {
      width: '100%',
      height: normalizeHeight(height),
      display: 'block'
    });
    return iframe;
  };
  var getIframeHtml = function (editor) {
    var bodyId, bodyClass, iframeHTML;
    iframeHTML = $_66vr6g2jjh8lywpf.getDocType(editor) + '<html><head>';
    if ($_66vr6g2jjh8lywpf.getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
      iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
    }
    iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    bodyId = $_66vr6g2jjh8lywpf.getBodyId(editor);
    bodyClass = $_66vr6g2jjh8lywpf.getBodyClass(editor);
    if ($_66vr6g2jjh8lywpf.getContentSecurityPolicy(editor)) {
      iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + $_66vr6g2jjh8lywpf.getContentSecurityPolicy(editor) + '" />';
    }
    iframeHTML += '</head><body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '"><br></body></html>';
    return iframeHTML;
  };
  var createIframe = function (editor, o) {
    var title = editor.editorManager.translate('Rich Text Area. Press ALT-F9 for menu. ' + 'Press ALT-F10 for toolbar. Press ALT-0 for help');
    var ifr = createIframeElement(editor.id, title, o.height, $_66vr6g2jjh8lywpf.getIframeAttrs(editor)).dom();
    ifr.onload = function () {
      ifr.onload = null;
      editor.fire('load');
    };
    var isDomainRelaxed = relaxDomain(editor, ifr);
    editor.contentAreaContainer = o.iframeContainer;
    editor.iframeElement = ifr;
    editor.iframeHTML = getIframeHtml(editor);
    DOM$3.add(o.iframeContainer, ifr);
    return isDomainRelaxed;
  };
  var init$1 = function (editor, boxInfo) {
    var isDomainRelaxed = createIframe(editor, boxInfo);
    if (boxInfo.editorContainer) {
      DOM$3.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
      editor.hidden = DOM$3.isHidden(boxInfo.editorContainer);
    }
    editor.getElement().style.display = 'none';
    DOM$3.setAttrib(editor.id, 'aria-hidden', 'true');
    if (!isDomainRelaxed) {
      $_g84rjb4rjh8lyx6v.initContentBody(editor);
    }
  };
  var $_9i7a4m7bjh8lyxnf = { init: init$1 };

  var DOM$4 = DOMUtils$1.DOM;
  var initPlugin = function (editor, initializedPlugins, plugin) {
    var Plugin = PluginManager$1.get(plugin);
    var pluginUrl, pluginInstance;
    pluginUrl = PluginManager$1.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
    plugin = $_ahowuxkjh8lywbj.trim(plugin);
    if (Plugin && $_ahowuxkjh8lywbj.inArray(initializedPlugins, plugin) === -1) {
      $_ahowuxkjh8lywbj.each(PluginManager$1.dependencies(plugin), function (dep) {
        initPlugin(editor, initializedPlugins, dep);
      });
      if (editor.plugins[plugin]) {
        return;
      }
      pluginInstance = new Plugin(editor, pluginUrl, editor.$);
      editor.plugins[plugin] = pluginInstance;
      if (pluginInstance.init) {
        pluginInstance.init(editor, pluginUrl);
        initializedPlugins.push(plugin);
      }
    }
  };
  var trimLegacyPrefix = function (name) {
    return name.replace(/^\-/, '');
  };
  var initPlugins = function (editor) {
    var initializedPlugins = [];
    $_ahowuxkjh8lywbj.each(editor.settings.plugins.split(/[ ,]/), function (name) {
      initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
    });
  };
  var initTheme = function (editor) {
    var Theme;
    var theme = editor.settings.theme;
    if ($_dp4g6d7jh8lyw3y.isString(theme)) {
      editor.settings.theme = trimLegacyPrefix(theme);
      Theme = ThemeManager.get(theme);
      editor.theme = new Theme(editor, ThemeManager.urls[theme]);
      if (editor.theme.init) {
        editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
      }
    } else {
      editor.theme = {};
    }
  };
  var renderFromLoadedTheme = function (editor) {
    var w, h, minHeight, re, info;
    var settings = editor.settings;
    var elm = editor.getElement();
    w = settings.width || DOM$4.getStyle(elm, 'width') || '100%';
    h = settings.height || DOM$4.getStyle(elm, 'height') || elm.offsetHeight;
    minHeight = settings.min_height || 100;
    re = /^[0-9\.]+(|px)$/i;
    if (re.test('' + w)) {
      w = Math.max(parseInt(w, 10), 100);
    }
    if (re.test('' + h)) {
      h = Math.max(parseInt(h, 10), minHeight);
    }
    info = editor.theme.renderUI({
      targetNode: elm,
      width: w,
      height: h,
      deltaWidth: settings.delta_width,
      deltaHeight: settings.delta_height
    });
    if (!settings.content_editable) {
      h = (info.iframeHeight || h) + (typeof h === 'number' ? info.deltaHeight || 0 : '');
      if (h < minHeight) {
        h = minHeight;
      }
    }
    info.height = h;
    return info;
  };
  var renderFromThemeFunc = function (editor) {
    var info;
    var elm = editor.getElement();
    info = editor.settings.theme(editor, elm);
    if (info.editorContainer.nodeType) {
      info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
    }
    if (info.iframeContainer && info.iframeContainer.nodeType) {
      info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
    }
    info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
    return info;
  };
  var createThemeFalseResult = function (element) {
    return {
      editorContainer: element,
      iframeContainer: element
    };
  };
  var renderThemeFalseIframe = function (targetElement) {
    var iframeContainer = DOM$4.create('div');
    DOM$4.insertAfter(iframeContainer, targetElement);
    return createThemeFalseResult(iframeContainer);
  };
  var renderThemeFalse = function (editor) {
    var targetElement = editor.getElement();
    return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  };
  var renderThemeUi = function (editor) {
    var settings = editor.settings, elm = editor.getElement();
    editor.orgDisplay = elm.style.display;
    if ($_dp4g6d7jh8lyw3y.isString(settings.theme)) {
      return renderFromLoadedTheme(editor);
    } else if ($_dp4g6d7jh8lyw3y.isFunction(settings.theme)) {
      return renderFromThemeFunc(editor);
    } else {
      return renderThemeFalse(editor);
    }
  };
  var init$2 = function (editor) {
    var settings = editor.settings;
    var elm = editor.getElement();
    var boxInfo;
    editor.rtl = settings.rtl_ui || editor.editorManager.i18n.rtl;
    editor.editorManager.i18n.setCode(settings.language);
    settings.aria_label = settings.aria_label || DOM$4.getAttrib(elm, 'aria-label', editor.getLang('aria.rich_text_area'));
    editor.fire('ScriptsLoaded');
    initTheme(editor);
    initPlugins(editor);
    boxInfo = renderThemeUi(editor);
    editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
    if (settings.content_css) {
      $_ahowuxkjh8lywbj.each($_ahowuxkjh8lywbj.explode(settings.content_css), function (u) {
        editor.contentCSS.push(editor.documentBaseURI.toAbsolute(u));
      });
    }
    if (settings.content_editable) {
      return $_g84rjb4rjh8lyx6v.initContentBody(editor);
    } else {
      return $_9i7a4m7bjh8lyxnf.init(editor, boxInfo);
    }
  };
  var $_bynk2f4ojh8lyx6l = { init: init$2 };

  var DOM$5 = DOMUtils$1.DOM;
  var hasSkipLoadPrefix = function (name) {
    return name.charAt(0) === '-';
  };
  var loadLanguage = function (scriptLoader, editor) {
    var settings = editor.settings;
    if (settings.language && settings.language !== 'en' && !settings.language_url) {
      settings.language_url = editor.editorManager.baseURL + '/langs/' + settings.language + '.js';
    }
    if (settings.language_url && !editor.editorManager.i18n.data[settings.language]) {
      scriptLoader.add(settings.language_url);
    }
  };
  var loadTheme = function (scriptLoader, editor, suffix, callback) {
    var settings = editor.settings, theme = settings.theme;
    if ($_dp4g6d7jh8lyw3y.isString(theme)) {
      if (!hasSkipLoadPrefix(theme) && !ThemeManager.urls.hasOwnProperty(theme)) {
        var themeUrl = settings.theme_url;
        if (themeUrl) {
          ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
        } else {
          ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
        }
      }
      scriptLoader.loadQueue(function () {
        ThemeManager.waitFor(theme, callback);
      });
    } else {
      callback();
    }
  };
  var loadPlugins = function (settings, suffix) {
    if ($_ahowuxkjh8lywbj.isArray(settings.plugins)) {
      settings.plugins = settings.plugins.join(' ');
    }
    $_ahowuxkjh8lywbj.each(settings.external_plugins, function (url, name) {
      PluginManager$1.load(name, url);
      settings.plugins += ' ' + name;
    });
    $_ahowuxkjh8lywbj.each(settings.plugins.split(/[ ,]/), function (plugin) {
      plugin = $_ahowuxkjh8lywbj.trim(plugin);
      if (plugin && !PluginManager$1.urls[plugin]) {
        if (hasSkipLoadPrefix(plugin)) {
          plugin = plugin.substr(1, plugin.length);
          var dependencies = PluginManager$1.dependencies(plugin);
          $_ahowuxkjh8lywbj.each(dependencies, function (dep) {
            var defaultSettings = {
              prefix: 'plugins/',
              resource: dep,
              suffix: '/plugin' + suffix + '.js'
            };
            dep = PluginManager$1.createUrl(defaultSettings, dep);
            PluginManager$1.load(dep.resource, dep);
          });
        } else {
          PluginManager$1.load(plugin, {
            prefix: 'plugins/',
            resource: plugin,
            suffix: '/plugin' + suffix + '.js'
          });
        }
      }
    });
  };
  var loadScripts = function (editor, suffix) {
    var scriptLoader = ScriptLoader.ScriptLoader;
    loadTheme(scriptLoader, editor, suffix, function () {
      loadLanguage(scriptLoader, editor);
      loadPlugins(editor.settings, suffix);
      scriptLoader.loadQueue(function () {
        if (!editor.removed) {
          $_bynk2f4ojh8lyx6l.init(editor);
        }
      }, editor, function (urls) {
        $_5vy074njh8lyx6h.pluginLoadError(editor, urls[0]);
        if (!editor.removed) {
          $_bynk2f4ojh8lyx6l.init(editor);
        }
      });
    });
  };
  var render = function (editor) {
    var settings = editor.settings, id = editor.id;
    var readyHandler = function () {
      DOM$5.unbind(window, 'ready', readyHandler);
      editor.render();
    };
    if (!EventUtils.Event.domLoaded) {
      DOM$5.bind(window, 'ready', readyHandler);
      return;
    }
    if (!editor.getElement()) {
      return;
    }
    if (!$_9bpim8ajh8lyw68.contentEditable) {
      return;
    }
    if (!settings.inline) {
      editor.orgVisibility = editor.getElement().style.visibility;
      editor.getElement().style.visibility = 'hidden';
    } else {
      editor.inline = true;
    }
    var form = editor.getElement().form || DOM$5.getParent(id, 'form');
    if (form) {
      editor.formElement = form;
      if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(editor.getElement().nodeName)) {
        DOM$5.insertAfter(DOM$5.create('input', {
          type: 'hidden',
          name: id
        }), id);
        editor.hasHiddenInput = true;
      }
      editor.formEventDelegate = function (e) {
        editor.fire(e.type, e);
      };
      DOM$5.bind(form, 'submit reset', editor.formEventDelegate);
      editor.on('reset', function () {
        editor.setContent(editor.startContent, { format: 'raw' });
      });
      if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
        form._mceOldSubmit = form.submit;
        form.submit = function () {
          editor.editorManager.triggerSave();
          editor.setDirty(false);
          return form._mceOldSubmit(form);
        };
      }
    }
    editor.windowManager = WindowManager(editor);
    editor.notificationManager = NotificationManager(editor);
    if (settings.encoding === 'xml') {
      editor.on('GetContent', function (e) {
        if (e.save) {
          e.content = DOM$5.encode(e.content);
        }
      });
    }
    if (settings.add_form_submit_trigger) {
      editor.on('submit', function () {
        if (editor.initialized) {
          editor.save();
        }
      });
    }
    if (settings.add_unload_trigger) {
      editor._beforeUnload = function () {
        if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
          editor.save({
            format: 'raw',
            no_events: true,
            set_dirty: false
          });
        }
      };
      editor.editorManager.on('BeforeUnload', editor._beforeUnload);
    }
    editor.editorManager.add(editor);
    loadScripts(editor, editor.suffix);
  };
  var $_64g0n44hjh8lyx5e = { render: render };

  var add$3 = function (editor, name, settings) {
    var sidebars = editor.sidebars ? editor.sidebars : [];
    sidebars.push({
      name: name,
      settings: settings
    });
    editor.sidebars = sidebars;
  };
  var $_67cz5d7cjh8lyxnm = { add: add$3 };

  var each$20 = $_ahowuxkjh8lywbj.each;
  var trim$4 = $_ahowuxkjh8lywbj.trim;
  var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  var DEFAULT_PORTS = {
    ftp: 21,
    http: 80,
    https: 443,
    mailto: 25
  };
  var URI = function (url, settings) {
    var self = this;
    var baseUri, baseUrl;
    url = trim$4(url);
    settings = self.settings = settings || {};
    baseUri = settings.base_uri;
    if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
      self.source = url;
      return;
    }
    var isProtocolRelative = url.indexOf('//') === 0;
    if (url.indexOf('/') === 0 && !isProtocolRelative) {
      url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
    }
    if (!/^[\w\-]*:?\/\//.test(url)) {
      baseUrl = settings.base_uri ? settings.base_uri.path : new URI(document.location.href).directory;
      if (settings.base_uri.protocol == '') {
        url = '//mce_host' + self.toAbsPath(baseUrl, url);
      } else {
        url = /([^#?]*)([#?]?.*)/.exec(url);
        url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, url[1]) + url[2];
      }
    }
    url = url.replace(/@@/g, '(mce_at)');
    url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
    each$20(queryParts, function (v, i) {
      var part = url[i];
      if (part) {
        part = part.replace(/\(mce_at\)/g, '@@');
      }
      self[v] = part;
    });
    if (baseUri) {
      if (!self.protocol) {
        self.protocol = baseUri.protocol;
      }
      if (!self.userInfo) {
        self.userInfo = baseUri.userInfo;
      }
      if (!self.port && self.host === 'mce_host') {
        self.port = baseUri.port;
      }
      if (!self.host || self.host === 'mce_host') {
        self.host = baseUri.host;
      }
      self.source = '';
    }
    if (isProtocolRelative) {
      self.protocol = '';
    }
  };
  URI.prototype = {
    setPath: function (path) {
      var self = this;
      path = /^(.*?)\/?(\w+)?$/.exec(path);
      self.path = path[0];
      self.directory = path[1];
      self.file = path[2];
      self.source = '';
      self.getURI();
    },
    toRelative: function (uri) {
      var self = this;
      var output;
      if (uri === './') {
        return uri;
      }
      uri = new URI(uri, { base_uri: self });
      if (uri.host !== 'mce_host' && self.host !== uri.host && uri.host || self.port !== uri.port || self.protocol !== uri.protocol && uri.protocol !== '') {
        return uri.getURI();
      }
      var tu = self.getURI(), uu = uri.getURI();
      if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
        return tu;
      }
      output = self.toRelPath(self.path, uri.path);
      if (uri.query) {
        output += '?' + uri.query;
      }
      if (uri.anchor) {
        output += '#' + uri.anchor;
      }
      return output;
    },
    toAbsolute: function (uri, noHost) {
      uri = new URI(uri, { base_uri: this });
      return uri.getURI(noHost && this.isSameOrigin(uri));
    },
    isSameOrigin: function (uri) {
      if (this.host == uri.host && this.protocol == uri.protocol) {
        if (this.port == uri.port) {
          return true;
        }
        var defaultPort = DEFAULT_PORTS[this.protocol];
        if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
          return true;
        }
      }
      return false;
    },
    toRelPath: function (base, path) {
      var items, breakPoint = 0, out = '', i, l;
      base = base.substring(0, base.lastIndexOf('/'));
      base = base.split('/');
      items = path.split('/');
      if (base.length >= items.length) {
        for (i = 0, l = base.length; i < l; i++) {
          if (i >= items.length || base[i] !== items[i]) {
            breakPoint = i + 1;
            break;
          }
        }
      }
      if (base.length < items.length) {
        for (i = 0, l = items.length; i < l; i++) {
          if (i >= base.length || base[i] !== items[i]) {
            breakPoint = i + 1;
            break;
          }
        }
      }
      if (breakPoint === 1) {
        return path;
      }
      for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) {
        out += '../';
      }
      for (i = breakPoint - 1, l = items.length; i < l; i++) {
        if (i !== breakPoint - 1) {
          out += '/' + items[i];
        } else {
          out += items[i];
        }
      }
      return out;
    },
    toAbsPath: function (base, path) {
      var i, nb = 0, o = [], tr, outPath;
      tr = /\/$/.test(path) ? '/' : '';
      base = base.split('/');
      path = path.split('/');
      each$20(base, function (k) {
        if (k) {
          o.push(k);
        }
      });
      base = o;
      for (i = path.length - 1, o = []; i >= 0; i--) {
        if (path[i].length === 0 || path[i] === '.') {
          continue;
        }
        if (path[i] === '..') {
          nb++;
          continue;
        }
        if (nb > 0) {
          nb--;
          continue;
        }
        o.push(path[i]);
      }
      i = base.length - nb;
      if (i <= 0) {
        outPath = o.reverse().join('/');
      } else {
        outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');
      }
      if (outPath.indexOf('/') !== 0) {
        outPath = '/' + outPath;
      }
      if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
        outPath += tr;
      }
      return outPath;
    },
    getURI: function (noProtoHost) {
      var s;
      var self = this;
      if (!self.source || noProtoHost) {
        s = '';
        if (!noProtoHost) {
          if (self.protocol) {
            s += self.protocol + '://';
          } else {
            s += '//';
          }
          if (self.userInfo) {
            s += self.userInfo + '@';
          }
          if (self.host) {
            s += self.host;
          }
          if (self.port) {
            s += ':' + self.port;
          }
        }
        if (self.path) {
          s += self.path;
        }
        if (self.query) {
          s += '?' + self.query;
        }
        if (self.anchor) {
          s += '#' + self.anchor;
        }
        self.source = s;
      }
      return self.source;
    }
  };
  URI.parseDataUri = function (uri) {
    var type, matches;
    uri = decodeURIComponent(uri).split(',');
    matches = /data:([^;]+)/.exec(uri[0]);
    if (matches) {
      type = matches[1];
    }
    return {
      type: type,
      data: uri[1]
    };
  };
  URI.getDocumentBaseUrl = function (loc) {
    var baseUrl;
    if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
      baseUrl = loc.href;
    } else {
      baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
    }
    if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
      baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
      if (!/[\/\\]$/.test(baseUrl)) {
        baseUrl += '/';
      }
    }
    return baseUrl;
  };

  var defaultFormat = 'html';
  var trimEmptyContents = function (editor, html) {
    var blockName = $_66vr6g2jjh8lywpf.getForcedRootBlock(editor);
    var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
    return html.replace(emptyRegExp, '');
  };
  var getContentFromBody = function (editor, args, body) {
    var content;
    args.format = args.format ? args.format : defaultFormat;
    args.get = true;
    args.getInner = true;
    if (!args.no_events) {
      editor.fire('BeforeGetContent', args);
    }
    if (args.format === 'raw') {
      content = $_ahowuxkjh8lywbj.trim($_8lol015jjh8lyxbf.trimExternal(editor.serializer, body.innerHTML));
    } else if (args.format === 'text') {
      content = $_d383mr21jh8lywlv.trim(body.innerText || body.textContent);
    } else if (args.format === 'tree') {
      return editor.serializer.serialize(body, args);
    } else {
      content = trimEmptyContents(editor, editor.serializer.serialize(body, args));
    }
    if (args.format !== 'text' && !isWsPreserveElement($_cgttw3zjh8lywdq.fromDom(body))) {
      args.content = $_ahowuxkjh8lywbj.trim(content);
    } else {
      args.content = content;
    }
    if (!args.no_events) {
      editor.fire('GetContent', args);
    }
    return args.content;
  };
  var getContent$1 = function (editor, args) {
    if (args === void 0) {
      args = {};
    }
    return Option.from(editor.getBody()).fold($_eqpqvr6jh8lyw3s.constant(args.format === 'tree' ? new Node$2('body', 11) : ''), function (body) {
      return getContentFromBody(editor, args, body);
    });
  };

  var traverse = function (node, fn) {
    fn(node);
    if (node.firstChild) {
      traverse(node.firstChild, fn);
    }
    if (node.next) {
      traverse(node.next, fn);
    }
  };
  var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
    var nodeMatches = {};
    var attrMatches = {};
    var matches = [];
    if (node.firstChild) {
      traverse(node.firstChild, function (node) {
        $_5wjzy24jh8lyw2t.each(nodeFilters, function (filter) {
          if (filter.name === node.name) {
            if (nodeMatches[filter.name]) {
              nodeMatches[filter.name].nodes.push(node);
            } else {
              nodeMatches[filter.name] = {
                filter: filter,
                nodes: [node]
              };
            }
          }
        });
        $_5wjzy24jh8lyw2t.each(attributeFilters, function (filter) {
          if (typeof node.attr(filter.name) === 'string') {
            if (attrMatches[filter.name]) {
              attrMatches[filter.name].nodes.push(node);
            } else {
              attrMatches[filter.name] = {
                filter: filter,
                nodes: [node]
              };
            }
          }
        });
      });
    }
    for (var name_1 in nodeMatches) {
      if (nodeMatches.hasOwnProperty(name_1)) {
        matches.push(nodeMatches[name_1]);
      }
    }
    for (var name_2 in attrMatches) {
      if (attrMatches.hasOwnProperty(name_2)) {
        matches.push(attrMatches[name_2]);
      }
    }
    return matches;
  };
  var filter$3 = function (nodeFilters, attributeFilters, node) {
    var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
    $_5wjzy24jh8lyw2t.each(matches, function (match) {
      $_5wjzy24jh8lyw2t.each(match.filter.callbacks, function (callback) {
        callback(match.nodes, match.filter.name, {});
      });
    });
  };

  var defaultFormat$1 = 'html';
  var isTreeNode = function (content) {
    return content instanceof Node$2;
  };
  var moveSelection = function (editor) {
    if ($_cnu79r4ejh8lyx4x.hasFocus(editor)) {
      $_9kvypj2cjh8lywnz.firstPositionIn(editor.getBody()).each(function (pos) {
        var node = pos.getNode();
        var caretPos = $_5oonaz1qjh8lywhz.isTable(node) ? $_9kvypj2cjh8lywnz.firstPositionIn(node).getOr(pos) : pos;
        editor.selection.setRng(caretPos.toRange());
      });
    }
  };
  var setEditorHtml = function (editor, html) {
    editor.dom.setHTML(editor.getBody(), html);
    moveSelection(editor);
  };
  var setContentString = function (editor, body, content, args) {
    var forcedRootBlockName, padd;
    if (content.length === 0 || /^\s+$/.test(content)) {
      padd = '<br data-mce-bogus="1">';
      if (body.nodeName === 'TABLE') {
        content = '<tr><td>' + padd + '</td></tr>';
      } else if (/^(UL|OL)$/.test(body.nodeName)) {
        content = '<li>' + padd + '</li>';
      }
      forcedRootBlockName = $_66vr6g2jjh8lywpf.getForcedRootBlock(editor);
      if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
        content = padd;
        content = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs, content);
      } else if (!content) {
        content = '<br data-mce-bogus="1">';
      }
      setEditorHtml(editor, content);
      editor.fire('SetContent', args);
    } else {
      if (args.format !== 'raw') {
        content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
          isRootContent: true,
          insert: true
        }));
      }
      args.content = isWsPreserveElement($_cgttw3zjh8lywdq.fromDom(body)) ? content : $_ahowuxkjh8lywbj.trim(content);
      setEditorHtml(editor, args.content);
      if (!args.no_events) {
        editor.fire('SetContent', args);
      }
    }
    return args.content;
  };
  var setContentTree = function (editor, body, content, args) {
    filter$3(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
    var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
    args.content = isWsPreserveElement($_cgttw3zjh8lywdq.fromDom(body)) ? html : $_ahowuxkjh8lywbj.trim(html);
    setEditorHtml(editor, args.content);
    if (!args.no_events) {
      editor.fire('SetContent', args);
    }
    return content;
  };
  var setContent$1 = function (editor, content, args) {
    if (args === void 0) {
      args = {};
    }
    args.format = args.format ? args.format : defaultFormat$1;
    args.set = true;
    args.content = isTreeNode(content) ? '' : content;
    if (!isTreeNode(content) && !args.no_events) {
      editor.fire('BeforeSetContent', args);
      content = args.content;
    }
    return Option.from(editor.getBody()).fold($_eqpqvr6jh8lyw3s.constant(content), function (body) {
      return isTreeNode(content) ? setContentTree(editor, body, content, args) : setContentString(editor, body, content, args);
    });
  };

  var DOM$6 = DOMUtils$1.DOM;
  var restoreOriginalStyles = function (editor) {
    DOM$6.setStyle(editor.id, 'display', editor.orgDisplay);
  };
  var safeDestroy = function (x) {
    return Option.from(x).each(function (x) {
      return x.destroy();
    });
  };
  var clearDomReferences = function (editor) {
    editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
    editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
    editor.iframeElement = editor.targetElm = null;
    if (editor.selection) {
      editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
    }
  };
  var restoreForm = function (editor) {
    var form = editor.formElement;
    if (form) {
      if (form._mceOldSubmit) {
        form.submit = form._mceOldSubmit;
        form._mceOldSubmit = null;
      }
      DOM$6.unbind(form, 'submit reset', editor.formEventDelegate);
    }
  };
  var remove$8 = function (editor) {
    if (!editor.removed) {
      var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
      var body = editor.getBody();
      var element = editor.getElement();
      if (body) {
        editor.save();
      }
      editor.removed = true;
      editor.unbindAllNativeEvents();
      if (editor.hasHiddenInput && element) {
        DOM$6.remove(element.nextSibling);
      }
      if (!editor.inline && body) {
        restoreOriginalStyles(editor);
      }
      $_a4fgrn4cjh8lyx4q.fireRemove(editor);
      editor.editorManager.remove(editor);
      DOM$6.remove(editor.getContainer());
      safeDestroy(_selectionOverrides);
      safeDestroy(editorUpload);
      editor.destroy();
    }
  };
  var destroy = function (editor, automatic) {
    var selection = editor.selection, dom = editor.dom;
    if (editor.destroyed) {
      return;
    }
    if (!automatic && !editor.removed) {
      editor.remove();
      return;
    }
    if (!automatic) {
      editor.editorManager.off('beforeunload', editor._beforeUnload);
      if (editor.theme && editor.theme.destroy) {
        editor.theme.destroy();
      }
      safeDestroy(selection);
      safeDestroy(dom);
    }
    restoreForm(editor);
    clearDomReferences(editor);
    editor.destroyed = true;
  };

  var DOM$7 = DOMUtils$1.DOM;
  var extend$4 = $_ahowuxkjh8lywbj.extend;
  var each$21 = $_ahowuxkjh8lywbj.each;
  var resolve$4 = $_ahowuxkjh8lywbj.resolve;
  var ie$2 = $_9bpim8ajh8lyw68.ie;
  var Editor = function (id, settings, editorManager) {
    var self = this;
    var documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL;
    var baseUri = editorManager.baseURI;
    settings = getEditorSettings(self, id, documentBaseUrl, editorManager.defaultSettings, settings);
    self.settings = settings;
    AddOnManager.language = settings.language || 'en';
    AddOnManager.languageLoad = settings.language_load;
    AddOnManager.baseURL = editorManager.baseURL;
    self.id = id;
    self.setDirty(false);
    self.plugins = {};
    self.documentBaseURI = new URI(settings.document_base_url, { base_uri: baseUri });
    self.baseURI = baseUri;
    self.contentCSS = [];
    self.contentStyles = [];
    self.shortcuts = new Shortcuts(self);
    self.loadedCSS = {};
    self.editorCommands = new EditorCommands(self);
    self.suffix = editorManager.suffix;
    self.editorManager = editorManager;
    self.inline = settings.inline;
    self.buttons = {};
    self.menuItems = {};
    if (settings.cache_suffix) {
      $_9bpim8ajh8lyw68.cacheSuffix = settings.cache_suffix.replace(/^[\?\&]+/, '');
    }
    if (settings.override_viewport === false) {
      $_9bpim8ajh8lyw68.overrideViewPort = false;
    }
    editorManager.fire('SetupEditor', { editor: self });
    self.execCallback('setup', self);
    self.$ = DomQuery.overrideDefaults(function () {
      return {
        context: self.inline ? self.getBody() : self.getDoc(),
        element: self.getBody()
      };
    });
  };
  Editor.prototype = {
    render: function () {
      $_64g0n44hjh8lyx5e.render(this);
    },
    focus: function (skipFocus) {
      $_cnu79r4ejh8lyx4x.focus(this, skipFocus);
    },
    hasFocus: function () {
      return $_cnu79r4ejh8lyx4x.hasFocus(this);
    },
    execCallback: function (name) {
      var x = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        x[_i - 1] = arguments[_i];
      }
      var self = this;
      var callback = self.settings[name], scope;
      if (!callback) {
        return;
      }
      if (self.callbackLookup && (scope = self.callbackLookup[name])) {
        callback = scope.func;
        scope = scope.scope;
      }
      if (typeof callback === 'string') {
        scope = callback.replace(/\.\w+$/, '');
        scope = scope ? resolve$4(scope) : 0;
        callback = resolve$4(callback);
        self.callbackLookup = self.callbackLookup || {};
        self.callbackLookup[name] = {
          func: callback,
          scope: scope
        };
      }
      return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
    },
    translate: function (text) {
      if (text && $_ahowuxkjh8lywbj.is(text, 'string')) {
        var lang_1 = this.settings.language || 'en', i18n_1 = this.editorManager.i18n;
        text = i18n_1.data[lang_1 + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function (a, b) {
          return i18n_1.data[lang_1 + '.' + b] || '{#' + b + '}';
        });
      }
      return this.editorManager.translate(text);
    },
    getLang: function (name, defaultVal) {
      return this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] || (defaultVal !== undefined ? defaultVal : '{#' + name + '}');
    },
    getParam: function (name, defaultVal, type) {
      return getParam(this, name, defaultVal, type);
    },
    nodeChanged: function (args) {
      this._nodeChangeDispatcher.nodeChanged(args);
    },
    addButton: function (name, settings) {
      var self = this;
      if (settings.cmd) {
        settings.onclick = function () {
          self.execCommand(settings.cmd);
        };
      }
      if (settings.stateSelector && typeof settings.active === 'undefined') {
        settings.active = false;
      }
      if (!settings.text && !settings.icon) {
        settings.icon = name;
      }
      self.buttons = self.buttons;
      settings.tooltip = settings.tooltip || settings.title;
      self.buttons[name] = settings;
    },
    addSidebar: function (name, settings) {
      return $_67cz5d7cjh8lyxnm.add(this, name, settings);
    },
    addMenuItem: function (name, settings) {
      var self = this;
      if (settings.cmd) {
        settings.onclick = function () {
          self.execCommand(settings.cmd);
        };
      }
      self.menuItems = self.menuItems;
      self.menuItems[name] = settings;
    },
    addContextToolbar: function (predicate, items) {
      var self = this;
      var selector;
      self.contextToolbars = self.contextToolbars || [];
      if (typeof predicate === 'string') {
        selector = predicate;
        predicate = function (elm) {
          return self.dom.is(elm, selector);
        };
      }
      self.contextToolbars.push({
        id: $_co2y7g52jh8lyx8f.uuid('mcet'),
        predicate: predicate,
        items: items
      });
    },
    addCommand: function (name, callback, scope) {
      this.editorCommands.addCommand(name, callback, scope);
    },
    addQueryStateHandler: function (name, callback, scope) {
      this.editorCommands.addQueryStateHandler(name, callback, scope);
    },
    addQueryValueHandler: function (name, callback, scope) {
      this.editorCommands.addQueryValueHandler(name, callback, scope);
    },
    addShortcut: function (pattern, desc, cmdFunc, scope) {
      this.shortcuts.add(pattern, desc, cmdFunc, scope);
    },
    execCommand: function (cmd, ui, value, args) {
      return this.editorCommands.execCommand(cmd, ui, value, args);
    },
    queryCommandState: function (cmd) {
      return this.editorCommands.queryCommandState(cmd);
    },
    queryCommandValue: function (cmd) {
      return this.editorCommands.queryCommandValue(cmd);
    },
    queryCommandSupported: function (cmd) {
      return this.editorCommands.queryCommandSupported(cmd);
    },
    show: function () {
      var self = this;
      if (self.hidden) {
        self.hidden = false;
        if (self.inline) {
          self.getBody().contentEditable = true;
        } else {
          DOM$7.show(self.getContainer());
          DOM$7.hide(self.id);
        }
        self.load();
        self.fire('show');
      }
    },
    hide: function () {
      var self = this, doc = self.getDoc();
      if (!self.hidden) {
        if (ie$2 && doc && !self.inline) {
          doc.execCommand('SelectAll');
        }
        self.save();
        if (self.inline) {
          self.getBody().contentEditable = false;
          if (self === self.editorManager.focusedEditor) {
            self.editorManager.focusedEditor = null;
          }
        } else {
          DOM$7.hide(self.getContainer());
          DOM$7.setStyle(self.id, 'display', self.orgDisplay);
        }
        self.hidden = true;
        self.fire('hide');
      }
    },
    isHidden: function () {
      return !!this.hidden;
    },
    setProgressState: function (state, time) {
      this.fire('ProgressState', {
        state: state,
        time: time
      });
    },
    load: function (args) {
      var self = this;
      var elm = self.getElement(), html;
      if (self.removed) {
        return '';
      }
      if (elm) {
        args = args || {};
        args.load = true;
        html = self.setContent(elm.value !== undefined ? elm.value : elm.innerHTML, args);
        args.element = elm;
        if (!args.no_events) {
          self.fire('LoadContent', args);
        }
        args.element = elm = null;
        return html;
      }
    },
    save: function (args) {
      var self = this;
      var elm = self.getElement(), html, form;
      if (!elm || !self.initialized || self.removed) {
        return;
      }
      args = args || {};
      args.save = true;
      args.element = elm;
      html = args.content = self.getContent(args);
      if (!args.no_events) {
        self.fire('SaveContent', args);
      }
      if (args.format === 'raw') {
        self.fire('RawSaveContent', args);
      }
      html = args.content;
      if (!/TEXTAREA|INPUT/i.test(elm.nodeName)) {
        if (!self.inline) {
          elm.innerHTML = html;
        }
        if (form = DOM$7.getParent(self.id, 'form')) {
          each$21(form.elements, function (elm) {
            if (elm.name === self.id) {
              elm.value = html;
              return false;
            }
          });
        }
      } else {
        elm.value = html;
      }
      args.element = elm = null;
      if (args.set_dirty !== false) {
        self.setDirty(false);
      }
      return html;
    },
    setContent: function (content, args) {
      return setContent$1(this, content, args);
    },
    getContent: function (args) {
      return getContent$1(this, args);
    },
    insertContent: function (content, args) {
      if (args) {
        content = extend$4({ content: content }, args);
      }
      this.execCommand('mceInsertContent', false, content);
    },
    isDirty: function () {
      return !this.isNotDirty;
    },
    setDirty: function (state) {
      var oldState = !this.isNotDirty;
      this.isNotDirty = !state;
      if (state && state !== oldState) {
        this.fire('dirty');
      }
    },
    setMode: function (mode) {
      setMode(this, mode);
    },
    getContainer: function () {
      var self = this;
      if (!self.container) {
        self.container = DOM$7.get(self.editorContainer || self.id + '_parent');
      }
      return self.container;
    },
    getContentAreaContainer: function () {
      return this.contentAreaContainer;
    },
    getElement: function () {
      if (!this.targetElm) {
        this.targetElm = DOM$7.get(this.id);
      }
      return this.targetElm;
    },
    getWin: function () {
      var self = this;
      var elm;
      if (!self.contentWindow) {
        elm = self.iframeElement;
        if (elm) {
          self.contentWindow = elm.contentWindow;
        }
      }
      return self.contentWindow;
    },
    getDoc: function () {
      var self = this;
      var win;
      if (!self.contentDocument) {
        win = self.getWin();
        if (win) {
          self.contentDocument = win.document;
        }
      }
      return self.contentDocument;
    },
    getBody: function () {
      var doc = this.getDoc();
      return this.bodyElement || (doc ? doc.body : null);
    },
    convertURL: function (url, name, elm) {
      var self = this, settings = self.settings;
      if (settings.urlconverter_callback) {
        return self.execCallback('urlconverter_callback', url, elm, true, name);
      }
      if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
        return url;
      }
      if (settings.relative_urls) {
        return self.documentBaseURI.toRelative(url);
      }
      url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
      return url;
    },
    addVisual: function (elm) {
      var self = this;
      var settings = self.settings;
      var dom = self.dom;
      var cls;
      elm = elm || self.getBody();
      if (self.hasVisual === undefined) {
        self.hasVisual = settings.visual;
      }
      each$21(dom.select('table,a', elm), function (elm) {
        var value;
        switch (elm.nodeName) {
        case 'TABLE':
          cls = settings.visual_table_class || 'mce-item-table';
          value = dom.getAttrib(elm, 'border');
          if ((!value || value === '0') && self.hasVisual) {
            dom.addClass(elm, cls);
          } else {
            dom.removeClass(elm, cls);
          }
          return;
        case 'A':
          if (!dom.getAttrib(elm, 'href')) {
            value = dom.getAttrib(elm, 'name') || elm.id;
            cls = settings.visual_anchor_class || 'mce-item-anchor';
            if (value && self.hasVisual) {
              dom.addClass(elm, cls);
            } else {
              dom.removeClass(elm, cls);
            }
          }
          return;
        }
      });
      self.fire('VisualAid', {
        element: elm,
        hasVisual: self.hasVisual
      });
    },
    remove: function () {
      remove$8(this);
    },
    destroy: function (automatic) {
      destroy(this, automatic);
    },
    uploadImages: function (callback) {
      return this.editorUpload.uploadImages(callback);
    },
    _scanForImages: function () {
      return this.editorUpload.scanForImages();
    }
  };
  extend$4(Editor.prototype, EditorObservable$1);

  var isEditorUIElement = function (elm) {
    return elm.className.toString().indexOf('mce-') !== -1;
  };
  var $_bmt26v7ljh8lyxp9 = { isEditorUIElement: isEditorUIElement };

  var isManualNodeChange = function (e) {
    return e.type === 'nodechange' && e.selectionChange;
  };
  var registerPageMouseUp = function (editor, throttledStore) {
    var mouseUpPage = function () {
      throttledStore.throttle();
    };
    DOMUtils$1.DOM.bind(document, 'mouseup', mouseUpPage);
    editor.on('remove', function () {
      DOMUtils$1.DOM.unbind(document, 'mouseup', mouseUpPage);
    });
  };
  var registerFocusOut = function (editor) {
    editor.on('focusout', function () {
      $_eqs11m40jh8lyx31.store(editor);
    });
  };
  var registerMouseUp = function (editor, throttledStore) {
    editor.on('mouseup touchend', function (e) {
      throttledStore.throttle();
    });
  };
  var registerEditorEvents = function (editor, throttledStore) {
    var browser = $_9hkktfnjh8lywc6.detect().browser;
    if (browser.isIE()) {
      registerFocusOut(editor);
    } else {
      registerMouseUp(editor, throttledStore);
    }
    editor.on('keyup nodechange', function (e) {
      if (!isManualNodeChange(e)) {
        $_eqs11m40jh8lyx31.store(editor);
      }
    });
  };
  var register$3 = function (editor) {
    var throttledStore = $_de600j5fjh8lyxas.first(function () {
      $_eqs11m40jh8lyx31.store(editor);
    }, 0);
    if (editor.inline) {
      registerPageMouseUp(editor, throttledStore);
    }
    editor.on('init', function () {
      registerEditorEvents(editor, throttledStore);
    });
    editor.on('remove', function () {
      throttledStore.cancel();
    });
  };
  var $_2mabdn7mjh8lyxpa = { register: register$3 };

  var documentFocusInHandler;
  var DOM$8 = DOMUtils$1.DOM;
  var isEditorUIElement$1 = function (elm) {
    return $_bmt26v7ljh8lyxp9.isEditorUIElement(elm);
  };
  var isUIElement = function (editor, elm) {
    var customSelector = editor ? editor.settings.custom_ui_selector : '';
    var parent = DOM$8.getParent(elm, function (elm) {
      return isEditorUIElement$1(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
    });
    return parent !== null;
  };
  var getActiveElement = function () {
    try {
      return document.activeElement;
    } catch (ex) {
      return document.body;
    }
  };
  var registerEvents = function (editorManager, e) {
    var editor = e.editor;
    $_2mabdn7mjh8lyxpa.register(editor);
    editor.on('focusin', function () {
      var self = this;
      var focusedEditor = editorManager.focusedEditor;
      if (focusedEditor !== self) {
        if (focusedEditor) {
          focusedEditor.fire('blur', { focusedEditor: self });
        }
        editorManager.setActive(self);
        editorManager.focusedEditor = self;
        self.fire('focus', { blurredEditor: focusedEditor });
        self.focus(true);
      }
    });
    editor.on('focusout', function () {
      var self = this;
      $_8sy3pfhjh8lyw95.setEditorTimeout(self, function () {
        var focusedEditor = editorManager.focusedEditor;
        if (!isUIElement(self, getActiveElement()) && focusedEditor === self) {
          self.fire('blur', { focusedEditor: null });
          editorManager.focusedEditor = null;
        }
      });
    });
    if (!documentFocusInHandler) {
      documentFocusInHandler = function (e) {
        var activeEditor = editorManager.activeEditor;
        var target;
        target = e.target;
        if (activeEditor && target.ownerDocument === document) {
          if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
            activeEditor.fire('blur', { focusedEditor: null });
            editorManager.focusedEditor = null;
          }
        }
      };
      DOM$8.bind(document, 'focusin', documentFocusInHandler);
    }
  };
  var unregisterDocumentEvents = function (editorManager, e) {
    if (editorManager.focusedEditor === e.editor) {
      editorManager.focusedEditor = null;
    }
    if (!editorManager.activeEditor) {
      DOM$8.unbind(document, 'focusin', documentFocusInHandler);
      documentFocusInHandler = null;
    }
  };
  var setup$13 = function (editorManager) {
    editorManager.on('AddEditor', $_eqpqvr6jh8lyw3s.curry(registerEvents, editorManager));
    editorManager.on('RemoveEditor', $_eqpqvr6jh8lyw3s.curry(unregisterDocumentEvents, editorManager));
  };
  var $_k2ieq7kjh8lyxp5 = {
    setup: setup$13,
    isEditorUIElement: isEditorUIElement$1,
    isUIElement: isUIElement
  };

  var data = {};
  var code = 'en';
  var $_1tjgyr7njh8lyxpg = {
    setCode: function (newCode) {
      if (newCode) {
        code = newCode;
        this.rtl = this.data[newCode] ? this.data[newCode]._dir === 'rtl' : false;
      }
    },
    getCode: function () {
      return code;
    },
    rtl: false,
    add: function (code, items) {
      var langData = data[code];
      if (!langData) {
        data[code] = langData = {};
      }
      for (var name_1 in items) {
        langData[name_1] = items[name_1];
      }
      this.setCode(code);
    },
    translate: function (text) {
      var langData = data[code] || {};
      var toString = function (obj) {
        if ($_ahowuxkjh8lywbj.is(obj, 'function')) {
          return Object.prototype.toString.call(obj);
        }
        return !isEmpty(obj) ? '' + obj : '';
      };
      var isEmpty = function (text) {
        return text === '' || text === null || $_ahowuxkjh8lywbj.is(text, 'undefined');
      };
      var getLangData = function (text) {
        text = toString(text);
        return $_ahowuxkjh8lywbj.hasOwn(langData, text) ? toString(langData[text]) : text;
      };
      if (isEmpty(text)) {
        return '';
      }
      if ($_ahowuxkjh8lywbj.is(text, 'object') && $_ahowuxkjh8lywbj.hasOwn(text, 'raw')) {
        return toString(text.raw);
      }
      if ($_ahowuxkjh8lywbj.is(text, 'array')) {
        var values_1 = text.slice(1);
        text = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
          return $_ahowuxkjh8lywbj.hasOwn(values_1, $2) ? toString(values_1[$2]) : $1;
        });
      }
      return getLangData(text).replace(/{context:\w+}$/, '');
    },
    data: data
  };

  var DOM$9 = DOMUtils$1.DOM;
  var explode$4 = $_ahowuxkjh8lywbj.explode;
  var each$22 = $_ahowuxkjh8lywbj.each;
  var extend$5 = $_ahowuxkjh8lywbj.extend;
  var instanceCounter = 0;
  var beforeUnloadDelegate;
  var EditorManager;
  var boundGlobalEvents = false;
  var legacyEditors = [];
  var editors = [];
  var isValidLegacyKey = function (id) {
    return id !== 'length';
  };
  var globalEventDelegate = function (e) {
    each$22(EditorManager.get(), function (editor) {
      if (e.type === 'scroll') {
        editor.fire('ScrollWindow', e);
      } else {
        editor.fire('ResizeWindow', e);
      }
    });
  };
  var toggleGlobalEvents = function (state) {
    if (state !== boundGlobalEvents) {
      if (state) {
        DomQuery(window).on('resize scroll', globalEventDelegate);
      } else {
        DomQuery(window).off('resize scroll', globalEventDelegate);
      }
      boundGlobalEvents = state;
    }
  };
  var removeEditorFromList = function (targetEditor) {
    var oldEditors = editors;
    delete legacyEditors[targetEditor.id];
    for (var i = 0; i < legacyEditors.length; i++) {
      if (legacyEditors[i] === targetEditor) {
        legacyEditors.splice(i, 1);
        break;
      }
    }
    editors = $_5wjzy24jh8lyw2t.filter(editors, function (editor) {
      return targetEditor !== editor;
    });
    if (EditorManager.activeEditor === targetEditor) {
      EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
    }
    if (EditorManager.focusedEditor === targetEditor) {
      EditorManager.focusedEditor = null;
    }
    return oldEditors.length !== editors.length;
  };
  var purgeDestroyedEditor = function (editor) {
    if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
      removeEditorFromList(editor);
      editor.unbindAllNativeEvents();
      editor.destroy(true);
      editor.removed = true;
      editor = null;
    }
    return editor;
  };
  EditorManager = {
    defaultSettings: {},
    $: DomQuery,
    majorVersion: '4',
    minorVersion: '7.13',
    releaseDate: '2018-05-16',
    editors: legacyEditors,
    i18n: $_1tjgyr7njh8lyxpg,
    activeEditor: null,
    settings: {},
    setup: function () {
      var self = this;
      var baseURL, documentBaseURL, suffix = '', preInit, src;
      documentBaseURL = URI.getDocumentBaseUrl(document.location);
      if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
        documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
        if (!/[\/\\]$/.test(documentBaseURL)) {
          documentBaseURL += '/';
        }
      }
      preInit = window.tinymce || window.tinyMCEPreInit;
      if (preInit) {
        baseURL = preInit.base || preInit.baseURL;
        suffix = preInit.suffix;
      } else {
        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++) {
          src = scripts[i].src;
          var srcScript = src.substring(src.lastIndexOf('/'));
          if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
            if (srcScript.indexOf('.min') !== -1) {
              suffix = '.min';
            }
            baseURL = src.substring(0, src.lastIndexOf('/'));
            break;
          }
        }
        if (!baseURL && document.currentScript) {
          src = document.currentScript.src;
          if (src.indexOf('.min') !== -1) {
            suffix = '.min';
          }
          baseURL = src.substring(0, src.lastIndexOf('/'));
        }
      }
      self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
      self.documentBaseURL = documentBaseURL;
      self.baseURI = new URI(self.baseURL);
      self.suffix = suffix;
      $_k2ieq7kjh8lyxp5.setup(self);
    },
    overrideDefaults: function (defaultSettings) {
      var baseUrl, suffix;
      baseUrl = defaultSettings.base_url;
      if (baseUrl) {
        this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
        this.baseURI = new URI(this.baseURL);
      }
      suffix = defaultSettings.suffix;
      if (defaultSettings.suffix) {
        this.suffix = suffix;
      }
      this.defaultSettings = defaultSettings;
      var pluginBaseUrls = defaultSettings.plugin_base_urls;
      for (var name_1 in pluginBaseUrls) {
        AddOnManager.PluginManager.urls[name_1] = pluginBaseUrls[name_1];
      }
    },
    init: function (settings) {
      var self = this;
      var result, invalidInlineTargets;
      invalidInlineTargets = $_ahowuxkjh8lywbj.makeMap('area base basefont br col frame hr img input isindex link meta param embed source wbr track ' + 'colgroup option tbody tfoot thead tr script noscript style textarea video audio iframe object menu', ' ');
      var isInvalidInlineTarget = function (settings, elm) {
        return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
      };
      var createId = function (elm) {
        var id = elm.id;
        if (!id) {
          id = elm.name;
          if (id && !DOM$9.get(id)) {
            id = elm.name;
          } else {
            id = DOM$9.uniqueId();
          }
          elm.setAttribute('id', id);
        }
        return id;
      };
      var execCallback = function (name) {
        var callback = settings[name];
        if (!callback) {
          return;
        }
        return callback.apply(self, Array.prototype.slice.call(arguments, 2));
      };
      var hasClass = function (elm, className) {
        return className.constructor === RegExp ? className.test(elm.className) : DOM$9.hasClass(elm, className);
      };
      var findTargets = function (settings) {
        var l, targets = [];
        if ($_9bpim8ajh8lyw68.ie && $_9bpim8ajh8lyw68.ie < 11) {
          $_5vy074njh8lyx6h.initError('TinyMCE does not support the browser you are using. For a list of supported' + ' browsers please see: https://www.tinymce.com/docs/get-started/system-requirements/');
          return [];
        }
        if (settings.types) {
          each$22(settings.types, function (type) {
            targets = targets.concat(DOM$9.select(type.selector));
          });
          return targets;
        } else if (settings.selector) {
          return DOM$9.select(settings.selector);
        } else if (settings.target) {
          return [settings.target];
        }
        switch (settings.mode) {
        case 'exact':
          l = settings.elements || '';
          if (l.length > 0) {
            each$22(explode$4(l), function (id) {
              var elm;
              if (elm = DOM$9.get(id)) {
                targets.push(elm);
              } else {
                each$22(document.forms, function (f) {
                  each$22(f.elements, function (e) {
                    if (e.name === id) {
                      id = 'mce_editor_' + instanceCounter++;
                      DOM$9.setAttrib(e, 'id', id);
                      targets.push(e);
                    }
                  });
                });
              }
            });
          }
          break;
        case 'textareas':
        case 'specific_textareas':
          each$22(DOM$9.select('textarea'), function (elm) {
            if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
              return;
            }
            if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
              targets.push(elm);
            }
          });
          break;
        }
        return targets;
      };
      var provideResults = function (editors) {
        result = editors;
      };
      var initEditors = function () {
        var initCount = 0;
        var editors = [];
        var targets;
        var createEditor = function (id, settings, targetElm) {
          var editor = new Editor(id, settings, self);
          editors.push(editor);
          editor.on('init', function () {
            if (++initCount === targets.length) {
              provideResults(editors);
            }
          });
          editor.targetElm = editor.targetElm || targetElm;
          editor.render();
        };
        DOM$9.unbind(window, 'ready', initEditors);
        execCallback('onpageload');
        targets = DomQuery.unique(findTargets(settings));
        if (settings.types) {
          each$22(settings.types, function (type) {
            $_ahowuxkjh8lywbj.each(targets, function (elm) {
              if (DOM$9.is(elm, type.selector)) {
                createEditor(createId(elm), extend$5({}, settings, type), elm);
                return false;
              }
              return true;
            });
          });
          return;
        }
        $_ahowuxkjh8lywbj.each(targets, function (elm) {
          purgeDestroyedEditor(self.get(elm.id));
        });
        targets = $_ahowuxkjh8lywbj.grep(targets, function (elm) {
          return !self.get(elm.id);
        });
        if (targets.length === 0) {
          provideResults([]);
        } else {
          each$22(targets, function (elm) {
            if (isInvalidInlineTarget(settings, elm)) {
              $_5vy074njh8lyx6h.initError('Could not initialize inline editor on invalid inline target element', elm);
            } else {
              createEditor(createId(elm), settings, elm);
            }
          });
        }
      };
      self.settings = settings;
      DOM$9.bind(window, 'ready', initEditors);
      return new promiseObj(function (resolve) {
        if (result) {
          resolve(result);
        } else {
          provideResults = function (editors) {
            resolve(editors);
          };
        }
      });
    },
    get: function (id) {
      if (arguments.length === 0) {
        return editors.slice(0);
      } else if ($_dp4g6d7jh8lyw3y.isString(id)) {
        return $_5wjzy24jh8lyw2t.find(editors, function (editor) {
          return editor.id === id;
        }).getOr(null);
      } else if ($_dp4g6d7jh8lyw3y.isNumber(id)) {
        return editors[id] ? editors[id] : null;
      } else {
        return null;
      }
    },
    add: function (editor) {
      var self = this;
      var existingEditor;
      existingEditor = legacyEditors[editor.id];
      if (existingEditor === editor) {
        return editor;
      }
      if (self.get(editor.id) === null) {
        if (isValidLegacyKey(editor.id)) {
          legacyEditors[editor.id] = editor;
        }
        legacyEditors.push(editor);
        editors.push(editor);
      }
      toggleGlobalEvents(true);
      self.activeEditor = editor;
      self.fire('AddEditor', { editor: editor });
      if (!beforeUnloadDelegate) {
        beforeUnloadDelegate = function () {
          self.fire('BeforeUnload');
        };
        DOM$9.bind(window, 'beforeunload', beforeUnloadDelegate);
      }
      return editor;
    },
    createEditor: function (id, settings) {
      return this.add(new Editor(id, settings, this));
    },
    remove: function (selector) {
      var self = this;
      var i, editor;
      if (!selector) {
        for (i = editors.length - 1; i >= 0; i--) {
          self.remove(editors[i]);
        }
        return;
      }
      if ($_dp4g6d7jh8lyw3y.isString(selector)) {
        selector = selector.selector || selector;
        each$22(DOM$9.select(selector), function (elm) {
          editor = self.get(elm.id);
          if (editor) {
            self.remove(editor);
          }
        });
        return;
      }
      editor = selector;
      if ($_dp4g6d7jh8lyw3y.isNull(self.get(editor.id))) {
        return null;
      }
      if (removeEditorFromList(editor)) {
        self.fire('RemoveEditor', { editor: editor });
      }
      if (editors.length === 0) {
        DOM$9.unbind(window, 'beforeunload', beforeUnloadDelegate);
      }
      editor.remove();
      toggleGlobalEvents(editors.length > 0);
      return editor;
    },
    execCommand: function (cmd, ui, value) {
      var self = this, editor = self.get(value);
      switch (cmd) {
      case 'mceAddEditor':
        if (!self.get(value)) {
          new Editor(value, self.settings, self).render();
        }
        return true;
      case 'mceRemoveEditor':
        if (editor) {
          editor.remove();
        }
        return true;
      case 'mceToggleEditor':
        if (!editor) {
          self.execCommand('mceAddEditor', 0, value);
          return true;
        }
        if (editor.isHidden()) {
          editor.show();
        } else {
          editor.hide();
        }
        return true;
      }
      if (self.activeEditor) {
        return self.activeEditor.execCommand(cmd, ui, value);
      }
      return false;
    },
    triggerSave: function () {
      each$22(editors, function (editor) {
        editor.save();
      });
    },
    addI18n: function (code, items) {
      $_1tjgyr7njh8lyxpg.add(code, items);
    },
    translate: function (text) {
      return $_1tjgyr7njh8lyxpg.translate(text);
    },
    setActive: function (editor) {
      var activeEditor = this.activeEditor;
      if (this.activeEditor !== editor) {
        if (activeEditor) {
          activeEditor.fire('deactivate', { relatedTarget: editor });
        }
        editor.fire('activate', { relatedTarget: activeEditor });
      }
      this.activeEditor = editor;
    }
  };
  extend$5(EditorManager, $_fuzxjg45jh8lyx45);
  EditorManager.setup();
  var EditorManager$1 = EditorManager;

  function RangeUtils(dom) {
    var walk = function (rng, callback) {
      return $_90itx05zjh8lyxeq.walk(dom, rng, callback);
    };
    var split = $_5hrcpr5vjh8lyxe2.split;
    var normalize = function (rng) {
      return $_4v2pn63yjh8lyx2s.normalize(dom, rng).fold($_eqpqvr6jh8lyw3s.constant(false), function (normalizedRng) {
        rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
        rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
        return true;
      });
    };
    return {
      walk: walk,
      split: split,
      normalize: normalize
    };
  }
  (function (RangeUtils) {
    RangeUtils.compareRanges = $_aayq8q3zjh8lyx2z.isEq;
    RangeUtils.getCaretRangeFromPoint = $_ct0ht56jjh8lyxif.fromPoint;
    RangeUtils.getSelectedNode = getSelectedNode;
    RangeUtils.getNode = getNode;
  }(RangeUtils || (RangeUtils = {})));
  var RangeUtils$1 = RangeUtils;

  var min = Math.min;
  var max = Math.max;
  var round$2 = Math.round;
  var relativePosition = function (rect, targetRect, rel) {
    var x, y, w, h, targetW, targetH;
    x = targetRect.x;
    y = targetRect.y;
    w = rect.w;
    h = rect.h;
    targetW = targetRect.w;
    targetH = targetRect.h;
    rel = (rel || '').split('');
    if (rel[0] === 'b') {
      y += targetH;
    }
    if (rel[1] === 'r') {
      x += targetW;
    }
    if (rel[0] === 'c') {
      y += round$2(targetH / 2);
    }
    if (rel[1] === 'c') {
      x += round$2(targetW / 2);
    }
    if (rel[3] === 'b') {
      y -= h;
    }
    if (rel[4] === 'r') {
      x -= w;
    }
    if (rel[3] === 'c') {
      y -= round$2(h / 2);
    }
    if (rel[4] === 'c') {
      x -= round$2(w / 2);
    }
    return create$2(x, y, w, h);
  };
  var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
    var pos, i;
    for (i = 0; i < rels.length; i++) {
      pos = relativePosition(rect, targetRect, rels[i]);
      if (pos.x >= constrainRect.x && pos.x + pos.w <= constrainRect.w + constrainRect.x && pos.y >= constrainRect.y && pos.y + pos.h <= constrainRect.h + constrainRect.y) {
        return rels[i];
      }
    }
    return null;
  };
  var inflate = function (rect, w, h) {
    return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  };
  var intersect = function (rect, cropRect) {
    var x1, y1, x2, y2;
    x1 = max(rect.x, cropRect.x);
    y1 = max(rect.y, cropRect.y);
    x2 = min(rect.x + rect.w, cropRect.x + cropRect.w);
    y2 = min(rect.y + rect.h, cropRect.y + cropRect.h);
    if (x2 - x1 < 0 || y2 - y1 < 0) {
      return null;
    }
    return create$2(x1, y1, x2 - x1, y2 - y1);
  };
  var clamp$1 = function (rect, clampRect, fixedSize) {
    var underflowX1, underflowY1, overflowX2, overflowY2, x1, y1, x2, y2, cx2, cy2;
    x1 = rect.x;
    y1 = rect.y;
    x2 = rect.x + rect.w;
    y2 = rect.y + rect.h;
    cx2 = clampRect.x + clampRect.w;
    cy2 = clampRect.y + clampRect.h;
    underflowX1 = max(0, clampRect.x - x1);
    underflowY1 = max(0, clampRect.y - y1);
    overflowX2 = max(0, x2 - cx2);
    overflowY2 = max(0, y2 - cy2);
    x1 += underflowX1;
    y1 += underflowY1;
    if (fixedSize) {
      x2 += underflowX1;
      y2 += underflowY1;
      x1 -= overflowX2;
      y1 -= overflowY2;
    }
    x2 -= overflowX2;
    y2 -= overflowY2;
    return create$2(x1, y1, x2 - x1, y2 - y1);
  };
  var create$2 = function (x, y, w, h) {
    return {
      x: x,
      y: y,
      w: w,
      h: h
    };
  };
  var fromClientRect = function (clientRect) {
    return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  };
  var $_fa0t9p7pjh8lyxpo = {
    inflate: inflate,
    relativePosition: relativePosition,
    findBestRelativePosition: findBestRelativePosition,
    intersect: intersect,
    clamp: clamp$1,
    create: create$2,
    fromClientRect: fromClientRect
  };

  var types = {};
  var $_fym6l27qjh8lyxpr = {
    add: function (type, typeClass) {
      types[type.toLowerCase()] = typeClass;
    },
    has: function (type) {
      return !!types[type.toLowerCase()];
    },
    get: function (type) {
      var lctype = type.toLowerCase();
      var controlType = types.hasOwnProperty(lctype) ? types[lctype] : null;
      if (controlType === null) {
        throw new Error('Could not find module for type: ' + type);
      }
      return controlType;
    },
    create: function (type, settings) {
      var ControlType;
      if (typeof type === 'string') {
        settings = settings || {};
        settings.type = type;
      } else {
        settings = type;
        type = settings.type;
      }
      type = type.toLowerCase();
      ControlType = types[type];
      if (!ControlType) {
        throw new Error('Could not find control by type: ' + type);
      }
      ControlType = new ControlType(settings);
      ControlType.type = type;
      return ControlType;
    }
  };

  var each$23 = $_ahowuxkjh8lywbj.each;
  var extend$6 = $_ahowuxkjh8lywbj.extend;
  var extendClass;
  var initializing;
  var Class$1 = function () {
  };
  Class$1.extend = extendClass = function (prop) {
    var self = this;
    var _super = self.prototype;
    var prototype, name, member;
    var Class = function () {
      var i, mixins, mixin;
      var self = this;
      if (!initializing) {
        if (self.init) {
          self.init.apply(self, arguments);
        }
        mixins = self.Mixins;
        if (mixins) {
          i = mixins.length;
          while (i--) {
            mixin = mixins[i];
            if (mixin.init) {
              mixin.init.apply(self, arguments);
            }
          }
        }
      }
    };
    var dummy = function () {
      return this;
    };
    var createMethod = function (name, fn) {
      return function () {
        var self = this;
        var tmp = self._super;
        var ret;
        self._super = _super[name];
        ret = fn.apply(self, arguments);
        self._super = tmp;
        return ret;
      };
    };
    initializing = true;
    prototype = new self();
    initializing = false;
    if (prop.Mixins) {
      each$23(prop.Mixins, function (mixin) {
        for (var name_1 in mixin) {
          if (name_1 !== 'init') {
            prop[name_1] = mixin[name_1];
          }
        }
      });
      if (_super.Mixins) {
        prop.Mixins = _super.Mixins.concat(prop.Mixins);
      }
    }
    if (prop.Methods) {
      each$23(prop.Methods.split(','), function (name) {
        prop[name] = dummy;
      });
    }
    if (prop.Properties) {
      each$23(prop.Properties.split(','), function (name) {
        var fieldName = '_' + name;
        prop[name] = function (value) {
          var self = this;
          if (value !== undefined) {
            self[fieldName] = value;
            return self;
          }
          return self[fieldName];
        };
      });
    }
    if (prop.Statics) {
      each$23(prop.Statics, function (func, name) {
        Class[name] = func;
      });
    }
    if (prop.Defaults && _super.Defaults) {
      prop.Defaults = extend$6({}, _super.Defaults, prop.Defaults);
    }
    for (name in prop) {
      member = prop[name];
      if (typeof member === 'function' && _super[name]) {
        prototype[name] = createMethod(name, member);
      } else {
        prototype[name] = member;
      }
    }
    Class.prototype = prototype;
    Class.constructor = Class;
    Class.extend = extendClass;
    return Class;
  };

  var min$1 = Math.min;
  var max$1 = Math.max;
  var round$3 = Math.round;
  var Color = function (value) {
    var self = {};
    var r = 0, g = 0, b = 0;
    var rgb2hsv = function (r, g, b) {
      var h, s, v, d, minRGB, maxRGB;
      h = 0;
      s = 0;
      v = 0;
      r = r / 255;
      g = g / 255;
      b = b / 255;
      minRGB = min$1(r, min$1(g, b));
      maxRGB = max$1(r, max$1(g, b));
      if (minRGB === maxRGB) {
        v = minRGB;
        return {
          h: 0,
          s: 0,
          v: v * 100
        };
      }
      d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
      h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
      h = 60 * (h - d / (maxRGB - minRGB));
      s = (maxRGB - minRGB) / maxRGB;
      v = maxRGB;
      return {
        h: round$3(h),
        s: round$3(s * 100),
        v: round$3(v * 100)
      };
    };
    var hsvToRgb = function (hue, saturation, brightness) {
      var side, chroma, x, match;
      hue = (parseInt(hue, 10) || 0) % 360;
      saturation = parseInt(saturation, 10) / 100;
      brightness = parseInt(brightness, 10) / 100;
      saturation = max$1(0, min$1(saturation, 1));
      brightness = max$1(0, min$1(brightness, 1));
      if (saturation === 0) {
        r = g = b = round$3(255 * brightness);
        return;
      }
      side = hue / 60;
      chroma = brightness * saturation;
      x = chroma * (1 - Math.abs(side % 2 - 1));
      match = brightness - chroma;
      switch (Math.floor(side)) {
      case 0:
        r = chroma;
        g = x;
        b = 0;
        break;
      case 1:
        r = x;
        g = chroma;
        b = 0;
        break;
      case 2:
        r = 0;
        g = chroma;
        b = x;
        break;
      case 3:
        r = 0;
        g = x;
        b = chroma;
        break;
      case 4:
        r = x;
        g = 0;
        b = chroma;
        break;
      case 5:
        r = chroma;
        g = 0;
        b = x;
        break;
      default:
        r = g = b = 0;
      }
      r = round$3(255 * (r + match));
      g = round$3(255 * (g + match));
      b = round$3(255 * (b + match));
    };
    var toHex = function () {
      var hex = function (val) {
        val = parseInt(val, 10).toString(16);
        return val.length > 1 ? val : '0' + val;
      };
      return '#' + hex(r) + hex(g) + hex(b);
    };
    var toRgb = function () {
      return {
        r: r,
        g: g,
        b: b
      };
    };
    var toHsv = function () {
      return rgb2hsv(r, g, b);
    };
    var parse = function (value) {
      var matches;
      if (typeof value === 'object') {
        if ('r' in value) {
          r = value.r;
          g = value.g;
          b = value.b;
        } else if ('v' in value) {
          hsvToRgb(value.h, value.s, value.v);
        }
      } else {
        if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
          r = parseInt(matches[1], 10);
          g = parseInt(matches[2], 10);
          b = parseInt(matches[3], 10);
        } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
          r = parseInt(matches[1], 16);
          g = parseInt(matches[2], 16);
          b = parseInt(matches[3], 16);
        } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
          r = parseInt(matches[1] + matches[1], 16);
          g = parseInt(matches[2] + matches[2], 16);
          b = parseInt(matches[3] + matches[3], 16);
        }
      }
      r = r < 0 ? 0 : r > 255 ? 255 : r;
      g = g < 0 ? 0 : g > 255 ? 255 : g;
      b = b < 0 ? 0 : b > 255 ? 255 : b;
      return self;
    };
    if (value) {
      parse(value);
    }
    self.toRgb = toRgb;
    self.toHsv = toHsv;
    self.toHex = toHex;
    self.parse = parse;
    return self;
  };

  var serialize = function (o, quote) {
    var i, v, t, name;
    quote = quote || '"';
    if (o === null) {
      return 'null';
    }
    t = typeof o;
    if (t === 'string') {
      v = '\bb\tt\nn\ff\rr""\'\'\\\\';
      return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function (a, b) {
        if (quote === '"' && a === '\'') {
          return a;
        }
        i = v.indexOf(b);
        if (i + 1) {
          return '\\' + v.charAt(i + 1);
        }
        a = b.charCodeAt().toString(16);
        return '\\u' + '0000'.substring(a.length) + a;
      }) + quote;
    }
    if (t === 'object') {
      if (o.hasOwnProperty && Object.prototype.toString.call(o) === '[object Array]') {
        for (i = 0, v = '['; i < o.length; i++) {
          v += (i > 0 ? ',' : '') + serialize(o[i], quote);
        }
        return v + ']';
      }
      v = '{';
      for (name in o) {
        if (o.hasOwnProperty(name)) {
          v += typeof o[name] !== 'function' ? (v.length > 1 ? ',' + quote : quote) + name + quote + ':' + serialize(o[name], quote) : '';
        }
      }
      return v + '}';
    }
    return '' + o;
  };
  var $_7z82167tjh8lyxq1 = {
    serialize: serialize,
    parse: function (text) {
      try {
        return JSON.parse(text);
      } catch (ex) {
      }
    }
  };

  var $_2v08kz7ujh8lyxq4 = {
    callbacks: {},
    count: 0,
    send: function (settings) {
      var self = this, dom = DOMUtils$1.DOM, count = settings.count !== undefined ? settings.count : self.count;
      var id = 'tinymce_jsonp_' + count;
      self.callbacks[count] = function (json) {
        dom.remove(id);
        delete self.callbacks[count];
        settings.callback(json);
      };
      dom.add(dom.doc.body, 'script', {
        id: id,
        src: settings.url,
        type: 'text/javascript'
      });
      self.count++;
    }
  };

  var XHR = {
    send: function (settings) {
      var xhr, count = 0;
      var ready = function () {
        if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
          if (settings.success && count < 10000 && xhr.status === 200) {
            settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
          } else if (settings.error) {
            settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
          }
          xhr = null;
        } else {
          setTimeout(ready, 10);
        }
      };
      settings.scope = settings.scope || this;
      settings.success_scope = settings.success_scope || settings.scope;
      settings.error_scope = settings.error_scope || settings.scope;
      settings.async = settings.async === false ? false : true;
      settings.data = settings.data || '';
      XHR.fire('beforeInitialize', { settings: settings });
      xhr = new XMLHttpRequest();
      if (xhr) {
        if (xhr.overrideMimeType) {
          xhr.overrideMimeType(settings.content_type);
        }
        xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
        if (settings.crossDomain) {
          xhr.withCredentials = true;
        }
        if (settings.content_type) {
          xhr.setRequestHeader('Content-Type', settings.content_type);
        }
        if (settings.requestheaders) {
          $_ahowuxkjh8lywbj.each(settings.requestheaders, function (header) {
            xhr.setRequestHeader(header.key, header.value);
          });
        }
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr = XHR.fire('beforeSend', {
          xhr: xhr,
          settings: settings
        }).xhr;
        xhr.send(settings.data);
        if (!settings.async) {
          return ready();
        }
        setTimeout(ready, 10);
      }
    }
  };
  $_ahowuxkjh8lywbj.extend(XHR, $_fuzxjg45jh8lyx45);

  var extend$7 = $_ahowuxkjh8lywbj.extend;
  var JSONRequest = function (settings) {
    this.settings = extend$7({}, settings);
    this.count = 0;
  };
  JSONRequest.sendRPC = function (o) {
    return new JSONRequest().send(o);
  };
  JSONRequest.prototype = {
    send: function (args) {
      var ecb = args.error, scb = args.success;
      args = extend$7(this.settings, args);
      args.success = function (c, x) {
        c = $_7z82167tjh8lyxq1.parse(c);
        if (typeof c === 'undefined') {
          c = { error: 'JSON Parse error.' };
        }
        if (c.error) {
          ecb.call(args.error_scope || args.scope, c.error, x);
        } else {
          scb.call(args.success_scope || args.scope, c.result);
        }
      };
      args.error = function (ty, x) {
        if (ecb) {
          ecb.call(args.error_scope || args.scope, ty, x);
        }
      };
      args.data = $_7z82167tjh8lyxq1.serialize({
        id: args.id || 'c' + this.count++,
        method: args.method,
        params: args.params
      });
      args.content_type = 'application/json';
      XHR.send(args);
    }
  };

  var localStorage = window.localStorage;

  var tinymce = EditorManager$1;
  var publicApi = {
    geom: { Rect: $_fa0t9p7pjh8lyxpo },
    util: {
      Promise: promiseObj,
      Delay: $_8sy3pfhjh8lyw95,
      Tools: $_ahowuxkjh8lywbj,
      VK: $_6lsk4i5gjh8lyxau,
      URI: URI,
      Class: Class$1,
      EventDispatcher: Dispatcher,
      Observable: $_fuzxjg45jh8lyx45,
      I18n: $_1tjgyr7njh8lyxpg,
      XHR: XHR,
      JSON: $_7z82167tjh8lyxq1,
      JSONRequest: JSONRequest,
      JSONP: $_2v08kz7ujh8lyxq4,
      LocalStorage: localStorage,
      Color: Color
    },
    dom: {
      EventUtils: EventUtils,
      Sizzle: Sizzle,
      DomQuery: DomQuery,
      TreeWalker: TreeWalker,
      DOMUtils: DOMUtils$1,
      ScriptLoader: ScriptLoader,
      RangeUtils: RangeUtils$1,
      Serializer: DomSerializer$1,
      ControlSelection: ControlSelection,
      BookmarkManager: BookmarkManager$1,
      Selection: Selection$1,
      Event: EventUtils.Event
    },
    html: {
      Styles: Styles,
      Entities: $_gex7a11rjh8lywi4,
      Node: Node$2,
      Schema: Schema,
      SaxParser: SaxParser$1,
      DomParser: DomParser,
      Writer: Writer,
      Serializer: HtmlSerializer
    },
    ui: { Factory: $_fym6l27qjh8lyxpr },
    Env: $_9bpim8ajh8lyw68,
    AddOnManager: AddOnManager,
    Formatter: Formatter,
    UndoManager: UndoManager,
    EditorCommands: EditorCommands,
    WindowManager: WindowManager,
    NotificationManager: NotificationManager,
    EditorObservable: EditorObservable$1,
    Shortcuts: Shortcuts,
    Editor: Editor,
    FocusManager: $_bmt26v7ljh8lyxp9,
    EditorManager: EditorManager$1,
    DOM: DOMUtils$1.DOM,
    ScriptLoader: ScriptLoader.ScriptLoader,
    PluginManager: AddOnManager.PluginManager,
    ThemeManager: AddOnManager.ThemeManager,
    trim: $_ahowuxkjh8lywbj.trim,
    isArray: $_ahowuxkjh8lywbj.isArray,
    is: $_ahowuxkjh8lywbj.is,
    toArray: $_ahowuxkjh8lywbj.toArray,
    makeMap: $_ahowuxkjh8lywbj.makeMap,
    each: $_ahowuxkjh8lywbj.each,
    map: $_ahowuxkjh8lywbj.map,
    grep: $_ahowuxkjh8lywbj.grep,
    inArray: $_ahowuxkjh8lywbj.inArray,
    extend: $_ahowuxkjh8lywbj.extend,
    create: $_ahowuxkjh8lywbj.create,
    walk: $_ahowuxkjh8lywbj.walk,
    createNS: $_ahowuxkjh8lywbj.createNS,
    resolve: $_ahowuxkjh8lywbj.resolve,
    explode: $_ahowuxkjh8lywbj.explode,
    _addCacheSuffix: $_ahowuxkjh8lywbj._addCacheSuffix,
    isOpera: $_9bpim8ajh8lyw68.opera,
    isWebKit: $_9bpim8ajh8lyw68.webkit,
    isIE: $_9bpim8ajh8lyw68.ie,
    isGecko: $_9bpim8ajh8lyw68.gecko,
    isMac: $_9bpim8ajh8lyw68.mac
  };
  tinymce = $_ahowuxkjh8lywbj.extend(tinymce, publicApi);
  var Tinymce = tinymce;

  var exportToModuleLoaders = function (tinymce) {
    if (typeof module === 'object') {
      try {
        module.exports = tinymce;
      } catch (_) {
      }
    }
  };
  var exportToWindowGlobal = function (tinymce) {
    window.tinymce = tinymce;
    window.tinyMCE = tinymce;
  };
  exportToWindowGlobal(Tinymce);
  exportToModuleLoaders(Tinymce);

}());
})();

return (function () { this.tinyMCE.DOM.events.domLoaded = true; return this.tinyMCE; }.apply(this, arguments)) || window.tinyMCE;
  }).apply(root, arguments);
});
}(this));


define('text!mockup-patterns-tinymce-url/templates/result.xml',[],function () { return '<div class="pattern-relateditems-result pattern-relateditems-type-<%= portal_type %> <% if (selected) { %>pattern-active<% } %>">\n  <a href="#" class="pattern-relateditems-result-select <% if (selectable) { %>selectable<% } %>">\n    <% if (!folderish) { %>\n    <span class="pattern-relateditems-result-image">\n      <img src="<%= generateImageUrl(_item, \'thumb\') %>" />\n    </span>\n    <% } %>\n    <span class="pattern-relateditems-result-title"><%= Title %></span>\n    <span class="pattern-relateditems-result-path"><%= path %></span>\n  </a>\n  <span class="pattern-relateditems-buttons">\n    <% if (folderish) { %>\n      <a class="pattern-relateditems-result-browse" href="#" data-path="<%= path %>"></a>\n    <% } %>\n  </span>\n</div>\n';});


define('text!mockup-patterns-tinymce-url/templates/selection.xml',[],function () { return '<span class="pattern-relateditems-item pattern-relateditems-type-<%= portal_type %>">\n <span class="pattern-relateditems-result-image">\n   <img src="<%= generateImageUrl(_item, \'thumb\') %>" />\n </span>\n <span class="pattern-relateditems-item-title"><%= Title %></span>\n <span class="pattern-relateditems-item-path"><%= path %></span>\n</span>\'\n';});


define('text!mockup-patterns-tinymce-url/templates/link.xml',[],function () { return '<div>\n  <div class="linkModal">\n    <h1><%- insertHeading %></h1>\n\n    <div class="linkTypes pat-autotoc autotabs"\n         data-pat-autotoc="section:fieldset;levels:legend;IDPrefix:tinymce-autotoc-">\n\n      <fieldset class="linkType internal" data-linkType="internal">\n        <legend id="tinylink-internal">Internal</legend>\n        <div>\n          <div class="form-group main">\n            <!-- this gives the name to the "linkType" -->\n            <input type="text" name="internal" />\n          </div>\n          <div class="form-group urltype">\n            <label for="external">URL Type</label>\n            <select type="text" class="form-control url-type" name="urlType">\n              <option value="/view" selected="true">View</option>\n              <option value="_direct_">Download</option>\n            </select>\n          </div>\n        </div>\n      </fieldset>\n\n      <fieldset class="linkType external" data-linkType="external">\n        <legend id="tinylink-external">External</legend>\n        <div class="form-group main">\n          <label for="external"><%- externalText %></label>\n          <input type="text" class="form-control" name="external" />\n        </div>\n      </fieldset>\n\n      <fieldset class="linkType email" data-linkType="email">\n        <legend id="tinylink-email">Email</legend>\n        <div class="form-inline">\n          <div class="form-group main">\n            <label><%- emailText %></label>\n            <input type="text" class="form-control" name="email" />\n          </div>\n          <div class="form-group">\n            <label><%- subjectText %></label>\n            <input type="text" class="form-control" name="subject" />\n          </div>\n        </div>\n      </fieldset>\n\n      <fieldset class="linkType anchor" data-linkType="anchor">\n        <legend id="tinylink-anchor">Anchor</legend>\n        <div>\n          <div class="form-group main">\n            <label>Select an anchor</label>\n            <div class="input-wrapper">\n              <select name="anchor" class="pat-select2" style="width:500px" />\n            </div>\n          </div>\n        </div>\n      </fieldset>\n\n      <% if(linkTypes.indexOf(\'modallink\') !== -1){ %>\n      <fieldset class="linkType modallink" data-linkType="modallink">\n        <legend id="tinylink-modal">Modal</legend>\n        <div>\n          <div class="form-group main">\n            <label>Select content for modal</label>\n            <!-- reuse internal value here! -->\n            <input type="text" name="internal" />\n          </div>\n        </div>\n      </fieldset>\n      <% } %>\n\n    </div><!-- / tabs -->\n\n    <div class="common-controls">\n      <div class="form-group">\n        <label>Target</label>\n        <select name="target" class="form-control">\n          <% _.each(targetList, function(target){ %>\n            <option value="<%- target.value %>"><%- target.text %></option>\n          <% }); %>\n        </select>\n      </div>\n      <div class="form-group">\n        <label><%- titleText %></label>\n        <input type="text" name="title" />\n      </div>\n    </div>\n\n    <input type="submit" class="plone-btn" name="cancel" value="<%- cancelBtn %>" />\n    <input type="submit" class="plone-btn plone-btn-primary context" name="insert" value="<%- insertBtn %>" />\n  </div>\n</div>\n';});


define('text!mockup-patterns-tinymce-url/templates/image.xml',[],function () { return '<div>\n  <div class="linkModal">\n    <h1><%- insertHeading %></h1>\n\n    <div class="linkTypes pat-autotoc autotabs"\n         data-pat-autotoc="section:fieldset;levels:legend;IDPrefix:tinymce-autotoc-">\n\n        <% if(_.contains(linkTypes, \'image\')){ %>\n      <fieldset class="linkType image" data-linkType="image">\n        <legend id="tinylink-image">Internal Image</legend>\n        <div class="form">\n          <div class="form-group main">\n            <input type="text" name="image" />\n          </div>\n          <div class="form-group scale">\n            <label><%- scaleText %></label>\n            <select name="scale">\n              <option value="">Original</option>\n                <% _.each(scales, function(scale){ %>\n                  <option value="<%- scale.part %>" <% if(scale.name === options.defaultScale){ %>selected<% } %> >\n                    <%- scale.label %>\n                  </option>\n                <% }); %>\n            </select>\n          </div>\n        </div>\n      </fieldset>\n        <% } %>\n\n      <% if(_.contains(linkTypes, \'externalImage\')){ %>\n      <fieldset class="linkType externalImage" data-linkType="externalImage">\n        <legend id="tinylink-externalImage">External Image</legend>\n        <div>\n          <div class="form-group main">\n            <label><%- externalImageText %></label>\n            <input type="text" name="externalImage" />\n          </div>\n        </div>\n      </fieldset>\n      <% } %>\n\n    </div><!-- / tabs -->\n\n    <div class="common-controls">\n      <div class="form-group text">\n        <label>Summary</label>\n        <input type="text" name="alt" />\n      </div>\n      <div class="form-group align">\n        <label><%- imageAlignText %></label>\n        <select name="align">\n          <% _.each([\'inline\', \'right\', \'left\'], function(align){ %>\n              <option value="<%- align %>">\n              <%- align.charAt(0).toUpperCase() + align.slice(1) %>\n              </option>\n          <% }); %>\n        <select>\n      </div>\n    </div>\n\n    <input type="submit" class="plone-btn" name="cancel" value="<%- cancelBtn %>" />\n    <input type="submit" class="plone-btn plone-btn-primary context" name="insert" value="<%- insertBtn %>" />\n\n  </div>\n</div>\n';});

define('mockup-patterns-tinymce-url/js/links',[
  'jquery',
  'underscore',
  'pat-registry',
  'pat-base',
  'tinymce',
  'text!mockup-patterns-tinymce-url/templates/link.xml',
  'text!mockup-patterns-tinymce-url/templates/image.xml',
  'mockup-patterns-relateditems',
  'castle-url/components/utils',
  'mockup-utils',
  'mockup-patterns-autotoc',
  'mockup-patterns-modal'
], function($, _, registry, Base, tinymce, LinkTemplate, ImageTemplate, RelatedItems, cutils, utils) {
  'use strict';

  var DIRECT_URL_TYPE = '_direct_';

  var LinkType = Base.extend({
    defaults: {
      linkModal: null // required
    },

    init: function() {
      this.linkModal = this.options.linkModal;
      this.tinypattern = this.options.tinypattern;
      this.tiny = this.tinypattern.tiny;
      this.dom = this.tiny.dom;
    },

    getEl: function(){
      return this.$el.find('input').first();
    },

    value: function() {
      return $.trim(this.getEl().val());
    },

    toUrl: function() {
      return this.value();
    },

    load: function(element) {
      this.getEl().attr('value', this.tiny.dom.getAttrib(element, 'data-val'));
    },

    set: function(val) {
      var $el = this.getEl();
      $el.attr('value', val);
      $el.val(val);
    },

    attributes: function() {
      return {
        'data-val': this.value()
      };
    }
  });

  var ExternalLink = LinkType.extend({
    init: function() {
      LinkType.prototype.init.call(this);
      this.getEl().on('change', function(){
        // check here if we should automatically add in http:// to url
        var val = $(this).val();
        if((new RegExp("https?\:\/\/")).test(val)){
          // already valid url
          return;
        }
        var domain = $(this).val().split('/')[0];
        if(domain.indexOf('.') !== -1){
          $(this).val('http://' + val);
        }
      });
    }
  });

  var InternalLink = LinkType.extend({
    init: function() {
      LinkType.prototype.init.call(this);
      this.getEl().addClass('pat-relateditems');
      this.createRelatedItems();
    },

    getEl: function(){
      return this.$el.find('input:not(.select2-input)').first();
    },

    createRelatedItems: function() {
      this.relatedItems = new RelatedItems(this.getEl().first(),
        this.linkModal.options.relatedItems);
    },

    value: function() {
      var val = this.getEl().val();
      if (val){
        if(typeof(val) === 'object') {
          val = val[0];
        } else if(typeof(val) === "string"){
          val = {
            UID: val
          };
        }
      }
      return val;
    },

    toUrl: function() {
      var value = this.value();
      if (value) {
        return this.tinypattern.generateUrl(value);
      }
      return null;
    },
    load: function(element) {
      var val = this.tiny.dom.getAttrib(element, 'data-val');
      if (val) {
        this.set(val);
      }
    },

    set: function(val) {
      var $el = this.getEl().first();
      $el[0].component.setState({
        selected: [val]
      });
      $el[0].component.selectionUpdated();
    },

    attributes: function() {
      var val = this.value();
      if (val) {
        return {
          'data-val': val.UID
        };
      }
      return {};
    }
  });

  var ImageLink = InternalLink.extend({
    toUrl: function() {
      var value = this.value();
      return this.tinypattern.generateImageUrl(value, this.linkModal.$scale.val());
    },
    createRelatedItems: function() {
      // slightly different because we want to start browsing at /image-repository
      this.relatedItems = new RelatedItems(this.getEl().first(),
        cutils.extend(this.linkModal.options.relatedItems, {
          initialPath: '/image-repository'
        }));
    }
  });

  var EmailLink = LinkType.extend({
    toUrl: function() {
      var self = this;
      var val = self.value();
      if (val) {
        var subject = self.getSubject();
        var href = 'mailto:' + val;
        if (subject) {
          href += '?subject=' + subject;
        }
        return href;
      }
      return null;
    },

    load: function(element) {
      LinkType.prototype.load.apply(this, [element]);
      this.linkModal.$subject.val(this.tiny.dom.getAttrib(element, 'data-subject'));
    },

    getSubject: function() {
      return this.linkModal.$subject.val();
    },

    attributes: function() {
      var attribs = LinkType.prototype.attributes.call(this);
      attribs['data-subject'] = this.getSubject();
      return attribs;
    }
  });

  var AnchorLink = LinkType.extend({
    init: function() {
      LinkType.prototype.init.call(this);
      this.$select = this.$el.find('select');
      this.anchorNodes = [];
      this.anchorData = [];
      this.populate();
    },

    value: function() {
      var val = this.$select.val();
      if (val) {
        return this.findData(val);
      }
      return;
    },

    updated: function(){
      this.populate();
    },

    populate: function() {
      var self = this;
      self.anchorNodes = [];
      self.anchorData = [];

      self.addAnchors(
        $('a.mceItemAnchor,img.mceItemAnchor,a.mce-item-anchor,img.mce-item-anchor,a[id]:not([href])'));

      var selected = self.linkModal.linkTypes.internal.value();
      if(selected && selected.UID){
        selected = selected.UID && selected.UID || selected;
        // use ajax to get the contents of the page and find anchor tags
        $.ajax({
          url: $('body').attr('data-portal-url') + '/resolveuid/' + selected + '/view'
        }).done(function(data){
          var $dom = $(utils.parseBodyTag(data));
          var title = _.find($.parseHTML(data), function(el){ return el.tagName === 'TITLE'; });
          if(title){
            title = title.innerHTML;
          }else{
            title = undefined;
          }
          self.addAnchors($('a[id]:not([href])', $dom), title + ': ', selected);
          // initial loading probably failed, try again now...
          var id = self.$select.attr('data-selected');
          self.createSelect2(id);
        }).fail(function(){
          self.createSelect2();
        });
      }else {
        self.createSelect2();
      }
    },

    addAnchors: function(nodes, prefix, uid){
      var self = this;
      var node, i, name, id;
      if(!prefix){
        prefix = '';
      }
      for (i = 0; i < nodes.length; i = i + 1) {
        node = nodes[i];
        id = self.tiny.dom.getAttrib(node, 'id');
        name = self.tiny.dom.getAttrib(node, 'name');
        if (!name) {
          name = id;
        }
        if(!id){
          id = name;
        }
        if (id !== '') {
          self.anchorNodes.push(node);
          self.anchorData.push({name: name, label: prefix + name, id: id, uid: uid});
        }
      }
    },

    createSelect2: function(selected){
      var self = this;
      self.$select.select2("destroy");
      self.$select.empty();
      var i;
      if (self.anchorNodes.length > 0) {
        for (i = 0; i < self.anchorData.length; i = i + 1) {
          var data = self.anchorData[i];
          var id = self.getAnchorId(data);
          var $option = $("<option value='" + id + "'>" + data.label + '</option>');
          if(selected == id){
            $option[0].selected = true;
          }
          self.$select.append($option);
        }
      } else {
        self.$select.append('<option>No anchors found..</option>');
      }
      this.$select.select2();
    },

    getAnchorId: function(data){
      var id = data.id;
      if(data.uid){
        id += data.uid;
      }
      return id;
    },

    findData: function(id){
      var self = this;
      for(var i=0; i<self.anchorData.length; i++){
        if(id === self.getAnchorId(self.anchorData[i])){
          return self.anchorData[i];
        }
      }
    },

    toUrl: function() {
      var val = this.value();
      if (val) {
        if(val.uid){
          return this.linkModal.linkTypes.internal.toUrl() + '#' + val.id;
        }else{
          return '#' + val.id;
        }
      }
      return null;
    },

    attributes: function(){
      var val = this.value();
      return {
        'data-val': val.uid,
        'data-id': this.getAnchorId(val)
      };
    },

    load: function(el){
      var $el = $(el);
      var uid = $el.attr('data-val');
      var id = $el.attr('data-id');
      this.$select.attr('data-selected', id);
      var data = this.findData(id);
      if(data){
        this.set(data);
      }
      // load link type as well
      if(uid){
        this.linkModal.linkTypes.internal.load($el);
      }
    },

    set: function(data) {
      var id = this.getAnchorId(data);
      this.$select.select2('data', id);
    }
  });

  tinymce.PluginManager.add('ploneimage', function(editor) {
    editor.addButton('ploneimage', {
      icon: 'image',
      tooltip: 'Insert/edit image',
      onclick: editor.settings.addImageClicked,
      stateSelector: 'img:not([data-mce-object])'
    });

    editor.addMenuItem('ploneimage', {
      icon: 'image',
      text: 'Insert image',
      onclick: editor.settings.addImageClicked,
      context: 'insert',
      prependToContext: true
    });
  });

  /* register the tinymce plugin */
  tinymce.PluginManager.add('plonelink', function(editor) {
    editor.addButton('plonelink', {
      icon: 'link',
      tooltip: 'Insert/edit link',
      shortcut: 'Ctrl+K',
      onclick: editor.settings.addLinkClicked,
      stateSelector: 'a[href]'
    });

    editor.addButton('unlink', {
      icon: 'unlink',
      tooltip: 'Remove link(s)',
      cmd: 'unlink',
      stateSelector: 'a[href]'
    });

    editor.addShortcut('Ctrl+K', '', editor.settings.addLinkClicked);

    editor.addMenuItem('plonelink', {
      icon: 'link',
      text: 'Insert link',
      shortcut: 'Ctrl+K',
      onclick: editor.settings.addLinkClicked,
      stateSelector: 'a[href]',
      context: 'insert',
      prependToContext: true
    });
  });


  var LinkModal = Base.extend({
    name: 'linkmodal',
    trigger: '.pat-linkmodal',
    defaults: {
      anchorSelector: 'h1,h2,h3',
      linkTypes: [
        /* available, none activate by default because these options
         * only get merged, not set.
        'internal',
        'modallink',
        'external',
        'email',
        'anchor',
        'image'
        'externalImage'*/
      ],
      initialLinkType: 'internal',
      text: {
        insertHeading: 'Insert Link'
      },
      linkTypeClassMapping: {
        'internal': InternalLink,
        'modallink': InternalLink,
        'external': ExternalLink,
        'email': EmailLink,
        'anchor': AnchorLink,
        'image': ImageLink,
        'externalImage': LinkType
      }
    },
    // XXX: this is a temporary work around for having separated templates.
    // Image modal is going to have its own modal class, funcs and template.
    linkTypeTemplateMapping: {
      'internal': LinkTemplate,
      'modallink': LinkTemplate,
      'external': LinkTemplate,
      'email': LinkTemplate,
      'anchor': LinkTemplate,
      'image': ImageTemplate,
      'externalImage': ImageTemplate
    },

    template: function(data) {
      return _.template(this.linkTypeTemplateMapping[this.linkType])(data);
    },

    init: function() {
      var self = this;
      self.$selectedTile = $('.mosaic-selected-tile');

      self.tinypattern = self.options.tinypattern;
      if (self.tinypattern.options.anchorSelector) {
        self.options.anchorSelector = self.tinypattern.options.anchorSelector;
      }
      self.tiny = self.tinypattern.tiny;
      self.dom = self.tiny.dom;
      self.linkType = self.options.initialLinkType;
      self.urlType = '/view';
      self.linkTypes = {};

      self.modal = registry.patterns['plone-modal'].init(self.$el, {
        html: self.generateModalHtml(),
        content: null,
        buttons: '.plone-btn'
      });
      self.modal.on('shown', function(e) {
        self.modalShown.apply(self, [e]);
      });
      self.modal.on('hide', function(e) {
        if(self.$selectedTile.length > 0){
          var Tile = require('mosaic-url/mosaic.tile');
          var tile = new Tile(self.$selectedTile);
          tile.select();
        }
        self.tiny.selection.setRng(self.rng);
      });
    },

    isOnlyTextSelected: function() {
      /* pulled from TinyMCE link plugin */
      var html = this.tiny.selection.getContent();

      // Partial html and not a fully selected anchor element
      if (/</.test(html) && (!/^<a [^>]+>[^<]+<\/a>$/.test(html) || html.indexOf('href=') === -1)) {
        return false;
      }

      if (this.anchorElm) {
        var nodes = this.anchorElm.childNodes, i;

        if (nodes.length === 0) {
          return false;
        }

        for (var ii = nodes.length - 1; ii >= 0; ii--) {
          if (nodes[ii].nodeType !== 3) {
            return false;
          }
        }
      }

      return true;
    },

    generateModalHtml: function() {
      return this.template({
        options: this.options,
        text: this.options.text,
        insertHeading: this.options.text.insertHeading,
        linkTypes: this.options.linkTypes,
        externalText: this.options.text.external,
        emailText: this.options.text.email,
        subjectText: this.options.text.subject,
        targetList: this.options.targetList,
        titleText: this.options.text.title,
        externalImageText: this.options.text.externalImage,
        altText: this.options.text.alt,
        imageAlignText: this.options.text.imageAlign,
        scaleText: this.options.text.scale,
        scales: this.options.scales,
        cancelBtn: this.options.text.cancelBtn,
        insertBtn: this.options.text.insertBtn
      });
    },

    isImageMode: function() {
      return ['image', 'externalImage'].indexOf(this.linkType) !== -1;
    },

    emitLinkLoaded: function(){
      var self = this;
      _.each(self.options.linkTypes, function(type) {
        if(self.linkTypes[type].updated){
          self.linkTypes[type].updated();
        }
      });
    },

    initElements: function() {
      var self = this;
      self.$selectedTile = $('.mosaic-selected-tile');
      self.$target = $('select[name="target"]', self.modal.$modal);
      self.$button = $('.plone-modal-footer input[name="insert"]', self.modal.$modal);
      self.$title = $('input[name="title"]', self.modal.$modal);
      self.$subject = $('input[name="subject"]', self.modal.$modal);
      self.$urlTypeContainer = $('.urltype', self.modal.$modal);
      self.$urlType = $('select[name="urlType"]', self.$urlTypeContainer);
      self.$urlTypeContainer.hide();

      self.$alt = $('input[name="alt"]', self.modal.$modal);
      self.$align = $('select[name="align"]', self.modal.$modal);
      self.$scale = $('select[name="scale"]', self.modal.$modal);

      /* load up all the link types */
      _.each(self.options.linkTypes, function(type) {
        var $container = $('.linkType.' + type + ' .main', self.modal.$modal);
        self.linkTypes[type] = new self.options.linkTypeClassMapping[type]($container, {
          linkModal: self,
          tinypattern: self.tinypattern
        });
        if(type === 'internal' || type === 'modallink'){
          var relatedItems = self.linkTypes[type].relatedItems;
          relatedItems.$el.on('loaded', function(){
            var item = relatedItems.component.state.items[0];
            if(item && ['File', 'Video', 'Audio', 'Image'].indexOf(item.portal_type) !== -1){
              self.$urlTypeContainer.show();
            }else{
              self.$urlTypeContainer.hide();
              self.urlType = DIRECT_URL_TYPE;
              self.$urlType.val(DIRECT_URL_TYPE);
            }
            self.emitLinkLoaded();
          });
        }
      });

      $('.autotoc-nav a', self.modal.$modal).click(function() {
        var $fieldset = $('fieldset.linkType', self.modal.$modal).eq($(this).index());
        var classes = $fieldset[0].className.split(/\s+/);
        _.each(classes, function(val) {
          if (_.indexOf(self.options.linkTypes, val) !== -1){
            self.linkType = val;
          }
        });
      });

      self.data = {};
      // get selection BEFORE..
      // This is pulled from TinyMCE link plugin
      self.initialText = null;
      var value;
      self.rng = self.tiny.selection.getRng();
      self.selectedElm = self.tiny.selection.getNode();
      self.anchorElm = self.tiny.dom.getParent(self.selectedElm, 'a[href]');
      self.onlyText = self.isOnlyTextSelected();

      self.data.text = self.initialText = self.anchorElm ? (self.anchorElm.innerText || self.anchorElm.textContent) : self.tiny.selection.getContent({format: 'text'});
      self.data.href = self.anchorElm ? self.tiny.dom.getAttrib(self.anchorElm, 'href') : '';

      if (self.anchorElm) {
        self.data.target = self.tiny.dom.getAttrib(self.anchorElm, 'target');
      } else if (self.tiny.settings.default_link_target) {
        self.data.target = self.tiny.settings.default_link_target;
      }

      if ((value = self.tiny.dom.getAttrib(self.anchorElm, 'rel'))) {
        self.data.rel = value;
      }

      if ((value = self.tiny.dom.getAttrib(self.anchorElm, 'class'))) {
        self.data['class'] = value;
      }

      if ((value = self.tiny.dom.getAttrib(self.anchorElm, 'title'))) {
        self.data.title = value;
      }

      // always default to first tab...
      $('.autotoc-nav a:first', self.modal.$modal).trigger('click');
    },

    getLinkUrl: function() {
      // get the url, only get one uid
      return this.linkTypes[this.linkType].toUrl();
    },

    getValue: function() {
      return this.linkTypes[this.linkType].value();
    },

    updateAnchor: function(href) {
      var self = this;

      self.urlType = self.$urlType.val() || DIRECT_URL_TYPE;

      self.tiny.focus();
      self.tiny.selection.setRng(self.rng);

      if((self.linkType === 'internal' || self.linkType === 'modallink') &&
         self.urlType !== DIRECT_URL_TYPE){
        href += self.urlType;
      }

      var target = self.$target.val();
      var title = self.$title.val();
      var linkAttrs = $.extend(true, self.data, {
        title: title ? title : null,
        target: target ? target : null,
        'data-linkType': self.linkType,
        'data-urltype': self.urlType,
        href: href
      }, self.linkTypes[self.linkType].attributes());
      if (self.anchorElm) {

        if (self.onlyText && linkAttrs.text !== self.initialText) {
          if ("innerText" in self.anchorElm) {
            self.anchorElm.innerText = self.data.text;
          } else {
            self.anchorElm.textContent = self.data.text;
          }
        }

        self.tiny.dom.setAttribs(self.anchorElm, linkAttrs);

        self.tiny.selection.select(self.anchorElm);
        self.tiny.undoManager.add();
      } else {
        if (self.onlyText) {
          self.tiny.insertContent(
            self.tiny.dom.createHTML('a', linkAttrs,
                                     self.tiny.dom.encode(self.data.text)));
        } else {
          self.tiny.execCommand('mceInsertLink', false, linkAttrs);
        }
      }
    },

    focusElement: function(elm) {
      this.tiny.focus();
      this.tiny.selection.select(elm);
      this.tiny.nodeChanged();
    },

    updateImage: function(src) {
      var self = this;
      var title = self.$title.val();

      self.tiny.focus();
      self.tiny.selection.setRng(self.rng);

      var data = $.extend(true, {}, {
        src: src,
        title: title ? title : null,
        alt: self.$alt.val(),
        'class': 'image-' + self.$align.val(),
        'data-linkType': self.linkType,
        'data-scale': self.$scale.val()
      }, self.linkTypes[self.linkType].attributes());
      if (self.imgElm && !self.imgElm.getAttribute('data-mce-object')) {
        data.width = self.dom.getAttrib(self.imgElm, 'width');
        data.height = self.dom.getAttrib(self.imgElm, 'height');
      } else {
        self.imgElm = null;
      }

      function waitLoad(imgElm) {
        imgElm.onload = imgElm.onerror = function() {
          imgElm.onload = imgElm.onerror = null;
          self.focusElement(imgElm);
        };
      }

      if (!self.imgElm) {
        data.id = '__mcenew';
        self.tiny.insertContent(self.dom.createHTML('img', data));
        self.imgElm = self.dom.get('__mcenew');
        self.dom.setAttrib(self.imgElm, 'id', null);
      } else {
        self.dom.setAttribs(self.imgElm, data);
      }

      waitLoad(self.imgElm);
      if (self.imgElm.complete) {
        self.focusElement(self.imgElm);
      }
    },

    modalShown: function(e) {
      var self = this;
      self.initElements();
      self.initData();

      self.$button.off('click').on('click', function(e) {
        self.hide();
        e.preventDefault();
        e.stopPropagation();
        self.linkType = self.modal.$modal.find('fieldset.active').data('linktype');
        var href;
        try{
            href = self.getLinkUrl();
        }catch(error){
            return;  // just cut out if no url
        }
        if (!href) {
          return; // just cut out if no url
        }
        if (self.isImageMode()) {
          self.updateImage(href);
        } else {
          /* regular anchor */
          self.updateAnchor(href);
        }
      });
      $('.plone-modal-footer input[name="cancel"]', self.modal.$modal).click(function(e) {
        e.preventDefault();
        self.hide();
      });
    },

    show: function() {
      this.modal.show();
    },

    hide: function() {
      this.modal.hide();
    },

    initData: function() {
      var self = this;
      self.selection = self.tiny.selection;
      self.tiny.focus();
      var selectedElm = self.imgElm = self.selection.getNode();
      self.anchorElm = self.dom.getParent(selectedElm, 'a[href]');

      var linkType;
      if (self.isImageMode()) {
        if (self.imgElm.nodeName !== 'IMG') {
          // try finding elsewhere
          if (self.anchorElm) {
            var imgs = self.anchorElm.getElementsByTagName('img');
            if (imgs.length > 0) {
              self.imgElm = imgs[0];
              self.focusElement(self.imgElm);
            }
          }
        }
        if (self.imgElm.nodeName !== 'IMG') {
          // okay, still no image, unset
          self.imgElm = null;
        }
        if (self.imgElm) {
          var src = self.dom.getAttrib(self.imgElm, 'src');
          self.$title.val(self.dom.getAttrib(self.imgElm, 'title'));
          self.$alt.val(self.dom.getAttrib(self.imgElm, 'alt'));
          linkType = self.dom.getAttrib(self.imgElm, 'data-linktype');
          if (linkType) {
            self.linkType = linkType;
            self.linkTypes[self.linkType].load(self.imgElm);
            var scale = self.dom.getAttrib(self.imgElm, 'data-scale');
            if(scale){
              self.$scale.val(scale);
            }
            $('#tinylink-' + self.linkType, self.modal.$modal).trigger('click');
          }else if (src) {
            self.guessImageLink(src);
          }
          var className = self.dom.getAttrib(self.imgElm, 'class');
          var klasses = className.split(' ');
          for (var i = 0; i < klasses.length; i = i + 1) {
            var klass = klasses[i];
            if (klass.indexOf('image-') !== -1) {
              self.$align.val(klass.replace('image-', ''));
            }
          }
        }
      }else if (self.anchorElm) {
        self.focusElement(self.anchorElm);
        var href = '';
        href = self.dom.getAttrib(self.anchorElm, 'href');
        self.$target.val(self.dom.getAttrib(self.anchorElm, 'target'));
        self.$title.val(self.dom.getAttrib(self.anchorElm, 'title'));
        linkType = self.dom.getAttrib(self.anchorElm, 'data-linktype');
        if (linkType) {
          self.linkType = linkType;
          self.linkTypes[self.linkType].load(self.anchorElm);
          $('#tinylink-' + self.linkType, self.modal.$modal).trigger('click');
        }else if (href) {
          self.guessAnchorLink(href);
        }
        var urlType = self.dom.getAttrib(self.anchorElm, 'data-urltype');
        if(urlType){
          self.urlType = urlType;
          self.$urlType.val(urlType);
        }
      }
    },

    guessImageLink: function(src) {
      if (src.indexOf(this.options.prependToScalePart) !== -1) {
        this.linkType = 'image';
        this.$scale.val(this.tinypattern.getScaleFromUrl(src));
        this.linkTypes.image.set(this.tinypattern.stripGeneratedUrl(src));
      } else {
        this.linkType = 'externalImage';
        this.linkTypes.externalImage.set(src);
      }
    },

    guessAnchorLink: function(href) {
      if (this.options.prependToUrl &&
          href.indexOf(this.options.prependToUrl) !== -1) {
        // XXX if using default configuration, it gets more difficult
        // here to detect internal urls so this might need to change...
        this.linkType = 'internal';
        this.linkTypes.internal.set(this.tinypattern.stripGeneratedUrl(href));
      } else if (href.indexOf('mailto:') !== -1) {
        this.linkType = 'email';
        var email = href.substring('mailto:'.length, href.length);
        var split = email.split('?subject=');
        this.linkTypes.email.set(split[0]);
        if (split.length > 1) {
          this.$subject.val(decodeURIComponent(split[1]));
        }
      } else if (href[0] === '#') {
        this.linkType = 'anchor';
        this.linkTypes.anchor.set(href.substring(1));
      } else {
        this.linkType = 'external';
        this.linkTypes.external.set(href);
      }
    },

    setSelectElement: function($el, val) {
      $el.find('option:selected').prop('selected', false);
      if (val) {
        // update
        $el.find('option[value="' + val + '"]').prop('selected', true);
      }
    },

    reinitialize: function() {
      /*
       * This will probably be called before show is run.
       * It will overwrite the base html template given to
       * be able to privde default values for the overlay
       */
      this.modal.options.html = this.generateModalHtml();
    }
  });
  return LinkModal;

});

(function(root) {
define("tinymce-modern-theme", ["tinymce"], function() {
  return (function() {
(function () {
var modern = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.ThemeManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.EditorManager');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var isBrandingEnabled = function (editor) {
    return editor.getParam('branding', true, 'boolean');
  };
  var hasMenubar = function (editor) {
    return getMenubar(editor) !== false;
  };
  var getMenubar = function (editor) {
    return editor.getParam('menubar');
  };
  var hasStatusbar = function (editor) {
    return editor.getParam('statusbar', true, 'boolean');
  };
  var getToolbarSize = function (editor) {
    return editor.getParam('toolbar_items_size');
  };
  var isReadOnly = function (editor) {
    return editor.getParam('readonly', false, 'boolean');
  };
  var getFixedToolbarContainer = function (editor) {
    return editor.getParam('fixed_toolbar_container');
  };
  var getInlineToolbarPositionHandler = function (editor) {
    return editor.getParam('inline_toolbar_position_handler');
  };
  var getMenu = function (editor) {
    return editor.getParam('menu');
  };
  var getRemovedMenuItems = function (editor) {
    return editor.getParam('removed_menuitems', '');
  };
  var getMinWidth = function (editor) {
    return editor.getParam('min_width', 100, 'number');
  };
  var getMinHeight = function (editor) {
    return editor.getParam('min_height', 100, 'number');
  };
  var getMaxWidth = function (editor) {
    return editor.getParam('max_width', 65535, 'number');
  };
  var getMaxHeight = function (editor) {
    return editor.getParam('max_height', 65535, 'number');
  };
  var isSkinDisabled = function (editor) {
    return editor.settings.skin === false;
  };
  var isInline = function (editor) {
    return editor.getParam('inline', false, 'boolean');
  };
  var getResize = function (editor) {
    var resize = editor.getParam('resize', 'vertical');
    if (resize === false) {
      return 'none';
    } else if (resize === 'both') {
      return 'both';
    } else {
      return 'vertical';
    }
  };
  var getSkinUrl = function (editor) {
    var settings = editor.settings;
    var skin = settings.skin;
    var skinUrl = settings.skin_url;
    if (skin !== false) {
      var skinName = skin ? skin : 'lightgray';
      if (skinUrl) {
        skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
      } else {
        skinUrl = global$1.baseURL + '/skins/' + skinName;
      }
    }
    return skinUrl;
  };
  var getIndexedToolbars = function (settings, defaultToolbar) {
    var toolbars = [];
    for (var i = 1; i < 10; i++) {
      var toolbar_1 = settings['toolbar' + i];
      if (!toolbar_1) {
        break;
      }
      toolbars.push(toolbar_1);
    }
    var mainToolbar = settings.toolbar ? [settings.toolbar] : [defaultToolbar];
    return toolbars.length > 0 ? toolbars : mainToolbar;
  };
  var getToolbars = function (editor) {
    var toolbar = editor.getParam('toolbar');
    var defaultToolbar = 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image';
    if (toolbar === false) {
      return [];
    } else if (global$2.isArray(toolbar)) {
      return global$2.grep(toolbar, function (toolbar) {
        return toolbar.length > 0;
      });
    } else {
      return getIndexedToolbars(editor.settings, defaultToolbar);
    }
  };

  var global$3 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$4 = tinymce.util.Tools.resolve('tinymce.ui.Factory');

  var global$5 = tinymce.util.Tools.resolve('tinymce.util.I18n');

  var fireSkinLoaded = function (editor) {
    return editor.fire('SkinLoaded');
  };
  var fireResizeEditor = function (editor) {
    return editor.fire('ResizeEditor');
  };
  var fireBeforeRenderUI = function (editor) {
    return editor.fire('BeforeRenderUI');
  };
  var $_aycuj2t7jh8lz3jp = {
    fireSkinLoaded: fireSkinLoaded,
    fireResizeEditor: fireResizeEditor,
    fireBeforeRenderUI: fireBeforeRenderUI
  };

  var focus = function (panel, type) {
    return function () {
      var item = panel.find(type)[0];
      if (item) {
        item.focus(true);
      }
    };
  };
  var addKeys = function (editor, panel) {
    editor.shortcuts.add('Alt+F9', '', focus(panel, 'menubar'));
    editor.shortcuts.add('Alt+F10,F10', '', focus(panel, 'toolbar'));
    editor.shortcuts.add('Alt+F11', '', focus(panel, 'elementpath'));
    panel.on('cancel', function () {
      editor.focus();
    });
  };
  var $_47hpztt8jh8lz3jq = { addKeys: addKeys };

  var global$6 = tinymce.util.Tools.resolve('tinymce.geom.Rect');

  var global$7 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var noop = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
  };
  var noarg = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return f();
    };
  };
  var compose = function (fa, fb) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return fa(fb.apply(null, arguments));
    };
  };
  var constant = function (value) {
    return function () {
      return value;
    };
  };
  var identity = function (x) {
    return x;
  };
  var tripleEquals = function (a, b) {
    return a === b;
  };
  var curry = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = new Array(arguments.length - 1);
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      var newArgs = new Array(arguments.length);
      for (var j = 0; j < newArgs.length; j++)
        newArgs[j] = arguments[j];
      var all = args.concat(newArgs);
      return f.apply(null, all);
    };
  };
  var not = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return !f.apply(null, arguments);
    };
  };
  var die = function (msg) {
    return function () {
      throw new Error(msg);
    };
  };
  var apply = function (f) {
    return f();
  };
  var call = function (f) {
    f();
  };
  var never = constant(false);
  var always = constant(true);
  var $_3pjweotejh8lz3k4 = {
    noop: noop,
    noarg: noarg,
    compose: compose,
    constant: constant,
    identity: identity,
    tripleEquals: tripleEquals,
    curry: curry,
    not: not,
    die: die,
    apply: apply,
    call: call,
    never: never,
    always: always
  };

  var never$1 = $_3pjweotejh8lz3k4.never;
  var always$1 = $_3pjweotejh8lz3k4.always;
  var none = function () {
    return NONE;
  };
  var NONE = function () {
    var eq = function (o) {
      return o.isNone();
    };
    var call = function (thunk) {
      return thunk();
    };
    var id = function (n) {
      return n;
    };
    var noop = function () {
    };
    var me = {
      fold: function (n, s) {
        return n();
      },
      is: never$1,
      isSome: never$1,
      isNone: always$1,
      getOr: id,
      getOrThunk: call,
      getOrDie: function (msg) {
        throw new Error(msg || 'error: getOrDie called on none.');
      },
      or: id,
      orThunk: call,
      map: none,
      ap: none,
      each: noop,
      bind: none,
      flatten: none,
      exists: never$1,
      forall: always$1,
      filter: none,
      equals: eq,
      equals_: eq,
      toArray: function () {
        return [];
      },
      toString: $_3pjweotejh8lz3k4.constant('none()')
    };
    if (Object.freeze)
      Object.freeze(me);
    return me;
  }();
  var some = function (a) {
    var constant_a = function () {
      return a;
    };
    var self = function () {
      return me;
    };
    var map = function (f) {
      return some(f(a));
    };
    var bind = function (f) {
      return f(a);
    };
    var me = {
      fold: function (n, s) {
        return s(a);
      },
      is: function (v) {
        return a === v;
      },
      isSome: always$1,
      isNone: never$1,
      getOr: constant_a,
      getOrThunk: constant_a,
      getOrDie: constant_a,
      or: self,
      orThunk: self,
      map: map,
      ap: function (optfab) {
        return optfab.fold(none, function (fab) {
          return some(fab(a));
        });
      },
      each: function (f) {
        f(a);
      },
      bind: bind,
      flatten: constant_a,
      exists: bind,
      forall: bind,
      filter: function (f) {
        return f(a) ? me : NONE;
      },
      equals: function (o) {
        return o.is(a);
      },
      equals_: function (o, elementEq) {
        return o.fold(never$1, function (b) {
          return elementEq(a, b);
        });
      },
      toArray: function () {
        return [a];
      },
      toString: function () {
        return 'some(' + a + ')';
      }
    };
    return me;
  };
  var from = function (value) {
    return value === null || value === undefined ? NONE : some(value);
  };
  var Option = {
    some: some,
    none: none,
    from: from
  };

  var getUiContainerDelta = function (ctrl) {
    var uiContainer = getUiContainer(ctrl);
    if (uiContainer && global$3.DOM.getStyle(uiContainer, 'position', true) !== 'static') {
      var containerPos = global$3.DOM.getPos(uiContainer);
      var dx = uiContainer.scrollLeft - containerPos.x;
      var dy = uiContainer.scrollTop - containerPos.y;
      return Option.some({
        x: dx,
        y: dy
      });
    } else {
      return Option.none();
    }
  };
  var setUiContainer = function (editor, ctrl) {
    var uiContainer = global$3.DOM.select(editor.settings.ui_container)[0];
    ctrl.getRoot().uiContainer = uiContainer;
  };
  var getUiContainer = function (ctrl) {
    return ctrl ? ctrl.getRoot().uiContainer : null;
  };
  var inheritUiContainer = function (fromCtrl, toCtrl) {
    return toCtrl.uiContainer = getUiContainer(fromCtrl);
  };
  var $_1jk3jvtcjh8lz3jy = {
    getUiContainerDelta: getUiContainerDelta,
    setUiContainer: setUiContainer,
    getUiContainer: getUiContainer,
    inheritUiContainer: inheritUiContainer
  };

  var createToolbar = function (editor, items, size) {
    var toolbarItems = [];
    var buttonGroup;
    if (!items) {
      return;
    }
    global$2.each(items.split(/[ ,]/), function (item) {
      var itemName;
      var bindSelectorChanged = function () {
        var selection = editor.selection;
        if (item.settings.stateSelector) {
          selection.selectorChanged(item.settings.stateSelector, function (state) {
            item.active(state);
          }, true);
        }
        if (item.settings.disabledStateSelector) {
          selection.selectorChanged(item.settings.disabledStateSelector, function (state) {
            item.disabled(state);
          });
        }
      };
      if (item === '|') {
        buttonGroup = null;
      } else {
        if (!buttonGroup) {
          buttonGroup = {
            type: 'buttongroup',
            items: []
          };
          toolbarItems.push(buttonGroup);
        }
        if (editor.buttons[item]) {
          itemName = item;
          item = editor.buttons[itemName];
          if (typeof item === 'function') {
            item = item();
          }
          item.type = item.type || 'button';
          item.size = size;
          item = global$4.create(item);
          buttonGroup.items.push(item);
          if (editor.initialized) {
            bindSelectorChanged();
          } else {
            editor.on('init', bindSelectorChanged);
          }
        }
      }
    });
    return {
      type: 'toolbar',
      layout: 'flow',
      items: toolbarItems
    };
  };
  var createToolbars = function (editor, size) {
    var toolbars = [];
    var addToolbar = function (items) {
      if (items) {
        toolbars.push(createToolbar(editor, items, size));
      }
    };
    global$2.each(getToolbars(editor), function (toolbar) {
      addToolbar(toolbar);
    });
    if (toolbars.length) {
      return {
        type: 'panel',
        layout: 'stack',
        classes: 'toolbar-grp',
        ariaRoot: true,
        ariaRemember: true,
        items: toolbars
      };
    }
  };
  var $_fudqhrtfjh8lz3k7 = {
    createToolbar: createToolbar,
    createToolbars: createToolbars
  };

  var DOM = global$3.DOM;
  var toClientRect = function (geomRect) {
    return {
      left: geomRect.x,
      top: geomRect.y,
      width: geomRect.w,
      height: geomRect.h,
      right: geomRect.x + geomRect.w,
      bottom: geomRect.y + geomRect.h
    };
  };
  var hideAllFloatingPanels = function (editor) {
    global$2.each(editor.contextToolbars, function (toolbar) {
      if (toolbar.panel) {
        toolbar.panel.hide();
      }
    });
  };
  var movePanelTo = function (panel, pos) {
    panel.moveTo(pos.left, pos.top);
  };
  var togglePositionClass = function (panel, relPos, predicate) {
    relPos = relPos ? relPos.substr(0, 2) : '';
    global$2.each({
      t: 'down',
      b: 'up'
    }, function (cls, pos) {
      panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(0, 1)));
    });
    global$2.each({
      l: 'left',
      r: 'right'
    }, function (cls, pos) {
      panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(1, 1)));
    });
  };
  var userConstrain = function (handler, x, y, elementRect, contentAreaRect, panelRect) {
    panelRect = toClientRect({
      x: x,
      y: y,
      w: panelRect.w,
      h: panelRect.h
    });
    if (handler) {
      panelRect = handler({
        elementRect: toClientRect(elementRect),
        contentAreaRect: toClientRect(contentAreaRect),
        panelRect: panelRect
      });
    }
    return panelRect;
  };
  var addContextualToolbars = function (editor) {
    var scrollContainer;
    var getContextToolbars = function () {
      return editor.contextToolbars || [];
    };
    var getElementRect = function (elm) {
      var pos, targetRect, root;
      pos = DOM.getPos(editor.getContentAreaContainer());
      targetRect = editor.dom.getRect(elm);
      root = editor.dom.getRoot();
      if (root.nodeName === 'BODY') {
        targetRect.x -= root.ownerDocument.documentElement.scrollLeft || root.scrollLeft;
        targetRect.y -= root.ownerDocument.documentElement.scrollTop || root.scrollTop;
      }
      targetRect.x += pos.x;
      targetRect.y += pos.y;
      return targetRect;
    };
    var reposition = function (match, shouldShow) {
      var relPos, panelRect, elementRect, contentAreaRect, panel, relRect, testPositions, smallElementWidthThreshold;
      var handler = getInlineToolbarPositionHandler(editor);
      if (editor.removed) {
        return;
      }
      if (!match || !match.toolbar.panel) {
        hideAllFloatingPanels(editor);
        return;
      }
      testPositions = [
        'bc-tc',
        'tc-bc',
        'tl-bl',
        'bl-tl',
        'tr-br',
        'br-tr'
      ];
      panel = match.toolbar.panel;
      if (shouldShow) {
        panel.show();
      }
      elementRect = getElementRect(match.element);
      panelRect = DOM.getRect(panel.getEl());
      contentAreaRect = DOM.getRect(editor.getContentAreaContainer() || editor.getBody());
      var delta = $_1jk3jvtcjh8lz3jy.getUiContainerDelta(panel).getOr({
        x: 0,
        y: 0
      });
      elementRect.x += delta.x;
      elementRect.y += delta.y;
      panelRect.x += delta.x;
      panelRect.y += delta.y;
      contentAreaRect.x += delta.x;
      contentAreaRect.y += delta.y;
      smallElementWidthThreshold = 25;
      if (DOM.getStyle(match.element, 'display', true) !== 'inline') {
        var clientRect = match.element.getBoundingClientRect();
        elementRect.w = clientRect.width;
        elementRect.h = clientRect.height;
      }
      if (!editor.inline) {
        contentAreaRect.w = editor.getDoc().documentElement.offsetWidth;
      }
      if (editor.selection.controlSelection.isResizable(match.element) && elementRect.w < smallElementWidthThreshold) {
        elementRect = global$6.inflate(elementRect, 0, 8);
      }
      relPos = global$6.findBestRelativePosition(panelRect, elementRect, contentAreaRect, testPositions);
      elementRect = global$6.clamp(elementRect, contentAreaRect);
      if (relPos) {
        relRect = global$6.relativePosition(panelRect, elementRect, relPos);
        movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect));
      } else {
        contentAreaRect.h += panelRect.h;
        elementRect = global$6.intersect(contentAreaRect, elementRect);
        if (elementRect) {
          relPos = global$6.findBestRelativePosition(panelRect, elementRect, contentAreaRect, [
            'bc-tc',
            'bl-tl',
            'br-tr'
          ]);
          if (relPos) {
            relRect = global$6.relativePosition(panelRect, elementRect, relPos);
            movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect));
          } else {
            movePanelTo(panel, userConstrain(handler, elementRect.x, elementRect.y, elementRect, contentAreaRect, panelRect));
          }
        } else {
          panel.hide();
        }
      }
      togglePositionClass(panel, relPos, function (pos1, pos2) {
        return pos1 === pos2;
      });
    };
    var repositionHandler = function (show) {
      return function () {
        var execute = function () {
          if (editor.selection) {
            reposition(findFrontMostMatch(editor.selection.getNode()), show);
          }
        };
        global$7.requestAnimationFrame(execute);
      };
    };
    var bindScrollEvent = function (panel) {
      if (!scrollContainer) {
        var reposition_1 = repositionHandler(true);
        var uiContainer_1 = $_1jk3jvtcjh8lz3jy.getUiContainer(panel);
        scrollContainer = editor.selection.getScrollContainer() || editor.getWin();
        DOM.bind(scrollContainer, 'scroll', reposition_1);
        DOM.bind(uiContainer_1, 'scroll', reposition_1);
        editor.on('remove', function () {
          DOM.unbind(scrollContainer, 'scroll', reposition_1);
          DOM.unbind(uiContainer_1, 'scroll', reposition_1);
        });
      }
    };
    var showContextToolbar = function (match) {
      var panel;
      if (match.toolbar.panel) {
        match.toolbar.panel.show();
        reposition(match);
        return;
      }
      panel = global$4.create({
        type: 'floatpanel',
        role: 'dialog',
        classes: 'tinymce tinymce-inline arrow',
        ariaLabel: 'Inline toolbar',
        layout: 'flex',
        direction: 'column',
        align: 'stretch',
        autohide: false,
        autofix: true,
        fixed: true,
        border: 1,
        items: $_fudqhrtfjh8lz3k7.createToolbar(editor, match.toolbar.items),
        oncancel: function () {
          editor.focus();
        }
      });
      $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel);
      bindScrollEvent(panel);
      match.toolbar.panel = panel;
      panel.renderTo().reflow();
      reposition(match);
    };
    var hideAllContextToolbars = function () {
      global$2.each(getContextToolbars(), function (toolbar) {
        if (toolbar.panel) {
          toolbar.panel.hide();
        }
      });
    };
    var findFrontMostMatch = function (targetElm) {
      var i, y, parentsAndSelf;
      var toolbars = getContextToolbars();
      parentsAndSelf = editor.$(targetElm).parents().add(targetElm);
      for (i = parentsAndSelf.length - 1; i >= 0; i--) {
        for (y = toolbars.length - 1; y >= 0; y--) {
          if (toolbars[y].predicate(parentsAndSelf[i])) {
            return {
              toolbar: toolbars[y],
              element: parentsAndSelf[i]
            };
          }
        }
      }
      return null;
    };
    editor.on('click keyup setContent ObjectResized', function (e) {
      if (e.type === 'setcontent' && !e.selection) {
        return;
      }
      global$7.setEditorTimeout(editor, function () {
        var match;
        match = findFrontMostMatch(editor.selection.getNode());
        if (match) {
          hideAllContextToolbars();
          showContextToolbar(match);
        } else {
          hideAllContextToolbars();
        }
      });
    });
    editor.on('blur hide contextmenu', hideAllContextToolbars);
    editor.on('ObjectResizeStart', function () {
      var match = findFrontMostMatch(editor.selection.getNode());
      if (match && match.toolbar.panel) {
        match.toolbar.panel.hide();
      }
    });
    editor.on('ResizeEditor ResizeWindow', repositionHandler(true));
    editor.on('nodeChange', repositionHandler(false));
    editor.on('remove', function () {
      global$2.each(getContextToolbars(), function (toolbar) {
        if (toolbar.panel) {
          toolbar.panel.remove();
        }
      });
      editor.contextToolbars = {};
    });
    editor.shortcuts.add('ctrl+shift+e > ctrl+shift+p', '', function () {
      var match = findFrontMostMatch(editor.selection.getNode());
      if (match && match.toolbar.panel) {
        match.toolbar.panel.items()[0].focus();
      }
    });
  };
  var $_5kodmdt9jh8lz3js = { addContextualToolbars: addContextualToolbars };

  var typeOf = function (x) {
    if (x === null)
      return 'null';
    var t = typeof x;
    if (t === 'object' && Array.prototype.isPrototypeOf(x))
      return 'array';
    if (t === 'object' && String.prototype.isPrototypeOf(x))
      return 'string';
    return t;
  };
  var isType = function (type) {
    return function (value) {
      return typeOf(value) === type;
    };
  };
  var $_d8bie3tijh8lz3kn = {
    isString: isType('string'),
    isObject: isType('object'),
    isArray: isType('array'),
    isNull: isType('null'),
    isBoolean: isType('boolean'),
    isUndefined: isType('undefined'),
    isFunction: isType('function'),
    isNumber: isType('number')
  };

  var rawIndexOf = function () {
    var pIndexOf = Array.prototype.indexOf;
    var fastIndex = function (xs, x) {
      return pIndexOf.call(xs, x);
    };
    var slowIndex = function (xs, x) {
      return slowIndexOf(xs, x);
    };
    return pIndexOf === undefined ? slowIndex : fastIndex;
  }();
  var indexOf = function (xs, x) {
    var r = rawIndexOf(xs, x);
    return r === -1 ? Option.none() : Option.some(r);
  };
  var contains = function (xs, x) {
    return rawIndexOf(xs, x) > -1;
  };
  var exists = function (xs, pred) {
    return findIndex(xs, pred).isSome();
  };
  var range = function (num, f) {
    var r = [];
    for (var i = 0; i < num; i++) {
      r.push(f(i));
    }
    return r;
  };
  var chunk = function (array, size) {
    var r = [];
    for (var i = 0; i < array.length; i += size) {
      var s = array.slice(i, i + size);
      r.push(s);
    }
    return r;
  };
  var map = function (xs, f) {
    var len = xs.length;
    var r = new Array(len);
    for (var i = 0; i < len; i++) {
      var x = xs[i];
      r[i] = f(x, i, xs);
    }
    return r;
  };
  var each = function (xs, f) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var eachr = function (xs, f) {
    for (var i = xs.length - 1; i >= 0; i--) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var partition = function (xs, pred) {
    var pass = [];
    var fail = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      var arr = pred(x, i, xs) ? pass : fail;
      arr.push(x);
    }
    return {
      pass: pass,
      fail: fail
    };
  };
  var filter = function (xs, pred) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        r.push(x);
      }
    }
    return r;
  };
  var groupBy = function (xs, f) {
    if (xs.length === 0) {
      return [];
    } else {
      var wasType = f(xs[0]);
      var r = [];
      var group = [];
      for (var i = 0, len = xs.length; i < len; i++) {
        var x = xs[i];
        var type = f(x);
        if (type !== wasType) {
          r.push(group);
          group = [];
        }
        wasType = type;
        group.push(x);
      }
      if (group.length !== 0) {
        r.push(group);
      }
      return r;
    }
  };
  var foldr = function (xs, f, acc) {
    eachr(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var foldl = function (xs, f, acc) {
    each(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var find = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(x);
      }
    }
    return Option.none();
  };
  var findIndex = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(i);
      }
    }
    return Option.none();
  };
  var slowIndexOf = function (xs, x) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (xs[i] === x) {
        return i;
      }
    }
    return -1;
  };
  var push = Array.prototype.push;
  var flatten = function (xs) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (!Array.prototype.isPrototypeOf(xs[i]))
        throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
      push.apply(r, xs[i]);
    }
    return r;
  };
  var bind = function (xs, f) {
    var output = map(xs, f);
    return flatten(output);
  };
  var forall = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      var x = xs[i];
      if (pred(x, i, xs) !== true) {
        return false;
      }
    }
    return true;
  };
  var equal = function (a1, a2) {
    return a1.length === a2.length && forall(a1, function (x, i) {
      return x === a2[i];
    });
  };
  var slice = Array.prototype.slice;
  var reverse = function (xs) {
    var r = slice.call(xs, 0);
    r.reverse();
    return r;
  };
  var difference = function (a1, a2) {
    return filter(a1, function (x) {
      return !contains(a2, x);
    });
  };
  var mapToObject = function (xs, f) {
    var r = {};
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      r[String(x)] = f(x, i);
    }
    return r;
  };
  var pure = function (x) {
    return [x];
  };
  var sort = function (xs, comparator) {
    var copy = slice.call(xs, 0);
    copy.sort(comparator);
    return copy;
  };
  var head = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  };
  var last = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  };
  var from$1 = $_d8bie3tijh8lz3kn.isFunction(Array.from) ? Array.from : function (x) {
    return slice.call(x);
  };
  var $_f3qxhzthjh8lz3kg = {
    map: map,
    each: each,
    eachr: eachr,
    partition: partition,
    filter: filter,
    groupBy: groupBy,
    indexOf: indexOf,
    foldr: foldr,
    foldl: foldl,
    find: find,
    findIndex: findIndex,
    flatten: flatten,
    bind: bind,
    forall: forall,
    exists: exists,
    contains: contains,
    equal: equal,
    reverse: reverse,
    chunk: chunk,
    difference: difference,
    mapToObject: mapToObject,
    pure: pure,
    sort: sort,
    range: range,
    head: head,
    last: last,
    from: from$1
  };

  var defaultMenus = {
    file: {
      title: 'File',
      items: 'newdocument restoredraft | preview | print'
    },
    edit: {
      title: 'Edit',
      items: 'undo redo | cut copy paste pastetext | selectall'
    },
    view: {
      title: 'View',
      items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen'
    },
    insert: {
      title: 'Insert',
      items: 'image link media template codesample inserttable | charmap hr | pagebreak nonbreaking anchor toc | insertdatetime'
    },
    format: {
      title: 'Format',
      items: 'bold italic underline strikethrough superscript subscript codeformat | blockformats align | removeformat'
    },
    tools: {
      title: 'Tools',
      items: 'spellchecker spellcheckerlanguage | a11ycheck code'
    },
    table: { title: 'Table' },
    help: { title: 'Help' }
  };
  var delimiterMenuNamePair = function () {
    return {
      name: '|',
      item: { text: '|' }
    };
  };
  var createMenuNameItemPair = function (name, item) {
    var menuItem = item ? {
      name: name,
      item: item
    } : null;
    return name === '|' ? delimiterMenuNamePair() : menuItem;
  };
  var hasItemName = function (namedMenuItems, name) {
    return $_f3qxhzthjh8lz3kg.findIndex(namedMenuItems, function (namedMenuItem) {
      return namedMenuItem.name === name;
    }).isSome();
  };
  var isSeparator = function (namedMenuItem) {
    return namedMenuItem && namedMenuItem.item.text === '|';
  };
  var cleanupMenu = function (namedMenuItems, removedMenuItems) {
    var menuItemsPass1 = $_f3qxhzthjh8lz3kg.filter(namedMenuItems, function (namedMenuItem) {
      return removedMenuItems.hasOwnProperty(namedMenuItem.name) === false;
    });
    var menuItemsPass2 = $_f3qxhzthjh8lz3kg.filter(menuItemsPass1, function (namedMenuItem, i, namedMenuItems) {
      return !isSeparator(namedMenuItem) || !isSeparator(namedMenuItems[i - 1]);
    });
    return $_f3qxhzthjh8lz3kg.filter(menuItemsPass2, function (namedMenuItem, i, namedMenuItems) {
      return !isSeparator(namedMenuItem) || i > 0 && i < namedMenuItems.length - 1;
    });
  };
  var createMenu = function (editorMenuItems, menus, removedMenuItems, context) {
    var menuButton, menu, namedMenuItems, isUserDefined;
    if (menus) {
      menu = menus[context];
      isUserDefined = true;
    } else {
      menu = defaultMenus[context];
    }
    if (menu) {
      menuButton = { text: menu.title };
      namedMenuItems = [];
      global$2.each((menu.items || '').split(/[ ,]/), function (name) {
        var namedMenuItem = createMenuNameItemPair(name, editorMenuItems[name]);
        if (namedMenuItem) {
          namedMenuItems.push(namedMenuItem);
        }
      });
      if (!isUserDefined) {
        global$2.each(editorMenuItems, function (item, name) {
          if (item.context === context && !hasItemName(namedMenuItems, name)) {
            if (item.separator === 'before') {
              namedMenuItems.push(delimiterMenuNamePair());
            }
            if (item.prependToContext) {
              namedMenuItems.unshift(createMenuNameItemPair(name, item));
            } else {
              namedMenuItems.push(createMenuNameItemPair(name, item));
            }
            if (item.separator === 'after') {
              namedMenuItems.push(delimiterMenuNamePair());
            }
          }
        });
      }
      menuButton.menu = $_f3qxhzthjh8lz3kg.map(cleanupMenu(namedMenuItems, removedMenuItems), function (menuItem) {
        return menuItem.item;
      });
      if (!menuButton.menu.length) {
        return null;
      }
    }
    return menuButton;
  };
  var getDefaultMenubar = function (editor) {
    var name;
    var defaultMenuBar = [];
    var menu = getMenu(editor);
    if (menu) {
      for (name in menu) {
        defaultMenuBar.push(name);
      }
    } else {
      for (name in defaultMenus) {
        defaultMenuBar.push(name);
      }
    }
    return defaultMenuBar;
  };
  var createMenuButtons = function (editor) {
    var menuButtons = [];
    var defaultMenuBar = getDefaultMenubar(editor);
    var removedMenuItems = global$2.makeMap(getRemovedMenuItems(editor).split(/[ ,]/));
    var menubar = getMenubar(editor);
    var enabledMenuNames = typeof menubar === 'string' ? menubar.split(/[ ,]/) : defaultMenuBar;
    for (var i = 0; i < enabledMenuNames.length; i++) {
      var menuItems = enabledMenuNames[i];
      var menu = createMenu(editor.menuItems, getMenu(editor), removedMenuItems, menuItems);
      if (menu) {
        menuButtons.push(menu);
      }
    }
    return menuButtons;
  };
  var $_8i78rftgjh8lz3ka = { createMenuButtons: createMenuButtons };

  var DOM$1 = global$3.DOM;
  var getSize = function (elm) {
    return {
      width: elm.clientWidth,
      height: elm.clientHeight
    };
  };
  var resizeTo = function (editor, width, height) {
    var containerElm, iframeElm, containerSize, iframeSize;
    containerElm = editor.getContainer();
    iframeElm = editor.getContentAreaContainer().firstChild;
    containerSize = getSize(containerElm);
    iframeSize = getSize(iframeElm);
    if (width !== null) {
      width = Math.max(getMinWidth(editor), width);
      width = Math.min(getMaxWidth(editor), width);
      DOM$1.setStyle(containerElm, 'width', width + (containerSize.width - iframeSize.width));
      DOM$1.setStyle(iframeElm, 'width', width);
    }
    height = Math.max(getMinHeight(editor), height);
    height = Math.min(getMaxHeight(editor), height);
    DOM$1.setStyle(iframeElm, 'height', height);
    $_aycuj2t7jh8lz3jp.fireResizeEditor(editor);
  };
  var resizeBy = function (editor, dw, dh) {
    var elm = editor.getContentAreaContainer();
    resizeTo(editor, elm.clientWidth + dw, elm.clientHeight + dh);
  };
  var $_5toavetjjh8lz3ko = {
    resizeTo: resizeTo,
    resizeBy: resizeBy
  };

  var global$8 = tinymce.util.Tools.resolve('tinymce.Env');

  var api = function (elm) {
    return {
      element: function () {
        return elm;
      }
    };
  };
  var trigger = function (sidebar, panel, callbackName) {
    var callback = sidebar.settings[callbackName];
    if (callback) {
      callback(api(panel.getEl('body')));
    }
  };
  var hidePanels = function (name, container, sidebars) {
    global$2.each(sidebars, function (sidebar) {
      var panel = container.items().filter('#' + sidebar.name)[0];
      if (panel && panel.visible() && sidebar.name !== name) {
        trigger(sidebar, panel, 'onhide');
        panel.visible(false);
      }
    });
  };
  var deactivateButtons = function (toolbar) {
    toolbar.items().each(function (ctrl) {
      ctrl.active(false);
    });
  };
  var findSidebar = function (sidebars, name) {
    return global$2.grep(sidebars, function (sidebar) {
      return sidebar.name === name;
    })[0];
  };
  var showPanel = function (editor, name, sidebars) {
    return function (e) {
      var btnCtrl = e.control;
      var container = btnCtrl.parents().filter('panel')[0];
      var panel = container.find('#' + name)[0];
      var sidebar = findSidebar(sidebars, name);
      hidePanels(name, container, sidebars);
      deactivateButtons(btnCtrl.parent());
      if (panel && panel.visible()) {
        trigger(sidebar, panel, 'onhide');
        panel.hide();
        btnCtrl.active(false);
      } else {
        if (panel) {
          panel.show();
          trigger(sidebar, panel, 'onshow');
        } else {
          panel = global$4.create({
            type: 'container',
            name: name,
            layout: 'stack',
            classes: 'sidebar-panel',
            html: ''
          });
          container.prepend(panel);
          trigger(sidebar, panel, 'onrender');
          trigger(sidebar, panel, 'onshow');
        }
        btnCtrl.active(true);
      }
      $_aycuj2t7jh8lz3jp.fireResizeEditor(editor);
    };
  };
  var isModernBrowser = function () {
    return !global$8.ie || global$8.ie >= 11;
  };
  var hasSidebar = function (editor) {
    return isModernBrowser() && editor.sidebars ? editor.sidebars.length > 0 : false;
  };
  var createSidebar = function (editor) {
    var buttons = global$2.map(editor.sidebars, function (sidebar) {
      var settings = sidebar.settings;
      return {
        type: 'button',
        icon: settings.icon,
        image: settings.image,
        tooltip: settings.tooltip,
        onclick: showPanel(editor, sidebar.name, editor.sidebars)
      };
    });
    return {
      type: 'panel',
      name: 'sidebar',
      layout: 'stack',
      classes: 'sidebar',
      items: [{
          type: 'toolbar',
          layout: 'stack',
          classes: 'sidebar-toolbar',
          items: buttons
        }]
    };
  };
  var $_5buua9tkjh8lz3kq = {
    hasSidebar: hasSidebar,
    createSidebar: createSidebar
  };

  var fireSkinLoaded$1 = function (editor) {
    var done = function () {
      editor._skinLoaded = true;
      $_aycuj2t7jh8lz3jp.fireSkinLoaded(editor);
    };
    return function () {
      if (editor.initialized) {
        done();
      } else {
        editor.on('init', done);
      }
    };
  };
  var $_231e94tmjh8lz3ku = { fireSkinLoaded: fireSkinLoaded$1 };

  var DOM$2 = global$3.DOM;
  var switchMode = function (panel) {
    return function (e) {
      panel.find('*').disabled(e.mode === 'readonly');
    };
  };
  var editArea = function (border) {
    return {
      type: 'panel',
      name: 'iframe',
      layout: 'stack',
      classes: 'edit-area',
      border: border,
      html: ''
    };
  };
  var editAreaContainer = function (editor) {
    return {
      type: 'panel',
      layout: 'stack',
      classes: 'edit-aria-container',
      border: '1 0 0 0',
      items: [
        editArea('0'),
        $_5buua9tkjh8lz3kq.createSidebar(editor)
      ]
    };
  };
  var render = function (editor, theme, args) {
    var panel, resizeHandleCtrl, startSize;
    if (isSkinDisabled(editor) === false && args.skinUiCss) {
      DOM$2.styleSheetLoader.load(args.skinUiCss, $_231e94tmjh8lz3ku.fireSkinLoaded(editor));
    } else {
      $_231e94tmjh8lz3ku.fireSkinLoaded(editor)();
    }
    panel = theme.panel = global$4.create({
      type: 'panel',
      role: 'application',
      classes: 'tinymce',
      style: 'visibility: hidden',
      layout: 'stack',
      border: 1,
      items: [
        {
          type: 'container',
          classes: 'top-part',
          items: [
            hasMenubar(editor) === false ? null : {
              type: 'menubar',
              border: '0 0 1 0',
              items: $_8i78rftgjh8lz3ka.createMenuButtons(editor)
            },
            $_fudqhrtfjh8lz3k7.createToolbars(editor, getToolbarSize(editor))
          ]
        },
        $_5buua9tkjh8lz3kq.hasSidebar(editor) ? editAreaContainer(editor) : editArea('1 0 0 0')
      ]
    });
    $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel);
    if (getResize(editor) !== 'none') {
      resizeHandleCtrl = {
        type: 'resizehandle',
        direction: getResize(editor),
        onResizeStart: function () {
          var elm = editor.getContentAreaContainer().firstChild;
          startSize = {
            width: elm.clientWidth,
            height: elm.clientHeight
          };
        },
        onResize: function (e) {
          if (getResize(editor) === 'both') {
            $_5toavetjjh8lz3ko.resizeTo(editor, startSize.width + e.deltaX, startSize.height + e.deltaY);
          } else {
            $_5toavetjjh8lz3ko.resizeTo(editor, null, startSize.height + e.deltaY);
          }
        }
      };
    }
    if (hasStatusbar(editor)) {
      var linkHtml = '<a href="https://www.tinymce.com/?utm_campaign=editor_referral&amp;utm_medium=poweredby&amp;utm_source=tinymce" rel="noopener" target="_blank" role="presentation" tabindex="-1">tinymce</a>';
      var html = global$5.translate([
        'Powered by {0}',
        linkHtml
      ]);
      var brandingLabel = isBrandingEnabled(editor) ? {
        type: 'label',
        classes: 'branding',
        html: ' ' + html
      } : null;
      panel.add({
        type: 'panel',
        name: 'statusbar',
        classes: 'statusbar',
        layout: 'flow',
        border: '1 0 0 0',
        ariaRoot: true,
        items: [
          {
            type: 'elementpath',
            editor: editor
          },
          resizeHandleCtrl,
          brandingLabel
        ]
      });
    }
    $_aycuj2t7jh8lz3jp.fireBeforeRenderUI(editor);
    editor.on('SwitchMode', switchMode(panel));
    panel.renderBefore(args.targetNode).reflow();
    if (isReadOnly(editor)) {
      editor.setMode('readonly');
    }
    if (args.width) {
      DOM$2.setStyle(panel.getEl(), 'width', args.width);
    }
    editor.on('remove', function () {
      panel.remove();
      panel = null;
    });
    $_47hpztt8jh8lz3jq.addKeys(editor, panel);
    $_5kodmdt9jh8lz3js.addContextualToolbars(editor);
    return {
      iframeContainer: panel.find('#iframe')[0].getEl(),
      editorContainer: panel.getEl()
    };
  };
  var $_4cj0a3t3jh8lz3jk = { render: render };

  var global$9 = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');

  var count = 0;
  var funcs = {
    id: function () {
      return 'mceu_' + count++;
    },
    create: function (name, attrs, children) {
      var elm = document.createElement(name);
      global$3.DOM.setAttribs(elm, attrs);
      if (typeof children === 'string') {
        elm.innerHTML = children;
      } else {
        global$2.each(children, function (child) {
          if (child.nodeType) {
            elm.appendChild(child);
          }
        });
      }
      return elm;
    },
    createFragment: function (html) {
      return global$3.DOM.createFragment(html);
    },
    getWindowSize: function () {
      return global$3.DOM.getViewPort();
    },
    getSize: function (elm) {
      var width, height;
      if (elm.getBoundingClientRect) {
        var rect = elm.getBoundingClientRect();
        width = Math.max(rect.width || rect.right - rect.left, elm.offsetWidth);
        height = Math.max(rect.height || rect.bottom - rect.bottom, elm.offsetHeight);
      } else {
        width = elm.offsetWidth;
        height = elm.offsetHeight;
      }
      return {
        width: width,
        height: height
      };
    },
    getPos: function (elm, root) {
      return global$3.DOM.getPos(elm, root || funcs.getContainer());
    },
    getContainer: function () {
      return global$8.container ? global$8.container : document.body;
    },
    getViewPort: function (win) {
      return global$3.DOM.getViewPort(win);
    },
    get: function (id) {
      return document.getElementById(id);
    },
    addClass: function (elm, cls) {
      return global$3.DOM.addClass(elm, cls);
    },
    removeClass: function (elm, cls) {
      return global$3.DOM.removeClass(elm, cls);
    },
    hasClass: function (elm, cls) {
      return global$3.DOM.hasClass(elm, cls);
    },
    toggleClass: function (elm, cls, state) {
      return global$3.DOM.toggleClass(elm, cls, state);
    },
    css: function (elm, name, value) {
      return global$3.DOM.setStyle(elm, name, value);
    },
    getRuntimeStyle: function (elm, name) {
      return global$3.DOM.getStyle(elm, name, true);
    },
    on: function (target, name, callback, scope) {
      return global$3.DOM.bind(target, name, callback, scope);
    },
    off: function (target, name, callback) {
      return global$3.DOM.unbind(target, name, callback);
    },
    fire: function (target, name, args) {
      return global$3.DOM.fire(target, name, args);
    },
    innerHtml: function (elm, html) {
      global$3.DOM.setHTML(elm, html);
    }
  };

  var isStatic = function (elm) {
    return funcs.getRuntimeStyle(elm, 'position') === 'static';
  };
  var isFixed = function (ctrl) {
    return ctrl.state.get('fixed');
  };
  function calculateRelativePosition(ctrl, targetElm, rel) {
    var ctrlElm, pos, x, y, selfW, selfH, targetW, targetH, viewport, size;
    viewport = getWindowViewPort();
    pos = funcs.getPos(targetElm, $_1jk3jvtcjh8lz3jy.getUiContainer(ctrl));
    x = pos.x;
    y = pos.y;
    if (isFixed(ctrl) && isStatic(document.body)) {
      x -= viewport.x;
      y -= viewport.y;
    }
    ctrlElm = ctrl.getEl();
    size = funcs.getSize(ctrlElm);
    selfW = size.width;
    selfH = size.height;
    size = funcs.getSize(targetElm);
    targetW = size.width;
    targetH = size.height;
    rel = (rel || '').split('');
    if (rel[0] === 'b') {
      y += targetH;
    }
    if (rel[1] === 'r') {
      x += targetW;
    }
    if (rel[0] === 'c') {
      y += Math.round(targetH / 2);
    }
    if (rel[1] === 'c') {
      x += Math.round(targetW / 2);
    }
    if (rel[3] === 'b') {
      y -= selfH;
    }
    if (rel[4] === 'r') {
      x -= selfW;
    }
    if (rel[3] === 'c') {
      y -= Math.round(selfH / 2);
    }
    if (rel[4] === 'c') {
      x -= Math.round(selfW / 2);
    }
    return {
      x: x,
      y: y,
      w: selfW,
      h: selfH
    };
  }
  var getUiContainerViewPort = function (customUiContainer) {
    return {
      x: 0,
      y: 0,
      w: customUiContainer.scrollWidth - 1,
      h: customUiContainer.scrollHeight - 1
    };
  };
  var getWindowViewPort = function () {
    var win = window;
    var x = Math.max(win.pageXOffset, document.body.scrollLeft, document.documentElement.scrollLeft);
    var y = Math.max(win.pageYOffset, document.body.scrollTop, document.documentElement.scrollTop);
    var w = win.innerWidth || document.documentElement.clientWidth;
    var h = win.innerHeight || document.documentElement.clientHeight;
    return {
      x: x,
      y: y,
      w: x + w,
      h: y + h
    };
  };
  var getViewPortRect = function (ctrl) {
    var customUiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(ctrl);
    return customUiContainer && !isFixed(ctrl) ? getUiContainerViewPort(customUiContainer) : getWindowViewPort();
  };
  var $_d97gfctrjh8lz3lm = {
    testMoveRel: function (elm, rels) {
      var viewPortRect = getViewPortRect(this);
      for (var i = 0; i < rels.length; i++) {
        var pos = calculateRelativePosition(this, elm, rels[i]);
        if (isFixed(this)) {
          if (pos.x > 0 && pos.x + pos.w < viewPortRect.w && pos.y > 0 && pos.y + pos.h < viewPortRect.h) {
            return rels[i];
          }
        } else {
          if (pos.x > viewPortRect.x && pos.x + pos.w < viewPortRect.w && pos.y > viewPortRect.y && pos.y + pos.h < viewPortRect.h) {
            return rels[i];
          }
        }
      }
      return rels[0];
    },
    moveRel: function (elm, rel) {
      if (typeof rel !== 'string') {
        rel = this.testMoveRel(elm, rel);
      }
      var pos = calculateRelativePosition(this, elm, rel);
      return this.moveTo(pos.x, pos.y);
    },
    moveBy: function (dx, dy) {
      var self = this, rect = self.layoutRect();
      self.moveTo(rect.x + dx, rect.y + dy);
      return self;
    },
    moveTo: function (x, y) {
      var self = this;
      function constrain(value, max, size) {
        if (value < 0) {
          return 0;
        }
        if (value + size > max) {
          value = max - size;
          return value < 0 ? 0 : value;
        }
        return value;
      }
      if (self.settings.constrainToViewport) {
        var viewPortRect = getViewPortRect(this);
        var layoutRect = self.layoutRect();
        x = constrain(x, viewPortRect.w, layoutRect.w);
        y = constrain(y, viewPortRect.h, layoutRect.h);
      }
      var uiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(self);
      if (uiContainer && isStatic(uiContainer) && !isFixed(self)) {
        x -= uiContainer.scrollLeft;
        y -= uiContainer.scrollTop;
      }
      if (uiContainer) {
        x += 1;
        y += 1;
      }
      if (self.state.get('rendered')) {
        self.layoutRect({
          x: x,
          y: y
        }).repaint();
      } else {
        self.settings.x = x;
        self.settings.y = y;
      }
      self.fire('move', {
        x: x,
        y: y
      });
      return self;
    }
  };

  var global$10 = tinymce.util.Tools.resolve('tinymce.util.Class');

  var global$11 = tinymce.util.Tools.resolve('tinymce.util.EventDispatcher');

  var $_focdcktxjh8lz3mn = {
    parseBox: function (value) {
      var len;
      var radix = 10;
      if (!value) {
        return;
      }
      if (typeof value === 'number') {
        value = value || 0;
        return {
          top: value,
          left: value,
          bottom: value,
          right: value
        };
      }
      value = value.split(' ');
      len = value.length;
      if (len === 1) {
        value[1] = value[2] = value[3] = value[0];
      } else if (len === 2) {
        value[2] = value[0];
        value[3] = value[1];
      } else if (len === 3) {
        value[3] = value[1];
      }
      return {
        top: parseInt(value[0], radix) || 0,
        right: parseInt(value[1], radix) || 0,
        bottom: parseInt(value[2], radix) || 0,
        left: parseInt(value[3], radix) || 0
      };
    },
    measureBox: function (elm, prefix) {
      function getStyle(name) {
        var defaultView = elm.ownerDocument.defaultView;
        if (defaultView) {
          var computedStyle = defaultView.getComputedStyle(elm, null);
          if (computedStyle) {
            name = name.replace(/[A-Z]/g, function (a) {
              return '-' + a;
            });
            return computedStyle.getPropertyValue(name);
          } else {
            return null;
          }
        }
        return elm.currentStyle[name];
      }
      function getSide(name) {
        var val = parseFloat(getStyle(name));
        return isNaN(val) ? 0 : val;
      }
      return {
        top: getSide(prefix + 'TopWidth'),
        right: getSide(prefix + 'RightWidth'),
        bottom: getSide(prefix + 'BottomWidth'),
        left: getSide(prefix + 'LeftWidth')
      };
    }
  };

  function noop$1() {
  }
  function ClassList(onchange) {
    this.cls = [];
    this.cls._map = {};
    this.onchange = onchange || noop$1;
    this.prefix = '';
  }
  global$2.extend(ClassList.prototype, {
    add: function (cls) {
      if (cls && !this.contains(cls)) {
        this.cls._map[cls] = true;
        this.cls.push(cls);
        this._change();
      }
      return this;
    },
    remove: function (cls) {
      if (this.contains(cls)) {
        var i = void 0;
        for (i = 0; i < this.cls.length; i++) {
          if (this.cls[i] === cls) {
            break;
          }
        }
        this.cls.splice(i, 1);
        delete this.cls._map[cls];
        this._change();
      }
      return this;
    },
    toggle: function (cls, state) {
      var curState = this.contains(cls);
      if (curState !== state) {
        if (curState) {
          this.remove(cls);
        } else {
          this.add(cls);
        }
        this._change();
      }
      return this;
    },
    contains: function (cls) {
      return !!this.cls._map[cls];
    },
    _change: function () {
      delete this.clsValue;
      this.onchange.call(this);
    }
  });
  ClassList.prototype.toString = function () {
    var value;
    if (this.clsValue) {
      return this.clsValue;
    }
    value = '';
    for (var i = 0; i < this.cls.length; i++) {
      if (i > 0) {
        value += ' ';
      }
      value += this.prefix + this.cls[i];
    }
    return value;
  };

  function unique(array) {
    var uniqueItems = [];
    var i = array.length, item;
    while (i--) {
      item = array[i];
      if (!item.__checked) {
        uniqueItems.push(item);
        item.__checked = 1;
      }
    }
    i = uniqueItems.length;
    while (i--) {
      delete uniqueItems[i].__checked;
    }
    return uniqueItems;
  }
  var expression = /^([\w\\*]+)?(?:#([\w\-\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i;
  var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g;
  var whiteSpace = /^\s*|\s*$/g;
  var Collection;
  var Selector = global$10.extend({
    init: function (selector) {
      var match = this.match;
      function compileNameFilter(name) {
        if (name) {
          name = name.toLowerCase();
          return function (item) {
            return name === '*' || item.type === name;
          };
        }
      }
      function compileIdFilter(id) {
        if (id) {
          return function (item) {
            return item._name === id;
          };
        }
      }
      function compileClassesFilter(classes) {
        if (classes) {
          classes = classes.split('.');
          return function (item) {
            var i = classes.length;
            while (i--) {
              if (!item.classes.contains(classes[i])) {
                return false;
              }
            }
            return true;
          };
        }
      }
      function compileAttrFilter(name, cmp, check) {
        if (name) {
          return function (item) {
            var value = item[name] ? item[name]() : '';
            return !cmp ? !!check : cmp === '=' ? value === check : cmp === '*=' ? value.indexOf(check) >= 0 : cmp === '~=' ? (' ' + value + ' ').indexOf(' ' + check + ' ') >= 0 : cmp === '!=' ? value !== check : cmp === '^=' ? value.indexOf(check) === 0 : cmp === '$=' ? value.substr(value.length - check.length) === check : false;
          };
        }
      }
      function compilePsuedoFilter(name) {
        var notSelectors;
        if (name) {
          name = /(?:not\((.+)\))|(.+)/i.exec(name);
          if (!name[1]) {
            name = name[2];
            return function (item, index, length) {
              return name === 'first' ? index === 0 : name === 'last' ? index === length - 1 : name === 'even' ? index % 2 === 0 : name === 'odd' ? index % 2 === 1 : item[name] ? item[name]() : false;
            };
          }
          notSelectors = parseChunks(name[1], []);
          return function (item) {
            return !match(item, notSelectors);
          };
        }
      }
      function compile(selector, filters, direct) {
        var parts;
        function add(filter) {
          if (filter) {
            filters.push(filter);
          }
        }
        parts = expression.exec(selector.replace(whiteSpace, ''));
        add(compileNameFilter(parts[1]));
        add(compileIdFilter(parts[2]));
        add(compileClassesFilter(parts[3]));
        add(compileAttrFilter(parts[4], parts[5], parts[6]));
        add(compilePsuedoFilter(parts[7]));
        filters.pseudo = !!parts[7];
        filters.direct = direct;
        return filters;
      }
      function parseChunks(selector, selectors) {
        var parts = [];
        var extra, matches, i;
        do {
          chunker.exec('');
          matches = chunker.exec(selector);
          if (matches) {
            selector = matches[3];
            parts.push(matches[1]);
            if (matches[2]) {
              extra = matches[3];
              break;
            }
          }
        } while (matches);
        if (extra) {
          parseChunks(extra, selectors);
        }
        selector = [];
        for (i = 0; i < parts.length; i++) {
          if (parts[i] !== '>') {
            selector.push(compile(parts[i], [], parts[i - 1] === '>'));
          }
        }
        selectors.push(selector);
        return selectors;
      }
      this._selectors = parseChunks(selector, []);
    },
    match: function (control, selectors) {
      var i, l, si, sl, selector, fi, fl, filters, index, length, siblings, count, item;
      selectors = selectors || this._selectors;
      for (i = 0, l = selectors.length; i < l; i++) {
        selector = selectors[i];
        sl = selector.length;
        item = control;
        count = 0;
        for (si = sl - 1; si >= 0; si--) {
          filters = selector[si];
          while (item) {
            if (filters.pseudo) {
              siblings = item.parent().items();
              index = length = siblings.length;
              while (index--) {
                if (siblings[index] === item) {
                  break;
                }
              }
            }
            for (fi = 0, fl = filters.length; fi < fl; fi++) {
              if (!filters[fi](item, index, length)) {
                fi = fl + 1;
                break;
              }
            }
            if (fi === fl) {
              count++;
              break;
            } else {
              if (si === sl - 1) {
                break;
              }
            }
            item = item.parent();
          }
        }
        if (count === sl) {
          return true;
        }
      }
      return false;
    },
    find: function (container) {
      var matches = [], i, l;
      var selectors = this._selectors;
      function collect(items, selector, index) {
        var i, l, fi, fl, item;
        var filters = selector[index];
        for (i = 0, l = items.length; i < l; i++) {
          item = items[i];
          for (fi = 0, fl = filters.length; fi < fl; fi++) {
            if (!filters[fi](item, i, l)) {
              fi = fl + 1;
              break;
            }
          }
          if (fi === fl) {
            if (index === selector.length - 1) {
              matches.push(item);
            } else {
              if (item.items) {
                collect(item.items(), selector, index + 1);
              }
            }
          } else if (filters.direct) {
            return;
          }
          if (item.items) {
            collect(item.items(), selector, index);
          }
        }
      }
      if (container.items) {
        for (i = 0, l = selectors.length; i < l; i++) {
          collect(container.items(), selectors[i], 0);
        }
        if (l > 1) {
          matches = unique(matches);
        }
      }
      if (!Collection) {
        Collection = Selector.Collection;
      }
      return new Collection(matches);
    }
  });

  var Collection$1;
  var proto;
  var push$1 = Array.prototype.push;
  var slice$1 = Array.prototype.slice;
  proto = {
    length: 0,
    init: function (items) {
      if (items) {
        this.add(items);
      }
    },
    add: function (items) {
      var self = this;
      if (!global$2.isArray(items)) {
        if (items instanceof Collection$1) {
          self.add(items.toArray());
        } else {
          push$1.call(self, items);
        }
      } else {
        push$1.apply(self, items);
      }
      return self;
    },
    set: function (items) {
      var self = this;
      var len = self.length;
      var i;
      self.length = 0;
      self.add(items);
      for (i = self.length; i < len; i++) {
        delete self[i];
      }
      return self;
    },
    filter: function (selector) {
      var self = this;
      var i, l;
      var matches = [];
      var item, match;
      if (typeof selector === 'string') {
        selector = new Selector(selector);
        match = function (item) {
          return selector.match(item);
        };
      } else {
        match = selector;
      }
      for (i = 0, l = self.length; i < l; i++) {
        item = self[i];
        if (match(item)) {
          matches.push(item);
        }
      }
      return new Collection$1(matches);
    },
    slice: function () {
      return new Collection$1(slice$1.apply(this, arguments));
    },
    eq: function (index) {
      return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
    },
    each: function (callback) {
      global$2.each(this, callback);
      return this;
    },
    toArray: function () {
      return global$2.toArray(this);
    },
    indexOf: function (ctrl) {
      var self = this;
      var i = self.length;
      while (i--) {
        if (self[i] === ctrl) {
          break;
        }
      }
      return i;
    },
    reverse: function () {
      return new Collection$1(global$2.toArray(this).reverse());
    },
    hasClass: function (cls) {
      return this[0] ? this[0].classes.contains(cls) : false;
    },
    prop: function (name, value) {
      var self = this;
      var item;
      if (value !== undefined) {
        self.each(function (item) {
          if (item[name]) {
            item[name](value);
          }
        });
        return self;
      }
      item = self[0];
      if (item && item[name]) {
        return item[name]();
      }
    },
    exec: function (name) {
      var self = this, args = global$2.toArray(arguments).slice(1);
      self.each(function (item) {
        if (item[name]) {
          item[name].apply(item, args);
        }
      });
      return self;
    },
    remove: function () {
      var i = this.length;
      while (i--) {
        this[i].remove();
      }
      return this;
    },
    addClass: function (cls) {
      return this.each(function (item) {
        item.classes.add(cls);
      });
    },
    removeClass: function (cls) {
      return this.each(function (item) {
        item.classes.remove(cls);
      });
    }
  };
  global$2.each('fire on off show hide append prepend before after reflow'.split(' '), function (name) {
    proto[name] = function () {
      var args = global$2.toArray(arguments);
      this.each(function (ctrl) {
        if (name in ctrl) {
          ctrl[name].apply(ctrl, args);
        }
      });
      return this;
    };
  });
  global$2.each('text name disabled active selected checked visible parent value data'.split(' '), function (name) {
    proto[name] = function (value) {
      return this.prop(name, value);
    };
  });
  Collection$1 = global$10.extend(proto);
  Selector.Collection = Collection$1;
  var Collection$2 = Collection$1;

  var Binding = function (settings) {
    this.create = settings.create;
  };
  Binding.create = function (model, name) {
    return new Binding({
      create: function (otherModel, otherName) {
        var bindings;
        var fromSelfToOther = function (e) {
          otherModel.set(otherName, e.value);
        };
        var fromOtherToSelf = function (e) {
          model.set(name, e.value);
        };
        otherModel.on('change:' + otherName, fromOtherToSelf);
        model.on('change:' + name, fromSelfToOther);
        bindings = otherModel._bindings;
        if (!bindings) {
          bindings = otherModel._bindings = [];
          otherModel.on('destroy', function () {
            var i = bindings.length;
            while (i--) {
              bindings[i]();
            }
          });
        }
        bindings.push(function () {
          model.off('change:' + name, fromSelfToOther);
        });
        return model.get(name);
      }
    });
  };

  var global$12 = tinymce.util.Tools.resolve('tinymce.util.Observable');

  function isNode(node) {
    return node.nodeType > 0;
  }
  function isEqual(a, b) {
    var k, checked;
    if (a === b) {
      return true;
    }
    if (a === null || b === null) {
      return a === b;
    }
    if (typeof a !== 'object' || typeof b !== 'object') {
      return a === b;
    }
    if (global$2.isArray(b)) {
      if (a.length !== b.length) {
        return false;
      }
      k = a.length;
      while (k--) {
        if (!isEqual(a[k], b[k])) {
          return false;
        }
      }
    }
    if (isNode(a) || isNode(b)) {
      return a === b;
    }
    checked = {};
    for (k in b) {
      if (!isEqual(a[k], b[k])) {
        return false;
      }
      checked[k] = true;
    }
    for (k in a) {
      if (!checked[k] && !isEqual(a[k], b[k])) {
        return false;
      }
    }
    return true;
  }
  var ObservableObject = global$10.extend({
    Mixins: [global$12],
    init: function (data) {
      var name, value;
      data = data || {};
      for (name in data) {
        value = data[name];
        if (value instanceof Binding) {
          data[name] = value.create(this, name);
        }
      }
      this.data = data;
    },
    set: function (name, value) {
      var key, args;
      var oldValue = this.data[name];
      if (value instanceof Binding) {
        value = value.create(this, name);
      }
      if (typeof name === 'object') {
        for (key in name) {
          this.set(key, name[key]);
        }
        return this;
      }
      if (!isEqual(oldValue, value)) {
        this.data[name] = value;
        args = {
          target: this,
          name: name,
          value: value,
          oldValue: oldValue
        };
        this.fire('change:' + name, args);
        this.fire('change', args);
      }
      return this;
    },
    get: function (name) {
      return this.data[name];
    },
    has: function (name) {
      return name in this.data;
    },
    bind: function (name) {
      return Binding.create(this, name);
    },
    destroy: function () {
      this.fire('destroy');
    }
  });

  var dirtyCtrls = {};
  var animationFrameRequested;
  var $_ef12j5u4jh8lz3nl = {
    add: function (ctrl) {
      var parent = ctrl.parent();
      if (parent) {
        if (!parent._layout || parent._layout.isNative()) {
          return;
        }
        if (!dirtyCtrls[parent._id]) {
          dirtyCtrls[parent._id] = parent;
        }
        if (!animationFrameRequested) {
          animationFrameRequested = true;
          global$7.requestAnimationFrame(function () {
            var id, ctrl;
            animationFrameRequested = false;
            for (id in dirtyCtrls) {
              ctrl = dirtyCtrls[id];
              if (ctrl.state.get('rendered')) {
                ctrl.reflow();
              }
            }
            dirtyCtrls = {};
          }, document.body);
        }
      }
    },
    remove: function (ctrl) {
      if (dirtyCtrls[ctrl._id]) {
        delete dirtyCtrls[ctrl._id];
      }
    }
  };

  var hasMouseWheelEventSupport = 'onmousewheel' in document;
  var hasWheelEventSupport = false;
  var classPrefix = 'mce-';
  var Control;
  var idCounter = 0;
  var proto$1 = {
    Statics: { classPrefix: classPrefix },
    isRtl: function () {
      return Control.rtl;
    },
    classPrefix: classPrefix,
    init: function (settings) {
      var self = this;
      var classes, defaultClasses;
      function applyClasses(classes) {
        var i;
        classes = classes.split(' ');
        for (i = 0; i < classes.length; i++) {
          self.classes.add(classes[i]);
        }
      }
      self.settings = settings = global$2.extend({}, self.Defaults, settings);
      self._id = settings.id || 'mceu_' + idCounter++;
      self._aria = { role: settings.role };
      self._elmCache = {};
      self.$ = global$9;
      self.state = new ObservableObject({
        visible: true,
        active: false,
        disabled: false,
        value: ''
      });
      self.data = new ObservableObject(settings.data);
      self.classes = new ClassList(function () {
        if (self.state.get('rendered')) {
          self.getEl().className = this.toString();
        }
      });
      self.classes.prefix = self.classPrefix;
      classes = settings.classes;
      if (classes) {
        if (self.Defaults) {
          defaultClasses = self.Defaults.classes;
          if (defaultClasses && classes !== defaultClasses) {
            applyClasses(defaultClasses);
          }
        }
        applyClasses(classes);
      }
      global$2.each('title text name visible disabled active value'.split(' '), function (name) {
        if (name in settings) {
          self[name](settings[name]);
        }
      });
      self.on('click', function () {
        if (self.disabled()) {
          return false;
        }
      });
      self.settings = settings;
      self.borderBox = $_focdcktxjh8lz3mn.parseBox(settings.border);
      self.paddingBox = $_focdcktxjh8lz3mn.parseBox(settings.padding);
      self.marginBox = $_focdcktxjh8lz3mn.parseBox(settings.margin);
      if (settings.hidden) {
        self.hide();
      }
    },
    Properties: 'parent,name',
    getContainerElm: function () {
      var uiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(this);
      return uiContainer ? uiContainer : funcs.getContainer();
    },
    getParentCtrl: function (elm) {
      var ctrl;
      var lookup = this.getRoot().controlIdLookup;
      while (elm && lookup) {
        ctrl = lookup[elm.id];
        if (ctrl) {
          break;
        }
        elm = elm.parentNode;
      }
      return ctrl;
    },
    initLayoutRect: function () {
      var self = this;
      var settings = self.settings;
      var borderBox, layoutRect;
      var elm = self.getEl();
      var width, height, minWidth, minHeight, autoResize;
      var startMinWidth, startMinHeight, initialSize;
      borderBox = self.borderBox = self.borderBox || $_focdcktxjh8lz3mn.measureBox(elm, 'border');
      self.paddingBox = self.paddingBox || $_focdcktxjh8lz3mn.measureBox(elm, 'padding');
      self.marginBox = self.marginBox || $_focdcktxjh8lz3mn.measureBox(elm, 'margin');
      initialSize = funcs.getSize(elm);
      startMinWidth = settings.minWidth;
      startMinHeight = settings.minHeight;
      minWidth = startMinWidth || initialSize.width;
      minHeight = startMinHeight || initialSize.height;
      width = settings.width;
      height = settings.height;
      autoResize = settings.autoResize;
      autoResize = typeof autoResize !== 'undefined' ? autoResize : !width && !height;
      width = width || minWidth;
      height = height || minHeight;
      var deltaW = borderBox.left + borderBox.right;
      var deltaH = borderBox.top + borderBox.bottom;
      var maxW = settings.maxWidth || 65535;
      var maxH = settings.maxHeight || 65535;
      self._layoutRect = layoutRect = {
        x: settings.x || 0,
        y: settings.y || 0,
        w: width,
        h: height,
        deltaW: deltaW,
        deltaH: deltaH,
        contentW: width - deltaW,
        contentH: height - deltaH,
        innerW: width - deltaW,
        innerH: height - deltaH,
        startMinWidth: startMinWidth || 0,
        startMinHeight: startMinHeight || 0,
        minW: Math.min(minWidth, maxW),
        minH: Math.min(minHeight, maxH),
        maxW: maxW,
        maxH: maxH,
        autoResize: autoResize,
        scrollW: 0
      };
      self._lastLayoutRect = {};
      return layoutRect;
    },
    layoutRect: function (newRect) {
      var self = this;
      var curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, repaintControls;
      if (!curRect) {
        curRect = self.initLayoutRect();
      }
      if (newRect) {
        deltaWidth = curRect.deltaW;
        deltaHeight = curRect.deltaH;
        if (newRect.x !== undefined) {
          curRect.x = newRect.x;
        }
        if (newRect.y !== undefined) {
          curRect.y = newRect.y;
        }
        if (newRect.minW !== undefined) {
          curRect.minW = newRect.minW;
        }
        if (newRect.minH !== undefined) {
          curRect.minH = newRect.minH;
        }
        size = newRect.w;
        if (size !== undefined) {
          size = size < curRect.minW ? curRect.minW : size;
          size = size > curRect.maxW ? curRect.maxW : size;
          curRect.w = size;
          curRect.innerW = size - deltaWidth;
        }
        size = newRect.h;
        if (size !== undefined) {
          size = size < curRect.minH ? curRect.minH : size;
          size = size > curRect.maxH ? curRect.maxH : size;
          curRect.h = size;
          curRect.innerH = size - deltaHeight;
        }
        size = newRect.innerW;
        if (size !== undefined) {
          size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size;
          size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size;
          curRect.innerW = size;
          curRect.w = size + deltaWidth;
        }
        size = newRect.innerH;
        if (size !== undefined) {
          size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size;
          size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size;
          curRect.innerH = size;
          curRect.h = size + deltaHeight;
        }
        if (newRect.contentW !== undefined) {
          curRect.contentW = newRect.contentW;
        }
        if (newRect.contentH !== undefined) {
          curRect.contentH = newRect.contentH;
        }
        lastLayoutRect = self._lastLayoutRect;
        if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y || lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) {
          repaintControls = Control.repaintControls;
          if (repaintControls) {
            if (repaintControls.map && !repaintControls.map[self._id]) {
              repaintControls.push(self);
              repaintControls.map[self._id] = true;
            }
          }
          lastLayoutRect.x = curRect.x;
          lastLayoutRect.y = curRect.y;
          lastLayoutRect.w = curRect.w;
          lastLayoutRect.h = curRect.h;
        }
        return self;
      }
      return curRect;
    },
    repaint: function () {
      var self = this;
      var style, bodyStyle, bodyElm, rect, borderBox;
      var borderW, borderH, lastRepaintRect, round, value;
      round = !document.createRange ? Math.round : function (value) {
        return value;
      };
      style = self.getEl().style;
      rect = self._layoutRect;
      lastRepaintRect = self._lastRepaintRect || {};
      borderBox = self.borderBox;
      borderW = borderBox.left + borderBox.right;
      borderH = borderBox.top + borderBox.bottom;
      if (rect.x !== lastRepaintRect.x) {
        style.left = round(rect.x) + 'px';
        lastRepaintRect.x = rect.x;
      }
      if (rect.y !== lastRepaintRect.y) {
        style.top = round(rect.y) + 'px';
        lastRepaintRect.y = rect.y;
      }
      if (rect.w !== lastRepaintRect.w) {
        value = round(rect.w - borderW);
        style.width = (value >= 0 ? value : 0) + 'px';
        lastRepaintRect.w = rect.w;
      }
      if (rect.h !== lastRepaintRect.h) {
        value = round(rect.h - borderH);
        style.height = (value >= 0 ? value : 0) + 'px';
        lastRepaintRect.h = rect.h;
      }
      if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) {
        value = round(rect.innerW);
        bodyElm = self.getEl('body');
        if (bodyElm) {
          bodyStyle = bodyElm.style;
          bodyStyle.width = (value >= 0 ? value : 0) + 'px';
        }
        lastRepaintRect.innerW = rect.innerW;
      }
      if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) {
        value = round(rect.innerH);
        bodyElm = bodyElm || self.getEl('body');
        if (bodyElm) {
          bodyStyle = bodyStyle || bodyElm.style;
          bodyStyle.height = (value >= 0 ? value : 0) + 'px';
        }
        lastRepaintRect.innerH = rect.innerH;
      }
      self._lastRepaintRect = lastRepaintRect;
      self.fire('repaint', {}, false);
    },
    updateLayoutRect: function () {
      var self = this;
      self.parent()._lastRect = null;
      funcs.css(self.getEl(), {
        width: '',
        height: ''
      });
      self._layoutRect = self._lastRepaintRect = self._lastLayoutRect = null;
      self.initLayoutRect();
    },
    on: function (name, callback) {
      var self = this;
      function resolveCallbackName(name) {
        var callback, scope;
        if (typeof name !== 'string') {
          return name;
        }
        return function (e) {
          if (!callback) {
            self.parentsAndSelf().each(function (ctrl) {
              var callbacks = ctrl.settings.callbacks;
              if (callbacks && (callback = callbacks[name])) {
                scope = ctrl;
                return false;
              }
            });
          }
          if (!callback) {
            e.action = name;
            this.fire('execute', e);
            return;
          }
          return callback.call(scope, e);
        };
      }
      getEventDispatcher(self).on(name, resolveCallbackName(callback));
      return self;
    },
    off: function (name, callback) {
      getEventDispatcher(this).off(name, callback);
      return this;
    },
    fire: function (name, args, bubble) {
      var self = this;
      args = args || {};
      if (!args.control) {
        args.control = self;
      }
      args = getEventDispatcher(self).fire(name, args);
      if (bubble !== false && self.parent) {
        var parent_1 = self.parent();
        while (parent_1 && !args.isPropagationStopped()) {
          parent_1.fire(name, args, false);
          parent_1 = parent_1.parent();
        }
      }
      return args;
    },
    hasEventListeners: function (name) {
      return getEventDispatcher(this).has(name);
    },
    parents: function (selector) {
      var self = this;
      var ctrl, parents = new Collection$2();
      for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) {
        parents.add(ctrl);
      }
      if (selector) {
        parents = parents.filter(selector);
      }
      return parents;
    },
    parentsAndSelf: function (selector) {
      return new Collection$2(this).add(this.parents(selector));
    },
    next: function () {
      var parentControls = this.parent().items();
      return parentControls[parentControls.indexOf(this) + 1];
    },
    prev: function () {
      var parentControls = this.parent().items();
      return parentControls[parentControls.indexOf(this) - 1];
    },
    innerHtml: function (html) {
      this.$el.html(html);
      return this;
    },
    getEl: function (suffix) {
      var id = suffix ? this._id + '-' + suffix : this._id;
      if (!this._elmCache[id]) {
        this._elmCache[id] = global$9('#' + id)[0];
      }
      return this._elmCache[id];
    },
    show: function () {
      return this.visible(true);
    },
    hide: function () {
      return this.visible(false);
    },
    focus: function () {
      try {
        this.getEl().focus();
      } catch (ex) {
      }
      return this;
    },
    blur: function () {
      this.getEl().blur();
      return this;
    },
    aria: function (name, value) {
      var self = this, elm = self.getEl(self.ariaTarget);
      if (typeof value === 'undefined') {
        return self._aria[name];
      }
      self._aria[name] = value;
      if (self.state.get('rendered')) {
        elm.setAttribute(name === 'role' ? name : 'aria-' + name, value);
      }
      return self;
    },
    encode: function (text, translate) {
      if (translate !== false) {
        text = this.translate(text);
      }
      return (text || '').replace(/[&<>"]/g, function (match) {
        return '&#' + match.charCodeAt(0) + ';';
      });
    },
    translate: function (text) {
      return Control.translate ? Control.translate(text) : text;
    },
    before: function (items) {
      var self = this, parent = self.parent();
      if (parent) {
        parent.insert(items, parent.items().indexOf(self), true);
      }
      return self;
    },
    after: function (items) {
      var self = this, parent = self.parent();
      if (parent) {
        parent.insert(items, parent.items().indexOf(self));
      }
      return self;
    },
    remove: function () {
      var self = this;
      var elm = self.getEl();
      var parent = self.parent();
      var newItems, i;
      if (self.items) {
        var controls = self.items().toArray();
        i = controls.length;
        while (i--) {
          controls[i].remove();
        }
      }
      if (parent && parent.items) {
        newItems = [];
        parent.items().each(function (item) {
          if (item !== self) {
            newItems.push(item);
          }
        });
        parent.items().set(newItems);
        parent._lastRect = null;
      }
      if (self._eventsRoot && self._eventsRoot === self) {
        global$9(elm).off();
      }
      var lookup = self.getRoot().controlIdLookup;
      if (lookup) {
        delete lookup[self._id];
      }
      if (elm && elm.parentNode) {
        elm.parentNode.removeChild(elm);
      }
      self.state.set('rendered', false);
      self.state.destroy();
      self.fire('remove');
      return self;
    },
    renderBefore: function (elm) {
      global$9(elm).before(this.renderHtml());
      this.postRender();
      return this;
    },
    renderTo: function (elm) {
      global$9(elm || this.getContainerElm()).append(this.renderHtml());
      this.postRender();
      return this;
    },
    preRender: function () {
    },
    render: function () {
    },
    renderHtml: function () {
      return '<div id="' + this._id + '" class="' + this.classes + '"></div>';
    },
    postRender: function () {
      var self = this;
      var settings = self.settings;
      var elm, box, parent, name, parentEventsRoot;
      self.$el = global$9(self.getEl());
      self.state.set('rendered', true);
      for (name in settings) {
        if (name.indexOf('on') === 0) {
          self.on(name.substr(2), settings[name]);
        }
      }
      if (self._eventsRoot) {
        for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) {
          parentEventsRoot = parent._eventsRoot;
        }
        if (parentEventsRoot) {
          for (name in parentEventsRoot._nativeEvents) {
            self._nativeEvents[name] = true;
          }
        }
      }
      bindPendingEvents(self);
      if (settings.style) {
        elm = self.getEl();
        if (elm) {
          elm.setAttribute('style', settings.style);
          elm.style.cssText = settings.style;
        }
      }
      if (self.settings.border) {
        box = self.borderBox;
        self.$el.css({
          'border-top-width': box.top,
          'border-right-width': box.right,
          'border-bottom-width': box.bottom,
          'border-left-width': box.left
        });
      }
      var root = self.getRoot();
      if (!root.controlIdLookup) {
        root.controlIdLookup = {};
      }
      root.controlIdLookup[self._id] = self;
      for (var key in self._aria) {
        self.aria(key, self._aria[key]);
      }
      if (self.state.get('visible') === false) {
        self.getEl().style.display = 'none';
      }
      self.bindStates();
      self.state.on('change:visible', function (e) {
        var state = e.value;
        var parentCtrl;
        if (self.state.get('rendered')) {
          self.getEl().style.display = state === false ? 'none' : '';
          self.getEl().getBoundingClientRect();
        }
        parentCtrl = self.parent();
        if (parentCtrl) {
          parentCtrl._lastRect = null;
        }
        self.fire(state ? 'show' : 'hide');
        $_ef12j5u4jh8lz3nl.add(self);
      });
      self.fire('postrender', {}, false);
    },
    bindStates: function () {
    },
    scrollIntoView: function (align) {
      function getOffset(elm, rootElm) {
        var x, y, parent = elm;
        x = y = 0;
        while (parent && parent !== rootElm && parent.nodeType) {
          x += parent.offsetLeft || 0;
          y += parent.offsetTop || 0;
          parent = parent.offsetParent;
        }
        return {
          x: x,
          y: y
        };
      }
      var elm = this.getEl(), parentElm = elm.parentNode;
      var x, y, width, height, parentWidth, parentHeight;
      var pos = getOffset(elm, parentElm);
      x = pos.x;
      y = pos.y;
      width = elm.offsetWidth;
      height = elm.offsetHeight;
      parentWidth = parentElm.clientWidth;
      parentHeight = parentElm.clientHeight;
      if (align === 'end') {
        x -= parentWidth - width;
        y -= parentHeight - height;
      } else if (align === 'center') {
        x -= parentWidth / 2 - width / 2;
        y -= parentHeight / 2 - height / 2;
      }
      parentElm.scrollLeft = x;
      parentElm.scrollTop = y;
      return this;
    },
    getRoot: function () {
      var ctrl = this, rootControl;
      var parents = [];
      while (ctrl) {
        if (ctrl.rootControl) {
          rootControl = ctrl.rootControl;
          break;
        }
        parents.push(ctrl);
        rootControl = ctrl;
        ctrl = ctrl.parent();
      }
      if (!rootControl) {
        rootControl = this;
      }
      var i = parents.length;
      while (i--) {
        parents[i].rootControl = rootControl;
      }
      return rootControl;
    },
    reflow: function () {
      $_ef12j5u4jh8lz3nl.remove(this);
      var parent = this.parent();
      if (parent && parent._layout && !parent._layout.isNative()) {
        parent.reflow();
      }
      return this;
    }
  };
  global$2.each('text title visible disabled active value'.split(' '), function (name) {
    proto$1[name] = function (value) {
      if (arguments.length === 0) {
        return this.state.get(name);
      }
      if (typeof value !== 'undefined') {
        this.state.set(name, value);
      }
      return this;
    };
  });
  Control = global$10.extend(proto$1);
  function getEventDispatcher(obj) {
    if (!obj._eventDispatcher) {
      obj._eventDispatcher = new global$11({
        scope: obj,
        toggleEvent: function (name, state) {
          if (state && global$11.isNative(name)) {
            if (!obj._nativeEvents) {
              obj._nativeEvents = {};
            }
            obj._nativeEvents[name] = true;
            if (obj.state.get('rendered')) {
              bindPendingEvents(obj);
            }
          }
        }
      });
    }
    return obj._eventDispatcher;
  }
  function bindPendingEvents(eventCtrl) {
    var i, l, parents, eventRootCtrl, nativeEvents, name;
    function delegate(e) {
      var control = eventCtrl.getParentCtrl(e.target);
      if (control) {
        control.fire(e.type, e);
      }
    }
    function mouseLeaveHandler() {
      var ctrl = eventRootCtrl._lastHoverCtrl;
      if (ctrl) {
        ctrl.fire('mouseleave', { target: ctrl.getEl() });
        ctrl.parents().each(function (ctrl) {
          ctrl.fire('mouseleave', { target: ctrl.getEl() });
        });
        eventRootCtrl._lastHoverCtrl = null;
      }
    }
    function mouseEnterHandler(e) {
      var ctrl = eventCtrl.getParentCtrl(e.target), lastCtrl = eventRootCtrl._lastHoverCtrl, idx = 0, i, parents, lastParents;
      if (ctrl !== lastCtrl) {
        eventRootCtrl._lastHoverCtrl = ctrl;
        parents = ctrl.parents().toArray().reverse();
        parents.push(ctrl);
        if (lastCtrl) {
          lastParents = lastCtrl.parents().toArray().reverse();
          lastParents.push(lastCtrl);
          for (idx = 0; idx < lastParents.length; idx++) {
            if (parents[idx] !== lastParents[idx]) {
              break;
            }
          }
          for (i = lastParents.length - 1; i >= idx; i--) {
            lastCtrl = lastParents[i];
            lastCtrl.fire('mouseleave', { target: lastCtrl.getEl() });
          }
        }
        for (i = idx; i < parents.length; i++) {
          ctrl = parents[i];
          ctrl.fire('mouseenter', { target: ctrl.getEl() });
        }
      }
    }
    function fixWheelEvent(e) {
      e.preventDefault();
      if (e.type === 'mousewheel') {
        e.deltaY = -1 / 40 * e.wheelDelta;
        if (e.wheelDeltaX) {
          e.deltaX = -1 / 40 * e.wheelDeltaX;
        }
      } else {
        e.deltaX = 0;
        e.deltaY = e.detail;
      }
      e = eventCtrl.fire('wheel', e);
    }
    nativeEvents = eventCtrl._nativeEvents;
    if (nativeEvents) {
      parents = eventCtrl.parents().toArray();
      parents.unshift(eventCtrl);
      for (i = 0, l = parents.length; !eventRootCtrl && i < l; i++) {
        eventRootCtrl = parents[i]._eventsRoot;
      }
      if (!eventRootCtrl) {
        eventRootCtrl = parents[parents.length - 1] || eventCtrl;
      }
      eventCtrl._eventsRoot = eventRootCtrl;
      for (l = i, i = 0; i < l; i++) {
        parents[i]._eventsRoot = eventRootCtrl;
      }
      var eventRootDelegates = eventRootCtrl._delegates;
      if (!eventRootDelegates) {
        eventRootDelegates = eventRootCtrl._delegates = {};
      }
      for (name in nativeEvents) {
        if (!nativeEvents) {
          return false;
        }
        if (name === 'wheel' && !hasWheelEventSupport) {
          if (hasMouseWheelEventSupport) {
            global$9(eventCtrl.getEl()).on('mousewheel', fixWheelEvent);
          } else {
            global$9(eventCtrl.getEl()).on('DOMMouseScroll', fixWheelEvent);
          }
          continue;
        }
        if (name === 'mouseenter' || name === 'mouseleave') {
          if (!eventRootCtrl._hasMouseEnter) {
            global$9(eventRootCtrl.getEl()).on('mouseleave', mouseLeaveHandler).on('mouseover', mouseEnterHandler);
            eventRootCtrl._hasMouseEnter = 1;
          }
        } else if (!eventRootDelegates[name]) {
          global$9(eventRootCtrl.getEl()).on(name, delegate);
          eventRootDelegates[name] = true;
        }
        nativeEvents[name] = false;
      }
    }
  }
  var Control$1 = Control;

  var hasTabstopData = function (elm) {
    return elm.getAttribute('data-mce-tabstop') ? true : false;
  };
  function KeyboardNavigation (settings) {
    var root = settings.root;
    var focusedElement, focusedControl;
    function isElement(node) {
      return node && node.nodeType === 1;
    }
    try {
      focusedElement = document.activeElement;
    } catch (ex) {
      focusedElement = document.body;
    }
    focusedControl = root.getParentCtrl(focusedElement);
    function getRole(elm) {
      elm = elm || focusedElement;
      if (isElement(elm)) {
        return elm.getAttribute('role');
      }
      return null;
    }
    function getParentRole(elm) {
      var role, parent = elm || focusedElement;
      while (parent = parent.parentNode) {
        if (role = getRole(parent)) {
          return role;
        }
      }
    }
    function getAriaProp(name) {
      var elm = focusedElement;
      if (isElement(elm)) {
        return elm.getAttribute('aria-' + name);
      }
    }
    function isTextInputElement(elm) {
      var tagName = elm.tagName.toUpperCase();
      return tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT';
    }
    function canFocus(elm) {
      if (isTextInputElement(elm) && !elm.hidden) {
        return true;
      }
      if (hasTabstopData(elm)) {
        return true;
      }
      if (/^(button|menuitem|checkbox|tab|menuitemcheckbox|option|gridcell|slider)$/.test(getRole(elm))) {
        return true;
      }
      return false;
    }
    function getFocusElements(elm) {
      var elements = [];
      function collect(elm) {
        if (elm.nodeType !== 1 || elm.style.display === 'none' || elm.disabled) {
          return;
        }
        if (canFocus(elm)) {
          elements.push(elm);
        }
        for (var i = 0; i < elm.childNodes.length; i++) {
          collect(elm.childNodes[i]);
        }
      }
      collect(elm || root.getEl());
      return elements;
    }
    function getNavigationRoot(targetControl) {
      var navigationRoot, controls;
      targetControl = targetControl || focusedControl;
      controls = targetControl.parents().toArray();
      controls.unshift(targetControl);
      for (var i = 0; i < controls.length; i++) {
        navigationRoot = controls[i];
        if (navigationRoot.settings.ariaRoot) {
          break;
        }
      }
      return navigationRoot;
    }
    function focusFirst(targetControl) {
      var navigationRoot = getNavigationRoot(targetControl);
      var focusElements = getFocusElements(navigationRoot.getEl());
      if (navigationRoot.settings.ariaRemember && 'lastAriaIndex' in navigationRoot) {
        moveFocusToIndex(navigationRoot.lastAriaIndex, focusElements);
      } else {
        moveFocusToIndex(0, focusElements);
      }
    }
    function moveFocusToIndex(idx, elements) {
      if (idx < 0) {
        idx = elements.length - 1;
      } else if (idx >= elements.length) {
        idx = 0;
      }
      if (elements[idx]) {
        elements[idx].focus();
      }
      return idx;
    }
    function moveFocus(dir, elements) {
      var idx = -1;
      var navigationRoot = getNavigationRoot();
      elements = elements || getFocusElements(navigationRoot.getEl());
      for (var i = 0; i < elements.length; i++) {
        if (elements[i] === focusedElement) {
          idx = i;
        }
      }
      idx += dir;
      navigationRoot.lastAriaIndex = moveFocusToIndex(idx, elements);
    }
    function left() {
      var parentRole = getParentRole();
      if (parentRole === 'tablist') {
        moveFocus(-1, getFocusElements(focusedElement.parentNode));
      } else if (focusedControl.parent().submenu) {
        cancel();
      } else {
        moveFocus(-1);
      }
    }
    function right() {
      var role = getRole(), parentRole = getParentRole();
      if (parentRole === 'tablist') {
        moveFocus(1, getFocusElements(focusedElement.parentNode));
      } else if (role === 'menuitem' && parentRole === 'menu' && getAriaProp('haspopup')) {
        enter();
      } else {
        moveFocus(1);
      }
    }
    function up() {
      moveFocus(-1);
    }
    function down() {
      var role = getRole(), parentRole = getParentRole();
      if (role === 'menuitem' && parentRole === 'menubar') {
        enter();
      } else if (role === 'button' && getAriaProp('haspopup')) {
        enter({ key: 'down' });
      } else {
        moveFocus(1);
      }
    }
    function tab(e) {
      var parentRole = getParentRole();
      if (parentRole === 'tablist') {
        var elm = getFocusElements(focusedControl.getEl('body'))[0];
        if (elm) {
          elm.focus();
        }
      } else {
        moveFocus(e.shiftKey ? -1 : 1);
      }
    }
    function cancel() {
      focusedControl.fire('cancel');
    }
    function enter(aria) {
      aria = aria || {};
      focusedControl.fire('click', {
        target: focusedElement,
        aria: aria
      });
    }
    root.on('keydown', function (e) {
      function handleNonTabOrEscEvent(e, handler) {
        if (isTextInputElement(focusedElement) || hasTabstopData(focusedElement)) {
          return;
        }
        if (getRole(focusedElement) === 'slider') {
          return;
        }
        if (handler(e) !== false) {
          e.preventDefault();
        }
      }
      if (e.isDefaultPrevented()) {
        return;
      }
      switch (e.keyCode) {
      case 37:
        handleNonTabOrEscEvent(e, left);
        break;
      case 39:
        handleNonTabOrEscEvent(e, right);
        break;
      case 38:
        handleNonTabOrEscEvent(e, up);
        break;
      case 40:
        handleNonTabOrEscEvent(e, down);
        break;
      case 27:
        cancel();
        break;
      case 14:
      case 13:
      case 32:
        handleNonTabOrEscEvent(e, enter);
        break;
      case 9:
        tab(e);
        e.preventDefault();
        break;
      }
    });
    root.on('focusin', function (e) {
      focusedElement = e.target;
      focusedControl = e.control;
    });
    return { focusFirst: focusFirst };
  }

  var selectorCache = {};
  var Container = Control$1.extend({
    init: function (settings) {
      var self = this;
      self._super(settings);
      settings = self.settings;
      if (settings.fixed) {
        self.state.set('fixed', true);
      }
      self._items = new Collection$2();
      if (self.isRtl()) {
        self.classes.add('rtl');
      }
      self.bodyClasses = new ClassList(function () {
        if (self.state.get('rendered')) {
          self.getEl('body').className = this.toString();
        }
      });
      self.bodyClasses.prefix = self.classPrefix;
      self.classes.add('container');
      self.bodyClasses.add('container-body');
      if (settings.containerCls) {
        self.classes.add(settings.containerCls);
      }
      self._layout = global$4.create((settings.layout || '') + 'layout');
      if (self.settings.items) {
        self.add(self.settings.items);
      } else {
        self.add(self.render());
      }
      self._hasBody = true;
    },
    items: function () {
      return this._items;
    },
    find: function (selector) {
      selector = selectorCache[selector] = selectorCache[selector] || new Selector(selector);
      return selector.find(this);
    },
    add: function (items) {
      var self = this;
      self.items().add(self.create(items)).parent(self);
      return self;
    },
    focus: function (keyboard) {
      var self = this;
      var focusCtrl, keyboardNav, items;
      if (keyboard) {
        keyboardNav = self.keyboardNav || self.parents().eq(-1)[0].keyboardNav;
        if (keyboardNav) {
          keyboardNav.focusFirst(self);
          return;
        }
      }
      items = self.find('*');
      if (self.statusbar) {
        items.add(self.statusbar.items());
      }
      items.each(function (ctrl) {
        if (ctrl.settings.autofocus) {
          focusCtrl = null;
          return false;
        }
        if (ctrl.canFocus) {
          focusCtrl = focusCtrl || ctrl;
        }
      });
      if (focusCtrl) {
        focusCtrl.focus();
      }
      return self;
    },
    replace: function (oldItem, newItem) {
      var ctrlElm;
      var items = this.items();
      var i = items.length;
      while (i--) {
        if (items[i] === oldItem) {
          items[i] = newItem;
          break;
        }
      }
      if (i >= 0) {
        ctrlElm = newItem.getEl();
        if (ctrlElm) {
          ctrlElm.parentNode.removeChild(ctrlElm);
        }
        ctrlElm = oldItem.getEl();
        if (ctrlElm) {
          ctrlElm.parentNode.removeChild(ctrlElm);
        }
      }
      newItem.parent(this);
    },
    create: function (items) {
      var self = this;
      var settings;
      var ctrlItems = [];
      if (!global$2.isArray(items)) {
        items = [items];
      }
      global$2.each(items, function (item) {
        if (item) {
          if (!(item instanceof Control$1)) {
            if (typeof item === 'string') {
              item = { type: item };
            }
            settings = global$2.extend({}, self.settings.defaults, item);
            item.type = settings.type = settings.type || item.type || self.settings.defaultType || (settings.defaults ? settings.defaults.type : null);
            item = global$4.create(settings);
          }
          ctrlItems.push(item);
        }
      });
      return ctrlItems;
    },
    renderNew: function () {
      var self = this;
      self.items().each(function (ctrl, index) {
        var containerElm;
        ctrl.parent(self);
        if (!ctrl.state.get('rendered')) {
          containerElm = self.getEl('body');
          if (containerElm.hasChildNodes() && index <= containerElm.childNodes.length - 1) {
            global$9(containerElm.childNodes[index]).before(ctrl.renderHtml());
          } else {
            global$9(containerElm).append(ctrl.renderHtml());
          }
          ctrl.postRender();
          $_ef12j5u4jh8lz3nl.add(ctrl);
        }
      });
      self._layout.applyClasses(self.items().filter(':visible'));
      self._lastRect = null;
      return self;
    },
    append: function (items) {
      return this.add(items).renderNew();
    },
    prepend: function (items) {
      var self = this;
      self.items().set(self.create(items).concat(self.items().toArray()));
      return self.renderNew();
    },
    insert: function (items, index, before) {
      var self = this;
      var curItems, beforeItems, afterItems;
      items = self.create(items);
      curItems = self.items();
      if (!before && index < curItems.length - 1) {
        index += 1;
      }
      if (index >= 0 && index < curItems.length) {
        beforeItems = curItems.slice(0, index).toArray();
        afterItems = curItems.slice(index).toArray();
        curItems.set(beforeItems.concat(items, afterItems));
      }
      return self.renderNew();
    },
    fromJSON: function (data) {
      var self = this;
      for (var name_1 in data) {
        self.find('#' + name_1).value(data[name_1]);
      }
      return self;
    },
    toJSON: function () {
      var self = this, data = {};
      self.find('*').each(function (ctrl) {
        var name = ctrl.name(), value = ctrl.value();
        if (name && typeof value !== 'undefined') {
          data[name] = value;
        }
      });
      return data;
    },
    renderHtml: function () {
      var self = this, layout = self._layout, role = this.settings.role;
      self.preRender();
      layout.preRender(self);
      return '<div id="' + self._id + '" class="' + self.classes + '"' + (role ? ' role="' + this.settings.role + '"' : '') + '>' + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>';
    },
    postRender: function () {
      var self = this;
      var box;
      self.items().exec('postRender');
      self._super();
      self._layout.postRender(self);
      self.state.set('rendered', true);
      if (self.settings.style) {
        self.$el.css(self.settings.style);
      }
      if (self.settings.border) {
        box = self.borderBox;
        self.$el.css({
          'border-top-width': box.top,
          'border-right-width': box.right,
          'border-bottom-width': box.bottom,
          'border-left-width': box.left
        });
      }
      if (!self.parent()) {
        self.keyboardNav = KeyboardNavigation({ root: self });
      }
      return self;
    },
    initLayoutRect: function () {
      var self = this, layoutRect = self._super();
      self._layout.recalc(self);
      return layoutRect;
    },
    recalc: function () {
      var self = this;
      var rect = self._layoutRect;
      var lastRect = self._lastRect;
      if (!lastRect || lastRect.w !== rect.w || lastRect.h !== rect.h) {
        self._layout.recalc(self);
        rect = self.layoutRect();
        self._lastRect = {
          x: rect.x,
          y: rect.y,
          w: rect.w,
          h: rect.h
        };
        return true;
      }
    },
    reflow: function () {
      var i;
      $_ef12j5u4jh8lz3nl.remove(this);
      if (this.visible()) {
        Control$1.repaintControls = [];
        Control$1.repaintControls.map = {};
        this.recalc();
        i = Control$1.repaintControls.length;
        while (i--) {
          Control$1.repaintControls[i].repaint();
        }
        if (this.settings.layout !== 'flow' && this.settings.layout !== 'stack') {
          this.repaint();
        }
        Control$1.repaintControls = [];
      }
      return this;
    }
  });

  function getDocumentSize(doc) {
    var documentElement, body, scrollWidth, clientWidth;
    var offsetWidth, scrollHeight, clientHeight, offsetHeight;
    var max = Math.max;
    documentElement = doc.documentElement;
    body = doc.body;
    scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
    clientWidth = max(documentElement.clientWidth, body.clientWidth);
    offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
    scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
    clientHeight = max(documentElement.clientHeight, body.clientHeight);
    offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
    return {
      width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
      height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
    };
  }
  function updateWithTouchData(e) {
    var keys, i;
    if (e.changedTouches) {
      keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
      for (i = 0; i < keys.length; i++) {
        e[keys[i]] = e.changedTouches[0][keys[i]];
      }
    }
  }
  function DragHelper (id, settings) {
    var $eventOverlay;
    var doc = settings.document || document;
    var downButton;
    var start, stop, drag, startX, startY;
    settings = settings || {};
    var handleElement = doc.getElementById(settings.handle || id);
    start = function (e) {
      var docSize = getDocumentSize(doc);
      var handleElm, cursor;
      updateWithTouchData(e);
      e.preventDefault();
      downButton = e.button;
      handleElm = handleElement;
      startX = e.screenX;
      startY = e.screenY;
      if (window.getComputedStyle) {
        cursor = window.getComputedStyle(handleElm, null).getPropertyValue('cursor');
      } else {
        cursor = handleElm.runtimeStyle.cursor;
      }
      $eventOverlay = global$9('<div></div>').css({
        position: 'absolute',
        top: 0,
        left: 0,
        width: docSize.width,
        height: docSize.height,
        zIndex: 2147483647,
        opacity: 0.0001,
        cursor: cursor
      }).appendTo(doc.body);
      global$9(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop);
      settings.start(e);
    };
    drag = function (e) {
      updateWithTouchData(e);
      if (e.button !== downButton) {
        return stop(e);
      }
      e.deltaX = e.screenX - startX;
      e.deltaY = e.screenY - startY;
      e.preventDefault();
      settings.drag(e);
    };
    stop = function (e) {
      updateWithTouchData(e);
      global$9(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop);
      $eventOverlay.remove();
      if (settings.stop) {
        settings.stop(e);
      }
    };
    this.destroy = function () {
      global$9(handleElement).off();
    };
    global$9(handleElement).on('mousedown touchstart', start);
  }

  var $_4acv48u6jh8lz3ns = {
    init: function () {
      var self = this;
      self.on('repaint', self.renderScroll);
    },
    renderScroll: function () {
      var self = this, margin = 2;
      function repaintScroll() {
        var hasScrollH, hasScrollV, bodyElm;
        function repaintAxis(axisName, posName, sizeName, contentSizeName, hasScroll, ax) {
          var containerElm, scrollBarElm, scrollThumbElm;
          var containerSize, scrollSize, ratio, rect;
          var posNameLower, sizeNameLower;
          scrollBarElm = self.getEl('scroll' + axisName);
          if (scrollBarElm) {
            posNameLower = posName.toLowerCase();
            sizeNameLower = sizeName.toLowerCase();
            global$9(self.getEl('absend')).css(posNameLower, self.layoutRect()[contentSizeName] - 1);
            if (!hasScroll) {
              global$9(scrollBarElm).css('display', 'none');
              return;
            }
            global$9(scrollBarElm).css('display', 'block');
            containerElm = self.getEl('body');
            scrollThumbElm = self.getEl('scroll' + axisName + 't');
            containerSize = containerElm['client' + sizeName] - margin * 2;
            containerSize -= hasScrollH && hasScrollV ? scrollBarElm['client' + ax] : 0;
            scrollSize = containerElm['scroll' + sizeName];
            ratio = containerSize / scrollSize;
            rect = {};
            rect[posNameLower] = containerElm['offset' + posName] + margin;
            rect[sizeNameLower] = containerSize;
            global$9(scrollBarElm).css(rect);
            rect = {};
            rect[posNameLower] = containerElm['scroll' + posName] * ratio;
            rect[sizeNameLower] = containerSize * ratio;
            global$9(scrollThumbElm).css(rect);
          }
        }
        bodyElm = self.getEl('body');
        hasScrollH = bodyElm.scrollWidth > bodyElm.clientWidth;
        hasScrollV = bodyElm.scrollHeight > bodyElm.clientHeight;
        repaintAxis('h', 'Left', 'Width', 'contentW', hasScrollH, 'Height');
        repaintAxis('v', 'Top', 'Height', 'contentH', hasScrollV, 'Width');
      }
      function addScroll() {
        function addScrollAxis(axisName, posName, sizeName, deltaPosName, ax) {
          var scrollStart;
          var axisId = self._id + '-scroll' + axisName, prefix = self.classPrefix;
          global$9(self.getEl()).append('<div id="' + axisId + '" class="' + prefix + 'scrollbar ' + prefix + 'scrollbar-' + axisName + '">' + '<div id="' + axisId + 't" class="' + prefix + 'scrollbar-thumb"></div>' + '</div>');
          self.draghelper = new DragHelper(axisId + 't', {
            start: function () {
              scrollStart = self.getEl('body')['scroll' + posName];
              global$9('#' + axisId).addClass(prefix + 'active');
            },
            drag: function (e) {
              var ratio, hasScrollH, hasScrollV, containerSize;
              var layoutRect = self.layoutRect();
              hasScrollH = layoutRect.contentW > layoutRect.innerW;
              hasScrollV = layoutRect.contentH > layoutRect.innerH;
              containerSize = self.getEl('body')['client' + sizeName] - margin * 2;
              containerSize -= hasScrollH && hasScrollV ? self.getEl('scroll' + axisName)['client' + ax] : 0;
              ratio = containerSize / self.getEl('body')['scroll' + sizeName];
              self.getEl('body')['scroll' + posName] = scrollStart + e['delta' + deltaPosName] / ratio;
            },
            stop: function () {
              global$9('#' + axisId).removeClass(prefix + 'active');
            }
          });
        }
        self.classes.add('scroll');
        addScrollAxis('v', 'Top', 'Height', 'Y', 'Width');
        addScrollAxis('h', 'Left', 'Width', 'X', 'Height');
      }
      if (self.settings.autoScroll) {
        if (!self._hasScroll) {
          self._hasScroll = true;
          addScroll();
          self.on('wheel', function (e) {
            var bodyEl = self.getEl('body');
            bodyEl.scrollLeft += (e.deltaX || 0) * 10;
            bodyEl.scrollTop += e.deltaY * 10;
            repaintScroll();
          });
          global$9(self.getEl('body')).on('scroll', repaintScroll);
        }
        repaintScroll();
      }
    }
  };

  var Panel = Container.extend({
    Defaults: {
      layout: 'fit',
      containerCls: 'panel'
    },
    Mixins: [$_4acv48u6jh8lz3ns],
    renderHtml: function () {
      var self = this;
      var layout = self._layout;
      var innerHtml = self.settings.html;
      self.preRender();
      layout.preRender(self);
      if (typeof innerHtml === 'undefined') {
        innerHtml = '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + layout.renderHtml(self) + '</div>';
      } else {
        if (typeof innerHtml === 'function') {
          innerHtml = innerHtml.call(self);
        }
        self._hasBody = false;
      }
      return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1" role="group">' + (self._preBodyHtml || '') + innerHtml + '</div>';
    }
  });

  var $_8a2gtru8jh8lz3ny = {
    resizeToContent: function () {
      this._layoutRect.autoResize = true;
      this._lastRect = null;
      this.reflow();
    },
    resizeTo: function (w, h) {
      if (w <= 1 || h <= 1) {
        var rect = funcs.getWindowSize();
        w = w <= 1 ? w * rect.w : w;
        h = h <= 1 ? h * rect.h : h;
      }
      this._layoutRect.autoResize = false;
      return this.layoutRect({
        minW: w,
        minH: h,
        w: w,
        h: h
      }).reflow();
    },
    resizeBy: function (dw, dh) {
      var self = this, rect = self.layoutRect();
      return self.resizeTo(rect.w + dw, rect.h + dh);
    }
  };

  var documentClickHandler;
  var documentScrollHandler;
  var windowResizeHandler;
  var visiblePanels = [];
  var zOrder = [];
  var hasModal;
  function isChildOf(ctrl, parent) {
    while (ctrl) {
      if (ctrl === parent) {
        return true;
      }
      ctrl = ctrl.parent();
    }
  }
  function skipOrHidePanels(e) {
    var i = visiblePanels.length;
    while (i--) {
      var panel = visiblePanels[i], clickCtrl = panel.getParentCtrl(e.target);
      if (panel.settings.autohide) {
        if (clickCtrl) {
          if (isChildOf(clickCtrl, panel) || panel.parent() === clickCtrl) {
            continue;
          }
        }
        e = panel.fire('autohide', { target: e.target });
        if (!e.isDefaultPrevented()) {
          panel.hide();
        }
      }
    }
  }
  function bindDocumentClickHandler() {
    if (!documentClickHandler) {
      documentClickHandler = function (e) {
        if (e.button === 2) {
          return;
        }
        skipOrHidePanels(e);
      };
      global$9(document).on('click touchstart', documentClickHandler);
    }
  }
  function bindDocumentScrollHandler() {
    if (!documentScrollHandler) {
      documentScrollHandler = function () {
        var i;
        i = visiblePanels.length;
        while (i--) {
          repositionPanel(visiblePanels[i]);
        }
      };
      global$9(window).on('scroll', documentScrollHandler);
    }
  }
  function bindWindowResizeHandler() {
    if (!windowResizeHandler) {
      var docElm_1 = document.documentElement;
      var clientWidth_1 = docElm_1.clientWidth, clientHeight_1 = docElm_1.clientHeight;
      windowResizeHandler = function () {
        if (!document.all || clientWidth_1 !== docElm_1.clientWidth || clientHeight_1 !== docElm_1.clientHeight) {
          clientWidth_1 = docElm_1.clientWidth;
          clientHeight_1 = docElm_1.clientHeight;
          FloatPanel.hideAll();
        }
      };
      global$9(window).on('resize', windowResizeHandler);
    }
  }
  function repositionPanel(panel) {
    var scrollY = funcs.getViewPort().y;
    function toggleFixedChildPanels(fixed, deltaY) {
      var parent;
      for (var i = 0; i < visiblePanels.length; i++) {
        if (visiblePanels[i] !== panel) {
          parent = visiblePanels[i].parent();
          while (parent && (parent = parent.parent())) {
            if (parent === panel) {
              visiblePanels[i].fixed(fixed).moveBy(0, deltaY).repaint();
            }
          }
        }
      }
    }
    if (panel.settings.autofix) {
      if (!panel.state.get('fixed')) {
        panel._autoFixY = panel.layoutRect().y;
        if (panel._autoFixY < scrollY) {
          panel.fixed(true).layoutRect({ y: 0 }).repaint();
          toggleFixedChildPanels(true, scrollY - panel._autoFixY);
        }
      } else {
        if (panel._autoFixY > scrollY) {
          panel.fixed(false).layoutRect({ y: panel._autoFixY }).repaint();
          toggleFixedChildPanels(false, panel._autoFixY - scrollY);
        }
      }
    }
  }
  function addRemove(add, ctrl) {
    var i, zIndex = FloatPanel.zIndex || 65535, topModal;
    if (add) {
      zOrder.push(ctrl);
    } else {
      i = zOrder.length;
      while (i--) {
        if (zOrder[i] === ctrl) {
          zOrder.splice(i, 1);
        }
      }
    }
    if (zOrder.length) {
      for (i = 0; i < zOrder.length; i++) {
        if (zOrder[i].modal) {
          zIndex++;
          topModal = zOrder[i];
        }
        zOrder[i].getEl().style.zIndex = zIndex;
        zOrder[i].zIndex = zIndex;
        zIndex++;
      }
    }
    var modalBlockEl = global$9('#' + ctrl.classPrefix + 'modal-block', ctrl.getContainerElm())[0];
    if (topModal) {
      global$9(modalBlockEl).css('z-index', topModal.zIndex - 1);
    } else if (modalBlockEl) {
      modalBlockEl.parentNode.removeChild(modalBlockEl);
      hasModal = false;
    }
    FloatPanel.currentZIndex = zIndex;
  }
  var FloatPanel = Panel.extend({
    Mixins: [
      $_d97gfctrjh8lz3lm,
      $_8a2gtru8jh8lz3ny
    ],
    init: function (settings) {
      var self = this;
      self._super(settings);
      self._eventsRoot = self;
      self.classes.add('floatpanel');
      if (settings.autohide) {
        bindDocumentClickHandler();
        bindWindowResizeHandler();
        visiblePanels.push(self);
      }
      if (settings.autofix) {
        bindDocumentScrollHandler();
        self.on('move', function () {
          repositionPanel(this);
        });
      }
      self.on('postrender show', function (e) {
        if (e.control === self) {
          var $modalBlockEl_1;
          var prefix_1 = self.classPrefix;
          if (self.modal && !hasModal) {
            $modalBlockEl_1 = global$9('#' + prefix_1 + 'modal-block', self.getContainerElm());
            if (!$modalBlockEl_1[0]) {
              $modalBlockEl_1 = global$9('<div id="' + prefix_1 + 'modal-block" class="' + prefix_1 + 'reset ' + prefix_1 + 'fade"></div>').appendTo(self.getContainerElm());
            }
            global$7.setTimeout(function () {
              $modalBlockEl_1.addClass(prefix_1 + 'in');
              global$9(self.getEl()).addClass(prefix_1 + 'in');
            });
            hasModal = true;
          }
          addRemove(true, self);
        }
      });
      self.on('show', function () {
        self.parents().each(function (ctrl) {
          if (ctrl.state.get('fixed')) {
            self.fixed(true);
            return false;
          }
        });
      });
      if (settings.popover) {
        self._preBodyHtml = '<div class="' + self.classPrefix + 'arrow"></div>';
        self.classes.add('popover').add('bottom').add(self.isRtl() ? 'end' : 'start');
      }
      self.aria('label', settings.ariaLabel);
      self.aria('labelledby', self._id);
      self.aria('describedby', self.describedBy || self._id + '-none');
    },
    fixed: function (state) {
      var self = this;
      if (self.state.get('fixed') !== state) {
        if (self.state.get('rendered')) {
          var viewport = funcs.getViewPort();
          if (state) {
            self.layoutRect().y -= viewport.y;
          } else {
            self.layoutRect().y += viewport.y;
          }
        }
        self.classes.toggle('fixed', state);
        self.state.set('fixed', state);
      }
      return self;
    },
    show: function () {
      var self = this;
      var i;
      var state = self._super();
      i = visiblePanels.length;
      while (i--) {
        if (visiblePanels[i] === self) {
          break;
        }
      }
      if (i === -1) {
        visiblePanels.push(self);
      }
      return state;
    },
    hide: function () {
      removeVisiblePanel(this);
      addRemove(false, this);
      return this._super();
    },
    hideAll: function () {
      FloatPanel.hideAll();
    },
    close: function () {
      var self = this;
      if (!self.fire('close').isDefaultPrevented()) {
        self.remove();
        addRemove(false, self);
      }
      return self;
    },
    remove: function () {
      removeVisiblePanel(this);
      this._super();
    },
    postRender: function () {
      var self = this;
      if (self.settings.bodyRole) {
        this.getEl('body').setAttribute('role', self.settings.bodyRole);
      }
      return self._super();
    }
  });
  FloatPanel.hideAll = function () {
    var i = visiblePanels.length;
    while (i--) {
      var panel = visiblePanels[i];
      if (panel && panel.settings.autohide) {
        panel.hide();
        visiblePanels.splice(i, 1);
      }
    }
  };
  function removeVisiblePanel(panel) {
    var i;
    i = visiblePanels.length;
    while (i--) {
      if (visiblePanels[i] === panel) {
        visiblePanels.splice(i, 1);
      }
    }
    i = zOrder.length;
    while (i--) {
      if (zOrder[i] === panel) {
        zOrder.splice(i, 1);
      }
    }
  }

  var isFixed$1 = function (inlineToolbarContainer, editor) {
    return !!(inlineToolbarContainer && !editor.settings.ui_container);
  };
  var render$1 = function (editor, theme, args) {
    var panel, inlineToolbarContainer;
    var DOM = global$3.DOM;
    var fixedToolbarContainer = getFixedToolbarContainer(editor);
    if (fixedToolbarContainer) {
      inlineToolbarContainer = DOM.select(fixedToolbarContainer)[0];
    }
    var reposition = function () {
      if (panel && panel.moveRel && panel.visible() && !panel._fixed) {
        var scrollContainer = editor.selection.getScrollContainer(), body = editor.getBody();
        var deltaX = 0, deltaY = 0;
        if (scrollContainer) {
          var bodyPos = DOM.getPos(body), scrollContainerPos = DOM.getPos(scrollContainer);
          deltaX = Math.max(0, scrollContainerPos.x - bodyPos.x);
          deltaY = Math.max(0, scrollContainerPos.y - bodyPos.y);
        }
        panel.fixed(false).moveRel(body, editor.rtl ? [
          'tr-br',
          'br-tr'
        ] : [
          'tl-bl',
          'bl-tl',
          'tr-br'
        ]).moveBy(deltaX, deltaY);
      }
    };
    var show = function () {
      if (panel) {
        panel.show();
        reposition();
        DOM.addClass(editor.getBody(), 'mce-edit-focus');
      }
    };
    var hide = function () {
      if (panel) {
        panel.hide();
        FloatPanel.hideAll();
        DOM.removeClass(editor.getBody(), 'mce-edit-focus');
      }
    };
    var render = function () {
      if (panel) {
        if (!panel.visible()) {
          show();
        }
        return;
      }
      panel = theme.panel = global$4.create({
        type: inlineToolbarContainer ? 'panel' : 'floatpanel',
        role: 'application',
        classes: 'tinymce tinymce-inline',
        layout: 'flex',
        direction: 'column',
        align: 'stretch',
        autohide: false,
        autofix: isFixed$1(inlineToolbarContainer, editor),
        fixed: isFixed$1(inlineToolbarContainer, editor),
        border: 1,
        items: [
          hasMenubar(editor) === false ? null : {
            type: 'menubar',
            border: '0 0 1 0',
            items: $_8i78rftgjh8lz3ka.createMenuButtons(editor)
          },
          $_fudqhrtfjh8lz3k7.createToolbars(editor, getToolbarSize(editor))
        ]
      });
      $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel);
      $_aycuj2t7jh8lz3jp.fireBeforeRenderUI(editor);
      if (inlineToolbarContainer) {
        panel.renderTo(inlineToolbarContainer).reflow();
      } else {
        panel.renderTo().reflow();
      }
      $_47hpztt8jh8lz3jq.addKeys(editor, panel);
      show();
      $_5kodmdt9jh8lz3js.addContextualToolbars(editor);
      editor.on('nodeChange', reposition);
      editor.on('ResizeWindow', reposition);
      editor.on('activate', show);
      editor.on('deactivate', hide);
      editor.nodeChanged();
    };
    editor.settings.content_editable = true;
    editor.on('focus', function () {
      if (isSkinDisabled(editor) === false && args.skinUiCss) {
        DOM.styleSheetLoader.load(args.skinUiCss, render, render);
      } else {
        render();
      }
    });
    editor.on('blur hide', hide);
    editor.on('remove', function () {
      if (panel) {
        panel.remove();
        panel = null;
      }
    });
    if (isSkinDisabled(editor) === false && args.skinUiCss) {
      DOM.styleSheetLoader.load(args.skinUiCss, $_231e94tmjh8lz3ku.fireSkinLoaded(editor));
    } else {
      $_231e94tmjh8lz3ku.fireSkinLoaded(editor)();
    }
    return {};
  };
  var $_7wdylstnjh8lz3kv = { render: render$1 };

  function Throbber (elm, inline) {
    var self = this;
    var state;
    var classPrefix = Control$1.classPrefix;
    var timer;
    self.show = function (time, callback) {
      function render() {
        if (state) {
          global$9(elm).append('<div class="' + classPrefix + 'throbber' + (inline ? ' ' + classPrefix + 'throbber-inline' : '') + '"></div>');
          if (callback) {
            callback();
          }
        }
      }
      self.hide();
      state = true;
      if (time) {
        timer = global$7.setTimeout(render, time);
      } else {
        render();
      }
      return self;
    };
    self.hide = function () {
      var child = elm.lastChild;
      global$7.clearTimeout(timer);
      if (child && child.className.indexOf('throbber') !== -1) {
        child.parentNode.removeChild(child);
      }
      state = false;
      return self;
    };
  }

  var setup = function (editor, theme) {
    var throbber;
    editor.on('ProgressState', function (e) {
      throbber = throbber || new Throbber(theme.panel.getEl('body'));
      if (e.state) {
        throbber.show(e.time);
      } else {
        throbber.hide();
      }
    });
  };
  var $_e9w0qfu9jh8lz3nz = { setup: setup };

  var renderUI = function (editor, theme, args) {
    var skinUrl = getSkinUrl(editor);
    if (skinUrl) {
      args.skinUiCss = skinUrl + '/skin.min.css';
      editor.contentCSS.push(skinUrl + '/content' + (editor.inline ? '.inline' : '') + '.min.css');
    }
    $_e9w0qfu9jh8lz3nz.setup(editor, theme);
    return isInline(editor) ? $_7wdylstnjh8lz3kv.render(editor, theme, args) : $_4cj0a3t3jh8lz3jk.render(editor, theme, args);
  };
  var $_5ent4szjh8lz3ja = { renderUI: renderUI };

  var Tooltip = Control$1.extend({
    Mixins: [$_d97gfctrjh8lz3lm],
    Defaults: { classes: 'widget tooltip tooltip-n' },
    renderHtml: function () {
      var self = this, prefix = self.classPrefix;
      return '<div id="' + self._id + '" class="' + self.classes + '" role="presentation">' + '<div class="' + prefix + 'tooltip-arrow"></div>' + '<div class="' + prefix + 'tooltip-inner">' + self.encode(self.state.get('text')) + '</div>' + '</div>';
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:text', function (e) {
        self.getEl().lastChild.innerHTML = self.encode(e.value);
      });
      return self._super();
    },
    repaint: function () {
      var self = this;
      var style, rect;
      style = self.getEl().style;
      rect = self._layoutRect;
      style.left = rect.x + 'px';
      style.top = rect.y + 'px';
      style.zIndex = 65535 + 65535;
    }
  });

  var Widget = Control$1.extend({
    init: function (settings) {
      var self = this;
      self._super(settings);
      settings = self.settings;
      self.canFocus = true;
      if (settings.tooltip && Widget.tooltips !== false) {
        self.on('mouseenter', function (e) {
          var tooltip = self.tooltip().moveTo(-65535);
          if (e.control === self) {
            var rel = tooltip.text(settings.tooltip).show().testMoveRel(self.getEl(), [
              'bc-tc',
              'bc-tl',
              'bc-tr'
            ]);
            tooltip.classes.toggle('tooltip-n', rel === 'bc-tc');
            tooltip.classes.toggle('tooltip-nw', rel === 'bc-tl');
            tooltip.classes.toggle('tooltip-ne', rel === 'bc-tr');
            tooltip.moveRel(self.getEl(), rel);
          } else {
            tooltip.hide();
          }
        });
        self.on('mouseleave mousedown click', function () {
          self.tooltip().remove();
          self._tooltip = null;
        });
      }
      self.aria('label', settings.ariaLabel || settings.tooltip);
    },
    tooltip: function () {
      if (!this._tooltip) {
        this._tooltip = new Tooltip({ type: 'tooltip' });
        $_1jk3jvtcjh8lz3jy.inheritUiContainer(this, this._tooltip);
        this._tooltip.renderTo();
      }
      return this._tooltip;
    },
    postRender: function () {
      var self = this, settings = self.settings;
      self._super();
      if (!self.parent() && (settings.width || settings.height)) {
        self.initLayoutRect();
        self.repaint();
      }
      if (settings.autofocus) {
        self.focus();
      }
    },
    bindStates: function () {
      var self = this;
      function disable(state) {
        self.aria('disabled', state);
        self.classes.toggle('disabled', state);
      }
      function active(state) {
        self.aria('pressed', state);
        self.classes.toggle('active', state);
      }
      self.state.on('change:disabled', function (e) {
        disable(e.value);
      });
      self.state.on('change:active', function (e) {
        active(e.value);
      });
      if (self.state.get('disabled')) {
        disable(true);
      }
      if (self.state.get('active')) {
        active(true);
      }
      return self._super();
    },
    remove: function () {
      this._super();
      if (this._tooltip) {
        this._tooltip.remove();
        this._tooltip = null;
      }
    }
  });

  var Progress = Widget.extend({
    Defaults: { value: 0 },
    init: function (settings) {
      var self = this;
      self._super(settings);
      self.classes.add('progress');
      if (!self.settings.filter) {
        self.settings.filter = function (value) {
          return Math.round(value);
        };
      }
    },
    renderHtml: function () {
      var self = this, id = self._id, prefix = this.classPrefix;
      return '<div id="' + id + '" class="' + self.classes + '">' + '<div class="' + prefix + 'bar-container">' + '<div class="' + prefix + 'bar"></div>' + '</div>' + '<div class="' + prefix + 'text">0%</div>' + '</div>';
    },
    postRender: function () {
      var self = this;
      self._super();
      self.value(self.settings.value);
      return self;
    },
    bindStates: function () {
      var self = this;
      function setValue(value) {
        value = self.settings.filter(value);
        self.getEl().lastChild.innerHTML = value + '%';
        self.getEl().firstChild.firstChild.style.width = value + '%';
      }
      self.state.on('change:value', function (e) {
        setValue(e.value);
      });
      setValue(self.state.get('value'));
      return self._super();
    }
  });

  var updateLiveRegion = function (ctx, text) {
    ctx.getEl().lastChild.textContent = text + (ctx.progressBar ? ' ' + ctx.progressBar.value() + '%' : '');
  };
  var Notification = Control$1.extend({
    Mixins: [$_d97gfctrjh8lz3lm],
    Defaults: { classes: 'widget notification' },
    init: function (settings) {
      var self = this;
      self._super(settings);
      self.maxWidth = settings.maxWidth;
      if (settings.text) {
        self.text(settings.text);
      }
      if (settings.icon) {
        self.icon = settings.icon;
      }
      if (settings.color) {
        self.color = settings.color;
      }
      if (settings.type) {
        self.classes.add('notification-' + settings.type);
      }
      if (settings.timeout && (settings.timeout < 0 || settings.timeout > 0) && !settings.closeButton) {
        self.closeButton = false;
      } else {
        self.classes.add('has-close');
        self.closeButton = true;
      }
      if (settings.progressBar) {
        self.progressBar = new Progress();
      }
      self.on('click', function (e) {
        if (e.target.className.indexOf(self.classPrefix + 'close') !== -1) {
          self.close();
        }
      });
    },
    renderHtml: function () {
      var self = this;
      var prefix = self.classPrefix;
      var icon = '', closeButton = '', progressBar = '', notificationStyle = '';
      if (self.icon) {
        icon = '<i class="' + prefix + 'ico' + ' ' + prefix + 'i-' + self.icon + '"></i>';
      }
      notificationStyle = ' style="max-width: ' + self.maxWidth + 'px;' + (self.color ? 'background-color: ' + self.color + ';"' : '"');
      if (self.closeButton) {
        closeButton = '<button type="button" class="' + prefix + 'close" aria-hidden="true">\xD7</button>';
      }
      if (self.progressBar) {
        progressBar = self.progressBar.renderHtml();
      }
      return '<div id="' + self._id + '" class="' + self.classes + '"' + notificationStyle + ' role="presentation">' + icon + '<div class="' + prefix + 'notification-inner">' + self.state.get('text') + '</div>' + progressBar + closeButton + '<div style="clip: rect(1px, 1px, 1px, 1px);height: 1px;overflow: hidden;position: absolute;width: 1px;"' + ' aria-live="assertive" aria-relevant="additions" aria-atomic="true"></div>' + '</div>';
    },
    postRender: function () {
      var self = this;
      global$7.setTimeout(function () {
        self.$el.addClass(self.classPrefix + 'in');
        updateLiveRegion(self, self.state.get('text'));
      }, 100);
      return self._super();
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:text', function (e) {
        self.getEl().firstChild.innerHTML = e.value;
        updateLiveRegion(self, e.value);
      });
      if (self.progressBar) {
        self.progressBar.bindStates();
        self.progressBar.state.on('change:value', function (e) {
          updateLiveRegion(self, self.state.get('text'));
        });
      }
      return self._super();
    },
    close: function () {
      var self = this;
      if (!self.fire('close').isDefaultPrevented()) {
        self.remove();
      }
      return self;
    },
    repaint: function () {
      var self = this;
      var style, rect;
      style = self.getEl().style;
      rect = self._layoutRect;
      style.left = rect.x + 'px';
      style.top = rect.y + 'px';
      style.zIndex = 65535 - 1;
    }
  });

  function NotificationManagerImpl (editor) {
    var getEditorContainer = function (editor) {
      return editor.inline ? editor.getElement() : editor.getContentAreaContainer();
    };
    var getContainerWidth = function () {
      var container = getEditorContainer(editor);
      return funcs.getSize(container).width;
    };
    var prePositionNotifications = function (notifications) {
      $_f3qxhzthjh8lz3kg.each(notifications, function (notification) {
        notification.moveTo(0, 0);
      });
    };
    var positionNotifications = function (notifications) {
      if (notifications.length > 0) {
        var firstItem = notifications.slice(0, 1)[0];
        var container = getEditorContainer(editor);
        firstItem.moveRel(container, 'tc-tc');
        $_f3qxhzthjh8lz3kg.each(notifications, function (notification, index) {
          if (index > 0) {
            notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
          }
        });
      }
    };
    var reposition = function (notifications) {
      prePositionNotifications(notifications);
      positionNotifications(notifications);
    };
    var open = function (args, closeCallback) {
      var extendedArgs = global$2.extend(args, { maxWidth: getContainerWidth() });
      var notif = new Notification(extendedArgs);
      notif.args = extendedArgs;
      if (extendedArgs.timeout > 0) {
        notif.timer = setTimeout(function () {
          notif.close();
          closeCallback();
        }, extendedArgs.timeout);
      }
      notif.on('close', function () {
        closeCallback();
      });
      notif.renderTo();
      return notif;
    };
    var close = function (notification) {
      notification.close();
    };
    var getArgs = function (notification) {
      return notification.args;
    };
    return {
      open: open,
      close: close,
      reposition: reposition,
      getArgs: getArgs
    };
  }

  var windows = [];
  var oldMetaValue = '';
  function toggleFullScreenState(state) {
    var noScaleMetaValue = 'width=device-width,initial-scale=1.0,user-scalable=0,minimum-scale=1.0,maximum-scale=1.0';
    var viewport = global$9('meta[name=viewport]')[0], contentValue;
    if (global$8.overrideViewPort === false) {
      return;
    }
    if (!viewport) {
      viewport = document.createElement('meta');
      viewport.setAttribute('name', 'viewport');
      document.getElementsByTagName('head')[0].appendChild(viewport);
    }
    contentValue = viewport.getAttribute('content');
    if (contentValue && typeof oldMetaValue !== 'undefined') {
      oldMetaValue = contentValue;
    }
    viewport.setAttribute('content', state ? noScaleMetaValue : oldMetaValue);
  }
  function toggleBodyFullScreenClasses(classPrefix, state) {
    if (checkFullscreenWindows() && state === false) {
      global$9([
        document.documentElement,
        document.body
      ]).removeClass(classPrefix + 'fullscreen');
    }
  }
  function checkFullscreenWindows() {
    for (var i = 0; i < windows.length; i++) {
      if (windows[i]._fullscreen) {
        return true;
      }
    }
    return false;
  }
  function handleWindowResize() {
    if (!global$8.desktop) {
      var lastSize_1 = {
        w: window.innerWidth,
        h: window.innerHeight
      };
      global$7.setInterval(function () {
        var w = window.innerWidth, h = window.innerHeight;
        if (lastSize_1.w !== w || lastSize_1.h !== h) {
          lastSize_1 = {
            w: w,
            h: h
          };
          global$9(window).trigger('resize');
        }
      }, 100);
    }
    function reposition() {
      var i;
      var rect = funcs.getWindowSize();
      var layoutRect;
      for (i = 0; i < windows.length; i++) {
        layoutRect = windows[i].layoutRect();
        windows[i].moveTo(windows[i].settings.x || Math.max(0, rect.w / 2 - layoutRect.w / 2), windows[i].settings.y || Math.max(0, rect.h / 2 - layoutRect.h / 2));
      }
    }
    global$9(window).on('resize', reposition);
  }
  var Window = FloatPanel.extend({
    modal: true,
    Defaults: {
      border: 1,
      layout: 'flex',
      containerCls: 'panel',
      role: 'dialog',
      callbacks: {
        submit: function () {
          this.fire('submit', { data: this.toJSON() });
        },
        close: function () {
          this.close();
        }
      }
    },
    init: function (settings) {
      var self = this;
      self._super(settings);
      if (self.isRtl()) {
        self.classes.add('rtl');
      }
      self.classes.add('window');
      self.bodyClasses.add('window-body');
      self.state.set('fixed', true);
      if (settings.buttons) {
        self.statusbar = new Panel({
          layout: 'flex',
          border: '1 0 0 0',
          spacing: 3,
          padding: 10,
          align: 'center',
          pack: self.isRtl() ? 'start' : 'end',
          defaults: { type: 'button' },
          items: settings.buttons
        });
        self.statusbar.classes.add('foot');
        self.statusbar.parent(self);
      }
      self.on('click', function (e) {
        var closeClass = self.classPrefix + 'close';
        if (funcs.hasClass(e.target, closeClass) || funcs.hasClass(e.target.parentNode, closeClass)) {
          self.close();
        }
      });
      self.on('cancel', function () {
        self.close();
      });
      self.on('move', function (e) {
        if (e.control === self) {
          FloatPanel.hideAll();
        }
      });
      self.aria('describedby', self.describedBy || self._id + '-none');
      self.aria('label', settings.title);
      self._fullscreen = false;
    },
    recalc: function () {
      var self = this;
      var statusbar = self.statusbar;
      var layoutRect, width, x, needsRecalc;
      if (self._fullscreen) {
        self.layoutRect(funcs.getWindowSize());
        self.layoutRect().contentH = self.layoutRect().innerH;
      }
      self._super();
      layoutRect = self.layoutRect();
      if (self.settings.title && !self._fullscreen) {
        width = layoutRect.headerW;
        if (width > layoutRect.w) {
          x = layoutRect.x - Math.max(0, width / 2);
          self.layoutRect({
            w: width,
            x: x
          });
          needsRecalc = true;
        }
      }
      if (statusbar) {
        statusbar.layoutRect({ w: self.layoutRect().innerW }).recalc();
        width = statusbar.layoutRect().minW + layoutRect.deltaW;
        if (width > layoutRect.w) {
          x = layoutRect.x - Math.max(0, width - layoutRect.w);
          self.layoutRect({
            w: width,
            x: x
          });
          needsRecalc = true;
        }
      }
      if (needsRecalc) {
        self.recalc();
      }
    },
    initLayoutRect: function () {
      var self = this;
      var layoutRect = self._super();
      var deltaH = 0, headEl;
      if (self.settings.title && !self._fullscreen) {
        headEl = self.getEl('head');
        var size = funcs.getSize(headEl);
        layoutRect.headerW = size.width;
        layoutRect.headerH = size.height;
        deltaH += layoutRect.headerH;
      }
      if (self.statusbar) {
        deltaH += self.statusbar.layoutRect().h;
      }
      layoutRect.deltaH += deltaH;
      layoutRect.minH += deltaH;
      layoutRect.h += deltaH;
      var rect = funcs.getWindowSize();
      layoutRect.x = self.settings.x || Math.max(0, rect.w / 2 - layoutRect.w / 2);
      layoutRect.y = self.settings.y || Math.max(0, rect.h / 2 - layoutRect.h / 2);
      return layoutRect;
    },
    renderHtml: function () {
      var self = this, layout = self._layout, id = self._id, prefix = self.classPrefix;
      var settings = self.settings;
      var headerHtml = '', footerHtml = '', html = settings.html;
      self.preRender();
      layout.preRender(self);
      if (settings.title) {
        headerHtml = '<div id="' + id + '-head" class="' + prefix + 'window-head">' + '<div id="' + id + '-title" class="' + prefix + 'title">' + self.encode(settings.title) + '</div>' + '<div id="' + id + '-dragh" class="' + prefix + 'dragh"></div>' + '<button type="button" class="' + prefix + 'close" aria-hidden="true">' + '<i class="mce-ico mce-i-remove"></i>' + '</button>' + '</div>';
      }
      if (settings.url) {
        html = '<iframe src="' + settings.url + '" tabindex="-1"></iframe>';
      }
      if (typeof html === 'undefined') {
        html = layout.renderHtml(self);
      }
      if (self.statusbar) {
        footerHtml = self.statusbar.renderHtml();
      }
      return '<div id="' + id + '" class="' + self.classes + '" hidefocus="1">' + '<div class="' + self.classPrefix + 'reset" role="application">' + headerHtml + '<div id="' + id + '-body" class="' + self.bodyClasses + '">' + html + '</div>' + footerHtml + '</div>' + '</div>';
    },
    fullscreen: function (state) {
      var self = this;
      var documentElement = document.documentElement;
      var slowRendering;
      var prefix = self.classPrefix;
      var layoutRect;
      if (state !== self._fullscreen) {
        global$9(window).on('resize', function () {
          var time;
          if (self._fullscreen) {
            if (!slowRendering) {
              time = new Date().getTime();
              var rect = funcs.getWindowSize();
              self.moveTo(0, 0).resizeTo(rect.w, rect.h);
              if (new Date().getTime() - time > 50) {
                slowRendering = true;
              }
            } else {
              if (!self._timer) {
                self._timer = global$7.setTimeout(function () {
                  var rect = funcs.getWindowSize();
                  self.moveTo(0, 0).resizeTo(rect.w, rect.h);
                  self._timer = 0;
                }, 50);
              }
            }
          }
        });
        layoutRect = self.layoutRect();
        self._fullscreen = state;
        if (!state) {
          self.borderBox = $_focdcktxjh8lz3mn.parseBox(self.settings.border);
          self.getEl('head').style.display = '';
          layoutRect.deltaH += layoutRect.headerH;
          global$9([
            documentElement,
            document.body
          ]).removeClass(prefix + 'fullscreen');
          self.classes.remove('fullscreen');
          self.moveTo(self._initial.x, self._initial.y).resizeTo(self._initial.w, self._initial.h);
        } else {
          self._initial = {
            x: layoutRect.x,
            y: layoutRect.y,
            w: layoutRect.w,
            h: layoutRect.h
          };
          self.borderBox = $_focdcktxjh8lz3mn.parseBox('0');
          self.getEl('head').style.display = 'none';
          layoutRect.deltaH -= layoutRect.headerH + 2;
          global$9([
            documentElement,
            document.body
          ]).addClass(prefix + 'fullscreen');
          self.classes.add('fullscreen');
          var rect = funcs.getWindowSize();
          self.moveTo(0, 0).resizeTo(rect.w, rect.h);
        }
      }
      return self.reflow();
    },
    postRender: function () {
      var self = this;
      var startPos;
      setTimeout(function () {
        self.classes.add('in');
        self.fire('open');
      }, 0);
      self._super();
      if (self.statusbar) {
        self.statusbar.postRender();
      }
      self.focus();
      this.dragHelper = new DragHelper(self._id + '-dragh', {
        start: function () {
          startPos = {
            x: self.layoutRect().x,
            y: self.layoutRect().y
          };
        },
        drag: function (e) {
          self.moveTo(startPos.x + e.deltaX, startPos.y + e.deltaY);
        }
      });
      self.on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
          self.close();
        }
      });
      windows.push(self);
      toggleFullScreenState(true);
    },
    submit: function () {
      return this.fire('submit', { data: this.toJSON() });
    },
    remove: function () {
      var self = this;
      var i;
      self.dragHelper.destroy();
      self._super();
      if (self.statusbar) {
        this.statusbar.remove();
      }
      toggleBodyFullScreenClasses(self.classPrefix, false);
      i = windows.length;
      while (i--) {
        if (windows[i] === self) {
          windows.splice(i, 1);
        }
      }
      toggleFullScreenState(windows.length > 0);
    },
    getContentWindow: function () {
      var ifr = this.getEl().getElementsByTagName('iframe')[0];
      return ifr ? ifr.contentWindow : null;
    }
  });
  handleWindowResize();

  var MessageBox = Window.extend({
    init: function (settings) {
      settings = {
        border: 1,
        padding: 20,
        layout: 'flex',
        pack: 'center',
        align: 'center',
        containerCls: 'panel',
        autoScroll: true,
        buttons: {
          type: 'button',
          text: 'Ok',
          action: 'ok'
        },
        items: {
          type: 'label',
          multiline: true,
          maxWidth: 500,
          maxHeight: 200
        }
      };
      this._super(settings);
    },
    Statics: {
      OK: 1,
      OK_CANCEL: 2,
      YES_NO: 3,
      YES_NO_CANCEL: 4,
      msgBox: function (settings) {
        var buttons;
        var callback = settings.callback || function () {
        };
        function createButton(text, status, primary) {
          return {
            type: 'button',
            text: text,
            subtype: primary ? 'primary' : '',
            onClick: function (e) {
              e.control.parents()[1].close();
              callback(status);
            }
          };
        }
        switch (settings.buttons) {
        case MessageBox.OK_CANCEL:
          buttons = [
            createButton('Ok', true, true),
            createButton('Cancel', false)
          ];
          break;
        case MessageBox.YES_NO:
        case MessageBox.YES_NO_CANCEL:
          buttons = [
            createButton('Yes', 1, true),
            createButton('No', 0)
          ];
          if (settings.buttons === MessageBox.YES_NO_CANCEL) {
            buttons.push(createButton('Cancel', -1));
          }
          break;
        default:
          buttons = [createButton('Ok', true, true)];
          break;
        }
        return new Window({
          padding: 20,
          x: settings.x,
          y: settings.y,
          minWidth: 300,
          minHeight: 100,
          layout: 'flex',
          pack: 'center',
          align: 'center',
          buttons: buttons,
          title: settings.title,
          role: 'alertdialog',
          items: {
            type: 'label',
            multiline: true,
            maxWidth: 500,
            maxHeight: 200,
            text: settings.text
          },
          onPostRender: function () {
            this.aria('describedby', this.items()[0]._id);
          },
          onClose: settings.onClose,
          onCancel: function () {
            callback(false);
          }
        }).renderTo(document.body).reflow();
      },
      alert: function (settings, callback) {
        if (typeof settings === 'string') {
          settings = { text: settings };
        }
        settings.callback = callback;
        return MessageBox.msgBox(settings);
      },
      confirm: function (settings, callback) {
        if (typeof settings === 'string') {
          settings = { text: settings };
        }
        settings.callback = callback;
        settings.buttons = MessageBox.OK_CANCEL;
        return MessageBox.msgBox(settings);
      }
    }
  });

  function WindowManagerImpl (editor) {
    var open = function (args, params, closeCallback) {
      var win;
      args.title = args.title || ' ';
      args.url = args.url || args.file;
      if (args.url) {
        args.width = parseInt(args.width || 320, 10);
        args.height = parseInt(args.height || 240, 10);
      }
      if (args.body) {
        args.items = {
          defaults: args.defaults,
          type: args.bodyType || 'form',
          items: args.body,
          data: args.data,
          callbacks: args.commands
        };
      }
      if (!args.url && !args.buttons) {
        args.buttons = [
          {
            text: 'Ok',
            subtype: 'primary',
            onclick: function () {
              win.find('form')[0].submit();
            }
          },
          {
            text: 'Cancel',
            onclick: function () {
              win.close();
            }
          }
        ];
      }
      win = new Window(args);
      win.on('close', function () {
        closeCallback(win);
      });
      if (args.data) {
        win.on('postRender', function () {
          this.find('*').each(function (ctrl) {
            var name = ctrl.name();
            if (name in args.data) {
              ctrl.value(args.data[name]);
            }
          });
        });
      }
      win.features = args || {};
      win.params = params || {};
      win = win.renderTo(document.body).reflow();
      return win;
    };
    var alert = function (message, choiceCallback, closeCallback) {
      var win;
      win = MessageBox.alert(message, function () {
        choiceCallback();
      });
      win.on('close', function () {
        closeCallback(win);
      });
      return win;
    };
    var confirm = function (message, choiceCallback, closeCallback) {
      var win;
      win = MessageBox.confirm(message, function (state) {
        choiceCallback(state);
      });
      win.on('close', function () {
        closeCallback(win);
      });
      return win;
    };
    var close = function (window) {
      window.close();
    };
    var getParams = function (window) {
      return window.params;
    };
    var setParams = function (window, params) {
      window.params = params;
    };
    return {
      open: open,
      alert: alert,
      confirm: confirm,
      close: close,
      getParams: getParams,
      setParams: setParams
    };
  }

  var get = function (editor) {
    var renderUI = function (args) {
      return $_5ent4szjh8lz3ja.renderUI(editor, this, args);
    };
    var resizeTo = function (w, h) {
      return $_5toavetjjh8lz3ko.resizeTo(editor, w, h);
    };
    var resizeBy = function (dw, dh) {
      return $_5toavetjjh8lz3ko.resizeBy(editor, dw, dh);
    };
    var getNotificationManagerImpl = function () {
      return NotificationManagerImpl(editor);
    };
    var getWindowManagerImpl = function () {
      return WindowManagerImpl(editor);
    };
    return {
      renderUI: renderUI,
      resizeTo: resizeTo,
      resizeBy: resizeBy,
      getNotificationManagerImpl: getNotificationManagerImpl,
      getWindowManagerImpl: getWindowManagerImpl
    };
  };
  var $_1os0v5syjh8lz3j9 = { get: get };

  var Layout = global$10.extend({
    Defaults: {
      firstControlClass: 'first',
      lastControlClass: 'last'
    },
    init: function (settings) {
      this.settings = global$2.extend({}, this.Defaults, settings);
    },
    preRender: function (container) {
      container.bodyClasses.add(this.settings.containerClass);
    },
    applyClasses: function (items) {
      var self = this;
      var settings = self.settings;
      var firstClass, lastClass, firstItem, lastItem;
      firstClass = settings.firstControlClass;
      lastClass = settings.lastControlClass;
      items.each(function (item) {
        item.classes.remove(firstClass).remove(lastClass).add(settings.controlClass);
        if (item.visible()) {
          if (!firstItem) {
            firstItem = item;
          }
          lastItem = item;
        }
      });
      if (firstItem) {
        firstItem.classes.add(firstClass);
      }
      if (lastItem) {
        lastItem.classes.add(lastClass);
      }
    },
    renderHtml: function (container) {
      var self = this;
      var html = '';
      self.applyClasses(container.items());
      container.items().each(function (item) {
        html += item.renderHtml();
      });
      return html;
    },
    recalc: function () {
    },
    postRender: function () {
    },
    isNative: function () {
      return false;
    }
  });

  var AbsoluteLayout = Layout.extend({
    Defaults: {
      containerClass: 'abs-layout',
      controlClass: 'abs-layout-item'
    },
    recalc: function (container) {
      container.items().filter(':visible').each(function (ctrl) {
        var settings = ctrl.settings;
        ctrl.layoutRect({
          x: settings.x,
          y: settings.y,
          w: settings.w,
          h: settings.h
        });
        if (ctrl.recalc) {
          ctrl.recalc();
        }
      });
    },
    renderHtml: function (container) {
      return '<div id="' + container._id + '-absend" class="' + container.classPrefix + 'abs-end"></div>' + this._super(container);
    }
  });

  var Button = Widget.extend({
    Defaults: {
      classes: 'widget btn',
      role: 'button'
    },
    init: function (settings) {
      var self = this;
      var size;
      self._super(settings);
      settings = self.settings;
      size = self.settings.size;
      self.on('click mousedown', function (e) {
        e.preventDefault();
      });
      self.on('touchstart', function (e) {
        self.fire('click', e);
        e.preventDefault();
      });
      if (settings.subtype) {
        self.classes.add(settings.subtype);
      }
      if (size) {
        self.classes.add('btn-' + size);
      }
      if (settings.icon) {
        self.icon(settings.icon);
      }
    },
    icon: function (icon) {
      if (!arguments.length) {
        return this.state.get('icon');
      }
      this.state.set('icon', icon);
      return this;
    },
    repaint: function () {
      var btnElm = this.getEl().firstChild;
      var btnStyle;
      if (btnElm) {
        btnStyle = btnElm.style;
        btnStyle.width = btnStyle.height = '100%';
      }
      this._super();
    },
    renderHtml: function () {
      var self = this, id = self._id, prefix = self.classPrefix;
      var icon = self.state.get('icon'), image;
      var text = self.state.get('text');
      var textHtml = '';
      var ariaPressed;
      var settings = self.settings;
      image = settings.image;
      if (image) {
        icon = 'none';
        if (typeof image !== 'string') {
          image = window.getSelection ? image[0] : image[1];
        }
        image = ' style="background-image: url(\'' + image + '\')"';
      } else {
        image = '';
      }
      if (text) {
        self.classes.add('btn-has-text');
        textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>';
      }
      icon = icon ? prefix + 'ico ' + prefix + 'i-' + icon : '';
      ariaPressed = typeof settings.active === 'boolean' ? ' aria-pressed="' + settings.active + '"' : '';
      return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1"' + ariaPressed + '>' + '<button id="' + id + '-button" role="presentation" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + '</button>' + '</div>';
    },
    bindStates: function () {
      var self = this, $ = self.$, textCls = self.classPrefix + 'txt';
      function setButtonText(text) {
        var $span = $('span.' + textCls, self.getEl());
        if (text) {
          if (!$span[0]) {
            $('button:first', self.getEl()).append('<span class="' + textCls + '"></span>');
            $span = $('span.' + textCls, self.getEl());
          }
          $span.html(self.encode(text));
        } else {
          $span.remove();
        }
        self.classes.toggle('btn-has-text', !!text);
      }
      self.state.on('change:text', function (e) {
        setButtonText(e.value);
      });
      self.state.on('change:icon', function (e) {
        var icon = e.value;
        var prefix = self.classPrefix;
        self.settings.icon = icon;
        icon = icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : '';
        var btnElm = self.getEl().firstChild;
        var iconElm = btnElm.getElementsByTagName('i')[0];
        if (icon) {
          if (!iconElm || iconElm !== btnElm.firstChild) {
            iconElm = document.createElement('i');
            btnElm.insertBefore(iconElm, btnElm.firstChild);
          }
          iconElm.className = icon;
        } else if (iconElm) {
          btnElm.removeChild(iconElm);
        }
        setButtonText(self.state.get('text'));
      });
      return self._super();
    }
  });

  var BrowseButton = Button.extend({
    init: function (settings) {
      var self = this;
      settings = global$2.extend({
        text: 'Browse...',
        multiple: false,
        accept: null
      }, settings);
      self._super(settings);
      self.classes.add('browsebutton');
      if (settings.multiple) {
        self.classes.add('multiple');
      }
    },
    postRender: function () {
      var self = this;
      var input = funcs.create('input', {
        type: 'file',
        id: self._id + '-browse',
        accept: self.settings.accept
      });
      self._super();
      global$9(input).on('change', function (e) {
        var files = e.target.files;
        self.value = function () {
          if (!files.length) {
            return null;
          } else if (self.settings.multiple) {
            return files;
          } else {
            return files[0];
          }
        };
        e.preventDefault();
        if (files.length) {
          self.fire('change', e);
        }
      });
      global$9(input).on('click', function (e) {
        e.stopPropagation();
      });
      global$9(self.getEl('button')).on('click', function (e) {
        e.stopPropagation();
        input.click();
      });
      self.getEl().appendChild(input);
    },
    remove: function () {
      global$9(this.getEl('button')).off();
      global$9(this.getEl('input')).off();
      this._super();
    }
  });

  var ButtonGroup = Container.extend({
    Defaults: {
      defaultType: 'button',
      role: 'group'
    },
    renderHtml: function () {
      var self = this, layout = self._layout;
      self.classes.add('btn-group');
      self.preRender();
      layout.preRender(self);
      return '<div id="' + self._id + '" class="' + self.classes + '">' + '<div id="' + self._id + '-body">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>';
    }
  });

  var Checkbox = Widget.extend({
    Defaults: {
      classes: 'checkbox',
      role: 'checkbox',
      checked: false
    },
    init: function (settings) {
      var self = this;
      self._super(settings);
      self.on('click mousedown', function (e) {
        e.preventDefault();
      });
      self.on('click', function (e) {
        e.preventDefault();
        if (!self.disabled()) {
          self.checked(!self.checked());
        }
      });
      self.checked(self.settings.checked);
    },
    checked: function (state) {
      if (!arguments.length) {
        return this.state.get('checked');
      }
      this.state.set('checked', state);
      return this;
    },
    value: function (state) {
      if (!arguments.length) {
        return this.checked();
      }
      return this.checked(state);
    },
    renderHtml: function () {
      var self = this, id = self._id, prefix = self.classPrefix;
      return '<div id="' + id + '" class="' + self.classes + '" unselectable="on" aria-labelledby="' + id + '-al" tabindex="-1">' + '<i class="' + prefix + 'ico ' + prefix + 'i-checkbox"></i>' + '<span id="' + id + '-al" class="' + prefix + 'label">' + self.encode(self.state.get('text')) + '</span>' + '</div>';
    },
    bindStates: function () {
      var self = this;
      function checked(state) {
        self.classes.toggle('checked', state);
        self.aria('checked', state);
      }
      self.state.on('change:text', function (e) {
        self.getEl('al').firstChild.data = self.translate(e.value);
      });
      self.state.on('change:checked change:value', function (e) {
        self.fire('change');
        checked(e.value);
      });
      self.state.on('change:icon', function (e) {
        var icon = e.value;
        var prefix = self.classPrefix;
        if (typeof icon === 'undefined') {
          return self.settings.icon;
        }
        self.settings.icon = icon;
        icon = icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : '';
        var btnElm = self.getEl().firstChild;
        var iconElm = btnElm.getElementsByTagName('i')[0];
        if (icon) {
          if (!iconElm || iconElm !== btnElm.firstChild) {
            iconElm = document.createElement('i');
            btnElm.insertBefore(iconElm, btnElm.firstChild);
          }
          iconElm.className = icon;
        } else if (iconElm) {
          btnElm.removeChild(iconElm);
        }
      });
      if (self.state.get('checked')) {
        checked(true);
      }
      return self._super();
    }
  });

  var global$13 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var ComboBox = Widget.extend({
    init: function (settings) {
      var self = this;
      self._super(settings);
      settings = self.settings;
      self.classes.add('combobox');
      self.subinput = true;
      self.ariaTarget = 'inp';
      settings.menu = settings.menu || settings.values;
      if (settings.menu) {
        settings.icon = 'caret';
      }
      self.on('click', function (e) {
        var elm = e.target;
        var root = self.getEl();
        if (!global$9.contains(root, elm) && elm !== root) {
          return;
        }
        while (elm && elm !== root) {
          if (elm.id && elm.id.indexOf('-open') !== -1) {
            self.fire('action');
            if (settings.menu) {
              self.showMenu();
              if (e.aria) {
                self.menu.items()[0].focus();
              }
            }
          }
          elm = elm.parentNode;
        }
      });
      self.on('keydown', function (e) {
        var rootControl;
        if (e.keyCode === 13 && e.target.nodeName === 'INPUT') {
          e.preventDefault();
          self.parents().reverse().each(function (ctrl) {
            if (ctrl.toJSON) {
              rootControl = ctrl;
              return false;
            }
          });
          self.fire('submit', { data: rootControl.toJSON() });
        }
      });
      self.on('keyup', function (e) {
        if (e.target.nodeName === 'INPUT') {
          var oldValue = self.state.get('value');
          var newValue = e.target.value;
          if (newValue !== oldValue) {
            self.state.set('value', newValue);
            self.fire('autocomplete', e);
          }
        }
      });
      self.on('mouseover', function (e) {
        var tooltip = self.tooltip().moveTo(-65535);
        if (self.statusLevel() && e.target.className.indexOf(self.classPrefix + 'status') !== -1) {
          var statusMessage = self.statusMessage() || 'Ok';
          var rel = tooltip.text(statusMessage).show().testMoveRel(e.target, [
            'bc-tc',
            'bc-tl',
            'bc-tr'
          ]);
          tooltip.classes.toggle('tooltip-n', rel === 'bc-tc');
          tooltip.classes.toggle('tooltip-nw', rel === 'bc-tl');
          tooltip.classes.toggle('tooltip-ne', rel === 'bc-tr');
          tooltip.moveRel(e.target, rel);
        }
      });
    },
    statusLevel: function (value) {
      if (arguments.length > 0) {
        this.state.set('statusLevel', value);
      }
      return this.state.get('statusLevel');
    },
    statusMessage: function (value) {
      if (arguments.length > 0) {
        this.state.set('statusMessage', value);
      }
      return this.state.get('statusMessage');
    },
    showMenu: function () {
      var self = this;
      var settings = self.settings;
      var menu;
      if (!self.menu) {
        menu = settings.menu || [];
        if (menu.length) {
          menu = {
            type: 'menu',
            items: menu
          };
        } else {
          menu.type = menu.type || 'menu';
        }
        self.menu = global$4.create(menu).parent(self).renderTo(self.getContainerElm());
        self.fire('createmenu');
        self.menu.reflow();
        self.menu.on('cancel', function (e) {
          if (e.control === self.menu) {
            self.focus();
          }
        });
        self.menu.on('show hide', function (e) {
          e.control.items().each(function (ctrl) {
            ctrl.active(ctrl.value() === self.value());
          });
        }).fire('show');
        self.menu.on('select', function (e) {
          self.value(e.control.value());
        });
        self.on('focusin', function (e) {
          if (e.target.tagName.toUpperCase() === 'INPUT') {
            self.menu.hide();
          }
        });
        self.aria('expanded', true);
      }
      self.menu.show();
      self.menu.layoutRect({ w: self.layoutRect().w });
      self.menu.moveRel(self.getEl(), self.isRtl() ? [
        'br-tr',
        'tr-br'
      ] : [
        'bl-tl',
        'tl-bl'
      ]);
    },
    focus: function () {
      this.getEl('inp').focus();
    },
    repaint: function () {
      var self = this, elm = self.getEl(), openElm = self.getEl('open'), rect = self.layoutRect();
      var width, lineHeight, innerPadding = 0;
      var inputElm = elm.firstChild;
      if (self.statusLevel() && self.statusLevel() !== 'none') {
        innerPadding = parseInt(funcs.getRuntimeStyle(inputElm, 'padding-right'), 10) - parseInt(funcs.getRuntimeStyle(inputElm, 'padding-left'), 10);
      }
      if (openElm) {
        width = rect.w - funcs.getSize(openElm).width - 10;
      } else {
        width = rect.w - 10;
      }
      var doc = document;
      if (doc.all && (!doc.documentMode || doc.documentMode <= 8)) {
        lineHeight = self.layoutRect().h - 2 + 'px';
      }
      global$9(inputElm).css({
        width: width - innerPadding,
        lineHeight: lineHeight
      });
      self._super();
      return self;
    },
    postRender: function () {
      var self = this;
      global$9(this.getEl('inp')).on('change', function (e) {
        self.state.set('value', e.target.value);
        self.fire('change', e);
      });
      return self._super();
    },
    renderHtml: function () {
      var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix;
      var value = self.state.get('value') || '';
      var icon, text, openBtnHtml = '', extraAttrs = '', statusHtml = '';
      if ('spellcheck' in settings) {
        extraAttrs += ' spellcheck="' + settings.spellcheck + '"';
      }
      if (settings.maxLength) {
        extraAttrs += ' maxlength="' + settings.maxLength + '"';
      }
      if (settings.size) {
        extraAttrs += ' size="' + settings.size + '"';
      }
      if (settings.subtype) {
        extraAttrs += ' type="' + settings.subtype + '"';
      }
      statusHtml = '<i id="' + id + '-status" class="mce-status mce-ico" style="display: none"></i>';
      if (self.disabled()) {
        extraAttrs += ' disabled="disabled"';
      }
      icon = settings.icon;
      if (icon && icon !== 'caret') {
        icon = prefix + 'ico ' + prefix + 'i-' + settings.icon;
      }
      text = self.state.get('text');
      if (icon || text) {
        openBtnHtml = '<div id="' + id + '-open" class="' + prefix + 'btn ' + prefix + 'open" tabIndex="-1" role="button">' + '<button id="' + id + '-action" type="button" hidefocus="1" tabindex="-1">' + (icon !== 'caret' ? '<i class="' + icon + '"></i>' : '<i class="' + prefix + 'caret"></i>') + (text ? (icon ? ' ' : '') + text : '') + '</button>' + '</div>';
        self.classes.add('has-open');
      }
      return '<div id="' + id + '" class="' + self.classes + '">' + '<input id="' + id + '-inp" class="' + prefix + 'textbox" value="' + self.encode(value, false) + '" hidefocus="1"' + extraAttrs + ' placeholder="' + self.encode(settings.placeholder) + '" />' + statusHtml + openBtnHtml + '</div>';
    },
    value: function (value) {
      if (arguments.length) {
        this.state.set('value', value);
        return this;
      }
      if (this.state.get('rendered')) {
        this.state.set('value', this.getEl('inp').value);
      }
      return this.state.get('value');
    },
    showAutoComplete: function (items, term) {
      var self = this;
      if (items.length === 0) {
        self.hideMenu();
        return;
      }
      var insert = function (value, title) {
        return function () {
          self.fire('selectitem', {
            title: title,
            value: value
          });
        };
      };
      if (self.menu) {
        self.menu.items().remove();
      } else {
        self.menu = global$4.create({
          type: 'menu',
          classes: 'combobox-menu',
          layout: 'flow'
        }).parent(self).renderTo();
      }
      global$2.each(items, function (item) {
        self.menu.add({
          text: item.title,
          url: item.previewUrl,
          match: term,
          classes: 'menu-item-ellipsis',
          onclick: insert(item.value, item.title)
        });
      });
      self.menu.renderNew();
      self.hideMenu();
      self.menu.on('cancel', function (e) {
        if (e.control.parent() === self.menu) {
          e.stopPropagation();
          self.focus();
          self.hideMenu();
        }
      });
      self.menu.on('select', function () {
        self.focus();
      });
      var maxW = self.layoutRect().w;
      self.menu.layoutRect({
        w: maxW,
        minW: 0,
        maxW: maxW
      });
      self.menu.repaint();
      self.menu.reflow();
      self.menu.show();
      self.menu.moveRel(self.getEl(), self.isRtl() ? [
        'br-tr',
        'tr-br'
      ] : [
        'bl-tl',
        'tl-bl'
      ]);
    },
    hideMenu: function () {
      if (this.menu) {
        this.menu.hide();
      }
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:value', function (e) {
        if (self.getEl('inp').value !== e.value) {
          self.getEl('inp').value = e.value;
        }
      });
      self.state.on('change:disabled', function (e) {
        self.getEl('inp').disabled = e.value;
      });
      self.state.on('change:statusLevel', function (e) {
        var statusIconElm = self.getEl('status');
        var prefix = self.classPrefix, value = e.value;
        funcs.css(statusIconElm, 'display', value === 'none' ? 'none' : '');
        funcs.toggleClass(statusIconElm, prefix + 'i-checkmark', value === 'ok');
        funcs.toggleClass(statusIconElm, prefix + 'i-warning', value === 'warn');
        funcs.toggleClass(statusIconElm, prefix + 'i-error', value === 'error');
        self.classes.toggle('has-status', value !== 'none');
        self.repaint();
      });
      funcs.on(self.getEl('status'), 'mouseleave', function () {
        self.tooltip().hide();
      });
      self.on('cancel', function (e) {
        if (self.menu && self.menu.visible()) {
          e.stopPropagation();
          self.hideMenu();
        }
      });
      var focusIdx = function (idx, menu) {
        if (menu && menu.items().length > 0) {
          menu.items().eq(idx)[0].focus();
        }
      };
      self.on('keydown', function (e) {
        var keyCode = e.keyCode;
        if (e.target.nodeName === 'INPUT') {
          if (keyCode === global$13.DOWN) {
            e.preventDefault();
            self.fire('autocomplete');
            focusIdx(0, self.menu);
          } else if (keyCode === global$13.UP) {
            e.preventDefault();
            focusIdx(-1, self.menu);
          }
        }
      });
      return self._super();
    },
    remove: function () {
      global$9(this.getEl('inp')).off();
      if (this.menu) {
        this.menu.remove();
      }
      this._super();
    }
  });

  var ColorBox = ComboBox.extend({
    init: function (settings) {
      var self = this;
      settings.spellcheck = false;
      if (settings.onaction) {
        settings.icon = 'none';
      }
      self._super(settings);
      self.classes.add('colorbox');
      self.on('change keyup postrender', function () {
        self.repaintColor(self.value());
      });
    },
    repaintColor: function (value) {
      var openElm = this.getEl('open');
      var elm = openElm ? openElm.getElementsByTagName('i')[0] : null;
      if (elm) {
        try {
          elm.style.background = value;
        } catch (ex) {
        }
      }
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:value', function (e) {
        if (self.state.get('rendered')) {
          self.repaintColor(e.value);
        }
      });
      return self._super();
    }
  });

  var PanelButton = Button.extend({
    showPanel: function () {
      var self = this, settings = self.settings;
      self.classes.add('opened');
      if (!self.panel) {
        var panelSettings = settings.panel;
        if (panelSettings.type) {
          panelSettings = {
            layout: 'grid',
            items: panelSettings
          };
        }
        panelSettings.role = panelSettings.role || 'dialog';
        panelSettings.popover = true;
        panelSettings.autohide = true;
        panelSettings.ariaRoot = true;
        self.panel = new FloatPanel(panelSettings).on('hide', function () {
          self.classes.remove('opened');
        }).on('cancel', function (e) {
          e.stopPropagation();
          self.focus();
          self.hidePanel();
        }).parent(self).renderTo(self.getContainerElm());
        self.panel.fire('show');
        self.panel.reflow();
      } else {
        self.panel.show();
      }
      var rtlRels = [
        'bc-tc',
        'bc-tl',
        'bc-tr'
      ];
      var ltrRels = [
        'bc-tc',
        'bc-tr',
        'bc-tl',
        'tc-bc',
        'tc-br',
        'tc-bl'
      ];
      var rel = self.panel.testMoveRel(self.getEl(), settings.popoverAlign || (self.isRtl() ? rtlRels : ltrRels));
      self.panel.classes.toggle('start', rel.substr(-1) === 'l');
      self.panel.classes.toggle('end', rel.substr(-1) === 'r');
      var isTop = rel.substr(0, 1) === 't';
      self.panel.classes.toggle('bottom', !isTop);
      self.panel.classes.toggle('top', isTop);
      self.panel.moveRel(self.getEl(), rel);
    },
    hidePanel: function () {
      var self = this;
      if (self.panel) {
        self.panel.hide();
      }
    },
    postRender: function () {
      var self = this;
      self.aria('haspopup', true);
      self.on('click', function (e) {
        if (e.control === self) {
          if (self.panel && self.panel.visible()) {
            self.hidePanel();
          } else {
            self.showPanel();
            self.panel.focus(!!e.aria);
          }
        }
      });
      return self._super();
    },
    remove: function () {
      if (this.panel) {
        this.panel.remove();
        this.panel = null;
      }
      return this._super();
    }
  });

  var DOM$3 = global$3.DOM;
  var ColorButton = PanelButton.extend({
    init: function (settings) {
      this._super(settings);
      this.classes.add('splitbtn');
      this.classes.add('colorbutton');
    },
    color: function (color) {
      if (color) {
        this._color = color;
        this.getEl('preview').style.backgroundColor = color;
        return this;
      }
      return this._color;
    },
    resetColor: function () {
      this._color = null;
      this.getEl('preview').style.backgroundColor = null;
      return this;
    },
    renderHtml: function () {
      var self = this, id = self._id, prefix = self.classPrefix, text = self.state.get('text');
      var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : '';
      var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : '';
      var textHtml = '';
      if (text) {
        self.classes.add('btn-has-text');
        textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>';
      }
      return '<div id="' + id + '" class="' + self.classes + '" role="button" tabindex="-1" aria-haspopup="true">' + '<button role="presentation" hidefocus="1" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + '<span id="' + id + '-preview" class="' + prefix + 'preview"></span>' + textHtml + '</button>' + '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>';
    },
    postRender: function () {
      var self = this, onClickHandler = self.settings.onclick;
      self.on('click', function (e) {
        if (e.aria && e.aria.key === 'down') {
          return;
        }
        if (e.control === self && !DOM$3.getParent(e.target, '.' + self.classPrefix + 'open')) {
          e.stopImmediatePropagation();
          onClickHandler.call(self, e);
        }
      });
      delete self.settings.onclick;
      return self._super();
    }
  });

  var global$14 = tinymce.util.Tools.resolve('tinymce.util.Color');

  var ColorPicker = Widget.extend({
    Defaults: { classes: 'widget colorpicker' },
    init: function (settings) {
      this._super(settings);
    },
    postRender: function () {
      var self = this;
      var color = self.color();
      var hsv, hueRootElm, huePointElm, svRootElm, svPointElm;
      hueRootElm = self.getEl('h');
      huePointElm = self.getEl('hp');
      svRootElm = self.getEl('sv');
      svPointElm = self.getEl('svp');
      function getPos(elm, event) {
        var pos = funcs.getPos(elm);
        var x, y;
        x = event.pageX - pos.x;
        y = event.pageY - pos.y;
        x = Math.max(0, Math.min(x / elm.clientWidth, 1));
        y = Math.max(0, Math.min(y / elm.clientHeight, 1));
        return {
          x: x,
          y: y
        };
      }
      function updateColor(hsv, hueUpdate) {
        var hue = (360 - hsv.h) / 360;
        funcs.css(huePointElm, { top: hue * 100 + '%' });
        if (!hueUpdate) {
          funcs.css(svPointElm, {
            left: hsv.s + '%',
            top: 100 - hsv.v + '%'
          });
        }
        svRootElm.style.background = global$14({
          s: 100,
          v: 100,
          h: hsv.h
        }).toHex();
        self.color().parse({
          s: hsv.s,
          v: hsv.v,
          h: hsv.h
        });
      }
      function updateSaturationAndValue(e) {
        var pos;
        pos = getPos(svRootElm, e);
        hsv.s = pos.x * 100;
        hsv.v = (1 - pos.y) * 100;
        updateColor(hsv);
        self.fire('change');
      }
      function updateHue(e) {
        var pos;
        pos = getPos(hueRootElm, e);
        hsv = color.toHsv();
        hsv.h = (1 - pos.y) * 360;
        updateColor(hsv, true);
        self.fire('change');
      }
      self._repaint = function () {
        hsv = color.toHsv();
        updateColor(hsv);
      };
      self._super();
      self._svdraghelper = new DragHelper(self._id + '-sv', {
        start: updateSaturationAndValue,
        drag: updateSaturationAndValue
      });
      self._hdraghelper = new DragHelper(self._id + '-h', {
        start: updateHue,
        drag: updateHue
      });
      self._repaint();
    },
    rgb: function () {
      return this.color().toRgb();
    },
    value: function (value) {
      var self = this;
      if (arguments.length) {
        self.color().parse(value);
        if (self._rendered) {
          self._repaint();
        }
      } else {
        return self.color().toHex();
      }
    },
    color: function () {
      if (!this._color) {
        this._color = global$14();
      }
      return this._color;
    },
    renderHtml: function () {
      var self = this;
      var id = self._id;
      var prefix = self.classPrefix;
      var hueHtml;
      var stops = '#ff0000,#ff0080,#ff00ff,#8000ff,#0000ff,#0080ff,#00ffff,#00ff80,#00ff00,#80ff00,#ffff00,#ff8000,#ff0000';
      function getOldIeFallbackHtml() {
        var i, l, html = '', gradientPrefix, stopsList;
        gradientPrefix = 'filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=';
        stopsList = stops.split(',');
        for (i = 0, l = stopsList.length - 1; i < l; i++) {
          html += '<div class="' + prefix + 'colorpicker-h-chunk" style="' + 'height:' + 100 / l + '%;' + gradientPrefix + stopsList[i] + ',endColorstr=' + stopsList[i + 1] + ');' + '-ms-' + gradientPrefix + stopsList[i] + ',endColorstr=' + stopsList[i + 1] + ')' + '"></div>';
        }
        return html;
      }
      var gradientCssText = 'background: -ms-linear-gradient(top,' + stops + ');' + 'background: linear-gradient(to bottom,' + stops + ');';
      hueHtml = '<div id="' + id + '-h" class="' + prefix + 'colorpicker-h" style="' + gradientCssText + '">' + getOldIeFallbackHtml() + '<div id="' + id + '-hp" class="' + prefix + 'colorpicker-h-marker"></div>' + '</div>';
      return '<div id="' + id + '" class="' + self.classes + '">' + '<div id="' + id + '-sv" class="' + prefix + 'colorpicker-sv">' + '<div class="' + prefix + 'colorpicker-overlay1">' + '<div class="' + prefix + 'colorpicker-overlay2">' + '<div id="' + id + '-svp" class="' + prefix + 'colorpicker-selector1">' + '<div class="' + prefix + 'colorpicker-selector2"></div>' + '</div>' + '</div>' + '</div>' + '</div>' + hueHtml + '</div>';
    }
  });

  var DropZone = Widget.extend({
    init: function (settings) {
      var self = this;
      settings = global$2.extend({
        height: 100,
        text: 'Drop an image here',
        multiple: false,
        accept: null
      }, settings);
      self._super(settings);
      self.classes.add('dropzone');
      if (settings.multiple) {
        self.classes.add('multiple');
      }
    },
    renderHtml: function () {
      var self = this;
      var attrs, elm;
      var cfg = self.settings;
      attrs = {
        id: self._id,
        hidefocus: '1'
      };
      elm = funcs.create('div', attrs, '<span>' + this.translate(cfg.text) + '</span>');
      if (cfg.height) {
        funcs.css(elm, 'height', cfg.height + 'px');
      }
      if (cfg.width) {
        funcs.css(elm, 'width', cfg.width + 'px');
      }
      elm.className = self.classes;
      return elm.outerHTML;
    },
    postRender: function () {
      var self = this;
      var toggleDragClass = function (e) {
        e.preventDefault();
        self.classes.toggle('dragenter');
        self.getEl().className = self.classes;
      };
      var filter = function (files) {
        var accept = self.settings.accept;
        if (typeof accept !== 'string') {
          return files;
        }
        var re = new RegExp('(' + accept.split(/\s*,\s*/).join('|') + ')$', 'i');
        return global$2.grep(files, function (file) {
          return re.test(file.name);
        });
      };
      self._super();
      self.$el.on('dragover', function (e) {
        e.preventDefault();
      });
      self.$el.on('dragenter', toggleDragClass);
      self.$el.on('dragleave', toggleDragClass);
      self.$el.on('drop', function (e) {
        e.preventDefault();
        if (self.state.get('disabled')) {
          return;
        }
        var files = filter(e.dataTransfer.files);
        self.value = function () {
          if (!files.length) {
            return null;
          } else if (self.settings.multiple) {
            return files;
          } else {
            return files[0];
          }
        };
        if (files.length) {
          self.fire('change', e);
        }
      });
    },
    remove: function () {
      this.$el.off();
      this._super();
    }
  });

  var Path = Widget.extend({
    init: function (settings) {
      var self = this;
      if (!settings.delimiter) {
        settings.delimiter = '\xBB';
      }
      self._super(settings);
      self.classes.add('path');
      self.canFocus = true;
      self.on('click', function (e) {
        var index;
        var target = e.target;
        if (index = target.getAttribute('data-index')) {
          self.fire('select', {
            value: self.row()[index],
            index: index
          });
        }
      });
      self.row(self.settings.row);
    },
    focus: function () {
      var self = this;
      self.getEl().firstChild.focus();
      return self;
    },
    row: function (row) {
      if (!arguments.length) {
        return this.state.get('row');
      }
      this.state.set('row', row);
      return this;
    },
    renderHtml: function () {
      var self = this;
      return '<div id="' + self._id + '" class="' + self.classes + '">' + self._getDataPathHtml(self.state.get('row')) + '</div>';
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:row', function (e) {
        self.innerHtml(self._getDataPathHtml(e.value));
      });
      return self._super();
    },
    _getDataPathHtml: function (data) {
      var self = this;
      var parts = data || [];
      var i, l, html = '';
      var prefix = self.classPrefix;
      for (i = 0, l = parts.length; i < l; i++) {
        html += (i > 0 ? '<div class="' + prefix + 'divider" aria-hidden="true"> ' + self.settings.delimiter + ' </div>' : '') + '<div role="button" class="' + prefix + 'path-item' + (i === l - 1 ? ' ' + prefix + 'last' : '') + '" data-index="' + i + '" tabindex="-1" id="' + self._id + '-' + i + '" aria-level="' + (i + 1) + '">' + parts[i].name + '</div>';
      }
      if (!html) {
        html = '<div class="' + prefix + 'path-item">\xA0</div>';
      }
      return html;
    }
  });

  var ElementPath = Path.extend({
    postRender: function () {
      var self = this, editor = self.settings.editor;
      function isHidden(elm) {
        if (elm.nodeType === 1) {
          if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
            return true;
          }
          if (elm.getAttribute('data-mce-type') === 'bookmark') {
            return true;
          }
        }
        return false;
      }
      if (editor.settings.elementpath !== false) {
        self.on('select', function (e) {
          editor.focus();
          editor.selection.select(this.row()[e.index].element);
          editor.nodeChanged();
        });
        editor.on('nodeChange', function (e) {
          var outParents = [];
          var parents = e.parents;
          var i = parents.length;
          while (i--) {
            if (parents[i].nodeType === 1 && !isHidden(parents[i])) {
              var args = editor.fire('ResolveName', {
                name: parents[i].nodeName.toLowerCase(),
                target: parents[i]
              });
              if (!args.isDefaultPrevented()) {
                outParents.push({
                  name: args.name,
                  element: parents[i]
                });
              }
              if (args.isPropagationStopped()) {
                break;
              }
            }
          }
          self.row(outParents);
        });
      }
      return self._super();
    }
  });

  var FormItem = Container.extend({
    Defaults: {
      layout: 'flex',
      align: 'center',
      defaults: { flex: 1 }
    },
    renderHtml: function () {
      var self = this, layout = self._layout, prefix = self.classPrefix;
      self.classes.add('formitem');
      layout.preRender(self);
      return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + (self.settings.title ? '<div id="' + self._id + '-title" class="' + prefix + 'title">' + self.settings.title + '</div>' : '') + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>';
    }
  });

  var Form = Container.extend({
    Defaults: {
      containerCls: 'form',
      layout: 'flex',
      direction: 'column',
      align: 'stretch',
      flex: 1,
      padding: 15,
      labelGap: 30,
      spacing: 10,
      callbacks: {
        submit: function () {
          this.submit();
        }
      }
    },
    preRender: function () {
      var self = this, items = self.items();
      if (!self.settings.formItemDefaults) {
        self.settings.formItemDefaults = {
          layout: 'flex',
          autoResize: 'overflow',
          defaults: { flex: 1 }
        };
      }
      items.each(function (ctrl) {
        var formItem;
        var label = ctrl.settings.label;
        if (label) {
          formItem = new FormItem(global$2.extend({
            items: {
              type: 'label',
              id: ctrl._id + '-l',
              text: label,
              flex: 0,
              forId: ctrl._id,
              disabled: ctrl.disabled()
            }
          }, self.settings.formItemDefaults));
          formItem.type = 'formitem';
          ctrl.aria('labelledby', ctrl._id + '-l');
          if (typeof ctrl.settings.flex === 'undefined') {
            ctrl.settings.flex = 1;
          }
          self.replace(ctrl, formItem);
          formItem.add(ctrl);
        }
      });
    },
    submit: function () {
      return this.fire('submit', { data: this.toJSON() });
    },
    postRender: function () {
      var self = this;
      self._super();
      self.fromJSON(self.settings.data);
    },
    bindStates: function () {
      var self = this;
      self._super();
      function recalcLabels() {
        var maxLabelWidth = 0;
        var labels = [];
        var i, labelGap, items;
        if (self.settings.labelGapCalc === false) {
          return;
        }
        if (self.settings.labelGapCalc === 'children') {
          items = self.find('formitem');
        } else {
          items = self.items();
        }
        items.filter('formitem').each(function (item) {
          var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth;
          maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth;
          labels.push(labelCtrl);
        });
        labelGap = self.settings.labelGap || 0;
        i = labels.length;
        while (i--) {
          labels[i].settings.minWidth = maxLabelWidth + labelGap;
        }
      }
      self.on('show', recalcLabels);
      recalcLabels();
    }
  });

  var FieldSet = Form.extend({
    Defaults: {
      containerCls: 'fieldset',
      layout: 'flex',
      direction: 'column',
      align: 'stretch',
      flex: 1,
      padding: '25 15 5 15',
      labelGap: 30,
      spacing: 10,
      border: 1
    },
    renderHtml: function () {
      var self = this, layout = self._layout, prefix = self.classPrefix;
      self.preRender();
      layout.preRender(self);
      return '<fieldset id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + (self.settings.title ? '<legend id="' + self._id + '-title" class="' + prefix + 'fieldset-title">' + self.settings.title + '</legend>' : '') + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</fieldset>';
    }
  });

  var unique$1 = 0;
  var generate = function (prefix) {
    var date = new Date();
    var time = date.getTime();
    var random = Math.floor(Math.random() * 1000000000);
    unique$1++;
    return prefix + '_' + random + unique$1 + String(time);
  };
  var $_gdeezvv5jh8lz3rl = { generate: generate };

  var fromHtml = function (html, scope) {
    var doc = scope || document;
    var div = doc.createElement('div');
    div.innerHTML = html;
    if (!div.hasChildNodes() || div.childNodes.length > 1) {
      console.error('HTML does not have a single root node', html);
      throw 'HTML must have a single root node';
    }
    return fromDom(div.childNodes[0]);
  };
  var fromTag = function (tag, scope) {
    var doc = scope || document;
    var node = doc.createElement(tag);
    return fromDom(node);
  };
  var fromText = function (text, scope) {
    var doc = scope || document;
    var node = doc.createTextNode(text);
    return fromDom(node);
  };
  var fromDom = function (node) {
    if (node === null || node === undefined)
      throw new Error('Node cannot be null or undefined');
    return { dom: $_3pjweotejh8lz3k4.constant(node) };
  };
  var fromPoint = function (doc, x, y) {
    return Option.from(doc.dom().elementFromPoint(x, y)).map(fromDom);
  };
  var $_3bkrfxv6jh8lz3rm = {
    fromHtml: fromHtml,
    fromTag: fromTag,
    fromText: fromText,
    fromDom: fromDom,
    fromPoint: fromPoint
  };

  var cached = function (f) {
    var called = false;
    var r;
    return function () {
      if (!called) {
        called = true;
        r = f.apply(null, arguments);
      }
      return r;
    };
  };
  var $_8me1xevajh8lz3s0 = { cached: cached };

  var $_8xkvw6vcjh8lz3s2 = {
    ATTRIBUTE: 2,
    CDATA_SECTION: 4,
    COMMENT: 8,
    DOCUMENT: 9,
    DOCUMENT_TYPE: 10,
    DOCUMENT_FRAGMENT: 11,
    ELEMENT: 1,
    TEXT: 3,
    PROCESSING_INSTRUCTION: 7,
    ENTITY_REFERENCE: 5,
    ENTITY: 6,
    NOTATION: 12
  };

  var name = function (element) {
    var r = element.dom().nodeName;
    return r.toLowerCase();
  };
  var type = function (element) {
    return element.dom().nodeType;
  };
  var value = function (element) {
    return element.dom().nodeValue;
  };
  var isType$1 = function (t) {
    return function (element) {
      return type(element) === t;
    };
  };
  var isComment = function (element) {
    return type(element) === $_8xkvw6vcjh8lz3s2.COMMENT || name(element) === '#comment';
  };
  var isElement = isType$1($_8xkvw6vcjh8lz3s2.ELEMENT);
  var isText = isType$1($_8xkvw6vcjh8lz3s2.TEXT);
  var isDocument = isType$1($_8xkvw6vcjh8lz3s2.DOCUMENT);
  var $_11h2nlvbjh8lz3s1 = {
    name: name,
    type: type,
    value: value,
    isElement: isElement,
    isText: isText,
    isDocument: isDocument,
    isComment: isComment
  };

  var inBody = function (element) {
    var dom = $_11h2nlvbjh8lz3s1.isText(element) ? element.dom().parentNode : element.dom();
    return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  };
  var body = $_8me1xevajh8lz3s0.cached(function () {
    return getBody($_3bkrfxv6jh8lz3rm.fromDom(document));
  });
  var getBody = function (doc) {
    var body = doc.dom().body;
    if (body === null || body === undefined)
      throw 'Body is not available yet';
    return $_3bkrfxv6jh8lz3rm.fromDom(body);
  };
  var $_35bizev9jh8lz3rx = {
    body: body,
    getBody: getBody,
    inBody: inBody
  };

  function Immutable () {
    var fields = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      fields[_i] = arguments[_i];
    }
    return function () {
      var values = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        values[_i] = arguments[_i];
      }
      if (fields.length !== values.length) {
        throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
      }
      var struct = {};
      $_f3qxhzthjh8lz3kg.each(fields, function (name, i) {
        struct[name] = $_3pjweotejh8lz3k4.constant(values[i]);
      });
      return struct;
    };
  }

  var keys = function () {
    var fastKeys = Object.keys;
    var slowKeys = function (o) {
      var r = [];
      for (var i in o) {
        if (o.hasOwnProperty(i)) {
          r.push(i);
        }
      }
      return r;
    };
    return fastKeys === undefined ? slowKeys : fastKeys;
  }();
  var each$1 = function (obj, f) {
    var props = keys(obj);
    for (var k = 0, len = props.length; k < len; k++) {
      var i = props[k];
      var x = obj[i];
      f(x, i, obj);
    }
  };
  var objectMap = function (obj, f) {
    return tupleMap(obj, function (x, i, obj) {
      return {
        k: i,
        v: f(x, i, obj)
      };
    });
  };
  var tupleMap = function (obj, f) {
    var r = {};
    each$1(obj, function (x, i) {
      var tuple = f(x, i, obj);
      r[tuple.k] = tuple.v;
    });
    return r;
  };
  var bifilter = function (obj, pred) {
    var t = {};
    var f = {};
    each$1(obj, function (x, i) {
      var branch = pred(x, i) ? t : f;
      branch[i] = x;
    });
    return {
      t: t,
      f: f
    };
  };
  var mapToArray = function (obj, f) {
    var r = [];
    each$1(obj, function (value, name) {
      r.push(f(value, name));
    });
    return r;
  };
  var find$1 = function (obj, pred) {
    var props = keys(obj);
    for (var k = 0, len = props.length; k < len; k++) {
      var i = props[k];
      var x = obj[i];
      if (pred(x, i, obj)) {
        return Option.some(x);
      }
    }
    return Option.none();
  };
  var values = function (obj) {
    return mapToArray(obj, function (v) {
      return v;
    });
  };
  var size = function (obj) {
    return values(obj).length;
  };
  var $_el35e0vhjh8lz3sl = {
    bifilter: bifilter,
    each: each$1,
    map: objectMap,
    mapToArray: mapToArray,
    tupleMap: tupleMap,
    find: find$1,
    keys: keys,
    values: values,
    size: size
  };

  var sort$1 = function (arr) {
    return arr.slice(0).sort();
  };
  var reqMessage = function (required, keys) {
    throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
  };
  var unsuppMessage = function (unsupported) {
    throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
  };
  var validateStrArr = function (label, array) {
    if (!$_d8bie3tijh8lz3kn.isArray(array))
      throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
    $_f3qxhzthjh8lz3kg.each(array, function (a) {
      if (!$_d8bie3tijh8lz3kn.isString(a))
        throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
    });
  };
  var invalidTypeMessage = function (incorrect, type) {
    throw new Error('All values need to be of type: ' + type + '. Keys (' + sort$1(incorrect).join(', ') + ') were not.');
  };
  var checkDupes = function (everything) {
    var sorted = sort$1(everything);
    var dupe = $_f3qxhzthjh8lz3kg.find(sorted, function (s, i) {
      return i < sorted.length - 1 && s === sorted[i + 1];
    });
    dupe.each(function (d) {
      throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
    });
  };
  var $_6xoomwvijh8lz3sn = {
    sort: sort$1,
    reqMessage: reqMessage,
    unsuppMessage: unsuppMessage,
    validateStrArr: validateStrArr,
    invalidTypeMessage: invalidTypeMessage,
    checkDupes: checkDupes
  };

  function MixedBag (required, optional) {
    var everything = required.concat(optional);
    if (everything.length === 0)
      throw new Error('You must specify at least one required or optional field.');
    $_6xoomwvijh8lz3sn.validateStrArr('required', required);
    $_6xoomwvijh8lz3sn.validateStrArr('optional', optional);
    $_6xoomwvijh8lz3sn.checkDupes(everything);
    return function (obj) {
      var keys = $_el35e0vhjh8lz3sl.keys(obj);
      var allReqd = $_f3qxhzthjh8lz3kg.forall(required, function (req) {
        return $_f3qxhzthjh8lz3kg.contains(keys, req);
      });
      if (!allReqd)
        $_6xoomwvijh8lz3sn.reqMessage(required, keys);
      var unsupported = $_f3qxhzthjh8lz3kg.filter(keys, function (key) {
        return !$_f3qxhzthjh8lz3kg.contains(everything, key);
      });
      if (unsupported.length > 0)
        $_6xoomwvijh8lz3sn.unsuppMessage(unsupported);
      var r = {};
      $_f3qxhzthjh8lz3kg.each(required, function (req) {
        r[req] = $_3pjweotejh8lz3k4.constant(obj[req]);
      });
      $_f3qxhzthjh8lz3kg.each(optional, function (opt) {
        r[opt] = $_3pjweotejh8lz3k4.constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
      });
      return r;
    };
  }

  var $_57mdu6vejh8lz3sg = {
    immutable: Immutable,
    immutableBag: MixedBag
  };

  var toArray = function (target, f) {
    var r = [];
    var recurse = function (e) {
      r.push(e);
      return f(e);
    };
    var cur = f(target);
    do {
      cur = cur.bind(recurse);
    } while (cur.isSome());
    return r;
  };
  var $_861s8bvjjh8lz3sp = { toArray: toArray };

  var global$15 = typeof window !== 'undefined' ? window : Function('return this;')();

  var path = function (parts, scope) {
    var o = scope !== undefined && scope !== null ? scope : global$15;
    for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i)
      o = o[parts[i]];
    return o;
  };
  var resolve = function (p, scope) {
    var parts = p.split('.');
    return path(parts, scope);
  };
  var step = function (o, part) {
    if (o[part] === undefined || o[part] === null)
      o[part] = {};
    return o[part];
  };
  var forge = function (parts, target) {
    var o = target !== undefined ? target : global$15;
    for (var i = 0; i < parts.length; ++i)
      o = step(o, parts[i]);
    return o;
  };
  var namespace = function (name, target) {
    var parts = name.split('.');
    return forge(parts, target);
  };
  var $_1cxe7nvnjh8lz3td = {
    path: path,
    resolve: resolve,
    forge: forge,
    namespace: namespace
  };

  var unsafe = function (name, scope) {
    return $_1cxe7nvnjh8lz3td.resolve(name, scope);
  };
  var getOrDie = function (name, scope) {
    var actual = unsafe(name, scope);
    if (actual === undefined || actual === null)
      throw name + ' not available on this browser';
    return actual;
  };
  var $_eol4qgvmjh8lz3t9 = { getOrDie: getOrDie };

  var node = function () {
    var f = $_eol4qgvmjh8lz3t9.getOrDie('Node');
    return f;
  };
  var compareDocumentPosition = function (a, b, match) {
    return (a.compareDocumentPosition(b) & match) !== 0;
  };
  var documentPositionPreceding = function (a, b) {
    return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_PRECEDING);
  };
  var documentPositionContainedBy = function (a, b) {
    return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_CONTAINED_BY);
  };
  var $_7n27kvvljh8lz3t8 = {
    documentPositionPreceding: documentPositionPreceding,
    documentPositionContainedBy: documentPositionContainedBy
  };

  var firstMatch = function (regexes, s) {
    for (var i = 0; i < regexes.length; i++) {
      var x = regexes[i];
      if (x.test(s))
        return x;
    }
    return undefined;
  };
  var find$2 = function (regexes, agent) {
    var r = firstMatch(regexes, agent);
    if (!r)
      return {
        major: 0,
        minor: 0
      };
    var group = function (i) {
      return Number(agent.replace(r, '$' + i));
    };
    return nu(group(1), group(2));
  };
  var detect = function (versionRegexes, agent) {
    var cleanedAgent = String(agent).toLowerCase();
    if (versionRegexes.length === 0)
      return unknown();
    return find$2(versionRegexes, cleanedAgent);
  };
  var unknown = function () {
    return nu(0, 0);
  };
  var nu = function (major, minor) {
    return {
      major: major,
      minor: minor
    };
  };
  var $_afos0kvsjh8lz3tm = {
    nu: nu,
    detect: detect,
    unknown: unknown
  };

  var edge = 'Edge';
  var chrome = 'Chrome';
  var ie = 'IE';
  var opera = 'Opera';
  var firefox = 'Firefox';
  var safari = 'Safari';
  var isBrowser = function (name, current) {
    return function () {
      return current === name;
    };
  };
  var unknown$1 = function () {
    return nu$1({
      current: undefined,
      version: $_afos0kvsjh8lz3tm.unknown()
    });
  };
  var nu$1 = function (info) {
    var current = info.current;
    var version = info.version;
    return {
      current: current,
      version: version,
      isEdge: isBrowser(edge, current),
      isChrome: isBrowser(chrome, current),
      isIE: isBrowser(ie, current),
      isOpera: isBrowser(opera, current),
      isFirefox: isBrowser(firefox, current),
      isSafari: isBrowser(safari, current)
    };
  };
  var $_fidpetvrjh8lz3tj = {
    unknown: unknown$1,
    nu: nu$1,
    edge: $_3pjweotejh8lz3k4.constant(edge),
    chrome: $_3pjweotejh8lz3k4.constant(chrome),
    ie: $_3pjweotejh8lz3k4.constant(ie),
    opera: $_3pjweotejh8lz3k4.constant(opera),
    firefox: $_3pjweotejh8lz3k4.constant(firefox),
    safari: $_3pjweotejh8lz3k4.constant(safari)
  };

  var windows$1 = 'Windows';
  var ios = 'iOS';
  var android = 'Android';
  var linux = 'Linux';
  var osx = 'OSX';
  var solaris = 'Solaris';
  var freebsd = 'FreeBSD';
  var isOS = function (name, current) {
    return function () {
      return current === name;
    };
  };
  var unknown$2 = function () {
    return nu$2({
      current: undefined,
      version: $_afos0kvsjh8lz3tm.unknown()
    });
  };
  var nu$2 = function (info) {
    var current = info.current;
    var version = info.version;
    return {
      current: current,
      version: version,
      isWindows: isOS(windows$1, current),
      isiOS: isOS(ios, current),
      isAndroid: isOS(android, current),
      isOSX: isOS(osx, current),
      isLinux: isOS(linux, current),
      isSolaris: isOS(solaris, current),
      isFreeBSD: isOS(freebsd, current)
    };
  };
  var $_1z8n9kvtjh8lz3to = {
    unknown: unknown$2,
    nu: nu$2,
    windows: $_3pjweotejh8lz3k4.constant(windows$1),
    ios: $_3pjweotejh8lz3k4.constant(ios),
    android: $_3pjweotejh8lz3k4.constant(android),
    linux: $_3pjweotejh8lz3k4.constant(linux),
    osx: $_3pjweotejh8lz3k4.constant(osx),
    solaris: $_3pjweotejh8lz3k4.constant(solaris),
    freebsd: $_3pjweotejh8lz3k4.constant(freebsd)
  };

  function DeviceType (os, browser, userAgent) {
    var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
    var isiPhone = os.isiOS() && !isiPad;
    var isAndroid3 = os.isAndroid() && os.version.major === 3;
    var isAndroid4 = os.isAndroid() && os.version.major === 4;
    var isTablet = isiPad || isAndroid3 || isAndroid4 && /mobile/i.test(userAgent) === true;
    var isTouch = os.isiOS() || os.isAndroid();
    var isPhone = isTouch && !isTablet;
    var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
    return {
      isiPad: $_3pjweotejh8lz3k4.constant(isiPad),
      isiPhone: $_3pjweotejh8lz3k4.constant(isiPhone),
      isTablet: $_3pjweotejh8lz3k4.constant(isTablet),
      isPhone: $_3pjweotejh8lz3k4.constant(isPhone),
      isTouch: $_3pjweotejh8lz3k4.constant(isTouch),
      isAndroid: os.isAndroid,
      isiOS: os.isiOS,
      isWebView: $_3pjweotejh8lz3k4.constant(iOSwebview)
    };
  }

  var detect$1 = function (candidates, userAgent) {
    var agent = String(userAgent).toLowerCase();
    return $_f3qxhzthjh8lz3kg.find(candidates, function (candidate) {
      return candidate.search(agent);
    });
  };
  var detectBrowser = function (browsers, userAgent) {
    return detect$1(browsers, userAgent).map(function (browser) {
      var version = $_afos0kvsjh8lz3tm.detect(browser.versionRegexes, userAgent);
      return {
        current: browser.name,
        version: version
      };
    });
  };
  var detectOs = function (oses, userAgent) {
    return detect$1(oses, userAgent).map(function (os) {
      var version = $_afos0kvsjh8lz3tm.detect(os.versionRegexes, userAgent);
      return {
        current: os.name,
        version: version
      };
    });
  };
  var $_bvrih8vvjh8lz3tv = {
    detectBrowser: detectBrowser,
    detectOs: detectOs
  };

  var addToStart = function (str, prefix) {
    return prefix + str;
  };
  var addToEnd = function (str, suffix) {
    return str + suffix;
  };
  var removeFromStart = function (str, numChars) {
    return str.substring(numChars);
  };
  var removeFromEnd = function (str, numChars) {
    return str.substring(0, str.length - numChars);
  };
  var $_enj27ovyjh8lz3u7 = {
    addToStart: addToStart,
    addToEnd: addToEnd,
    removeFromStart: removeFromStart,
    removeFromEnd: removeFromEnd
  };

  var first = function (str, count) {
    return str.substr(0, count);
  };
  var last$1 = function (str, count) {
    return str.substr(str.length - count, str.length);
  };
  var head$1 = function (str) {
    return str === '' ? Option.none() : Option.some(str.substr(0, 1));
  };
  var tail = function (str) {
    return str === '' ? Option.none() : Option.some(str.substring(1));
  };
  var $_49etxbvzjh8lz3u8 = {
    first: first,
    last: last$1,
    head: head$1,
    tail: tail
  };

  var checkRange = function (str, substr, start) {
    if (substr === '')
      return true;
    if (str.length < substr.length)
      return false;
    var x = str.substr(start, start + substr.length);
    return x === substr;
  };
  var supplant = function (str, obj) {
    var isStringOrNumber = function (a) {
      var t = typeof a;
      return t === 'string' || t === 'number';
    };
    return str.replace(/\${([^{}]*)}/g, function (a, b) {
      var value = obj[b];
      return isStringOrNumber(value) ? value : a;
    });
  };
  var removeLeading = function (str, prefix) {
    return startsWith(str, prefix) ? $_enj27ovyjh8lz3u7.removeFromStart(str, prefix.length) : str;
  };
  var removeTrailing = function (str, prefix) {
    return endsWith(str, prefix) ? $_enj27ovyjh8lz3u7.removeFromEnd(str, prefix.length) : str;
  };
  var ensureLeading = function (str, prefix) {
    return startsWith(str, prefix) ? str : $_enj27ovyjh8lz3u7.addToStart(str, prefix);
  };
  var ensureTrailing = function (str, prefix) {
    return endsWith(str, prefix) ? str : $_enj27ovyjh8lz3u7.addToEnd(str, prefix);
  };
  var contains$1 = function (str, substr) {
    return str.indexOf(substr) !== -1;
  };
  var capitalize = function (str) {
    return $_49etxbvzjh8lz3u8.head(str).bind(function (head) {
      return $_49etxbvzjh8lz3u8.tail(str).map(function (tail) {
        return head.toUpperCase() + tail;
      });
    }).getOr(str);
  };
  var startsWith = function (str, prefix) {
    return checkRange(str, prefix, 0);
  };
  var endsWith = function (str, suffix) {
    return checkRange(str, suffix, str.length - suffix.length);
  };
  var trim = function (str) {
    return str.replace(/^\s+|\s+$/g, '');
  };
  var lTrim = function (str) {
    return str.replace(/^\s+/g, '');
  };
  var rTrim = function (str) {
    return str.replace(/\s+$/g, '');
  };
  var $_2absfgvxjh8lz3u4 = {
    supplant: supplant,
    startsWith: startsWith,
    removeLeading: removeLeading,
    removeTrailing: removeTrailing,
    ensureLeading: ensureLeading,
    ensureTrailing: ensureTrailing,
    endsWith: endsWith,
    contains: contains$1,
    trim: trim,
    lTrim: lTrim,
    rTrim: rTrim,
    capitalize: capitalize
  };

  var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  var checkContains = function (target) {
    return function (uastring) {
      return $_2absfgvxjh8lz3u4.contains(uastring, target);
    };
  };
  var browsers = [
    {
      name: 'Edge',
      versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
      search: function (uastring) {
        var monstrosity = $_2absfgvxjh8lz3u4.contains(uastring, 'edge/') && $_2absfgvxjh8lz3u4.contains(uastring, 'chrome') && $_2absfgvxjh8lz3u4.contains(uastring, 'safari') && $_2absfgvxjh8lz3u4.contains(uastring, 'applewebkit');
        return monstrosity;
      }
    },
    {
      name: 'Chrome',
      versionRegexes: [
        /.*?chrome\/([0-9]+)\.([0-9]+).*/,
        normalVersionRegex
      ],
      search: function (uastring) {
        return $_2absfgvxjh8lz3u4.contains(uastring, 'chrome') && !$_2absfgvxjh8lz3u4.contains(uastring, 'chromeframe');
      }
    },
    {
      name: 'IE',
      versionRegexes: [
        /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
        /.*?rv:([0-9]+)\.([0-9]+).*/
      ],
      search: function (uastring) {
        return $_2absfgvxjh8lz3u4.contains(uastring, 'msie') || $_2absfgvxjh8lz3u4.contains(uastring, 'trident');
      }
    },
    {
      name: 'Opera',
      versionRegexes: [
        normalVersionRegex,
        /.*?opera\/([0-9]+)\.([0-9]+).*/
      ],
      search: checkContains('opera')
    },
    {
      name: 'Firefox',
      versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
      search: checkContains('firefox')
    },
    {
      name: 'Safari',
      versionRegexes: [
        normalVersionRegex,
        /.*?cpu os ([0-9]+)_([0-9]+).*/
      ],
      search: function (uastring) {
        return ($_2absfgvxjh8lz3u4.contains(uastring, 'safari') || $_2absfgvxjh8lz3u4.contains(uastring, 'mobile/')) && $_2absfgvxjh8lz3u4.contains(uastring, 'applewebkit');
      }
    }
  ];
  var oses = [
    {
      name: 'Windows',
      search: checkContains('win'),
      versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
    },
    {
      name: 'iOS',
      search: function (uastring) {
        return $_2absfgvxjh8lz3u4.contains(uastring, 'iphone') || $_2absfgvxjh8lz3u4.contains(uastring, 'ipad');
      },
      versionRegexes: [
        /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
        /.*cpu os ([0-9]+)_([0-9]+).*/,
        /.*cpu iphone os ([0-9]+)_([0-9]+).*/
      ]
    },
    {
      name: 'Android',
      search: checkContains('android'),
      versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
    },
    {
      name: 'OSX',
      search: checkContains('os x'),
      versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
    },
    {
      name: 'Linux',
      search: checkContains('linux'),
      versionRegexes: []
    },
    {
      name: 'Solaris',
      search: checkContains('sunos'),
      versionRegexes: []
    },
    {
      name: 'FreeBSD',
      search: checkContains('freebsd'),
      versionRegexes: []
    }
  ];
  var $_dne06dvwjh8lz3ty = {
    browsers: $_3pjweotejh8lz3k4.constant(browsers),
    oses: $_3pjweotejh8lz3k4.constant(oses)
  };

  var detect$2 = function (userAgent) {
    var browsers = $_dne06dvwjh8lz3ty.browsers();
    var oses = $_dne06dvwjh8lz3ty.oses();
    var browser = $_bvrih8vvjh8lz3tv.detectBrowser(browsers, userAgent).fold($_fidpetvrjh8lz3tj.unknown, $_fidpetvrjh8lz3tj.nu);
    var os = $_bvrih8vvjh8lz3tv.detectOs(oses, userAgent).fold($_1z8n9kvtjh8lz3to.unknown, $_1z8n9kvtjh8lz3to.nu);
    var deviceType = DeviceType(os, browser, userAgent);
    return {
      browser: browser,
      os: os,
      deviceType: deviceType
    };
  };
  var $_8gsy8vqjh8lz3ti = { detect: detect$2 };

  var detect$3 = $_8me1xevajh8lz3s0.cached(function () {
    var userAgent = navigator.userAgent;
    return $_8gsy8vqjh8lz3ti.detect(userAgent);
  });
  var $_2rbkegvpjh8lz3tf = { detect: detect$3 };

  var ELEMENT = $_8xkvw6vcjh8lz3s2.ELEMENT;
  var DOCUMENT = $_8xkvw6vcjh8lz3s2.DOCUMENT;
  var is = function (element, selector) {
    var elem = element.dom();
    if (elem.nodeType !== ELEMENT)
      return false;
    else if (elem.matches !== undefined)
      return elem.matches(selector);
    else if (elem.msMatchesSelector !== undefined)
      return elem.msMatchesSelector(selector);
    else if (elem.webkitMatchesSelector !== undefined)
      return elem.webkitMatchesSelector(selector);
    else if (elem.mozMatchesSelector !== undefined)
      return elem.mozMatchesSelector(selector);
    else
      throw new Error('Browser lacks native selectors');
  };
  var bypassSelector = function (dom) {
    return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT || dom.childElementCount === 0;
  };
  var all = function (selector, scope) {
    var base = scope === undefined ? document : scope.dom();
    return bypassSelector(base) ? [] : $_f3qxhzthjh8lz3kg.map(base.querySelectorAll(selector), $_3bkrfxv6jh8lz3rm.fromDom);
  };
  var one = function (selector, scope) {
    var base = scope === undefined ? document : scope.dom();
    return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map($_3bkrfxv6jh8lz3rm.fromDom);
  };
  var $_2nczsvw0jh8lz3ua = {
    all: all,
    is: is,
    one: one
  };

  var eq = function (e1, e2) {
    return e1.dom() === e2.dom();
  };
  var isEqualNode = function (e1, e2) {
    return e1.dom().isEqualNode(e2.dom());
  };
  var member = function (element, elements) {
    return $_f3qxhzthjh8lz3kg.exists(elements, $_3pjweotejh8lz3k4.curry(eq, element));
  };
  var regularContains = function (e1, e2) {
    var d1 = e1.dom(), d2 = e2.dom();
    return d1 === d2 ? false : d1.contains(d2);
  };
  var ieContains = function (e1, e2) {
    return $_7n27kvvljh8lz3t8.documentPositionContainedBy(e1.dom(), e2.dom());
  };
  var browser = $_2rbkegvpjh8lz3tf.detect().browser;
  var contains$2 = browser.isIE() ? ieContains : regularContains;
  var $_9ypjy6vkjh8lz3sq = {
    eq: eq,
    isEqualNode: isEqualNode,
    member: member,
    contains: contains$2,
    is: $_2nczsvw0jh8lz3ua.is
  };

  var owner = function (element) {
    return $_3bkrfxv6jh8lz3rm.fromDom(element.dom().ownerDocument);
  };
  var documentElement = function (element) {
    var doc = owner(element);
    return $_3bkrfxv6jh8lz3rm.fromDom(doc.dom().documentElement);
  };
  var defaultView = function (element) {
    var el = element.dom();
    var defaultView = el.ownerDocument.defaultView;
    return $_3bkrfxv6jh8lz3rm.fromDom(defaultView);
  };
  var parent = function (element) {
    var dom = element.dom();
    return Option.from(dom.parentNode).map($_3bkrfxv6jh8lz3rm.fromDom);
  };
  var findIndex$1 = function (element) {
    return parent(element).bind(function (p) {
      var kin = children(p);
      return $_f3qxhzthjh8lz3kg.findIndex(kin, function (elem) {
        return $_9ypjy6vkjh8lz3sq.eq(element, elem);
      });
    });
  };
  var parents = function (element, isRoot) {
    var stop = $_d8bie3tijh8lz3kn.isFunction(isRoot) ? isRoot : $_3pjweotejh8lz3k4.constant(false);
    var dom = element.dom();
    var ret = [];
    while (dom.parentNode !== null && dom.parentNode !== undefined) {
      var rawParent = dom.parentNode;
      var parent = $_3bkrfxv6jh8lz3rm.fromDom(rawParent);
      ret.push(parent);
      if (stop(parent) === true)
        break;
      else
        dom = rawParent;
    }
    return ret;
  };
  var siblings = function (element) {
    var filterSelf = function (elements) {
      return $_f3qxhzthjh8lz3kg.filter(elements, function (x) {
        return !$_9ypjy6vkjh8lz3sq.eq(element, x);
      });
    };
    return parent(element).map(children).map(filterSelf).getOr([]);
  };
  var offsetParent = function (element) {
    var dom = element.dom();
    return Option.from(dom.offsetParent).map($_3bkrfxv6jh8lz3rm.fromDom);
  };
  var prevSibling = function (element) {
    var dom = element.dom();
    return Option.from(dom.previousSibling).map($_3bkrfxv6jh8lz3rm.fromDom);
  };
  var nextSibling = function (element) {
    var dom = element.dom();
    return Option.from(dom.nextSibling).map($_3bkrfxv6jh8lz3rm.fromDom);
  };
  var prevSiblings = function (element) {
    return $_f3qxhzthjh8lz3kg.reverse($_861s8bvjjh8lz3sp.toArray(element, prevSibling));
  };
  var nextSiblings = function (element) {
    return $_861s8bvjjh8lz3sp.toArray(element, nextSibling);
  };
  var children = function (element) {
    var dom = element.dom();
    return $_f3qxhzthjh8lz3kg.map(dom.childNodes, $_3bkrfxv6jh8lz3rm.fromDom);
  };
  var child = function (element, index) {
    var children = element.dom().childNodes;
    return Option.from(children[index]).map($_3bkrfxv6jh8lz3rm.fromDom);
  };
  var firstChild = function (element) {
    return child(element, 0);
  };
  var lastChild = function (element) {
    return child(element, element.dom().childNodes.length - 1);
  };
  var childNodesCount = function (element) {
    return element.dom().childNodes.length;
  };
  var hasChildNodes = function (element) {
    return element.dom().hasChildNodes();
  };
  var spot = $_57mdu6vejh8lz3sg.immutable('element', 'offset');
  var leaf = function (element, offset) {
    var cs = children(element);
    return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  };
  var $_3jmbxmvdjh8lz3s4 = {
    owner: owner,
    defaultView: defaultView,
    documentElement: documentElement,
    parent: parent,
    findIndex: findIndex$1,
    parents: parents,
    siblings: siblings,
    prevSibling: prevSibling,
    offsetParent: offsetParent,
    prevSiblings: prevSiblings,
    nextSibling: nextSibling,
    nextSiblings: nextSiblings,
    children: children,
    child: child,
    firstChild: firstChild,
    lastChild: lastChild,
    childNodesCount: childNodesCount,
    hasChildNodes: hasChildNodes,
    leaf: leaf
  };

  var all$1 = function (predicate) {
    return descendants($_35bizev9jh8lz3rx.body(), predicate);
  };
  var ancestors = function (scope, predicate, isRoot) {
    return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.parents(scope, isRoot), predicate);
  };
  var siblings$1 = function (scope, predicate) {
    return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.siblings(scope), predicate);
  };
  var children$1 = function (scope, predicate) {
    return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.children(scope), predicate);
  };
  var descendants = function (scope, predicate) {
    var result = [];
    $_f3qxhzthjh8lz3kg.each($_3jmbxmvdjh8lz3s4.children(scope), function (x) {
      if (predicate(x)) {
        result = result.concat([x]);
      }
      result = result.concat(descendants(x, predicate));
    });
    return result;
  };
  var $_dz5cwuv8jh8lz3rt = {
    all: all$1,
    ancestors: ancestors,
    siblings: siblings$1,
    children: children$1,
    descendants: descendants
  };

  var all$2 = function (selector) {
    return $_2nczsvw0jh8lz3ua.all(selector);
  };
  var ancestors$1 = function (scope, selector, isRoot) {
    return $_dz5cwuv8jh8lz3rt.ancestors(scope, function (e) {
      return $_2nczsvw0jh8lz3ua.is(e, selector);
    }, isRoot);
  };
  var siblings$2 = function (scope, selector) {
    return $_dz5cwuv8jh8lz3rt.siblings(scope, function (e) {
      return $_2nczsvw0jh8lz3ua.is(e, selector);
    });
  };
  var children$2 = function (scope, selector) {
    return $_dz5cwuv8jh8lz3rt.children(scope, function (e) {
      return $_2nczsvw0jh8lz3ua.is(e, selector);
    });
  };
  var descendants$1 = function (scope, selector) {
    return $_2nczsvw0jh8lz3ua.all(selector, scope);
  };
  var $_am3j0fv7jh8lz3rs = {
    all: all$2,
    ancestors: ancestors$1,
    siblings: siblings$2,
    children: children$2,
    descendants: descendants$1
  };

  var trim$1 = global$2.trim;
  var hasContentEditableState = function (value) {
    return function (node) {
      if (node && node.nodeType === 1) {
        if (node.contentEditable === value) {
          return true;
        }
        if (node.getAttribute('data-mce-contenteditable') === value) {
          return true;
        }
      }
      return false;
    };
  };
  var isContentEditableTrue = hasContentEditableState('true');
  var isContentEditableFalse = hasContentEditableState('false');
  var create = function (type, title, url, level, attach) {
    return {
      type: type,
      title: title,
      url: url,
      level: level,
      attach: attach
    };
  };
  var isChildOfContentEditableTrue = function (node) {
    while (node = node.parentNode) {
      var value = node.contentEditable;
      if (value && value !== 'inherit') {
        return isContentEditableTrue(node);
      }
    }
    return false;
  };
  var select = function (selector, root) {
    return $_f3qxhzthjh8lz3kg.map($_am3j0fv7jh8lz3rs.descendants($_3bkrfxv6jh8lz3rm.fromDom(root), selector), function (element) {
      return element.dom();
    });
  };
  var getElementText = function (elm) {
    return elm.innerText || elm.textContent;
  };
  var getOrGenerateId = function (elm) {
    return elm.id ? elm.id : $_gdeezvv5jh8lz3rl.generate('h');
  };
  var isAnchor = function (elm) {
    return elm && elm.nodeName === 'A' && (elm.id || elm.name);
  };
  var isValidAnchor = function (elm) {
    return isAnchor(elm) && isEditable(elm);
  };
  var isHeader = function (elm) {
    return elm && /^(H[1-6])$/.test(elm.nodeName);
  };
  var isEditable = function (elm) {
    return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  };
  var isValidHeader = function (elm) {
    return isHeader(elm) && isEditable(elm);
  };
  var getLevel = function (elm) {
    return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  };
  var headerTarget = function (elm) {
    var headerId = getOrGenerateId(elm);
    var attach = function () {
      elm.id = headerId;
    };
    return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  };
  var anchorTarget = function (elm) {
    var anchorId = elm.id || elm.name;
    var anchorText = getElementText(elm);
    return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, $_3pjweotejh8lz3k4.noop);
  };
  var getHeaderTargets = function (elms) {
    return $_f3qxhzthjh8lz3kg.map($_f3qxhzthjh8lz3kg.filter(elms, isValidHeader), headerTarget);
  };
  var getAnchorTargets = function (elms) {
    return $_f3qxhzthjh8lz3kg.map($_f3qxhzthjh8lz3kg.filter(elms, isValidAnchor), anchorTarget);
  };
  var getTargetElements = function (elm) {
    var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
    return elms;
  };
  var hasTitle = function (target) {
    return trim$1(target.title).length > 0;
  };
  var find$3 = function (elm) {
    var elms = getTargetElements(elm);
    return $_f3qxhzthjh8lz3kg.filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  };
  var $_p3wpev4jh8lz3ra = { find: find$3 };

  var getActiveEditor = function () {
    return window.tinymce ? window.tinymce.activeEditor : global$1.activeEditor;
  };
  var history = {};
  var HISTORY_LENGTH = 5;
  var clearHistory = function () {
    history = {};
  };
  var toMenuItem = function (target) {
    return {
      title: target.title,
      value: {
        title: { raw: target.title },
        url: target.url,
        attach: target.attach
      }
    };
  };
  var toMenuItems = function (targets) {
    return global$2.map(targets, toMenuItem);
  };
  var staticMenuItem = function (title, url) {
    return {
      title: title,
      value: {
        title: title,
        url: url,
        attach: $_3pjweotejh8lz3k4.noop
      }
    };
  };
  var isUniqueUrl = function (url, targets) {
    var foundTarget = $_f3qxhzthjh8lz3kg.exists(targets, function (target) {
      return target.url === url;
    });
    return !foundTarget;
  };
  var getSetting = function (editorSettings, name, defaultValue) {
    var value = name in editorSettings ? editorSettings[name] : defaultValue;
    return value === false ? null : value;
  };
  var createMenuItems = function (term, targets, fileType, editorSettings) {
    var separator = { title: '-' };
    var fromHistoryMenuItems = function (history) {
      var historyItems = history.hasOwnProperty(fileType) ? history[fileType] : [];
      var uniqueHistory = $_f3qxhzthjh8lz3kg.filter(historyItems, function (url) {
        return isUniqueUrl(url, targets);
      });
      return global$2.map(uniqueHistory, function (url) {
        return {
          title: url,
          value: {
            title: url,
            url: url,
            attach: $_3pjweotejh8lz3k4.noop
          }
        };
      });
    };
    var fromMenuItems = function (type) {
      var filteredTargets = $_f3qxhzthjh8lz3kg.filter(targets, function (target) {
        return target.type === type;
      });
      return toMenuItems(filteredTargets);
    };
    var anchorMenuItems = function () {
      var anchorMenuItems = fromMenuItems('anchor');
      var topAnchor = getSetting(editorSettings, 'anchor_top', '#top');
      var bottomAchor = getSetting(editorSettings, 'anchor_bottom', '#bottom');
      if (topAnchor !== null) {
        anchorMenuItems.unshift(staticMenuItem('<top>', topAnchor));
      }
      if (bottomAchor !== null) {
        anchorMenuItems.push(staticMenuItem('<bottom>', bottomAchor));
      }
      return anchorMenuItems;
    };
    var join = function (items) {
      return $_f3qxhzthjh8lz3kg.foldl(items, function (a, b) {
        var bothEmpty = a.length === 0 || b.length === 0;
        return bothEmpty ? a.concat(b) : a.concat(separator, b);
      }, []);
    };
    if (editorSettings.typeahead_urls === false) {
      return [];
    }
    return fileType === 'file' ? join([
      filterByQuery(term, fromHistoryMenuItems(history)),
      filterByQuery(term, fromMenuItems('header')),
      filterByQuery(term, anchorMenuItems())
    ]) : filterByQuery(term, fromHistoryMenuItems(history));
  };
  var addToHistory = function (url, fileType) {
    var items = history[fileType];
    if (!/^https?/.test(url)) {
      return;
    }
    if (items) {
      if ($_f3qxhzthjh8lz3kg.indexOf(items, url).isNone()) {
        history[fileType] = items.slice(0, HISTORY_LENGTH).concat(url);
      }
    } else {
      history[fileType] = [url];
    }
  };
  var filterByQuery = function (term, menuItems) {
    var lowerCaseTerm = term.toLowerCase();
    var result = global$2.grep(menuItems, function (item) {
      return item.title.toLowerCase().indexOf(lowerCaseTerm) !== -1;
    });
    return result.length === 1 && result[0].title === term ? [] : result;
  };
  var getTitle = function (linkDetails) {
    var title = linkDetails.title;
    return title.raw ? title.raw : title;
  };
  var setupAutoCompleteHandler = function (ctrl, editorSettings, bodyElm, fileType) {
    var autocomplete = function (term) {
      var linkTargets = $_p3wpev4jh8lz3ra.find(bodyElm);
      var menuItems = createMenuItems(term, linkTargets, fileType, editorSettings);
      ctrl.showAutoComplete(menuItems, term);
    };
    ctrl.on('autocomplete', function () {
      autocomplete(ctrl.value());
    });
    ctrl.on('selectitem', function (e) {
      var linkDetails = e.value;
      ctrl.value(linkDetails.url);
      var title = getTitle(linkDetails);
      if (fileType === 'image') {
        ctrl.fire('change', {
          meta: {
            alt: title,
            attach: linkDetails.attach
          }
        });
      } else {
        ctrl.fire('change', {
          meta: {
            text: title,
            attach: linkDetails.attach
          }
        });
      }
      ctrl.focus();
    });
    ctrl.on('click', function (e) {
      if (ctrl.value().length === 0 && e.target.nodeName === 'INPUT') {
        autocomplete('');
      }
    });
    ctrl.on('PostRender', function () {
      ctrl.getRoot().on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
          addToHistory(ctrl.value(), fileType);
        }
      });
    });
  };
  var statusToUiState = function (result) {
    var status = result.status, message = result.message;
    if (status === 'valid') {
      return {
        status: 'ok',
        message: message
      };
    } else if (status === 'unknown') {
      return {
        status: 'warn',
        message: message
      };
    } else if (status === 'invalid') {
      return {
        status: 'warn',
        message: message
      };
    } else {
      return {
        status: 'none',
        message: ''
      };
    }
  };
  var setupLinkValidatorHandler = function (ctrl, editorSettings, fileType) {
    var validatorHandler = editorSettings.filepicker_validator_handler;
    if (validatorHandler) {
      var validateUrl_1 = function (url) {
        if (url.length === 0) {
          ctrl.statusLevel('none');
          return;
        }
        validatorHandler({
          url: url,
          type: fileType
        }, function (result) {
          var uiState = statusToUiState(result);
          ctrl.statusMessage(uiState.message);
          ctrl.statusLevel(uiState.status);
        });
      };
      ctrl.state.on('change:value', function (e) {
        validateUrl_1(e.value);
      });
    }
  };
  var FilePicker = ComboBox.extend({
    Statics: { clearHistory: clearHistory },
    init: function (settings) {
      var self = this, editor = getActiveEditor(), editorSettings = editor.settings;
      var actionCallback, fileBrowserCallback, fileBrowserCallbackTypes;
      var fileType = settings.filetype;
      settings.spellcheck = false;
      fileBrowserCallbackTypes = editorSettings.file_picker_types || editorSettings.file_browser_callback_types;
      if (fileBrowserCallbackTypes) {
        fileBrowserCallbackTypes = global$2.makeMap(fileBrowserCallbackTypes, /[, ]/);
      }
      if (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType]) {
        fileBrowserCallback = editorSettings.file_picker_callback;
        if (fileBrowserCallback && (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType])) {
          actionCallback = function () {
            var meta = self.fire('beforecall').meta;
            meta = global$2.extend({ filetype: fileType }, meta);
            fileBrowserCallback.call(editor, function (value, meta) {
              self.value(value).fire('change', { meta: meta });
            }, self.value(), meta);
          };
        } else {
          fileBrowserCallback = editorSettings.file_browser_callback;
          if (fileBrowserCallback && (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType])) {
            actionCallback = function () {
              fileBrowserCallback(self.getEl('inp').id, self.value(), fileType, window);
            };
          }
        }
      }
      if (actionCallback) {
        settings.icon = 'browse';
        settings.onaction = actionCallback;
      }
      self._super(settings);
      self.classes.add('filepicker');
      setupAutoCompleteHandler(self, editorSettings, editor.getBody(), fileType);
      setupLinkValidatorHandler(self, editorSettings, fileType);
    }
  });

  var FitLayout = AbsoluteLayout.extend({
    recalc: function (container) {
      var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox;
      container.items().filter(':visible').each(function (ctrl) {
        ctrl.layoutRect({
          x: paddingBox.left,
          y: paddingBox.top,
          w: contLayoutRect.innerW - paddingBox.right - paddingBox.left,
          h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom
        });
        if (ctrl.recalc) {
          ctrl.recalc();
        }
      });
    }
  });

  var FlexLayout = AbsoluteLayout.extend({
    recalc: function (container) {
      var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction;
      var ctrl, ctrlLayoutRect, ctrlSettings, flex;
      var maxSizeItems = [];
      var size, maxSize, ratio, rect, pos, maxAlignEndPos;
      var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, deltaSizeName, contentSizeName;
      var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignBeforeName, alignAfterName;
      var alignDeltaSizeName, alignContentSizeName;
      var max = Math.max, min = Math.min;
      items = container.items().filter(':visible');
      contLayoutRect = container.layoutRect();
      contPaddingBox = container.paddingBox;
      contSettings = container.settings;
      direction = container.isRtl() ? contSettings.direction || 'row-reversed' : contSettings.direction;
      align = contSettings.align;
      pack = container.isRtl() ? contSettings.pack || 'end' : contSettings.pack;
      spacing = contSettings.spacing || 0;
      if (direction === 'row-reversed' || direction === 'column-reverse') {
        items = items.set(items.toArray().reverse());
        direction = direction.split('-')[0];
      }
      if (direction === 'column') {
        posName = 'y';
        sizeName = 'h';
        minSizeName = 'minH';
        maxSizeName = 'maxH';
        innerSizeName = 'innerH';
        beforeName = 'top';
        deltaSizeName = 'deltaH';
        contentSizeName = 'contentH';
        alignBeforeName = 'left';
        alignSizeName = 'w';
        alignAxisName = 'x';
        alignInnerSizeName = 'innerW';
        alignMinSizeName = 'minW';
        alignAfterName = 'right';
        alignDeltaSizeName = 'deltaW';
        alignContentSizeName = 'contentW';
      } else {
        posName = 'x';
        sizeName = 'w';
        minSizeName = 'minW';
        maxSizeName = 'maxW';
        innerSizeName = 'innerW';
        beforeName = 'left';
        deltaSizeName = 'deltaW';
        contentSizeName = 'contentW';
        alignBeforeName = 'top';
        alignSizeName = 'h';
        alignAxisName = 'y';
        alignInnerSizeName = 'innerH';
        alignMinSizeName = 'minH';
        alignAfterName = 'bottom';
        alignDeltaSizeName = 'deltaH';
        alignContentSizeName = 'contentH';
      }
      availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName];
      maxAlignEndPos = totalFlex = 0;
      for (i = 0, l = items.length; i < l; i++) {
        ctrl = items[i];
        ctrlLayoutRect = ctrl.layoutRect();
        ctrlSettings = ctrl.settings;
        flex = ctrlSettings.flex;
        availableSpace -= i < l - 1 ? spacing : 0;
        if (flex > 0) {
          totalFlex += flex;
          if (ctrlLayoutRect[maxSizeName]) {
            maxSizeItems.push(ctrl);
          }
          ctrlLayoutRect.flex = flex;
        }
        availableSpace -= ctrlLayoutRect[minSizeName];
        size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName];
        if (size > maxAlignEndPos) {
          maxAlignEndPos = size;
        }
      }
      rect = {};
      if (availableSpace < 0) {
        rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName];
      } else {
        rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName];
      }
      rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName];
      rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace;
      rect[alignContentSizeName] = maxAlignEndPos;
      rect.minW = min(rect.minW, contLayoutRect.maxW);
      rect.minH = min(rect.minH, contLayoutRect.maxH);
      rect.minW = max(rect.minW, contLayoutRect.startMinWidth);
      rect.minH = max(rect.minH, contLayoutRect.startMinHeight);
      if (contLayoutRect.autoResize && (rect.minW !== contLayoutRect.minW || rect.minH !== contLayoutRect.minH)) {
        rect.w = rect.minW;
        rect.h = rect.minH;
        container.layoutRect(rect);
        this.recalc(container);
        if (container._lastRect === null) {
          var parentCtrl = container.parent();
          if (parentCtrl) {
            parentCtrl._lastRect = null;
            parentCtrl.recalc();
          }
        }
        return;
      }
      ratio = availableSpace / totalFlex;
      for (i = 0, l = maxSizeItems.length; i < l; i++) {
        ctrl = maxSizeItems[i];
        ctrlLayoutRect = ctrl.layoutRect();
        maxSize = ctrlLayoutRect[maxSizeName];
        size = ctrlLayoutRect[minSizeName] + ctrlLayoutRect.flex * ratio;
        if (size > maxSize) {
          availableSpace -= ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName];
          totalFlex -= ctrlLayoutRect.flex;
          ctrlLayoutRect.flex = 0;
          ctrlLayoutRect.maxFlexSize = maxSize;
        } else {
          ctrlLayoutRect.maxFlexSize = 0;
        }
      }
      ratio = availableSpace / totalFlex;
      pos = contPaddingBox[beforeName];
      rect = {};
      if (totalFlex === 0) {
        if (pack === 'end') {
          pos = availableSpace + contPaddingBox[beforeName];
        } else if (pack === 'center') {
          pos = Math.round(contLayoutRect[innerSizeName] / 2 - (contLayoutRect[innerSizeName] - availableSpace) / 2) + contPaddingBox[beforeName];
          if (pos < 0) {
            pos = contPaddingBox[beforeName];
          }
        } else if (pack === 'justify') {
          pos = contPaddingBox[beforeName];
          spacing = Math.floor(availableSpace / (items.length - 1));
        }
      }
      rect[alignAxisName] = contPaddingBox[alignBeforeName];
      for (i = 0, l = items.length; i < l; i++) {
        ctrl = items[i];
        ctrlLayoutRect = ctrl.layoutRect();
        size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName];
        if (align === 'center') {
          rect[alignAxisName] = Math.round(contLayoutRect[alignInnerSizeName] / 2 - ctrlLayoutRect[alignSizeName] / 2);
        } else if (align === 'stretch') {
          rect[alignSizeName] = max(ctrlLayoutRect[alignMinSizeName] || 0, contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName]);
          rect[alignAxisName] = contPaddingBox[alignBeforeName];
        } else if (align === 'end') {
          rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top;
        }
        if (ctrlLayoutRect.flex > 0) {
          size += ctrlLayoutRect.flex * ratio;
        }
        rect[sizeName] = size;
        rect[posName] = pos;
        ctrl.layoutRect(rect);
        if (ctrl.recalc) {
          ctrl.recalc();
        }
        pos += size + spacing;
      }
    }
  });

  var FlowLayout = Layout.extend({
    Defaults: {
      containerClass: 'flow-layout',
      controlClass: 'flow-layout-item',
      endClass: 'break'
    },
    recalc: function (container) {
      container.items().filter(':visible').each(function (ctrl) {
        if (ctrl.recalc) {
          ctrl.recalc();
        }
      });
    },
    isNative: function () {
      return true;
    }
  });

  function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
    return is(scope, a) ? Option.some(scope) : $_d8bie3tijh8lz3kn.isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  }

  var first$1 = function (predicate) {
    return descendant($_35bizev9jh8lz3rx.body(), predicate);
  };
  var ancestor = function (scope, predicate, isRoot) {
    var element = scope.dom();
    var stop = $_d8bie3tijh8lz3kn.isFunction(isRoot) ? isRoot : $_3pjweotejh8lz3k4.constant(false);
    while (element.parentNode) {
      element = element.parentNode;
      var el = $_3bkrfxv6jh8lz3rm.fromDom(element);
      if (predicate(el))
        return Option.some(el);
      else if (stop(el))
        break;
    }
    return Option.none();
  };
  var closest = function (scope, predicate, isRoot) {
    var is = function (scope) {
      return predicate(scope);
    };
    return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  };
  var sibling = function (scope, predicate) {
    var element = scope.dom();
    if (!element.parentNode)
      return Option.none();
    return child$1($_3bkrfxv6jh8lz3rm.fromDom(element.parentNode), function (x) {
      return !$_9ypjy6vkjh8lz3sq.eq(scope, x) && predicate(x);
    });
  };
  var child$1 = function (scope, predicate) {
    var result = $_f3qxhzthjh8lz3kg.find(scope.dom().childNodes, $_3pjweotejh8lz3k4.compose(predicate, $_3bkrfxv6jh8lz3rm.fromDom));
    return result.map($_3bkrfxv6jh8lz3rm.fromDom);
  };
  var descendant = function (scope, predicate) {
    var descend = function (element) {
      for (var i = 0; i < element.childNodes.length; i++) {
        if (predicate($_3bkrfxv6jh8lz3rm.fromDom(element.childNodes[i])))
          return Option.some($_3bkrfxv6jh8lz3rm.fromDom(element.childNodes[i]));
        var res = descend(element.childNodes[i]);
        if (res.isSome())
          return res;
      }
      return Option.none();
    };
    return descend(scope.dom());
  };
  var $_5a72sw6jh8lz3uv = {
    first: first$1,
    ancestor: ancestor,
    closest: closest,
    sibling: sibling,
    child: child$1,
    descendant: descendant
  };

  var first$2 = function (selector) {
    return $_2nczsvw0jh8lz3ua.one(selector);
  };
  var ancestor$1 = function (scope, selector, isRoot) {
    return $_5a72sw6jh8lz3uv.ancestor(scope, function (e) {
      return $_2nczsvw0jh8lz3ua.is(e, selector);
    }, isRoot);
  };
  var sibling$1 = function (scope, selector) {
    return $_5a72sw6jh8lz3uv.sibling(scope, function (e) {
      return $_2nczsvw0jh8lz3ua.is(e, selector);
    });
  };
  var child$2 = function (scope, selector) {
    return $_5a72sw6jh8lz3uv.child(scope, function (e) {
      return $_2nczsvw0jh8lz3ua.is(e, selector);
    });
  };
  var descendant$1 = function (scope, selector) {
    return $_2nczsvw0jh8lz3ua.one(selector, scope);
  };
  var closest$1 = function (scope, selector, isRoot) {
    return ClosestOrAncestor($_2nczsvw0jh8lz3ua.is, ancestor$1, scope, selector, isRoot);
  };
  var $_9rr9rgw5jh8lz3uu = {
    first: first$2,
    ancestor: ancestor$1,
    sibling: sibling$1,
    child: child$2,
    descendant: descendant$1,
    closest: closest$1
  };

  var toggleFormat = function (editor, fmt) {
    return function () {
      editor.execCommand('mceToggleFormat', false, fmt);
    };
  };
  var addFormatChangedListener = function (editor, name, changed) {
    var handler = function (state) {
      changed(state, name);
    };
    if (editor.formatter) {
      editor.formatter.formatChanged(name, handler);
    } else {
      editor.on('init', function () {
        editor.formatter.formatChanged(name, handler);
      });
    }
  };
  var postRenderFormatToggle = function (editor, name) {
    return function (e) {
      addFormatChangedListener(editor, name, function (state) {
        e.control.active(state);
      });
    };
  };

  var register = function (editor) {
    var alignFormats = [
      'alignleft',
      'aligncenter',
      'alignright',
      'alignjustify'
    ];
    var defaultAlign = 'alignleft';
    var alignMenuItems = [
      {
        text: 'Left',
        icon: 'alignleft',
        onclick: toggleFormat(editor, 'alignleft')
      },
      {
        text: 'Center',
        icon: 'aligncenter',
        onclick: toggleFormat(editor, 'aligncenter')
      },
      {
        text: 'Right',
        icon: 'alignright',
        onclick: toggleFormat(editor, 'alignright')
      },
      {
        text: 'Justify',
        icon: 'alignjustify',
        onclick: toggleFormat(editor, 'alignjustify')
      }
    ];
    editor.addMenuItem('align', {
      text: 'Align',
      menu: alignMenuItems
    });
    editor.addButton('align', {
      type: 'menubutton',
      icon: defaultAlign,
      menu: alignMenuItems,
      onShowMenu: function (e) {
        var menu = e.control.menu;
        global$2.each(alignFormats, function (formatName, idx) {
          menu.items().eq(idx).each(function (item) {
            return item.active(editor.formatter.match(formatName));
          });
        });
      },
      onPostRender: function (e) {
        var ctrl = e.control;
        global$2.each(alignFormats, function (formatName, idx) {
          addFormatChangedListener(editor, formatName, function (state) {
            ctrl.icon(defaultAlign);
            if (state) {
              ctrl.icon(formatName);
            }
          });
        });
      }
    });
    global$2.each({
      alignleft: [
        'Align left',
        'JustifyLeft'
      ],
      aligncenter: [
        'Align center',
        'JustifyCenter'
      ],
      alignright: [
        'Align right',
        'JustifyRight'
      ],
      alignjustify: [
        'Justify',
        'JustifyFull'
      ],
      alignnone: [
        'No alignment',
        'JustifyNone'
      ]
    }, function (item, name) {
      editor.addButton(name, {
        active: false,
        tooltip: item[0],
        cmd: item[1],
        onPostRender: postRenderFormatToggle(editor, name)
      });
    });
  };
  var $_a6x5k4w8jh8lz3vh = { register: register };

  var getFirstFont = function (fontFamily) {
    return fontFamily ? fontFamily.split(',')[0] : '';
  };
  var findMatchingValue = function (items, fontFamily) {
    var font = fontFamily ? fontFamily.toLowerCase() : '';
    var value;
    global$2.each(items, function (item) {
      if (item.value.toLowerCase() === font) {
        value = item.value;
      }
    });
    global$2.each(items, function (item) {
      if (!value && getFirstFont(item.value).toLowerCase() === getFirstFont(font).toLowerCase()) {
        value = item.value;
      }
    });
    return value;
  };
  var createFontNameListBoxChangeHandler = function (editor, items) {
    return function () {
      var self = this;
      editor.on('init nodeChange', function (e) {
        var fontFamily = editor.queryCommandValue('FontName');
        var match = findMatchingValue(items, fontFamily);
        self.value(match ? match : null);
        if (!match && fontFamily) {
          self.text(getFirstFont(fontFamily));
        }
      });
    };
  };
  var createFormats = function (formats) {
    formats = formats.replace(/;$/, '').split(';');
    var i = formats.length;
    while (i--) {
      formats[i] = formats[i].split('=');
    }
    return formats;
  };
  var getFontItems = function (editor) {
    var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats';
    var fonts = createFormats(editor.settings.font_formats || defaultFontsFormats);
    return global$2.map(fonts, function (font) {
      return {
        text: { raw: font[0] },
        value: font[1],
        textStyle: font[1].indexOf('dings') === -1 ? 'font-family:' + font[1] : ''
      };
    });
  };
  var registerButtons = function (editor) {
    editor.addButton('fontselect', function () {
      var items = getFontItems(editor);
      return {
        type: 'listbox',
        text: 'Font Family',
        tooltip: 'Font Family',
        values: items,
        fixedWidth: true,
        onPostRender: createFontNameListBoxChangeHandler(editor, items),
        onselect: function (e) {
          if (e.control.settings.value) {
            editor.execCommand('FontName', false, e.control.settings.value);
          }
        }
      };
    });
  };
  var register$1 = function (editor) {
    registerButtons(editor);
  };
  var $_4hdsyewajh8lz3vk = { register: register$1 };

  var round = function (number, precision) {
    var factor = Math.pow(10, precision);
    return Math.round(number * factor) / factor;
  };
  var toPt = function (fontSize, precision) {
    if (/[0-9.]+px$/.test(fontSize)) {
      return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
    }
    return fontSize;
  };
  var findMatchingValue$1 = function (items, pt, px) {
    var value;
    global$2.each(items, function (item) {
      if (item.value === px) {
        value = px;
      } else if (item.value === pt) {
        value = pt;
      }
    });
    return value;
  };
  var createFontSizeListBoxChangeHandler = function (editor, items) {
    return function () {
      var self = this;
      editor.on('init nodeChange', function (e) {
        var px, pt, precision, match;
        px = editor.queryCommandValue('FontSize');
        if (px) {
          for (precision = 3; !match && precision >= 0; precision--) {
            pt = toPt(px, precision);
            match = findMatchingValue$1(items, pt, px);
          }
        }
        self.value(match ? match : null);
        if (!match) {
          self.text(pt);
        }
      });
    };
  };
  var getFontSizeItems = function (editor) {
    var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
    var fontsizeFormats = editor.settings.fontsize_formats || defaultFontsizeFormats;
    return global$2.map(fontsizeFormats.split(' '), function (item) {
      var text = item, value = item;
      var values = item.split('=');
      if (values.length > 1) {
        text = values[0];
        value = values[1];
      }
      return {
        text: text,
        value: value
      };
    });
  };
  var registerButtons$1 = function (editor) {
    editor.addButton('fontsizeselect', function () {
      var items = getFontSizeItems(editor);
      return {
        type: 'listbox',
        text: 'Font Sizes',
        tooltip: 'Font Sizes',
        values: items,
        fixedWidth: true,
        onPostRender: createFontSizeListBoxChangeHandler(editor, items),
        onclick: function (e) {
          if (e.control.settings.value) {
            editor.execCommand('FontSize', false, e.control.settings.value);
          }
        }
      };
    });
  };
  var register$2 = function (editor) {
    registerButtons$1(editor);
  };
  var $_du9atdwbjh8lz3vn = { register: register$2 };

  var hideMenuObjects = function (editor, menu) {
    var count = menu.length;
    global$2.each(menu, function (item) {
      if (item.menu) {
        item.hidden = hideMenuObjects(editor, item.menu) === 0;
      }
      var formatName = item.format;
      if (formatName) {
        item.hidden = !editor.formatter.canApply(formatName);
      }
      if (item.hidden) {
        count--;
      }
    });
    return count;
  };
  var hideFormatMenuItems = function (editor, menu) {
    var count = menu.items().length;
    menu.items().each(function (item) {
      if (item.menu) {
        item.visible(hideFormatMenuItems(editor, item.menu) > 0);
      }
      if (!item.menu && item.settings.menu) {
        item.visible(hideMenuObjects(editor, item.settings.menu) > 0);
      }
      var formatName = item.settings.format;
      if (formatName) {
        item.visible(editor.formatter.canApply(formatName));
      }
      if (!item.visible()) {
        count--;
      }
    });
    return count;
  };
  var createFormatMenu = function (editor) {
    var count = 0;
    var newFormats = [];
    var defaultStyleFormats = [
      {
        title: 'Headings',
        items: [
          {
            title: 'Heading 1',
            format: 'h1'
          },
          {
            title: 'Heading 2',
            format: 'h2'
          },
          {
            title: 'Heading 3',
            format: 'h3'
          },
          {
            title: 'Heading 4',
            format: 'h4'
          },
          {
            title: 'Heading 5',
            format: 'h5'
          },
          {
            title: 'Heading 6',
            format: 'h6'
          }
        ]
      },
      {
        title: 'Inline',
        items: [
          {
            title: 'Bold',
            icon: 'bold',
            format: 'bold'
          },
          {
            title: 'Italic',
            icon: 'italic',
            format: 'italic'
          },
          {
            title: 'Underline',
            icon: 'underline',
            format: 'underline'
          },
          {
            title: 'Strikethrough',
            icon: 'strikethrough',
            format: 'strikethrough'
          },
          {
            title: 'Superscript',
            icon: 'superscript',
            format: 'superscript'
          },
          {
            title: 'Subscript',
            icon: 'subscript',
            format: 'subscript'
          },
          {
            title: 'Code',
            icon: 'code',
            format: 'code'
          }
        ]
      },
      {
        title: 'Blocks',
        items: [
          {
            title: 'Paragraph',
            format: 'p'
          },
          {
            title: 'Blockquote',
            format: 'blockquote'
          },
          {
            title: 'Div',
            format: 'div'
          },
          {
            title: 'Pre',
            format: 'pre'
          }
        ]
      },
      {
        title: 'Alignment',
        items: [
          {
            title: 'Left',
            icon: 'alignleft',
            format: 'alignleft'
          },
          {
            title: 'Center',
            icon: 'aligncenter',
            format: 'aligncenter'
          },
          {
            title: 'Right',
            icon: 'alignright',
            format: 'alignright'
          },
          {
            title: 'Justify',
            icon: 'alignjustify',
            format: 'alignjustify'
          }
        ]
      }
    ];
    var createMenu = function (formats) {
      var menu = [];
      if (!formats) {
        return;
      }
      global$2.each(formats, function (format) {
        var menuItem = {
          text: format.title,
          icon: format.icon
        };
        if (format.items) {
          menuItem.menu = createMenu(format.items);
        } else {
          var formatName = format.format || 'custom' + count++;
          if (!format.format) {
            format.name = formatName;
            newFormats.push(format);
          }
          menuItem.format = formatName;
          menuItem.cmd = format.cmd;
        }
        menu.push(menuItem);
      });
      return menu;
    };
    var createStylesMenu = function () {
      var menu;
      if (editor.settings.style_formats_merge) {
        if (editor.settings.style_formats) {
          menu = createMenu(defaultStyleFormats.concat(editor.settings.style_formats));
        } else {
          menu = createMenu(defaultStyleFormats);
        }
      } else {
        menu = createMenu(editor.settings.style_formats || defaultStyleFormats);
      }
      return menu;
    };
    editor.on('init', function () {
      global$2.each(newFormats, function (format) {
        editor.formatter.register(format.name, format);
      });
    });
    return {
      type: 'menu',
      items: createStylesMenu(),
      onPostRender: function (e) {
        editor.fire('renderFormatsMenu', { control: e.control });
      },
      itemDefaults: {
        preview: true,
        textStyle: function () {
          if (this.settings.format) {
            return editor.formatter.getCssText(this.settings.format);
          }
        },
        onPostRender: function () {
          var self = this;
          self.parent().on('show', function () {
            var formatName, command;
            formatName = self.settings.format;
            if (formatName) {
              self.disabled(!editor.formatter.canApply(formatName));
              self.active(editor.formatter.match(formatName));
            }
            command = self.settings.cmd;
            if (command) {
              self.active(editor.queryCommandState(command));
            }
          });
        },
        onclick: function () {
          if (this.settings.format) {
            toggleFormat(editor, this.settings.format)();
          }
          if (this.settings.cmd) {
            editor.execCommand(this.settings.cmd);
          }
        }
      }
    };
  };
  var registerMenuItems = function (editor, formatMenu) {
    editor.addMenuItem('formats', {
      text: 'Formats',
      menu: formatMenu
    });
  };
  var registerButtons$2 = function (editor, formatMenu) {
    editor.addButton('styleselect', {
      type: 'menubutton',
      text: 'Formats',
      menu: formatMenu,
      onShowMenu: function () {
        if (editor.settings.style_formats_autohide) {
          hideFormatMenuItems(editor, this.menu);
        }
      }
    });
  };
  var register$3 = function (editor) {
    var formatMenu = createFormatMenu(editor);
    registerMenuItems(editor, formatMenu);
    registerButtons$2(editor, formatMenu);
  };
  var $_5xlhbcwcjh8lz3vr = { register: register$3 };

  var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  var createFormats$1 = function (formats) {
    formats = formats.replace(/;$/, '').split(';');
    var i = formats.length;
    while (i--) {
      formats[i] = formats[i].split('=');
    }
    return formats;
  };
  var createListBoxChangeHandler = function (editor, items, formatName) {
    return function () {
      var self = this;
      editor.on('nodeChange', function (e) {
        var formatter = editor.formatter;
        var value = null;
        global$2.each(e.parents, function (node) {
          global$2.each(items, function (item) {
            if (formatName) {
              if (formatter.matchNode(node, formatName, { value: item.value })) {
                value = item.value;
              }
            } else {
              if (formatter.matchNode(node, item.value)) {
                value = item.value;
              }
            }
            if (value) {
              return false;
            }
          });
          if (value) {
            return false;
          }
        });
        self.value(value);
      });
    };
  };
  var lazyFormatSelectBoxItems = function (editor, blocks) {
    return function () {
      var items = [];
      global$2.each(blocks, function (block) {
        items.push({
          text: block[0],
          value: block[1],
          textStyle: function () {
            return editor.formatter.getCssText(block[1]);
          }
        });
      });
      return {
        type: 'listbox',
        text: blocks[0][0],
        values: items,
        fixedWidth: true,
        onselect: function (e) {
          if (e.control) {
            var fmt = e.control.value();
            toggleFormat(editor, fmt)();
          }
        },
        onPostRender: createListBoxChangeHandler(editor, items)
      };
    };
  };
  var buildMenuItems = function (editor, blocks) {
    return global$2.map(blocks, function (block) {
      return {
        text: block[0],
        onclick: toggleFormat(editor, block[1]),
        textStyle: function () {
          return editor.formatter.getCssText(block[1]);
        }
      };
    });
  };
  var register$4 = function (editor) {
    var blocks = createFormats$1(editor.settings.block_formats || defaultBlocks);
    editor.addMenuItem('blockformats', {
      text: 'Blocks',
      menu: buildMenuItems(editor, blocks)
    });
    editor.addButton('formatselect', lazyFormatSelectBoxItems(editor, blocks));
  };
  var $_bj8nxmwdjh8lz3vw = { register: register$4 };

  var createCustomMenuItems = function (editor, names) {
    var items, nameList;
    if (typeof names === 'string') {
      nameList = names.split(' ');
    } else if (global$2.isArray(names)) {
      return $_f3qxhzthjh8lz3kg.flatten(global$2.map(names, function (names) {
        return createCustomMenuItems(editor, names);
      }));
    }
    items = global$2.grep(nameList, function (name) {
      return name === '|' || name in editor.menuItems;
    });
    return global$2.map(items, function (name) {
      return name === '|' ? { text: '-' } : editor.menuItems[name];
    });
  };
  var isSeparator$1 = function (menuItem) {
    return menuItem && menuItem.text === '-';
  };
  var trimMenuItems = function (menuItems) {
    var menuItems2 = $_f3qxhzthjh8lz3kg.filter(menuItems, function (menuItem, i, menuItems) {
      return !isSeparator$1(menuItem) || !isSeparator$1(menuItems[i - 1]);
    });
    return $_f3qxhzthjh8lz3kg.filter(menuItems2, function (menuItem, i, menuItems) {
      return !isSeparator$1(menuItem) || i > 0 && i < menuItems.length - 1;
    });
  };
  var createContextMenuItems = function (editor, context) {
    var outputMenuItems = [{ text: '-' }];
    var menuItems = global$2.grep(editor.menuItems, function (menuItem) {
      return menuItem.context === context;
    });
    global$2.each(menuItems, function (menuItem) {
      if (menuItem.separator === 'before') {
        outputMenuItems.push({ text: '|' });
      }
      if (menuItem.prependToContext) {
        outputMenuItems.unshift(menuItem);
      } else {
        outputMenuItems.push(menuItem);
      }
      if (menuItem.separator === 'after') {
        outputMenuItems.push({ text: '|' });
      }
    });
    return outputMenuItems;
  };
  var createInsertMenu = function (editor) {
    var insertButtonItems = editor.settings.insert_button_items;
    if (insertButtonItems) {
      return trimMenuItems(createCustomMenuItems(editor, insertButtonItems));
    } else {
      return trimMenuItems(createContextMenuItems(editor, 'insert'));
    }
  };
  var registerButtons$3 = function (editor) {
    editor.addButton('insert', {
      type: 'menubutton',
      icon: 'insert',
      menu: [],
      oncreatemenu: function () {
        this.menu.add(createInsertMenu(editor));
        this.menu.renderNew();
      }
    });
  };
  var register$5 = function (editor) {
    registerButtons$3(editor);
  };
  var $_drvzmkwejh8lz3vz = { register: register$5 };

  var registerFormatButtons = function (editor) {
    global$2.each({
      bold: 'Bold',
      italic: 'Italic',
      underline: 'Underline',
      strikethrough: 'Strikethrough',
      subscript: 'Subscript',
      superscript: 'Superscript'
    }, function (text, name) {
      editor.addButton(name, {
        active: false,
        tooltip: text,
        onPostRender: postRenderFormatToggle(editor, name),
        onclick: toggleFormat(editor, name)
      });
    });
  };
  var registerCommandButtons = function (editor) {
    global$2.each({
      outdent: [
        'Decrease indent',
        'Outdent'
      ],
      indent: [
        'Increase indent',
        'Indent'
      ],
      cut: [
        'Cut',
        'Cut'
      ],
      copy: [
        'Copy',
        'Copy'
      ],
      paste: [
        'Paste',
        'Paste'
      ],
      help: [
        'Help',
        'mceHelp'
      ],
      selectall: [
        'Select all',
        'SelectAll'
      ],
      visualaid: [
        'Visual aids',
        'mceToggleVisualAid'
      ],
      newdocument: [
        'New document',
        'mceNewDocument'
      ],
      removeformat: [
        'Clear formatting',
        'RemoveFormat'
      ],
      remove: [
        'Remove',
        'Delete'
      ]
    }, function (item, name) {
      editor.addButton(name, {
        tooltip: item[0],
        cmd: item[1]
      });
    });
  };
  var registerCommandToggleButtons = function (editor) {
    global$2.each({
      blockquote: [
        'Blockquote',
        'mceBlockQuote'
      ],
      subscript: [
        'Subscript',
        'Subscript'
      ],
      superscript: [
        'Superscript',
        'Superscript'
      ]
    }, function (item, name) {
      editor.addButton(name, {
        active: false,
        tooltip: item[0],
        cmd: item[1],
        onPostRender: postRenderFormatToggle(editor, name)
      });
    });
  };
  var registerButtons$4 = function (editor) {
    registerFormatButtons(editor);
    registerCommandButtons(editor);
    registerCommandToggleButtons(editor);
  };
  var registerMenuItems$1 = function (editor) {
    global$2.each({
      bold: [
        'Bold',
        'Bold',
        'Meta+B'
      ],
      italic: [
        'Italic',
        'Italic',
        'Meta+I'
      ],
      underline: [
        'Underline',
        'Underline',
        'Meta+U'
      ],
      strikethrough: [
        'Strikethrough',
        'Strikethrough'
      ],
      subscript: [
        'Subscript',
        'Subscript'
      ],
      superscript: [
        'Superscript',
        'Superscript'
      ],
      removeformat: [
        'Clear formatting',
        'RemoveFormat'
      ],
      newdocument: [
        'New document',
        'mceNewDocument'
      ],
      cut: [
        'Cut',
        'Cut',
        'Meta+X'
      ],
      copy: [
        'Copy',
        'Copy',
        'Meta+C'
      ],
      paste: [
        'Paste',
        'Paste',
        'Meta+V'
      ],
      selectall: [
        'Select all',
        'SelectAll',
        'Meta+A'
      ]
    }, function (item, name) {
      editor.addMenuItem(name, {
        text: item[0],
        icon: name,
        shortcut: item[2],
        cmd: item[1]
      });
    });
    editor.addMenuItem('codeformat', {
      text: 'Code',
      icon: 'code',
      onclick: toggleFormat(editor, 'code')
    });
  };
  var register$6 = function (editor) {
    registerButtons$4(editor);
    registerMenuItems$1(editor);
  };
  var $_2d67dwfjh8lz3w2 = { register: register$6 };

  var toggleUndoRedoState = function (editor, type) {
    return function () {
      var self = this;
      var checkState = function () {
        var typeFn = type === 'redo' ? 'hasRedo' : 'hasUndo';
        return editor.undoManager ? editor.undoManager[typeFn]() : false;
      };
      self.disabled(!checkState());
      editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', function () {
        self.disabled(editor.readonly || !checkState());
      });
    };
  };
  var registerMenuItems$2 = function (editor) {
    editor.addMenuItem('undo', {
      text: 'Undo',
      icon: 'undo',
      shortcut: 'Meta+Z',
      onPostRender: toggleUndoRedoState(editor, 'undo'),
      cmd: 'undo'
    });
    editor.addMenuItem('redo', {
      text: 'Redo',
      icon: 'redo',
      shortcut: 'Meta+Y',
      onPostRender: toggleUndoRedoState(editor, 'redo'),
      cmd: 'redo'
    });
  };
  var registerButtons$5 = function (editor) {
    editor.addButton('undo', {
      tooltip: 'Undo',
      onPostRender: toggleUndoRedoState(editor, 'undo'),
      cmd: 'undo'
    });
    editor.addButton('redo', {
      tooltip: 'Redo',
      onPostRender: toggleUndoRedoState(editor, 'redo'),
      cmd: 'redo'
    });
  };
  var register$7 = function (editor) {
    registerMenuItems$2(editor);
    registerButtons$5(editor);
  };
  var $_cd5m9xwgjh8lz3w5 = { register: register$7 };

  var toggleVisualAidState = function (editor) {
    return function () {
      var self = this;
      editor.on('VisualAid', function (e) {
        self.active(e.hasVisual);
      });
      self.active(editor.hasVisual);
    };
  };
  var registerMenuItems$3 = function (editor) {
    editor.addMenuItem('visualaid', {
      text: 'Visual aids',
      selectable: true,
      onPostRender: toggleVisualAidState(editor),
      cmd: 'mceToggleVisualAid'
    });
  };
  var register$8 = function (editor) {
    registerMenuItems$3(editor);
  };
  var $_1ojpofwhjh8lz3w6 = { register: register$8 };

  var setupEnvironment = function () {
    Widget.tooltips = !global$8.iOS;
    Control$1.translate = function (text) {
      return global$1.translate(text);
    };
  };
  var setupUiContainer = function (editor) {
    if (editor.settings.ui_container) {
      global$8.container = $_9rr9rgw5jh8lz3uu.descendant($_3bkrfxv6jh8lz3rm.fromDom(document.body), editor.settings.ui_container).fold($_3pjweotejh8lz3k4.constant(null), function (elm) {
        return elm.dom();
      });
    }
  };
  var setupRtlMode = function (editor) {
    if (editor.rtl) {
      Control$1.rtl = true;
    }
  };
  var setupHideFloatPanels = function (editor) {
    editor.on('mousedown', function () {
      FloatPanel.hideAll();
    });
  };
  var setup$1 = function (editor) {
    setupRtlMode(editor);
    setupHideFloatPanels(editor);
    setupUiContainer(editor);
    setupEnvironment();
    $_bj8nxmwdjh8lz3vw.register(editor);
    $_a6x5k4w8jh8lz3vh.register(editor);
    $_2d67dwfjh8lz3w2.register(editor);
    $_cd5m9xwgjh8lz3w5.register(editor);
    $_du9atdwbjh8lz3vn.register(editor);
    $_4hdsyewajh8lz3vk.register(editor);
    $_5xlhbcwcjh8lz3vr.register(editor);
    $_1ojpofwhjh8lz3w6.register(editor);
    $_drvzmkwejh8lz3vz.register(editor);
  };
  var $_4qdht3w4jh8lz3uo = { setup: setup$1 };

  var GridLayout = AbsoluteLayout.extend({
    recalc: function (container) {
      var settings, rows, cols, items, contLayoutRect, width, height, rect, ctrlLayoutRect, ctrl, x, y, posX, posY, ctrlSettings, contPaddingBox, align, spacingH, spacingV, alignH, alignV, maxX, maxY;
      var colWidths = [];
      var rowHeights = [];
      var ctrlMinWidth, ctrlMinHeight, availableWidth, availableHeight, reverseRows, idx;
      settings = container.settings;
      items = container.items().filter(':visible');
      contLayoutRect = container.layoutRect();
      cols = settings.columns || Math.ceil(Math.sqrt(items.length));
      rows = Math.ceil(items.length / cols);
      spacingH = settings.spacingH || settings.spacing || 0;
      spacingV = settings.spacingV || settings.spacing || 0;
      alignH = settings.alignH || settings.align;
      alignV = settings.alignV || settings.align;
      contPaddingBox = container.paddingBox;
      reverseRows = 'reverseRows' in settings ? settings.reverseRows : container.isRtl();
      if (alignH && typeof alignH === 'string') {
        alignH = [alignH];
      }
      if (alignV && typeof alignV === 'string') {
        alignV = [alignV];
      }
      for (x = 0; x < cols; x++) {
        colWidths.push(0);
      }
      for (y = 0; y < rows; y++) {
        rowHeights.push(0);
      }
      for (y = 0; y < rows; y++) {
        for (x = 0; x < cols; x++) {
          ctrl = items[y * cols + x];
          if (!ctrl) {
            break;
          }
          ctrlLayoutRect = ctrl.layoutRect();
          ctrlMinWidth = ctrlLayoutRect.minW;
          ctrlMinHeight = ctrlLayoutRect.minH;
          colWidths[x] = ctrlMinWidth > colWidths[x] ? ctrlMinWidth : colWidths[x];
          rowHeights[y] = ctrlMinHeight > rowHeights[y] ? ctrlMinHeight : rowHeights[y];
        }
      }
      availableWidth = contLayoutRect.innerW - contPaddingBox.left - contPaddingBox.right;
      for (maxX = 0, x = 0; x < cols; x++) {
        maxX += colWidths[x] + (x > 0 ? spacingH : 0);
        availableWidth -= (x > 0 ? spacingH : 0) + colWidths[x];
      }
      availableHeight = contLayoutRect.innerH - contPaddingBox.top - contPaddingBox.bottom;
      for (maxY = 0, y = 0; y < rows; y++) {
        maxY += rowHeights[y] + (y > 0 ? spacingV : 0);
        availableHeight -= (y > 0 ? spacingV : 0) + rowHeights[y];
      }
      maxX += contPaddingBox.left + contPaddingBox.right;
      maxY += contPaddingBox.top + contPaddingBox.bottom;
      rect = {};
      rect.minW = maxX + (contLayoutRect.w - contLayoutRect.innerW);
      rect.minH = maxY + (contLayoutRect.h - contLayoutRect.innerH);
      rect.contentW = rect.minW - contLayoutRect.deltaW;
      rect.contentH = rect.minH - contLayoutRect.deltaH;
      rect.minW = Math.min(rect.minW, contLayoutRect.maxW);
      rect.minH = Math.min(rect.minH, contLayoutRect.maxH);
      rect.minW = Math.max(rect.minW, contLayoutRect.startMinWidth);
      rect.minH = Math.max(rect.minH, contLayoutRect.startMinHeight);
      if (contLayoutRect.autoResize && (rect.minW !== contLayoutRect.minW || rect.minH !== contLayoutRect.minH)) {
        rect.w = rect.minW;
        rect.h = rect.minH;
        container.layoutRect(rect);
        this.recalc(container);
        if (container._lastRect === null) {
          var parentCtrl = container.parent();
          if (parentCtrl) {
            parentCtrl._lastRect = null;
            parentCtrl.recalc();
          }
        }
        return;
      }
      if (contLayoutRect.autoResize) {
        rect = container.layoutRect(rect);
        rect.contentW = rect.minW - contLayoutRect.deltaW;
        rect.contentH = rect.minH - contLayoutRect.deltaH;
      }
      var flexV;
      if (settings.packV === 'start') {
        flexV = 0;
      } else {
        flexV = availableHeight > 0 ? Math.floor(availableHeight / rows) : 0;
      }
      var totalFlex = 0;
      var flexWidths = settings.flexWidths;
      if (flexWidths) {
        for (x = 0; x < flexWidths.length; x++) {
          totalFlex += flexWidths[x];
        }
      } else {
        totalFlex = cols;
      }
      var ratio = availableWidth / totalFlex;
      for (x = 0; x < cols; x++) {
        colWidths[x] += flexWidths ? flexWidths[x] * ratio : ratio;
      }
      posY = contPaddingBox.top;
      for (y = 0; y < rows; y++) {
        posX = contPaddingBox.left;
        height = rowHeights[y] + flexV;
        for (x = 0; x < cols; x++) {
          if (reverseRows) {
            idx = y * cols + cols - 1 - x;
          } else {
            idx = y * cols + x;
          }
          ctrl = items[idx];
          if (!ctrl) {
            break;
          }
          ctrlSettings = ctrl.settings;
          ctrlLayoutRect = ctrl.layoutRect();
          width = Math.max(colWidths[x], ctrlLayoutRect.startMinWidth);
          ctrlLayoutRect.x = posX;
          ctrlLayoutRect.y = posY;
          align = ctrlSettings.alignH || (alignH ? alignH[x] || alignH[0] : null);
          if (align === 'center') {
            ctrlLayoutRect.x = posX + width / 2 - ctrlLayoutRect.w / 2;
          } else if (align === 'right') {
            ctrlLayoutRect.x = posX + width - ctrlLayoutRect.w;
          } else if (align === 'stretch') {
            ctrlLayoutRect.w = width;
          }
          align = ctrlSettings.alignV || (alignV ? alignV[x] || alignV[0] : null);
          if (align === 'center') {
            ctrlLayoutRect.y = posY + height / 2 - ctrlLayoutRect.h / 2;
          } else if (align === 'bottom') {
            ctrlLayoutRect.y = posY + height - ctrlLayoutRect.h;
          } else if (align === 'stretch') {
            ctrlLayoutRect.h = height;
          }
          ctrl.layoutRect(ctrlLayoutRect);
          posX += width + spacingH;
          if (ctrl.recalc) {
            ctrl.recalc();
          }
        }
        posY += height + spacingV;
      }
    }
  });

  var Iframe$1 = Widget.extend({
    renderHtml: function () {
      var self = this;
      self.classes.add('iframe');
      self.canFocus = false;
      return '<iframe id="' + self._id + '" class="' + self.classes + '" tabindex="-1" src="' + (self.settings.url || 'javascript:\'\'') + '" frameborder="0"></iframe>';
    },
    src: function (src) {
      this.getEl().src = src;
    },
    html: function (html, callback) {
      var self = this, body = this.getEl().contentWindow.document.body;
      if (!body) {
        global$7.setTimeout(function () {
          self.html(html);
        });
      } else {
        body.innerHTML = html;
        if (callback) {
          callback();
        }
      }
      return this;
    }
  });

  var InfoBox = Widget.extend({
    init: function (settings) {
      var self = this;
      self._super(settings);
      self.classes.add('widget').add('infobox');
      self.canFocus = false;
    },
    severity: function (level) {
      this.classes.remove('error');
      this.classes.remove('warning');
      this.classes.remove('success');
      this.classes.add(level);
    },
    help: function (state) {
      this.state.set('help', state);
    },
    renderHtml: function () {
      var self = this, prefix = self.classPrefix;
      return '<div id="' + self._id + '" class="' + self.classes + '">' + '<div id="' + self._id + '-body">' + self.encode(self.state.get('text')) + '<button role="button" tabindex="-1">' + '<i class="' + prefix + 'ico ' + prefix + 'i-help"></i>' + '</button>' + '</div>' + '</div>';
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:text', function (e) {
        self.getEl('body').firstChild.data = self.encode(e.value);
        if (self.state.get('rendered')) {
          self.updateLayoutRect();
        }
      });
      self.state.on('change:help', function (e) {
        self.classes.toggle('has-help', e.value);
        if (self.state.get('rendered')) {
          self.updateLayoutRect();
        }
      });
      return self._super();
    }
  });

  var Label = Widget.extend({
    init: function (settings) {
      var self = this;
      self._super(settings);
      self.classes.add('widget').add('label');
      self.canFocus = false;
      if (settings.multiline) {
        self.classes.add('autoscroll');
      }
      if (settings.strong) {
        self.classes.add('strong');
      }
    },
    initLayoutRect: function () {
      var self = this, layoutRect = self._super();
      if (self.settings.multiline) {
        var size = funcs.getSize(self.getEl());
        if (size.width > layoutRect.maxW) {
          layoutRect.minW = layoutRect.maxW;
          self.classes.add('multiline');
        }
        self.getEl().style.width = layoutRect.minW + 'px';
        layoutRect.startMinH = layoutRect.h = layoutRect.minH = Math.min(layoutRect.maxH, funcs.getSize(self.getEl()).height);
      }
      return layoutRect;
    },
    repaint: function () {
      var self = this;
      if (!self.settings.multiline) {
        self.getEl().style.lineHeight = self.layoutRect().h + 'px';
      }
      return self._super();
    },
    severity: function (level) {
      this.classes.remove('error');
      this.classes.remove('warning');
      this.classes.remove('success');
      this.classes.add(level);
    },
    renderHtml: function () {
      var self = this;
      var targetCtrl, forName, forId = self.settings.forId;
      var text = self.settings.html ? self.settings.html : self.encode(self.state.get('text'));
      if (!forId && (forName = self.settings.forName)) {
        targetCtrl = self.getRoot().find('#' + forName)[0];
        if (targetCtrl) {
          forId = targetCtrl._id;
        }
      }
      if (forId) {
        return '<label id="' + self._id + '" class="' + self.classes + '"' + (forId ? ' for="' + forId + '"' : '') + '>' + text + '</label>';
      }
      return '<span id="' + self._id + '" class="' + self.classes + '">' + text + '</span>';
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:text', function (e) {
        self.innerHtml(self.encode(e.value));
        if (self.state.get('rendered')) {
          self.updateLayoutRect();
        }
      });
      return self._super();
    }
  });

  var Toolbar$1 = Container.extend({
    Defaults: {
      role: 'toolbar',
      layout: 'flow'
    },
    init: function (settings) {
      var self = this;
      self._super(settings);
      self.classes.add('toolbar');
    },
    postRender: function () {
      var self = this;
      self.items().each(function (ctrl) {
        ctrl.classes.add('toolbar-item');
      });
      return self._super();
    }
  });

  var MenuBar = Toolbar$1.extend({
    Defaults: {
      role: 'menubar',
      containerCls: 'menubar',
      ariaRoot: true,
      defaults: { type: 'menubutton' }
    }
  });

  function isChildOf$1(node, parent) {
    while (node) {
      if (parent === node) {
        return true;
      }
      node = node.parentNode;
    }
    return false;
  }
  var MenuButton = Button.extend({
    init: function (settings) {
      var self = this;
      self._renderOpen = true;
      self._super(settings);
      settings = self.settings;
      self.classes.add('menubtn');
      if (settings.fixedWidth) {
        self.classes.add('fixed-width');
      }
      self.aria('haspopup', true);
      self.state.set('menu', settings.menu || self.render());
    },
    showMenu: function (toggle) {
      var self = this;
      var menu;
      if (self.menu && self.menu.visible() && toggle !== false) {
        return self.hideMenu();
      }
      if (!self.menu) {
        menu = self.state.get('menu') || [];
        self.classes.add('opened');
        if (menu.length) {
          menu = {
            type: 'menu',
            animate: true,
            items: menu
          };
        } else {
          menu.type = menu.type || 'menu';
          menu.animate = true;
        }
        if (!menu.renderTo) {
          self.menu = global$4.create(menu).parent(self).renderTo();
        } else {
          self.menu = menu.parent(self).show().renderTo();
        }
        self.fire('createmenu');
        self.menu.reflow();
        self.menu.on('cancel', function (e) {
          if (e.control.parent() === self.menu) {
            e.stopPropagation();
            self.focus();
            self.hideMenu();
          }
        });
        self.menu.on('select', function () {
          self.focus();
        });
        self.menu.on('show hide', function (e) {
          if (e.control === self.menu) {
            self.activeMenu(e.type === 'show');
            self.classes.toggle('opened', e.type === 'show');
          }
          self.aria('expanded', e.type === 'show');
        }).fire('show');
      }
      self.menu.show();
      self.menu.layoutRect({ w: self.layoutRect().w });
      self.menu.repaint();
      self.menu.moveRel(self.getEl(), self.isRtl() ? [
        'br-tr',
        'tr-br'
      ] : [
        'bl-tl',
        'tl-bl'
      ]);
      self.fire('showmenu');
    },
    hideMenu: function () {
      var self = this;
      if (self.menu) {
        self.menu.items().each(function (item) {
          if (item.hideMenu) {
            item.hideMenu();
          }
        });
        self.menu.hide();
      }
    },
    activeMenu: function (state) {
      this.classes.toggle('active', state);
    },
    renderHtml: function () {
      var self = this, id = self._id, prefix = self.classPrefix;
      var icon = self.settings.icon, image;
      var text = self.state.get('text');
      var textHtml = '';
      image = self.settings.image;
      if (image) {
        icon = 'none';
        if (typeof image !== 'string') {
          image = window.getSelection ? image[0] : image[1];
        }
        image = ' style="background-image: url(\'' + image + '\')"';
      } else {
        image = '';
      }
      if (text) {
        self.classes.add('btn-has-text');
        textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>';
      }
      icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + icon : '';
      self.aria('role', self.parent() instanceof MenuBar ? 'menuitem' : 'button');
      return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1" aria-labelledby="' + id + '">' + '<button id="' + id + '-open" role="presentation" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>';
    },
    postRender: function () {
      var self = this;
      self.on('click', function (e) {
        if (e.control === self && isChildOf$1(e.target, self.getEl())) {
          self.focus();
          self.showMenu(!e.aria);
          if (e.aria) {
            self.menu.items().filter(':visible')[0].focus();
          }
        }
      });
      self.on('mouseenter', function (e) {
        var overCtrl = e.control;
        var parent = self.parent();
        var hasVisibleSiblingMenu;
        if (overCtrl && parent && overCtrl instanceof MenuButton && overCtrl.parent() === parent) {
          parent.items().filter('MenuButton').each(function (ctrl) {
            if (ctrl.hideMenu && ctrl !== overCtrl) {
              if (ctrl.menu && ctrl.menu.visible()) {
                hasVisibleSiblingMenu = true;
              }
              ctrl.hideMenu();
            }
          });
          if (hasVisibleSiblingMenu) {
            overCtrl.focus();
            overCtrl.showMenu();
          }
        }
      });
      return self._super();
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:menu', function () {
        if (self.menu) {
          self.menu.remove();
        }
        self.menu = null;
      });
      return self._super();
    },
    remove: function () {
      this._super();
      if (this.menu) {
        this.menu.remove();
      }
    }
  });

  var Menu = FloatPanel.extend({
    Defaults: {
      defaultType: 'menuitem',
      border: 1,
      layout: 'stack',
      role: 'application',
      bodyRole: 'menu',
      ariaRoot: true
    },
    init: function (settings) {
      var self = this;
      settings.autohide = true;
      settings.constrainToViewport = true;
      if (typeof settings.items === 'function') {
        settings.itemsFactory = settings.items;
        settings.items = [];
      }
      if (settings.itemDefaults) {
        var items = settings.items;
        var i = items.length;
        while (i--) {
          items[i] = global$2.extend({}, settings.itemDefaults, items[i]);
        }
      }
      self._super(settings);
      self.classes.add('menu');
      if (settings.animate && global$8.ie !== 11) {
        self.classes.add('animate');
      }
    },
    repaint: function () {
      this.classes.toggle('menu-align', true);
      this._super();
      this.getEl().style.height = '';
      this.getEl('body').style.height = '';
      return this;
    },
    cancel: function () {
      var self = this;
      self.hideAll();
      self.fire('select');
    },
    load: function () {
      var self = this;
      var time, factory;
      function hideThrobber() {
        if (self.throbber) {
          self.throbber.hide();
          self.throbber = null;
        }
      }
      factory = self.settings.itemsFactory;
      if (!factory) {
        return;
      }
      if (!self.throbber) {
        self.throbber = new Throbber(self.getEl('body'), true);
        if (self.items().length === 0) {
          self.throbber.show();
          self.fire('loading');
        } else {
          self.throbber.show(100, function () {
            self.items().remove();
            self.fire('loading');
          });
        }
        self.on('hide close', hideThrobber);
      }
      self.requestTime = time = new Date().getTime();
      self.settings.itemsFactory(function (items) {
        if (items.length === 0) {
          self.hide();
          return;
        }
        if (self.requestTime !== time) {
          return;
        }
        self.getEl().style.width = '';
        self.getEl('body').style.width = '';
        hideThrobber();
        self.items().remove();
        self.getEl('body').innerHTML = '';
        self.add(items);
        self.renderNew();
        self.fire('loaded');
      });
    },
    hideAll: function () {
      var self = this;
      this.find('menuitem').exec('hideMenu');
      return self._super();
    },
    preRender: function () {
      var self = this;
      self.items().each(function (ctrl) {
        var settings = ctrl.settings;
        if (settings.icon || settings.image || settings.selectable) {
          self._hasIcons = true;
          return false;
        }
      });
      if (self.settings.itemsFactory) {
        self.on('postrender', function () {
          if (self.settings.itemsFactory) {
            self.load();
          }
        });
      }
      self.on('show hide', function (e) {
        if (e.control === self) {
          if (e.type === 'show') {
            global$7.setTimeout(function () {
              self.classes.add('in');
            }, 0);
          } else {
            self.classes.remove('in');
          }
        }
      });
      return self._super();
    }
  });

  var ListBox = MenuButton.extend({
    init: function (settings) {
      var self = this;
      var values, selected, selectedText, lastItemCtrl;
      function setSelected(menuValues) {
        for (var i = 0; i < menuValues.length; i++) {
          selected = menuValues[i].selected || settings.value === menuValues[i].value;
          if (selected) {
            selectedText = selectedText || menuValues[i].text;
            self.state.set('value', menuValues[i].value);
            return true;
          }
          if (menuValues[i].menu) {
            if (setSelected(menuValues[i].menu)) {
              return true;
            }
          }
        }
      }
      self._super(settings);
      settings = self.settings;
      self._values = values = settings.values;
      if (values) {
        if (typeof settings.value !== 'undefined') {
          setSelected(values);
        }
        if (!selected && values.length > 0) {
          selectedText = values[0].text;
          self.state.set('value', values[0].value);
        }
        self.state.set('menu', values);
      }
      self.state.set('text', settings.text || selectedText);
      self.classes.add('listbox');
      self.on('select', function (e) {
        var ctrl = e.control;
        if (lastItemCtrl) {
          e.lastControl = lastItemCtrl;
        }
        if (settings.multiple) {
          ctrl.active(!ctrl.active());
        } else {
          self.value(e.control.value());
        }
        lastItemCtrl = ctrl;
      });
    },
    value: function (value) {
      if (arguments.length === 0) {
        return this.state.get('value');
      }
      if (typeof value === 'undefined') {
        return this;
      }
      if (this.settings.values) {
        var matchingValues = global$2.grep(this.settings.values, function (a) {
          return a.value === value;
        });
        if (matchingValues.length > 0) {
          this.state.set('value', value);
        } else if (value === null) {
          this.state.set('value', null);
        }
      } else {
        this.state.set('value', value);
      }
      return this;
    },
    bindStates: function () {
      var self = this;
      function activateMenuItemsByValue(menu, value) {
        if (menu instanceof Menu) {
          menu.items().each(function (ctrl) {
            if (!ctrl.hasMenus()) {
              ctrl.active(ctrl.value() === value);
            }
          });
        }
      }
      function getSelectedItem(menuValues, value) {
        var selectedItem;
        if (!menuValues) {
          return;
        }
        for (var i = 0; i < menuValues.length; i++) {
          if (menuValues[i].value === value) {
            return menuValues[i];
          }
          if (menuValues[i].menu) {
            selectedItem = getSelectedItem(menuValues[i].menu, value);
            if (selectedItem) {
              return selectedItem;
            }
          }
        }
      }
      self.on('show', function (e) {
        activateMenuItemsByValue(e.control, self.value());
      });
      self.state.on('change:value', function (e) {
        var selectedItem = getSelectedItem(self.state.get('menu'), e.value);
        if (selectedItem) {
          self.text(selectedItem.text);
        } else {
          self.text(self.settings.text);
        }
      });
      return self._super();
    }
  });

  var toggleTextStyle = function (ctrl, state) {
    var textStyle = ctrl._textStyle;
    if (textStyle) {
      var textElm = ctrl.getEl('text');
      textElm.setAttribute('style', textStyle);
      if (state) {
        textElm.style.color = '';
        textElm.style.backgroundColor = '';
      }
    }
  };
  var MenuItem = Widget.extend({
    Defaults: {
      border: 0,
      role: 'menuitem'
    },
    init: function (settings) {
      var self = this;
      var text;
      self._super(settings);
      settings = self.settings;
      self.classes.add('menu-item');
      if (settings.menu) {
        self.classes.add('menu-item-expand');
      }
      if (settings.preview) {
        self.classes.add('menu-item-preview');
      }
      text = self.state.get('text');
      if (text === '-' || text === '|') {
        self.classes.add('menu-item-sep');
        self.aria('role', 'separator');
        self.state.set('text', '-');
      }
      if (settings.selectable) {
        self.aria('role', 'menuitemcheckbox');
        self.classes.add('menu-item-checkbox');
        settings.icon = 'selected';
      }
      if (!settings.preview && !settings.selectable) {
        self.classes.add('menu-item-normal');
      }
      self.on('mousedown', function (e) {
        e.preventDefault();
      });
      if (settings.menu && !settings.ariaHideMenu) {
        self.aria('haspopup', true);
      }
    },
    hasMenus: function () {
      return !!this.settings.menu;
    },
    showMenu: function () {
      var self = this;
      var settings = self.settings;
      var menu;
      var parent = self.parent();
      parent.items().each(function (ctrl) {
        if (ctrl !== self) {
          ctrl.hideMenu();
        }
      });
      if (settings.menu) {
        menu = self.menu;
        if (!menu) {
          menu = settings.menu;
          if (menu.length) {
            menu = {
              type: 'menu',
              items: menu
            };
          } else {
            menu.type = menu.type || 'menu';
          }
          if (parent.settings.itemDefaults) {
            menu.itemDefaults = parent.settings.itemDefaults;
          }
          menu = self.menu = global$4.create(menu).parent(self).renderTo();
          menu.reflow();
          menu.on('cancel', function (e) {
            e.stopPropagation();
            self.focus();
            menu.hide();
          });
          menu.on('show hide', function (e) {
            if (e.control.items) {
              e.control.items().each(function (ctrl) {
                ctrl.active(ctrl.settings.selected);
              });
            }
          }).fire('show');
          menu.on('hide', function (e) {
            if (e.control === menu) {
              self.classes.remove('selected');
            }
          });
          menu.submenu = true;
        } else {
          menu.show();
        }
        menu._parentMenu = parent;
        menu.classes.add('menu-sub');
        var rel = menu.testMoveRel(self.getEl(), self.isRtl() ? [
          'tl-tr',
          'bl-br',
          'tr-tl',
          'br-bl'
        ] : [
          'tr-tl',
          'br-bl',
          'tl-tr',
          'bl-br'
        ]);
        menu.moveRel(self.getEl(), rel);
        menu.rel = rel;
        rel = 'menu-sub-' + rel;
        menu.classes.remove(menu._lastRel).add(rel);
        menu._lastRel = rel;
        self.classes.add('selected');
        self.aria('expanded', true);
      }
    },
    hideMenu: function () {
      var self = this;
      if (self.menu) {
        self.menu.items().each(function (item) {
          if (item.hideMenu) {
            item.hideMenu();
          }
        });
        self.menu.hide();
        self.aria('expanded', false);
      }
      return self;
    },
    renderHtml: function () {
      var self = this;
      var id = self._id;
      var settings = self.settings;
      var prefix = self.classPrefix;
      var text = self.state.get('text');
      var icon = self.settings.icon, image = '', shortcut = settings.shortcut;
      var url = self.encode(settings.url), iconHtml = '';
      function convertShortcut(shortcut) {
        var i, value, replace = {};
        if (global$8.mac) {
          replace = {
            alt: '&#x2325;',
            ctrl: '&#x2318;',
            shift: '&#x21E7;',
            meta: '&#x2318;'
          };
        } else {
          replace = { meta: 'Ctrl' };
        }
        shortcut = shortcut.split('+');
        for (i = 0; i < shortcut.length; i++) {
          value = replace[shortcut[i].toLowerCase()];
          if (value) {
            shortcut[i] = value;
          }
        }
        return shortcut.join('+');
      }
      function escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      }
      function markMatches(text) {
        var match = settings.match || '';
        return match ? text.replace(new RegExp(escapeRegExp(match), 'gi'), function (match) {
          return '!mce~match[' + match + ']mce~match!';
        }) : text;
      }
      function boldMatches(text) {
        return text.replace(new RegExp(escapeRegExp('!mce~match['), 'g'), '<b>').replace(new RegExp(escapeRegExp(']mce~match!'), 'g'), '</b>');
      }
      if (icon) {
        self.parent().classes.add('menu-has-icons');
      }
      if (settings.image) {
        image = ' style="background-image: url(\'' + settings.image + '\')"';
      }
      if (shortcut) {
        shortcut = convertShortcut(shortcut);
      }
      icon = prefix + 'ico ' + prefix + 'i-' + (self.settings.icon || 'none');
      iconHtml = text !== '-' ? '<i class="' + icon + '"' + image + '></i>\xA0' : '';
      text = boldMatches(self.encode(markMatches(text)));
      url = boldMatches(self.encode(markMatches(url)));
      return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1">' + iconHtml + (text !== '-' ? '<span id="' + id + '-text" class="' + prefix + 'text">' + text + '</span>' : '') + (shortcut ? '<div id="' + id + '-shortcut" class="' + prefix + 'menu-shortcut">' + shortcut + '</div>' : '') + (settings.menu ? '<div class="' + prefix + 'caret"></div>' : '') + (url ? '<div class="' + prefix + 'menu-item-link">' + url + '</div>' : '') + '</div>';
    },
    postRender: function () {
      var self = this, settings = self.settings;
      var textStyle = settings.textStyle;
      if (typeof textStyle === 'function') {
        textStyle = textStyle.call(this);
      }
      if (textStyle) {
        var textElm = self.getEl('text');
        if (textElm) {
          textElm.setAttribute('style', textStyle);
          self._textStyle = textStyle;
        }
      }
      self.on('mouseenter click', function (e) {
        if (e.control === self) {
          if (!settings.menu && e.type === 'click') {
            self.fire('select');
            global$7.requestAnimationFrame(function () {
              self.parent().hideAll();
            });
          } else {
            self.showMenu();
            if (e.aria) {
              self.menu.focus(true);
            }
          }
        }
      });
      self._super();
      return self;
    },
    hover: function () {
      var self = this;
      self.parent().items().each(function (ctrl) {
        ctrl.classes.remove('selected');
      });
      self.classes.toggle('selected', true);
      return self;
    },
    active: function (state) {
      toggleTextStyle(this, state);
      if (typeof state !== 'undefined') {
        this.aria('checked', state);
      }
      return this._super(state);
    },
    remove: function () {
      this._super();
      if (this.menu) {
        this.menu.remove();
      }
    }
  });

  var Radio = Checkbox.extend({
    Defaults: {
      classes: 'radio',
      role: 'radio'
    }
  });

  var ResizeHandle = Widget.extend({
    renderHtml: function () {
      var self = this, prefix = self.classPrefix;
      self.classes.add('resizehandle');
      if (self.settings.direction === 'both') {
        self.classes.add('resizehandle-both');
      }
      self.canFocus = false;
      return '<div id="' + self._id + '" class="' + self.classes + '">' + '<i class="' + prefix + 'ico ' + prefix + 'i-resize"></i>' + '</div>';
    },
    postRender: function () {
      var self = this;
      self._super();
      self.resizeDragHelper = new DragHelper(this._id, {
        start: function () {
          self.fire('ResizeStart');
        },
        drag: function (e) {
          if (self.settings.direction !== 'both') {
            e.deltaX = 0;
          }
          self.fire('Resize', e);
        },
        stop: function () {
          self.fire('ResizeEnd');
        }
      });
    },
    remove: function () {
      if (this.resizeDragHelper) {
        this.resizeDragHelper.destroy();
      }
      return this._super();
    }
  });

  function createOptions(options) {
    var strOptions = '';
    if (options) {
      for (var i = 0; i < options.length; i++) {
        strOptions += '<option value="' + options[i] + '">' + options[i] + '</option>';
      }
    }
    return strOptions;
  }
  var SelectBox = Widget.extend({
    Defaults: {
      classes: 'selectbox',
      role: 'selectbox',
      options: []
    },
    init: function (settings) {
      var self = this;
      self._super(settings);
      if (self.settings.size) {
        self.size = self.settings.size;
      }
      if (self.settings.options) {
        self._options = self.settings.options;
      }
      self.on('keydown', function (e) {
        var rootControl;
        if (e.keyCode === 13) {
          e.preventDefault();
          self.parents().reverse().each(function (ctrl) {
            if (ctrl.toJSON) {
              rootControl = ctrl;
              return false;
            }
          });
          self.fire('submit', { data: rootControl.toJSON() });
        }
      });
    },
    options: function (state) {
      if (!arguments.length) {
        return this.state.get('options');
      }
      this.state.set('options', state);
      return this;
    },
    renderHtml: function () {
      var self = this;
      var options, size = '';
      options = createOptions(self._options);
      if (self.size) {
        size = ' size = "' + self.size + '"';
      }
      return '<select id="' + self._id + '" class="' + self.classes + '"' + size + '>' + options + '</select>';
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:options', function (e) {
        self.getEl().innerHTML = createOptions(e.value);
      });
      return self._super();
    }
  });

  function constrain(value, minVal, maxVal) {
    if (value < minVal) {
      value = minVal;
    }
    if (value > maxVal) {
      value = maxVal;
    }
    return value;
  }
  function setAriaProp(el, name, value) {
    el.setAttribute('aria-' + name, value);
  }
  function updateSliderHandle(ctrl, value) {
    var maxHandlePos, shortSizeName, sizeName, stylePosName, styleValue, handleEl;
    if (ctrl.settings.orientation === 'v') {
      stylePosName = 'top';
      sizeName = 'height';
      shortSizeName = 'h';
    } else {
      stylePosName = 'left';
      sizeName = 'width';
      shortSizeName = 'w';
    }
    handleEl = ctrl.getEl('handle');
    maxHandlePos = (ctrl.layoutRect()[shortSizeName] || 100) - funcs.getSize(handleEl)[sizeName];
    styleValue = maxHandlePos * ((value - ctrl._minValue) / (ctrl._maxValue - ctrl._minValue)) + 'px';
    handleEl.style[stylePosName] = styleValue;
    handleEl.style.height = ctrl.layoutRect().h + 'px';
    setAriaProp(handleEl, 'valuenow', value);
    setAriaProp(handleEl, 'valuetext', '' + ctrl.settings.previewFilter(value));
    setAriaProp(handleEl, 'valuemin', ctrl._minValue);
    setAriaProp(handleEl, 'valuemax', ctrl._maxValue);
  }
  var Slider = Widget.extend({
    init: function (settings) {
      var self = this;
      if (!settings.previewFilter) {
        settings.previewFilter = function (value) {
          return Math.round(value * 100) / 100;
        };
      }
      self._super(settings);
      self.classes.add('slider');
      if (settings.orientation === 'v') {
        self.classes.add('vertical');
      }
      self._minValue = $_d8bie3tijh8lz3kn.isNumber(settings.minValue) ? settings.minValue : 0;
      self._maxValue = $_d8bie3tijh8lz3kn.isNumber(settings.maxValue) ? settings.maxValue : 100;
      self._initValue = self.state.get('value');
    },
    renderHtml: function () {
      var self = this, id = self._id, prefix = self.classPrefix;
      return '<div id="' + id + '" class="' + self.classes + '">' + '<div id="' + id + '-handle" class="' + prefix + 'slider-handle" role="slider" tabindex="-1"></div>' + '</div>';
    },
    reset: function () {
      this.value(this._initValue).repaint();
    },
    postRender: function () {
      var self = this;
      var minValue, maxValue, screenCordName, stylePosName, sizeName, shortSizeName;
      function toFraction(min, max, val) {
        return (val + min) / (max - min);
      }
      function fromFraction(min, max, val) {
        return val * (max - min) - min;
      }
      function handleKeyboard(minValue, maxValue) {
        function alter(delta) {
          var value;
          value = self.value();
          value = fromFraction(minValue, maxValue, toFraction(minValue, maxValue, value) + delta * 0.05);
          value = constrain(value, minValue, maxValue);
          self.value(value);
          self.fire('dragstart', { value: value });
          self.fire('drag', { value: value });
          self.fire('dragend', { value: value });
        }
        self.on('keydown', function (e) {
          switch (e.keyCode) {
          case 37:
          case 38:
            alter(-1);
            break;
          case 39:
          case 40:
            alter(1);
            break;
          }
        });
      }
      function handleDrag(minValue, maxValue, handleEl) {
        var startPos, startHandlePos, maxHandlePos, handlePos, value;
        self._dragHelper = new DragHelper(self._id, {
          handle: self._id + '-handle',
          start: function (e) {
            startPos = e[screenCordName];
            startHandlePos = parseInt(self.getEl('handle').style[stylePosName], 10);
            maxHandlePos = (self.layoutRect()[shortSizeName] || 100) - funcs.getSize(handleEl)[sizeName];
            self.fire('dragstart', { value: value });
          },
          drag: function (e) {
            var delta = e[screenCordName] - startPos;
            handlePos = constrain(startHandlePos + delta, 0, maxHandlePos);
            handleEl.style[stylePosName] = handlePos + 'px';
            value = minValue + handlePos / maxHandlePos * (maxValue - minValue);
            self.value(value);
            self.tooltip().text('' + self.settings.previewFilter(value)).show().moveRel(handleEl, 'bc tc');
            self.fire('drag', { value: value });
          },
          stop: function () {
            self.tooltip().hide();
            self.fire('dragend', { value: value });
          }
        });
      }
      minValue = self._minValue;
      maxValue = self._maxValue;
      if (self.settings.orientation === 'v') {
        screenCordName = 'screenY';
        stylePosName = 'top';
        sizeName = 'height';
        shortSizeName = 'h';
      } else {
        screenCordName = 'screenX';
        stylePosName = 'left';
        sizeName = 'width';
        shortSizeName = 'w';
      }
      self._super();
      handleKeyboard(minValue, maxValue);
      handleDrag(minValue, maxValue, self.getEl('handle'));
    },
    repaint: function () {
      this._super();
      updateSliderHandle(this, this.value());
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:value', function (e) {
        updateSliderHandle(self, e.value);
      });
      return self._super();
    }
  });

  var Spacer = Widget.extend({
    renderHtml: function () {
      var self = this;
      self.classes.add('spacer');
      self.canFocus = false;
      return '<div id="' + self._id + '" class="' + self.classes + '"></div>';
    }
  });

  var SplitButton = MenuButton.extend({
    Defaults: {
      classes: 'widget btn splitbtn',
      role: 'button'
    },
    repaint: function () {
      var self = this;
      var elm = self.getEl();
      var rect = self.layoutRect();
      var mainButtonElm, menuButtonElm;
      self._super();
      mainButtonElm = elm.firstChild;
      menuButtonElm = elm.lastChild;
      global$9(mainButtonElm).css({
        width: rect.w - funcs.getSize(menuButtonElm).width,
        height: rect.h - 2
      });
      global$9(menuButtonElm).css({ height: rect.h - 2 });
      return self;
    },
    activeMenu: function (state) {
      var self = this;
      global$9(self.getEl().lastChild).toggleClass(self.classPrefix + 'active', state);
    },
    renderHtml: function () {
      var self = this;
      var id = self._id;
      var prefix = self.classPrefix;
      var image;
      var icon = self.state.get('icon');
      var text = self.state.get('text');
      var settings = self.settings;
      var textHtml = '', ariaPressed;
      image = settings.image;
      if (image) {
        icon = 'none';
        if (typeof image !== 'string') {
          image = window.getSelection ? image[0] : image[1];
        }
        image = ' style="background-image: url(\'' + image + '\')"';
      } else {
        image = '';
      }
      icon = settings.icon ? prefix + 'ico ' + prefix + 'i-' + icon : '';
      if (text) {
        self.classes.add('btn-has-text');
        textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>';
      }
      ariaPressed = typeof settings.active === 'boolean' ? ' aria-pressed="' + settings.active + '"' : '';
      return '<div id="' + id + '" class="' + self.classes + '" role="button"' + ariaPressed + ' tabindex="-1">' + '<button type="button" hidefocus="1" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + '</button>' + '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' + (self._menuBtnText ? (icon ? '\xA0' : '') + self._menuBtnText : '') + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>';
    },
    postRender: function () {
      var self = this, onClickHandler = self.settings.onclick;
      self.on('click', function (e) {
        var node = e.target;
        if (e.control === this) {
          while (node) {
            if (e.aria && e.aria.key !== 'down' || node.nodeName === 'BUTTON' && node.className.indexOf('open') === -1) {
              e.stopImmediatePropagation();
              if (onClickHandler) {
                onClickHandler.call(this, e);
              }
              return;
            }
            node = node.parentNode;
          }
        }
      });
      delete self.settings.onclick;
      return self._super();
    }
  });

  var StackLayout = FlowLayout.extend({
    Defaults: {
      containerClass: 'stack-layout',
      controlClass: 'stack-layout-item',
      endClass: 'break'
    },
    isNative: function () {
      return true;
    }
  });

  var TabPanel = Panel.extend({
    Defaults: {
      layout: 'absolute',
      defaults: { type: 'panel' }
    },
    activateTab: function (idx) {
      var activeTabElm;
      if (this.activeTabId) {
        activeTabElm = this.getEl(this.activeTabId);
        global$9(activeTabElm).removeClass(this.classPrefix + 'active');
        activeTabElm.setAttribute('aria-selected', 'false');
      }
      this.activeTabId = 't' + idx;
      activeTabElm = this.getEl('t' + idx);
      activeTabElm.setAttribute('aria-selected', 'true');
      global$9(activeTabElm).addClass(this.classPrefix + 'active');
      this.items()[idx].show().fire('showtab');
      this.reflow();
      this.items().each(function (item, i) {
        if (idx !== i) {
          item.hide();
        }
      });
    },
    renderHtml: function () {
      var self = this;
      var layout = self._layout;
      var tabsHtml = '';
      var prefix = self.classPrefix;
      self.preRender();
      layout.preRender(self);
      self.items().each(function (ctrl, i) {
        var id = self._id + '-t' + i;
        ctrl.aria('role', 'tabpanel');
        ctrl.aria('labelledby', id);
        tabsHtml += '<div id="' + id + '" class="' + prefix + 'tab" ' + 'unselectable="on" role="tab" aria-controls="' + ctrl._id + '" aria-selected="false" tabIndex="-1">' + self.encode(ctrl.settings.title) + '</div>';
      });
      return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + '<div id="' + self._id + '-head" class="' + prefix + 'tabs" role="tablist">' + tabsHtml + '</div>' + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + layout.renderHtml(self) + '</div>' + '</div>';
    },
    postRender: function () {
      var self = this;
      self._super();
      self.settings.activeTab = self.settings.activeTab || 0;
      self.activateTab(self.settings.activeTab);
      this.on('click', function (e) {
        var targetParent = e.target.parentNode;
        if (targetParent && targetParent.id === self._id + '-head') {
          var i = targetParent.childNodes.length;
          while (i--) {
            if (targetParent.childNodes[i] === e.target) {
              self.activateTab(i);
            }
          }
        }
      });
    },
    initLayoutRect: function () {
      var self = this;
      var rect, minW, minH;
      minW = funcs.getSize(self.getEl('head')).width;
      minW = minW < 0 ? 0 : minW;
      minH = 0;
      self.items().each(function (item) {
        minW = Math.max(minW, item.layoutRect().minW);
        minH = Math.max(minH, item.layoutRect().minH);
      });
      self.items().each(function (ctrl) {
        ctrl.settings.x = 0;
        ctrl.settings.y = 0;
        ctrl.settings.w = minW;
        ctrl.settings.h = minH;
        ctrl.layoutRect({
          x: 0,
          y: 0,
          w: minW,
          h: minH
        });
      });
      var headH = funcs.getSize(self.getEl('head')).height;
      self.settings.minWidth = minW;
      self.settings.minHeight = minH + headH;
      rect = self._super();
      rect.deltaH += headH;
      rect.innerH = rect.h - rect.deltaH;
      return rect;
    }
  });

  var TextBox = Widget.extend({
    init: function (settings) {
      var self = this;
      self._super(settings);
      self.classes.add('textbox');
      if (settings.multiline) {
        self.classes.add('multiline');
      } else {
        self.on('keydown', function (e) {
          var rootControl;
          if (e.keyCode === 13) {
            e.preventDefault();
            self.parents().reverse().each(function (ctrl) {
              if (ctrl.toJSON) {
                rootControl = ctrl;
                return false;
              }
            });
            self.fire('submit', { data: rootControl.toJSON() });
          }
        });
        self.on('keyup', function (e) {
          self.state.set('value', e.target.value);
        });
      }
    },
    repaint: function () {
      var self = this;
      var style, rect, borderBox, borderW, borderH = 0, lastRepaintRect;
      style = self.getEl().style;
      rect = self._layoutRect;
      lastRepaintRect = self._lastRepaintRect || {};
      var doc = document;
      if (!self.settings.multiline && doc.all && (!doc.documentMode || doc.documentMode <= 8)) {
        style.lineHeight = rect.h - borderH + 'px';
      }
      borderBox = self.borderBox;
      borderW = borderBox.left + borderBox.right + 8;
      borderH = borderBox.top + borderBox.bottom + (self.settings.multiline ? 8 : 0);
      if (rect.x !== lastRepaintRect.x) {
        style.left = rect.x + 'px';
        lastRepaintRect.x = rect.x;
      }
      if (rect.y !== lastRepaintRect.y) {
        style.top = rect.y + 'px';
        lastRepaintRect.y = rect.y;
      }
      if (rect.w !== lastRepaintRect.w) {
        style.width = rect.w - borderW + 'px';
        lastRepaintRect.w = rect.w;
      }
      if (rect.h !== lastRepaintRect.h) {
        style.height = rect.h - borderH + 'px';
        lastRepaintRect.h = rect.h;
      }
      self._lastRepaintRect = lastRepaintRect;
      self.fire('repaint', {}, false);
      return self;
    },
    renderHtml: function () {
      var self = this;
      var settings = self.settings;
      var attrs, elm;
      attrs = {
        id: self._id,
        hidefocus: '1'
      };
      global$2.each([
        'rows',
        'spellcheck',
        'maxLength',
        'size',
        'readonly',
        'min',
        'max',
        'step',
        'list',
        'pattern',
        'placeholder',
        'required',
        'multiple'
      ], function (name) {
        attrs[name] = settings[name];
      });
      if (self.disabled()) {
        attrs.disabled = 'disabled';
      }
      if (settings.subtype) {
        attrs.type = settings.subtype;
      }
      elm = funcs.create(settings.multiline ? 'textarea' : 'input', attrs);
      elm.value = self.state.get('value');
      elm.className = self.classes.toString();
      return elm.outerHTML;
    },
    value: function (value) {
      if (arguments.length) {
        this.state.set('value', value);
        return this;
      }
      if (this.state.get('rendered')) {
        this.state.set('value', this.getEl().value);
      }
      return this.state.get('value');
    },
    postRender: function () {
      var self = this;
      self.getEl().value = self.state.get('value');
      self._super();
      self.$el.on('change', function (e) {
        self.state.set('value', e.target.value);
        self.fire('change', e);
      });
    },
    bindStates: function () {
      var self = this;
      self.state.on('change:value', function (e) {
        if (self.getEl().value !== e.value) {
          self.getEl().value = e.value;
        }
      });
      self.state.on('change:disabled', function (e) {
        self.getEl().disabled = e.value;
      });
      return self._super();
    },
    remove: function () {
      this.$el.off();
      this._super();
    }
  });

  var getApi = function () {
    return {
      Selector: Selector,
      Collection: Collection$2,
      ReflowQueue: $_ef12j5u4jh8lz3nl,
      Control: Control$1,
      Factory: global$4,
      KeyboardNavigation: KeyboardNavigation,
      Container: Container,
      DragHelper: DragHelper,
      Scrollable: $_4acv48u6jh8lz3ns,
      Panel: Panel,
      Movable: $_d97gfctrjh8lz3lm,
      Resizable: $_8a2gtru8jh8lz3ny,
      FloatPanel: FloatPanel,
      Window: Window,
      MessageBox: MessageBox,
      Tooltip: Tooltip,
      Widget: Widget,
      Progress: Progress,
      Notification: Notification,
      Layout: Layout,
      AbsoluteLayout: AbsoluteLayout,
      Button: Button,
      ButtonGroup: ButtonGroup,
      Checkbox: Checkbox,
      ComboBox: ComboBox,
      ColorBox: ColorBox,
      PanelButton: PanelButton,
      ColorButton: ColorButton,
      ColorPicker: ColorPicker,
      Path: Path,
      ElementPath: ElementPath,
      FormItem: FormItem,
      Form: Form,
      FieldSet: FieldSet,
      FilePicker: FilePicker,
      FitLayout: FitLayout,
      FlexLayout: FlexLayout,
      FlowLayout: FlowLayout,
      FormatControls: $_4qdht3w4jh8lz3uo,
      GridLayout: GridLayout,
      Iframe: Iframe$1,
      InfoBox: InfoBox,
      Label: Label,
      Toolbar: Toolbar$1,
      MenuBar: MenuBar,
      MenuButton: MenuButton,
      MenuItem: MenuItem,
      Throbber: Throbber,
      Menu: Menu,
      ListBox: ListBox,
      Radio: Radio,
      ResizeHandle: ResizeHandle,
      SelectBox: SelectBox,
      Slider: Slider,
      Spacer: Spacer,
      SplitButton: SplitButton,
      StackLayout: StackLayout,
      TabPanel: TabPanel,
      TextBox: TextBox,
      DropZone: DropZone,
      BrowseButton: BrowseButton
    };
  };
  var appendTo = function (target) {
    if (target.ui) {
      global$2.each(getApi(), function (ref, key) {
        target.ui[key] = ref;
      });
    } else {
      target.ui = getApi();
    }
  };
  var registerToFactory = function () {
    global$2.each(getApi(), function (ref, key) {
      global$4.add(key, ref);
    });
  };
  var Api = {
    appendTo: appendTo,
    registerToFactory: registerToFactory
  };

  Api.registerToFactory();
  Api.appendTo(window.tinymce ? window.tinymce : {});
  global.add('modern', function (editor) {
    $_4qdht3w4jh8lz3uo.setup(editor);
    return $_1os0v5syjh8lz3j9.get(editor);
  });
  function Theme () {
  }

  return Theme;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-advlist", ["tinymce"], function() {
  return (function() {
(function () {
var advlist = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var applyListFormat = function (editor, listName, styleValue) {
    var cmd = listName === 'UL' ? 'InsertUnorderedList' : 'InsertOrderedList';
    editor.execCommand(cmd, false, styleValue === false ? null : { 'list-style-type': styleValue });
  };
  var $_2r1x1182jh8lyzqs = { applyListFormat: applyListFormat };

  var register = function (editor) {
    editor.addCommand('ApplyUnorderedListStyle', function (ui, value) {
      $_2r1x1182jh8lyzqs.applyListFormat(editor, 'UL', value['list-style-type']);
    });
    editor.addCommand('ApplyOrderedListStyle', function (ui, value) {
      $_2r1x1182jh8lyzqs.applyListFormat(editor, 'OL', value['list-style-type']);
    });
  };
  var $_hdktl81jh8lyzqr = { register: register };

  var getNumberStyles = function (editor) {
    var styles = editor.getParam('advlist_number_styles', 'default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman');
    return styles ? styles.split(/[ ,]/) : [];
  };
  var getBulletStyles = function (editor) {
    var styles = editor.getParam('advlist_bullet_styles', 'default,circle,disc,square');
    return styles ? styles.split(/[ ,]/) : [];
  };
  var $_3fjj2e84jh8lyzqy = {
    getNumberStyles: getNumberStyles,
    getBulletStyles: getBulletStyles
  };

  var isChildOfBody = function (editor, elm) {
    return editor.$.contains(editor.getBody(), elm);
  };
  var isTableCellNode = function (node) {
    return node && /^(TH|TD)$/.test(node.nodeName);
  };
  var isListNode = function (editor) {
    return function (node) {
      return node && /^(OL|UL|DL)$/.test(node.nodeName) && isChildOfBody(editor, node);
    };
  };
  var getSelectedStyleType = function (editor) {
    var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
    return editor.dom.getStyle(listElm, 'listStyleType') || '';
  };
  var $_9sbytx85jh8lyzqz = {
    isTableCellNode: isTableCellNode,
    isListNode: isListNode,
    getSelectedStyleType: getSelectedStyleType
  };

  var styleValueToText = function (styleValue) {
    return styleValue.replace(/\-/g, ' ').replace(/\b\w/g, function (chr) {
      return chr.toUpperCase();
    });
  };
  var toMenuItems = function (styles) {
    return global$1.map(styles, function (styleValue) {
      var text = styleValueToText(styleValue);
      var data = styleValue === 'default' ? '' : styleValue;
      return {
        text: text,
        data: data
      };
    });
  };
  var $_7vq0jr86jh8lyzr1 = { toMenuItems: toMenuItems };

  var findIndex = function (list, predicate) {
    for (var index = 0; index < list.length; index++) {
      var element = list[index];
      if (predicate(element)) {
        return index;
      }
    }
    return -1;
  };
  var listState = function (editor, listName) {
    return function (e) {
      var ctrl = e.control;
      editor.on('NodeChange', function (e) {
        var tableCellIndex = findIndex(e.parents, $_9sbytx85jh8lyzqz.isTableCellNode);
        var parents = tableCellIndex !== -1 ? e.parents.slice(0, tableCellIndex) : e.parents;
        var lists = global$1.grep(parents, $_9sbytx85jh8lyzqz.isListNode(editor));
        ctrl.active(lists.length > 0 && lists[0].nodeName === listName);
      });
    };
  };
  var updateSelection = function (editor) {
    return function (e) {
      var listStyleType = $_9sbytx85jh8lyzqz.getSelectedStyleType(editor);
      e.control.items().each(function (ctrl) {
        ctrl.active(ctrl.settings.data === listStyleType);
      });
    };
  };
  var addSplitButton = function (editor, id, tooltip, cmd, nodeName, styles) {
    editor.addButton(id, {
      active: false,
      type: 'splitbutton',
      tooltip: tooltip,
      menu: $_7vq0jr86jh8lyzr1.toMenuItems(styles),
      onPostRender: listState(editor, nodeName),
      onshow: updateSelection(editor),
      onselect: function (e) {
        $_2r1x1182jh8lyzqs.applyListFormat(editor, nodeName, e.control.settings.data);
      },
      onclick: function () {
        editor.execCommand(cmd);
      }
    });
  };
  var addButton = function (editor, id, tooltip, cmd, nodeName, styles) {
    editor.addButton(id, {
      active: false,
      type: 'button',
      tooltip: tooltip,
      onPostRender: listState(editor, nodeName),
      onclick: function () {
        editor.execCommand(cmd);
      }
    });
  };
  var addControl = function (editor, id, tooltip, cmd, nodeName, styles) {
    if (styles.length > 0) {
      addSplitButton(editor, id, tooltip, cmd, nodeName, styles);
    } else {
      addButton(editor, id, tooltip, cmd, nodeName, styles);
    }
  };
  var register$1 = function (editor) {
    addControl(editor, 'numlist', 'Numbered list', 'InsertOrderedList', 'OL', $_3fjj2e84jh8lyzqy.getNumberStyles(editor));
    addControl(editor, 'bullist', 'Bullet list', 'InsertUnorderedList', 'UL', $_3fjj2e84jh8lyzqy.getBulletStyles(editor));
  };
  var $_6bc80w83jh8lyzqu = { register: register$1 };

  global.add('advlist', function (editor) {
    var hasPlugin = function (editor, plugin) {
      var plugins = editor.settings.plugins ? editor.settings.plugins : '';
      return global$1.inArray(plugins.split(/[ ,]/), plugin) !== -1;
    };
    if (hasPlugin(editor, 'lists')) {
      $_6bc80w83jh8lyzqu.register(editor);
      $_hdktl81jh8lyzqr.register(editor);
    }
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-anchor", ["tinymce"], function() {
  return (function() {
(function () {
var anchor = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var isValidId = function (id) {
    return /^[A-Za-z][A-Za-z0-9\-:._]*$/.test(id);
  };
  var getId = function (editor) {
    var selectedNode = editor.selection.getNode();
    var isAnchor = selectedNode.tagName === 'A' && editor.dom.getAttrib(selectedNode, 'href') === '';
    return isAnchor ? selectedNode.id || selectedNode.name : '';
  };
  var insert = function (editor, id) {
    var selectedNode = editor.selection.getNode();
    var isAnchor = selectedNode.tagName === 'A' && editor.dom.getAttrib(selectedNode, 'href') === '';
    if (isAnchor) {
      selectedNode.removeAttribute('name');
      selectedNode.id = id;
      editor.undoManager.add();
    } else {
      editor.focus();
      editor.selection.collapse(true);
      editor.execCommand('mceInsertContent', false, editor.dom.createHTML('a', { id: id }));
    }
  };
  var $_3nbb0e8bjh8lyzrn = {
    isValidId: isValidId,
    getId: getId,
    insert: insert
  };

  var insertAnchor = function (editor, newId) {
    if (!$_3nbb0e8bjh8lyzrn.isValidId(newId)) {
      editor.windowManager.alert('Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.');
      return true;
    } else {
      $_3nbb0e8bjh8lyzrn.insert(editor, newId);
      return false;
    }
  };
  var open = function (editor) {
    var currentId = $_3nbb0e8bjh8lyzrn.getId(editor);
    editor.windowManager.open({
      title: 'Anchor',
      body: {
        type: 'textbox',
        name: 'id',
        size: 40,
        label: 'Id',
        value: currentId
      },
      onsubmit: function (e) {
        var newId = e.data.id;
        if (insertAnchor(editor, newId)) {
          e.preventDefault();
        }
      }
    });
  };
  var $_8ripo48ajh8lyzrl = { open: open };

  var register = function (editor) {
    editor.addCommand('mceAnchor', function () {
      $_8ripo48ajh8lyzrl.open(editor);
    });
  };
  var $_8icszx89jh8lyzrk = { register: register };

  var isAnchorNode = function (node) {
    return !node.attr('href') && (node.attr('id') || node.attr('name')) && !node.firstChild;
  };
  var setContentEditable = function (state) {
    return function (nodes) {
      for (var i = 0; i < nodes.length; i++) {
        if (isAnchorNode(nodes[i])) {
          nodes[i].attr('contenteditable', state);
        }
      }
    };
  };
  var setup = function (editor) {
    editor.on('PreInit', function () {
      editor.parser.addNodeFilter('a', setContentEditable('false'));
      editor.serializer.addNodeFilter('a', setContentEditable(null));
    });
  };
  var $_a3426h8cjh8lyzro = { setup: setup };

  var register$1 = function (editor) {
    editor.addButton('anchor', {
      icon: 'anchor',
      tooltip: 'Anchor',
      cmd: 'mceAnchor',
      stateSelector: 'a:not([href])'
    });
    editor.addMenuItem('anchor', {
      icon: 'anchor',
      text: 'Anchor',
      context: 'insert',
      cmd: 'mceAnchor'
    });
  };
  var $_afgepy8djh8lyzrq = { register: register$1 };

  global.add('anchor', function (editor) {
    $_a3426h8cjh8lyzro.setup(editor);
    $_8icszx89jh8lyzrk.register(editor);
    $_afgepy8djh8lyzrq.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-autolink", ["tinymce"], function() {
  return (function() {
(function () {
var autolink = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.Env');

  var getAutoLinkPattern = function (editor) {
    return editor.getParam('autolink_pattern', /^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|(?:mailto:)?[A-Z0-9._%+\-]+@)(.+)$/i);
  };
  var getDefaultLinkTarget = function (editor) {
    return editor.getParam('default_link_target', '');
  };
  var $_2pqfkt8ijh8lyzs9 = {
    getAutoLinkPattern: getAutoLinkPattern,
    getDefaultLinkTarget: getDefaultLinkTarget
  };

  var rangeEqualsDelimiterOrSpace = function (rangeString, delimiter) {
    return rangeString === delimiter || rangeString === ' ' || rangeString.charCodeAt(0) === 160;
  };
  var handleEclipse = function (editor) {
    parseCurrentLine(editor, -1, '(');
  };
  var handleSpacebar = function (editor) {
    parseCurrentLine(editor, 0, '');
  };
  var handleEnter = function (editor) {
    parseCurrentLine(editor, -1, '');
  };
  var scopeIndex = function (container, index) {
    if (index < 0) {
      index = 0;
    }
    if (container.nodeType === 3) {
      var len = container.data.length;
      if (index > len) {
        index = len;
      }
    }
    return index;
  };
  var setStart = function (rng, container, offset) {
    if (container.nodeType !== 1 || container.hasChildNodes()) {
      rng.setStart(container, scopeIndex(container, offset));
    } else {
      rng.setStartBefore(container);
    }
  };
  var setEnd = function (rng, container, offset) {
    if (container.nodeType !== 1 || container.hasChildNodes()) {
      rng.setEnd(container, scopeIndex(container, offset));
    } else {
      rng.setEndAfter(container);
    }
  };
  var parseCurrentLine = function (editor, endOffset, delimiter) {
    var rng, end, start, endContainer, bookmark, text, matches, prev, len, rngText;
    var autoLinkPattern = $_2pqfkt8ijh8lyzs9.getAutoLinkPattern(editor);
    var defaultLinkTarget = $_2pqfkt8ijh8lyzs9.getDefaultLinkTarget(editor);
    if (editor.selection.getNode().tagName === 'A') {
      return;
    }
    rng = editor.selection.getRng(true).cloneRange();
    if (rng.startOffset < 5) {
      prev = rng.endContainer.previousSibling;
      if (!prev) {
        if (!rng.endContainer.firstChild || !rng.endContainer.firstChild.nextSibling) {
          return;
        }
        prev = rng.endContainer.firstChild.nextSibling;
      }
      len = prev.length;
      setStart(rng, prev, len);
      setEnd(rng, prev, len);
      if (rng.endOffset < 5) {
        return;
      }
      end = rng.endOffset;
      endContainer = prev;
    } else {
      endContainer = rng.endContainer;
      if (endContainer.nodeType !== 3 && endContainer.firstChild) {
        while (endContainer.nodeType !== 3 && endContainer.firstChild) {
          endContainer = endContainer.firstChild;
        }
        if (endContainer.nodeType === 3) {
          setStart(rng, endContainer, 0);
          setEnd(rng, endContainer, endContainer.nodeValue.length);
        }
      }
      if (rng.endOffset === 1) {
        end = 2;
      } else {
        end = rng.endOffset - 1 - endOffset;
      }
    }
    start = end;
    do {
      setStart(rng, endContainer, end >= 2 ? end - 2 : 0);
      setEnd(rng, endContainer, end >= 1 ? end - 1 : 0);
      end -= 1;
      rngText = rng.toString();
    } while (rngText !== ' ' && rngText !== '' && rngText.charCodeAt(0) !== 160 && end - 2 >= 0 && rngText !== delimiter);
    if (rangeEqualsDelimiterOrSpace(rng.toString(), delimiter)) {
      setStart(rng, endContainer, end);
      setEnd(rng, endContainer, start);
      end += 1;
    } else if (rng.startOffset === 0) {
      setStart(rng, endContainer, 0);
      setEnd(rng, endContainer, start);
    } else {
      setStart(rng, endContainer, end);
      setEnd(rng, endContainer, start);
    }
    text = rng.toString();
    if (text.charAt(text.length - 1) === '.') {
      setEnd(rng, endContainer, start - 1);
    }
    text = rng.toString().trim();
    matches = text.match(autoLinkPattern);
    if (matches) {
      if (matches[1] === 'www.') {
        matches[1] = 'http://www.';
      } else if (/@$/.test(matches[1]) && !/^mailto:/.test(matches[1])) {
        matches[1] = 'mailto:' + matches[1];
      }
      bookmark = editor.selection.getBookmark();
      editor.selection.setRng(rng);
      editor.execCommand('createlink', false, matches[1] + matches[2]);
      if (defaultLinkTarget) {
        editor.dom.setAttrib(editor.selection.getNode(), 'target', defaultLinkTarget);
      }
      editor.selection.moveToBookmark(bookmark);
      editor.nodeChanged();
    }
  };
  var setup = function (editor) {
    var autoUrlDetectState;
    editor.on('keydown', function (e) {
      if (e.keyCode === 13) {
        return handleEnter(editor);
      }
    });
    if (global$1.ie) {
      editor.on('focus', function () {
        if (!autoUrlDetectState) {
          autoUrlDetectState = true;
          try {
            editor.execCommand('AutoUrlDetect', false, true);
          } catch (ex) {
          }
        }
      });
      return;
    }
    editor.on('keypress', function (e) {
      if (e.keyCode === 41) {
        return handleEclipse(editor);
      }
    });
    editor.on('keyup', function (e) {
      if (e.keyCode === 32) {
        return handleSpacebar(editor);
      }
    });
  };
  var $_3xb5x88gjh8lyzs3 = { setup: setup };

  global.add('autolink', function (editor) {
    $_3xb5x88gjh8lyzs3.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-autoresize", ["tinymce"], function() {
  return (function() {
(function () {
var autoresize = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.Env');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var getAutoResizeMinHeight = function (editor) {
    return parseInt(editor.getParam('autoresize_min_height', editor.getElement().offsetHeight), 10);
  };
  var getAutoResizeMaxHeight = function (editor) {
    return parseInt(editor.getParam('autoresize_max_height', 0), 10);
  };
  var getAutoResizeOverflowPadding = function (editor) {
    return editor.getParam('autoresize_overflow_padding', 1);
  };
  var getAutoResizeBottomMargin = function (editor) {
    return editor.getParam('autoresize_bottom_margin', 50);
  };
  var shouldAutoResizeOnInit = function (editor) {
    return editor.getParam('autoresize_on_init', true);
  };
  var $_gg12688qjh8lyzsz = {
    getAutoResizeMinHeight: getAutoResizeMinHeight,
    getAutoResizeMaxHeight: getAutoResizeMaxHeight,
    getAutoResizeOverflowPadding: getAutoResizeOverflowPadding,
    getAutoResizeBottomMargin: getAutoResizeBottomMargin,
    shouldAutoResizeOnInit: shouldAutoResizeOnInit
  };

  var isFullscreen = function (editor) {
    return editor.plugins.fullscreen && editor.plugins.fullscreen.isFullscreen();
  };
  var wait = function (editor, oldSize, times, interval, callback) {
    global$2.setEditorTimeout(editor, function () {
      resize(editor, oldSize);
      if (times--) {
        wait(editor, oldSize, times, interval, callback);
      } else if (callback) {
        callback();
      }
    }, interval);
  };
  var toggleScrolling = function (editor, state) {
    var body = editor.getBody();
    if (body) {
      body.style.overflowY = state ? '' : 'hidden';
      if (!state) {
        body.scrollTop = 0;
      }
    }
  };
  var resize = function (editor, oldSize) {
    var deltaSize, doc, body, resizeHeight, myHeight;
    var marginTop, marginBottom, paddingTop, paddingBottom, borderTop, borderBottom;
    var dom = editor.dom;
    doc = editor.getDoc();
    if (!doc) {
      return;
    }
    if (isFullscreen(editor)) {
      toggleScrolling(editor, true);
      return;
    }
    body = doc.body;
    resizeHeight = $_gg12688qjh8lyzsz.getAutoResizeMinHeight(editor);
    marginTop = dom.getStyle(body, 'margin-top', true);
    marginBottom = dom.getStyle(body, 'margin-bottom', true);
    paddingTop = dom.getStyle(body, 'padding-top', true);
    paddingBottom = dom.getStyle(body, 'padding-bottom', true);
    borderTop = dom.getStyle(body, 'border-top-width', true);
    borderBottom = dom.getStyle(body, 'border-bottom-width', true);
    myHeight = body.offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10) + parseInt(paddingTop, 10) + parseInt(paddingBottom, 10) + parseInt(borderTop, 10) + parseInt(borderBottom, 10);
    if (isNaN(myHeight) || myHeight <= 0) {
      myHeight = global$1.ie ? body.scrollHeight : global$1.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight;
    }
    if (myHeight > $_gg12688qjh8lyzsz.getAutoResizeMinHeight(editor)) {
      resizeHeight = myHeight;
    }
    var maxHeight = $_gg12688qjh8lyzsz.getAutoResizeMaxHeight(editor);
    if (maxHeight && myHeight > maxHeight) {
      resizeHeight = maxHeight;
      toggleScrolling(editor, true);
    } else {
      toggleScrolling(editor, false);
    }
    if (resizeHeight !== oldSize.get()) {
      deltaSize = resizeHeight - oldSize.get();
      dom.setStyle(editor.iframeElement, 'height', resizeHeight + 'px');
      oldSize.set(resizeHeight);
      if (global$1.webkit && deltaSize < 0) {
        resize(editor, oldSize);
      }
    }
  };
  var setup = function (editor, oldSize) {
    editor.on('init', function () {
      var overflowPadding, bottomMargin;
      var dom = editor.dom;
      overflowPadding = $_gg12688qjh8lyzsz.getAutoResizeOverflowPadding(editor);
      bottomMargin = $_gg12688qjh8lyzsz.getAutoResizeBottomMargin(editor);
      if (overflowPadding !== false) {
        dom.setStyles(editor.getBody(), {
          paddingLeft: overflowPadding,
          paddingRight: overflowPadding
        });
      }
      if (bottomMargin !== false) {
        dom.setStyles(editor.getBody(), { paddingBottom: bottomMargin });
      }
    });
    editor.on('nodechange setcontent keyup FullscreenStateChanged', function (e) {
      resize(editor, oldSize);
    });
    if ($_gg12688qjh8lyzsz.shouldAutoResizeOnInit(editor)) {
      editor.on('init', function () {
        wait(editor, oldSize, 20, 100, function () {
          wait(editor, oldSize, 5, 1000);
        });
      });
    }
  };
  var $_6ewswv8njh8lyzsu = {
    setup: setup,
    resize: resize
  };

  var register = function (editor, oldSize) {
    editor.addCommand('mceAutoResize', function () {
      $_6ewswv8njh8lyzsu.resize(editor, oldSize);
    });
  };
  var $_a778x48mjh8lyzss = { register: register };

  global.add('autoresize', function (editor) {
    if (!editor.inline) {
      var oldSize = Cell(0);
      $_a778x48mjh8lyzss.register(editor, oldSize);
      $_6ewswv8njh8lyzsu.setup(editor, oldSize);
    }
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-autosave", ["tinymce"], function() {
  return (function() {
(function () {
var autosave = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var fireRestoreDraft = function (editor) {
    return editor.fire('RestoreDraft');
  };
  var fireStoreDraft = function (editor) {
    return editor.fire('StoreDraft');
  };
  var fireRemoveDraft = function (editor) {
    return editor.fire('RemoveDraft');
  };
  var $_4ncezg8yjh8lyzts = {
    fireRestoreDraft: fireRestoreDraft,
    fireStoreDraft: fireStoreDraft,
    fireRemoveDraft: fireRemoveDraft
  };

  var parse = function (time, defaultTime) {
    var multiples = {
      s: 1000,
      m: 60000
    };
    time = /^(\d+)([ms]?)$/.exec('' + (time || defaultTime));
    return (time[2] ? multiples[time[2]] : 1) * parseInt(time, 10);
  };
  var $_cmmlud90jh8lyztv = { parse: parse };

  var shouldAskBeforeUnload = function (editor) {
    return editor.getParam('autosave_ask_before_unload', true);
  };
  var getAutoSavePrefix = function (editor) {
    var prefix = editor.getParam('autosave_prefix', 'tinymce-autosave-{path}{query}{hash}-{id}-');
    prefix = prefix.replace(/\{path\}/g, document.location.pathname);
    prefix = prefix.replace(/\{query\}/g, document.location.search);
    prefix = prefix.replace(/\{hash\}/g, document.location.hash);
    prefix = prefix.replace(/\{id\}/g, editor.id);
    return prefix;
  };
  var shouldRestoreWhenEmpty = function (editor) {
    return editor.getParam('autosave_restore_when_empty', false);
  };
  var getAutoSaveInterval = function (editor) {
    return $_cmmlud90jh8lyztv.parse(editor.settings.autosave_interval, '30s');
  };
  var getAutoSaveRetention = function (editor) {
    return $_cmmlud90jh8lyztv.parse(editor.settings.autosave_retention, '20m');
  };
  var $_55sjs08zjh8lyztt = {
    shouldAskBeforeUnload: shouldAskBeforeUnload,
    getAutoSavePrefix: getAutoSavePrefix,
    shouldRestoreWhenEmpty: shouldRestoreWhenEmpty,
    getAutoSaveInterval: getAutoSaveInterval,
    getAutoSaveRetention: getAutoSaveRetention
  };

  var isEmpty = function (editor, html) {
    var forcedRootBlockName = editor.settings.forced_root_block;
    html = global$2.trim(typeof html === 'undefined' ? editor.getBody().innerHTML : html);
    return html === '' || new RegExp('^<' + forcedRootBlockName + '[^>]*>((\xA0|&nbsp;|[ \t]|<br[^>]*>)+?|)</' + forcedRootBlockName + '>|<br>$', 'i').test(html);
  };
  var hasDraft = function (editor) {
    var time = parseInt(global$1.getItem($_55sjs08zjh8lyztt.getAutoSavePrefix(editor) + 'time'), 10) || 0;
    if (new Date().getTime() - time > $_55sjs08zjh8lyztt.getAutoSaveRetention(editor)) {
      removeDraft(editor, false);
      return false;
    }
    return true;
  };
  var removeDraft = function (editor, fire) {
    var prefix = $_55sjs08zjh8lyztt.getAutoSavePrefix(editor);
    global$1.removeItem(prefix + 'draft');
    global$1.removeItem(prefix + 'time');
    if (fire !== false) {
      $_4ncezg8yjh8lyzts.fireRemoveDraft(editor);
    }
  };
  var storeDraft = function (editor) {
    var prefix = $_55sjs08zjh8lyztt.getAutoSavePrefix(editor);
    if (!isEmpty(editor) && editor.isDirty()) {
      global$1.setItem(prefix + 'draft', editor.getContent({
        format: 'raw',
        no_events: true
      }));
      global$1.setItem(prefix + 'time', new Date().getTime().toString());
      $_4ncezg8yjh8lyzts.fireStoreDraft(editor);
    }
  };
  var restoreDraft = function (editor) {
    var prefix = $_55sjs08zjh8lyztt.getAutoSavePrefix(editor);
    if (hasDraft(editor)) {
      editor.setContent(global$1.getItem(prefix + 'draft'), { format: 'raw' });
      $_4ncezg8yjh8lyzts.fireRestoreDraft(editor);
    }
  };
  var startStoreDraft = function (editor, started) {
    var interval = $_55sjs08zjh8lyztt.getAutoSaveInterval(editor);
    if (!started.get()) {
      setInterval(function () {
        if (!editor.removed) {
          storeDraft(editor);
        }
      }, interval);
      started.set(true);
    }
  };
  var restoreLastDraft = function (editor) {
    editor.undoManager.transact(function () {
      restoreDraft(editor);
      removeDraft(editor);
    });
    editor.focus();
  };
  var $_fa8c2v8vjh8lyzto = {
    isEmpty: isEmpty,
    hasDraft: hasDraft,
    removeDraft: removeDraft,
    storeDraft: storeDraft,
    restoreDraft: restoreDraft,
    startStoreDraft: startStoreDraft,
    restoreLastDraft: restoreLastDraft
  };

  var curry = function (f, editor) {
    return function () {
      var args = Array.prototype.slice.call(arguments);
      return f.apply(null, [editor].concat(args));
    };
  };
  var get = function (editor) {
    return {
      hasDraft: curry($_fa8c2v8vjh8lyzto.hasDraft, editor),
      storeDraft: curry($_fa8c2v8vjh8lyzto.storeDraft, editor),
      restoreDraft: curry($_fa8c2v8vjh8lyzto.restoreDraft, editor),
      removeDraft: curry($_fa8c2v8vjh8lyzto.removeDraft, editor),
      isEmpty: curry($_fa8c2v8vjh8lyzto.isEmpty, editor)
    };
  };
  var $_7d5i5z8ujh8lyztn = { get: get };

  var global$3 = tinymce.util.Tools.resolve('tinymce.EditorManager');

  global$3._beforeUnloadHandler = function () {
    var msg;
    global$2.each(global$3.get(), function (editor) {
      if (editor.plugins.autosave) {
        editor.plugins.autosave.storeDraft();
      }
      if (!msg && editor.isDirty() && $_55sjs08zjh8lyztt.shouldAskBeforeUnload(editor)) {
        msg = editor.translate('You have unsaved changes are you sure you want to navigate away?');
      }
    });
    return msg;
  };
  var setup = function (editor) {
    window.onbeforeunload = global$3._beforeUnloadHandler;
  };
  var $_cxjwbi91jh8lyztw = { setup: setup };

  var postRender = function (editor, started) {
    return function (e) {
      var ctrl = e.control;
      ctrl.disabled(!$_fa8c2v8vjh8lyzto.hasDraft(editor));
      editor.on('StoreDraft RestoreDraft RemoveDraft', function () {
        ctrl.disabled(!$_fa8c2v8vjh8lyzto.hasDraft(editor));
      });
      $_fa8c2v8vjh8lyzto.startStoreDraft(editor, started);
    };
  };
  var register = function (editor, started) {
    editor.addButton('restoredraft', {
      title: 'Restore last draft',
      onclick: function () {
        $_fa8c2v8vjh8lyzto.restoreLastDraft(editor);
      },
      onPostRender: postRender(editor, started)
    });
    editor.addMenuItem('restoredraft', {
      text: 'Restore last draft',
      onclick: function () {
        $_fa8c2v8vjh8lyzto.restoreLastDraft(editor);
      },
      onPostRender: postRender(editor, started),
      context: 'file'
    });
  };
  var $_dic4wy93jh8lyzty = { register: register };

  global.add('autosave', function (editor) {
    var started = Cell(false);
    $_cxjwbi91jh8lyztw.setup(editor);
    $_dic4wy93jh8lyzty.register(editor, started);
    return $_7d5i5z8ujh8lyztn.get(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-bbcode", ["tinymce"], function() {
  return (function() {
(function () {
var bbcode = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var html2bbcode = function (s) {
    s = global$1.trim(s);
    var rep = function (re, str) {
      s = s.replace(re, str);
    };
    rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi, '[url=$1]$2[/url]');
    rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi, '[code][color=$1]$2[/color][/code]');
    rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi, '[quote][color=$1]$2[/color][/quote]');
    rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, '[code][color=$1]$2[/color][/code]');
    rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, '[quote][color=$1]$2[/color][/quote]');
    rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi, '[color=$1]$2[/color]');
    rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, '[color=$1]$2[/color]');
    rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi, '[size=$1]$2[/size]');
    rep(/<font>(.*?)<\/font>/gi, '$1');
    rep(/<img.*?src=\"(.*?)\".*?\/>/gi, '[img]$1[/img]');
    rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi, '[code]$1[/code]');
    rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi, '[quote]$1[/quote]');
    rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi, '[code][b]$1[/b][/code]');
    rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi, '[quote][b]$1[/b][/quote]');
    rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi, '[code][i]$1[/i][/code]');
    rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi, '[quote][i]$1[/i][/quote]');
    rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi, '[code][u]$1[/u][/code]');
    rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi, '[quote][u]$1[/u][/quote]');
    rep(/<\/(strong|b)>/gi, '[/b]');
    rep(/<(strong|b)>/gi, '[b]');
    rep(/<\/(em|i)>/gi, '[/i]');
    rep(/<(em|i)>/gi, '[i]');
    rep(/<\/u>/gi, '[/u]');
    rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi, '[u]$1[/u]');
    rep(/<u>/gi, '[u]');
    rep(/<blockquote[^>]*>/gi, '[quote]');
    rep(/<\/blockquote>/gi, '[/quote]');
    rep(/<br \/>/gi, '\n');
    rep(/<br\/>/gi, '\n');
    rep(/<br>/gi, '\n');
    rep(/<p>/gi, '');
    rep(/<\/p>/gi, '\n');
    rep(/&nbsp;|\u00a0/gi, ' ');
    rep(/&quot;/gi, '"');
    rep(/&lt;/gi, '<');
    rep(/&gt;/gi, '>');
    rep(/&amp;/gi, '&');
    return s;
  };
  var bbcode2html = function (s) {
    s = global$1.trim(s);
    var rep = function (re, str) {
      s = s.replace(re, str);
    };
    rep(/\n/gi, '<br />');
    rep(/\[b\]/gi, '<strong>');
    rep(/\[\/b\]/gi, '</strong>');
    rep(/\[i\]/gi, '<em>');
    rep(/\[\/i\]/gi, '</em>');
    rep(/\[u\]/gi, '<u>');
    rep(/\[\/u\]/gi, '</u>');
    rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi, '<a href="$1">$2</a>');
    rep(/\[url\](.*?)\[\/url\]/gi, '<a href="$1">$1</a>');
    rep(/\[img\](.*?)\[\/img\]/gi, '<img src="$1" />');
    rep(/\[color=(.*?)\](.*?)\[\/color\]/gi, '<font color="$1">$2</font>');
    rep(/\[code\](.*?)\[\/code\]/gi, '<span class="codeStyle">$1</span>&nbsp;');
    rep(/\[quote.*?\](.*?)\[\/quote\]/gi, '<span class="quoteStyle">$1</span>&nbsp;');
    return s;
  };
  var $_bryy4596jh8lyzuk = {
    html2bbcode: html2bbcode,
    bbcode2html: bbcode2html
  };

  global.add('bbcode', function () {
    return {
      init: function (editor) {
        editor.on('beforeSetContent', function (e) {
          e.content = $_bryy4596jh8lyzuk.bbcode2html(e.content);
        });
        editor.on('postProcess', function (e) {
          if (e.set) {
            e.content = $_bryy4596jh8lyzuk.bbcode2html(e.content);
          }
          if (e.get) {
            e.content = $_bryy4596jh8lyzuk.html2bbcode(e.content);
          }
        });
      }
    };
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-charmap", ["tinymce"], function() {
  return (function() {
(function () {
var charmap = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var fireInsertCustomChar = function (editor, chr) {
    return editor.fire('insertCustomChar', { chr: chr });
  };
  var $_ac4my89cjh8lyzv0 = { fireInsertCustomChar: fireInsertCustomChar };

  var insertChar = function (editor, chr) {
    var evtChr = $_ac4my89cjh8lyzv0.fireInsertCustomChar(editor, chr).chr;
    editor.execCommand('mceInsertContent', false, evtChr);
  };
  var $_dd5ogr9bjh8lyzv0 = { insertChar: insertChar };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var getCharMap = function (editor) {
    return editor.settings.charmap;
  };
  var getCharMapAppend = function (editor) {
    return editor.settings.charmap_append;
  };
  var $_a2f4bk9fjh8lyzvf = {
    getCharMap: getCharMap,
    getCharMapAppend: getCharMapAppend
  };

  var isArray = global$1.isArray;
  var getDefaultCharMap = function () {
    return [
      [
        '160',
        'no-break space'
      ],
      [
        '173',
        'soft hyphen'
      ],
      [
        '34',
        'quotation mark'
      ],
      [
        '162',
        'cent sign'
      ],
      [
        '8364',
        'euro sign'
      ],
      [
        '163',
        'pound sign'
      ],
      [
        '165',
        'yen sign'
      ],
      [
        '169',
        'copyright sign'
      ],
      [
        '174',
        'registered sign'
      ],
      [
        '8482',
        'trade mark sign'
      ],
      [
        '8240',
        'per mille sign'
      ],
      [
        '181',
        'micro sign'
      ],
      [
        '183',
        'middle dot'
      ],
      [
        '8226',
        'bullet'
      ],
      [
        '8230',
        'three dot leader'
      ],
      [
        '8242',
        'minutes / feet'
      ],
      [
        '8243',
        'seconds / inches'
      ],
      [
        '167',
        'section sign'
      ],
      [
        '182',
        'paragraph sign'
      ],
      [
        '223',
        'sharp s / ess-zed'
      ],
      [
        '8249',
        'single left-pointing angle quotation mark'
      ],
      [
        '8250',
        'single right-pointing angle quotation mark'
      ],
      [
        '171',
        'left pointing guillemet'
      ],
      [
        '187',
        'right pointing guillemet'
      ],
      [
        '8216',
        'left single quotation mark'
      ],
      [
        '8217',
        'right single quotation mark'
      ],
      [
        '8220',
        'left double quotation mark'
      ],
      [
        '8221',
        'right double quotation mark'
      ],
      [
        '8218',
        'single low-9 quotation mark'
      ],
      [
        '8222',
        'double low-9 quotation mark'
      ],
      [
        '60',
        'less-than sign'
      ],
      [
        '62',
        'greater-than sign'
      ],
      [
        '8804',
        'less-than or equal to'
      ],
      [
        '8805',
        'greater-than or equal to'
      ],
      [
        '8211',
        'en dash'
      ],
      [
        '8212',
        'em dash'
      ],
      [
        '175',
        'macron'
      ],
      [
        '8254',
        'overline'
      ],
      [
        '164',
        'currency sign'
      ],
      [
        '166',
        'broken bar'
      ],
      [
        '168',
        'diaeresis'
      ],
      [
        '161',
        'inverted exclamation mark'
      ],
      [
        '191',
        'turned question mark'
      ],
      [
        '710',
        'circumflex accent'
      ],
      [
        '732',
        'small tilde'
      ],
      [
        '176',
        'degree sign'
      ],
      [
        '8722',
        'minus sign'
      ],
      [
        '177',
        'plus-minus sign'
      ],
      [
        '247',
        'division sign'
      ],
      [
        '8260',
        'fraction slash'
      ],
      [
        '215',
        'multiplication sign'
      ],
      [
        '185',
        'superscript one'
      ],
      [
        '178',
        'superscript two'
      ],
      [
        '179',
        'superscript three'
      ],
      [
        '188',
        'fraction one quarter'
      ],
      [
        '189',
        'fraction one half'
      ],
      [
        '190',
        'fraction three quarters'
      ],
      [
        '402',
        'function / florin'
      ],
      [
        '8747',
        'integral'
      ],
      [
        '8721',
        'n-ary sumation'
      ],
      [
        '8734',
        'infinity'
      ],
      [
        '8730',
        'square root'
      ],
      [
        '8764',
        'similar to'
      ],
      [
        '8773',
        'approximately equal to'
      ],
      [
        '8776',
        'almost equal to'
      ],
      [
        '8800',
        'not equal to'
      ],
      [
        '8801',
        'identical to'
      ],
      [
        '8712',
        'element of'
      ],
      [
        '8713',
        'not an element of'
      ],
      [
        '8715',
        'contains as member'
      ],
      [
        '8719',
        'n-ary product'
      ],
      [
        '8743',
        'logical and'
      ],
      [
        '8744',
        'logical or'
      ],
      [
        '172',
        'not sign'
      ],
      [
        '8745',
        'intersection'
      ],
      [
        '8746',
        'union'
      ],
      [
        '8706',
        'partial differential'
      ],
      [
        '8704',
        'for all'
      ],
      [
        '8707',
        'there exists'
      ],
      [
        '8709',
        'diameter'
      ],
      [
        '8711',
        'backward difference'
      ],
      [
        '8727',
        'asterisk operator'
      ],
      [
        '8733',
        'proportional to'
      ],
      [
        '8736',
        'angle'
      ],
      [
        '180',
        'acute accent'
      ],
      [
        '184',
        'cedilla'
      ],
      [
        '170',
        'feminine ordinal indicator'
      ],
      [
        '186',
        'masculine ordinal indicator'
      ],
      [
        '8224',
        'dagger'
      ],
      [
        '8225',
        'double dagger'
      ],
      [
        '192',
        'A - grave'
      ],
      [
        '193',
        'A - acute'
      ],
      [
        '194',
        'A - circumflex'
      ],
      [
        '195',
        'A - tilde'
      ],
      [
        '196',
        'A - diaeresis'
      ],
      [
        '197',
        'A - ring above'
      ],
      [
        '256',
        'A - macron'
      ],
      [
        '198',
        'ligature AE'
      ],
      [
        '199',
        'C - cedilla'
      ],
      [
        '200',
        'E - grave'
      ],
      [
        '201',
        'E - acute'
      ],
      [
        '202',
        'E - circumflex'
      ],
      [
        '203',
        'E - diaeresis'
      ],
      [
        '274',
        'E - macron'
      ],
      [
        '204',
        'I - grave'
      ],
      [
        '205',
        'I - acute'
      ],
      [
        '206',
        'I - circumflex'
      ],
      [
        '207',
        'I - diaeresis'
      ],
      [
        '298',
        'I - macron'
      ],
      [
        '208',
        'ETH'
      ],
      [
        '209',
        'N - tilde'
      ],
      [
        '210',
        'O - grave'
      ],
      [
        '211',
        'O - acute'
      ],
      [
        '212',
        'O - circumflex'
      ],
      [
        '213',
        'O - tilde'
      ],
      [
        '214',
        'O - diaeresis'
      ],
      [
        '216',
        'O - slash'
      ],
      [
        '332',
        'O - macron'
      ],
      [
        '338',
        'ligature OE'
      ],
      [
        '352',
        'S - caron'
      ],
      [
        '217',
        'U - grave'
      ],
      [
        '218',
        'U - acute'
      ],
      [
        '219',
        'U - circumflex'
      ],
      [
        '220',
        'U - diaeresis'
      ],
      [
        '362',
        'U - macron'
      ],
      [
        '221',
        'Y - acute'
      ],
      [
        '376',
        'Y - diaeresis'
      ],
      [
        '562',
        'Y - macron'
      ],
      [
        '222',
        'THORN'
      ],
      [
        '224',
        'a - grave'
      ],
      [
        '225',
        'a - acute'
      ],
      [
        '226',
        'a - circumflex'
      ],
      [
        '227',
        'a - tilde'
      ],
      [
        '228',
        'a - diaeresis'
      ],
      [
        '229',
        'a - ring above'
      ],
      [
        '257',
        'a - macron'
      ],
      [
        '230',
        'ligature ae'
      ],
      [
        '231',
        'c - cedilla'
      ],
      [
        '232',
        'e - grave'
      ],
      [
        '233',
        'e - acute'
      ],
      [
        '234',
        'e - circumflex'
      ],
      [
        '235',
        'e - diaeresis'
      ],
      [
        '275',
        'e - macron'
      ],
      [
        '236',
        'i - grave'
      ],
      [
        '237',
        'i - acute'
      ],
      [
        '238',
        'i - circumflex'
      ],
      [
        '239',
        'i - diaeresis'
      ],
      [
        '299',
        'i - macron'
      ],
      [
        '240',
        'eth'
      ],
      [
        '241',
        'n - tilde'
      ],
      [
        '242',
        'o - grave'
      ],
      [
        '243',
        'o - acute'
      ],
      [
        '244',
        'o - circumflex'
      ],
      [
        '245',
        'o - tilde'
      ],
      [
        '246',
        'o - diaeresis'
      ],
      [
        '248',
        'o slash'
      ],
      [
        '333',
        'o macron'
      ],
      [
        '339',
        'ligature oe'
      ],
      [
        '353',
        's - caron'
      ],
      [
        '249',
        'u - grave'
      ],
      [
        '250',
        'u - acute'
      ],
      [
        '251',
        'u - circumflex'
      ],
      [
        '252',
        'u - diaeresis'
      ],
      [
        '363',
        'u - macron'
      ],
      [
        '253',
        'y - acute'
      ],
      [
        '254',
        'thorn'
      ],
      [
        '255',
        'y - diaeresis'
      ],
      [
        '563',
        'y - macron'
      ],
      [
        '913',
        'Alpha'
      ],
      [
        '914',
        'Beta'
      ],
      [
        '915',
        'Gamma'
      ],
      [
        '916',
        'Delta'
      ],
      [
        '917',
        'Epsilon'
      ],
      [
        '918',
        'Zeta'
      ],
      [
        '919',
        'Eta'
      ],
      [
        '920',
        'Theta'
      ],
      [
        '921',
        'Iota'
      ],
      [
        '922',
        'Kappa'
      ],
      [
        '923',
        'Lambda'
      ],
      [
        '924',
        'Mu'
      ],
      [
        '925',
        'Nu'
      ],
      [
        '926',
        'Xi'
      ],
      [
        '927',
        'Omicron'
      ],
      [
        '928',
        'Pi'
      ],
      [
        '929',
        'Rho'
      ],
      [
        '931',
        'Sigma'
      ],
      [
        '932',
        'Tau'
      ],
      [
        '933',
        'Upsilon'
      ],
      [
        '934',
        'Phi'
      ],
      [
        '935',
        'Chi'
      ],
      [
        '936',
        'Psi'
      ],
      [
        '937',
        'Omega'
      ],
      [
        '945',
        'alpha'
      ],
      [
        '946',
        'beta'
      ],
      [
        '947',
        'gamma'
      ],
      [
        '948',
        'delta'
      ],
      [
        '949',
        'epsilon'
      ],
      [
        '950',
        'zeta'
      ],
      [
        '951',
        'eta'
      ],
      [
        '952',
        'theta'
      ],
      [
        '953',
        'iota'
      ],
      [
        '954',
        'kappa'
      ],
      [
        '955',
        'lambda'
      ],
      [
        '956',
        'mu'
      ],
      [
        '957',
        'nu'
      ],
      [
        '958',
        'xi'
      ],
      [
        '959',
        'omicron'
      ],
      [
        '960',
        'pi'
      ],
      [
        '961',
        'rho'
      ],
      [
        '962',
        'final sigma'
      ],
      [
        '963',
        'sigma'
      ],
      [
        '964',
        'tau'
      ],
      [
        '965',
        'upsilon'
      ],
      [
        '966',
        'phi'
      ],
      [
        '967',
        'chi'
      ],
      [
        '968',
        'psi'
      ],
      [
        '969',
        'omega'
      ],
      [
        '8501',
        'alef symbol'
      ],
      [
        '982',
        'pi symbol'
      ],
      [
        '8476',
        'real part symbol'
      ],
      [
        '978',
        'upsilon - hook symbol'
      ],
      [
        '8472',
        'Weierstrass p'
      ],
      [
        '8465',
        'imaginary part'
      ],
      [
        '8592',
        'leftwards arrow'
      ],
      [
        '8593',
        'upwards arrow'
      ],
      [
        '8594',
        'rightwards arrow'
      ],
      [
        '8595',
        'downwards arrow'
      ],
      [
        '8596',
        'left right arrow'
      ],
      [
        '8629',
        'carriage return'
      ],
      [
        '8656',
        'leftwards double arrow'
      ],
      [
        '8657',
        'upwards double arrow'
      ],
      [
        '8658',
        'rightwards double arrow'
      ],
      [
        '8659',
        'downwards double arrow'
      ],
      [
        '8660',
        'left right double arrow'
      ],
      [
        '8756',
        'therefore'
      ],
      [
        '8834',
        'subset of'
      ],
      [
        '8835',
        'superset of'
      ],
      [
        '8836',
        'not a subset of'
      ],
      [
        '8838',
        'subset of or equal to'
      ],
      [
        '8839',
        'superset of or equal to'
      ],
      [
        '8853',
        'circled plus'
      ],
      [
        '8855',
        'circled times'
      ],
      [
        '8869',
        'perpendicular'
      ],
      [
        '8901',
        'dot operator'
      ],
      [
        '8968',
        'left ceiling'
      ],
      [
        '8969',
        'right ceiling'
      ],
      [
        '8970',
        'left floor'
      ],
      [
        '8971',
        'right floor'
      ],
      [
        '9001',
        'left-pointing angle bracket'
      ],
      [
        '9002',
        'right-pointing angle bracket'
      ],
      [
        '9674',
        'lozenge'
      ],
      [
        '9824',
        'black spade suit'
      ],
      [
        '9827',
        'black club suit'
      ],
      [
        '9829',
        'black heart suit'
      ],
      [
        '9830',
        'black diamond suit'
      ],
      [
        '8194',
        'en space'
      ],
      [
        '8195',
        'em space'
      ],
      [
        '8201',
        'thin space'
      ],
      [
        '8204',
        'zero width non-joiner'
      ],
      [
        '8205',
        'zero width joiner'
      ],
      [
        '8206',
        'left-to-right mark'
      ],
      [
        '8207',
        'right-to-left mark'
      ]
    ];
  };
  var charmapFilter = function (charmap) {
    return global$1.grep(charmap, function (item) {
      return isArray(item) && item.length === 2;
    });
  };
  var getCharsFromSetting = function (settingValue) {
    if (isArray(settingValue)) {
      return [].concat(charmapFilter(settingValue));
    }
    if (typeof settingValue === 'function') {
      return settingValue();
    }
    return [];
  };
  var extendCharMap = function (editor, charmap) {
    var userCharMap = $_a2f4bk9fjh8lyzvf.getCharMap(editor);
    if (userCharMap) {
      charmap = getCharsFromSetting(userCharMap);
    }
    var userCharMapAppend = $_a2f4bk9fjh8lyzvf.getCharMapAppend(editor);
    if (userCharMapAppend) {
      return [].concat(charmap).concat(getCharsFromSetting(userCharMapAppend));
    }
    return charmap;
  };
  var getCharMap$1 = function (editor) {
    return extendCharMap(editor, getDefaultCharMap());
  };
  var $_1gjkpm9djh8lyzv2 = { getCharMap: getCharMap$1 };

  var get = function (editor) {
    var getCharMap = function () {
      return $_1gjkpm9djh8lyzv2.getCharMap(editor);
    };
    var insertChar = function (chr) {
      $_dd5ogr9bjh8lyzv0.insertChar(editor, chr);
    };
    return {
      getCharMap: getCharMap,
      insertChar: insertChar
    };
  };
  var $_bms9m09ajh8lyzuy = { get: get };

  var getHtml = function (charmap) {
    var gridHtml, x, y;
    var width = Math.min(charmap.length, 25);
    var height = Math.ceil(charmap.length / width);
    gridHtml = '<table role="presentation" cellspacing="0" class="mce-charmap"><tbody>';
    for (y = 0; y < height; y++) {
      gridHtml += '<tr>';
      for (x = 0; x < width; x++) {
        var index = y * width + x;
        if (index < charmap.length) {
          var chr = charmap[index];
          var charCode = parseInt(chr[0], 10);
          var chrText = chr ? String.fromCharCode(charCode) : '&nbsp;';
          gridHtml += '<td title="' + chr[1] + '">' + '<div tabindex="-1" title="' + chr[1] + '" role="button" data-chr="' + charCode + '">' + chrText + '</div>' + '</td>';
        } else {
          gridHtml += '<td />';
        }
      }
      gridHtml += '</tr>';
    }
    gridHtml += '</tbody></table>';
    return gridHtml;
  };
  var $_a7xe5b9ijh8lyzvk = { getHtml: getHtml };

  var getParentTd = function (elm) {
    while (elm) {
      if (elm.nodeName === 'TD') {
        return elm;
      }
      elm = elm.parentNode;
    }
  };
  var open = function (editor) {
    var win;
    var charMapPanel = {
      type: 'container',
      html: $_a7xe5b9ijh8lyzvk.getHtml($_1gjkpm9djh8lyzv2.getCharMap(editor)),
      onclick: function (e) {
        var target = e.target;
        if (/^(TD|DIV)$/.test(target.nodeName)) {
          var charDiv = getParentTd(target).firstChild;
          if (charDiv && charDiv.hasAttribute('data-chr')) {
            var charCodeString = charDiv.getAttribute('data-chr');
            var charCode = parseInt(charCodeString, 10);
            if (!isNaN(charCode)) {
              $_dd5ogr9bjh8lyzv0.insertChar(editor, String.fromCharCode(charCode));
            }
            if (!e.ctrlKey) {
              win.close();
            }
          }
        }
      },
      onmouseover: function (e) {
        var td = getParentTd(e.target);
        if (td && td.firstChild) {
          win.find('#preview').text(td.firstChild.firstChild.data);
          win.find('#previewTitle').text(td.title);
        } else {
          win.find('#preview').text(' ');
          win.find('#previewTitle').text(' ');
        }
      }
    };
    win = editor.windowManager.open({
      title: 'Special character',
      spacing: 10,
      padding: 10,
      items: [
        charMapPanel,
        {
          type: 'container',
          layout: 'flex',
          direction: 'column',
          align: 'center',
          spacing: 5,
          minWidth: 160,
          minHeight: 160,
          items: [
            {
              type: 'label',
              name: 'preview',
              text: ' ',
              style: 'font-size: 40px; text-align: center',
              border: 1,
              minWidth: 140,
              minHeight: 80
            },
            {
              type: 'spacer',
              minHeight: 20
            },
            {
              type: 'label',
              name: 'previewTitle',
              text: ' ',
              style: 'white-space: pre-wrap;',
              border: 1,
              minWidth: 140
            }
          ]
        }
      ],
      buttons: [{
          text: 'Close',
          onclick: function () {
            win.close();
          }
        }]
    });
  };
  var $_5dcojo9hjh8lyzvh = { open: open };

  var register = function (editor) {
    editor.addCommand('mceShowCharmap', function () {
      $_5dcojo9hjh8lyzvh.open(editor);
    });
  };
  var $_ce5y9z9gjh8lyzvg = { register: register };

  var register$1 = function (editor) {
    editor.addButton('charmap', {
      icon: 'charmap',
      tooltip: 'Special character',
      cmd: 'mceShowCharmap'
    });
    editor.addMenuItem('charmap', {
      icon: 'charmap',
      text: 'Special character',
      cmd: 'mceShowCharmap',
      context: 'insert'
    });
  };
  var $_381q489jjh8lyzvl = { register: register$1 };

  global.add('charmap', function (editor) {
    $_ce5y9z9gjh8lyzvg.register(editor);
    $_381q489jjh8lyzvl.register(editor);
    return $_bms9m09ajh8lyzuy.get(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-code", ["tinymce"], function() {
  return (function() {
(function () {
var code = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var getMinWidth = function (editor) {
    return editor.getParam('code_dialog_width', 600);
  };
  var getMinHeight = function (editor) {
    return editor.getParam('code_dialog_height', Math.min(global$1.DOM.getViewPort().h - 200, 500));
  };
  var $_co65cu9ojh8lyzwe = {
    getMinWidth: getMinWidth,
    getMinHeight: getMinHeight
  };

  var setContent = function (editor, html) {
    editor.focus();
    editor.undoManager.transact(function () {
      editor.setContent(html);
    });
    editor.selection.setCursorLocation();
    editor.nodeChanged();
  };
  var getContent = function (editor) {
    return editor.getContent({ source_view: true });
  };
  var $_foko8h9qjh8lyzwf = {
    setContent: setContent,
    getContent: getContent
  };

  var open = function (editor) {
    var minWidth = $_co65cu9ojh8lyzwe.getMinWidth(editor);
    var minHeight = $_co65cu9ojh8lyzwe.getMinHeight(editor);
    var win = editor.windowManager.open({
      title: 'Source code',
      body: {
        type: 'textbox',
        name: 'code',
        multiline: true,
        minWidth: minWidth,
        minHeight: minHeight,
        spellcheck: false,
        style: 'direction: ltr; text-align: left'
      },
      onSubmit: function (e) {
        $_foko8h9qjh8lyzwf.setContent(editor, e.data.code);
      }
    });
    win.find('#code').value($_foko8h9qjh8lyzwf.getContent(editor));
  };
  var $_e52w2l9njh8lyzwc = { open: open };

  var register = function (editor) {
    editor.addCommand('mceCodeEditor', function () {
      $_e52w2l9njh8lyzwc.open(editor);
    });
  };
  var $_curgce9mjh8lyzwb = { register: register };

  var register$1 = function (editor) {
    editor.addButton('code', {
      icon: 'code',
      tooltip: 'Source code',
      onclick: function () {
        $_e52w2l9njh8lyzwc.open(editor);
      }
    });
    editor.addMenuItem('code', {
      icon: 'code',
      text: 'Source code',
      onclick: function () {
        $_e52w2l9njh8lyzwc.open(editor);
      }
    });
  };
  var $_y8a369rjh8lyzwg = { register: register$1 };

  global.add('code', function (editor) {
    $_curgce9mjh8lyzwb.register(editor);
    $_y8a369rjh8lyzwg.register(editor);
    return {};
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-colorpicker", ["tinymce"], function() {
  return (function() {
(function () {
var colorpicker = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Color');

  var showPreview = function (win, hexColor) {
    win.find('#preview')[0].getEl().style.background = hexColor;
  };
  var setColor = function (win, value) {
    var color = global$1(value), rgb = color.toRgb();
    win.fromJSON({
      r: rgb.r,
      g: rgb.g,
      b: rgb.b,
      hex: color.toHex().substr(1)
    });
    showPreview(win, color.toHex());
  };
  var open = function (editor, callback, value) {
    var win = editor.windowManager.open({
      title: 'Color',
      items: {
        type: 'container',
        layout: 'flex',
        direction: 'row',
        align: 'stretch',
        padding: 5,
        spacing: 10,
        items: [
          {
            type: 'colorpicker',
            value: value,
            onchange: function () {
              var rgb = this.rgb();
              if (win) {
                win.find('#r').value(rgb.r);
                win.find('#g').value(rgb.g);
                win.find('#b').value(rgb.b);
                win.find('#hex').value(this.value().substr(1));
                showPreview(win, this.value());
              }
            }
          },
          {
            type: 'form',
            padding: 0,
            labelGap: 5,
            defaults: {
              type: 'textbox',
              size: 7,
              value: '0',
              flex: 1,
              spellcheck: false,
              onchange: function () {
                var colorPickerCtrl = win.find('colorpicker')[0];
                var name, value;
                name = this.name();
                value = this.value();
                if (name === 'hex') {
                  value = '#' + value;
                  setColor(win, value);
                  colorPickerCtrl.value(value);
                  return;
                }
                value = {
                  r: win.find('#r').value(),
                  g: win.find('#g').value(),
                  b: win.find('#b').value()
                };
                colorPickerCtrl.value(value);
                setColor(win, value);
              }
            },
            items: [
              {
                name: 'r',
                label: 'R',
                autofocus: 1
              },
              {
                name: 'g',
                label: 'G'
              },
              {
                name: 'b',
                label: 'B'
              },
              {
                name: 'hex',
                label: '#',
                value: '000000'
              },
              {
                name: 'preview',
                type: 'container',
                border: 1
              }
            ]
          }
        ]
      },
      onSubmit: function () {
        callback('#' + win.toJSON().hex);
      }
    });
    setColor(win, value);
  };
  var $_5hgtbua8jh8lyzzp = { open: open };

  global.add('colorpicker', function (editor) {
    if (!editor.settings.color_picker_callback) {
      editor.settings.color_picker_callback = function (callback, value) {
        $_5hgtbua8jh8lyzzp.open(editor, callback, value);
      };
    }
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-contextmenu", ["tinymce"], function() {
  return (function() {
(function () {
var contextmenu = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var get = function (visibleState) {
    var isContextMenuVisible = function () {
      return visibleState.get();
    };
    return { isContextMenuVisible: isContextMenuVisible };
  };
  var $_c2oibgadjh8lz004 = { get: get };

  var shouldNeverUseNative = function (editor) {
    return editor.settings.contextmenu_never_use_native;
  };
  var getContextMenu = function (editor) {
    return editor.getParam('contextmenu', 'link openlink image inserttable | cell row column deletetable');
  };
  var $_gduzdnafjh8lz006 = {
    shouldNeverUseNative: shouldNeverUseNative,
    getContextMenu: getContextMenu
  };

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var getUiContainer = function (editor) {
    return global$1.DOM.select(editor.settings.ui_container)[0];
  };

  var nu = function (x, y) {
    return {
      x: x,
      y: y
    };
  };
  var transpose = function (pos, dx, dy) {
    return nu(pos.x + dx, pos.y + dy);
  };
  var fromPageXY = function (e) {
    return nu(e.pageX, e.pageY);
  };
  var fromClientXY = function (e) {
    return nu(e.clientX, e.clientY);
  };
  var transposeUiContainer = function (element, pos) {
    if (element && global$1.DOM.getStyle(element, 'position', true) !== 'static') {
      var containerPos = global$1.DOM.getPos(element);
      var dx = containerPos.x - element.scrollLeft;
      var dy = containerPos.y - element.scrollTop;
      return transpose(pos, -dx, -dy);
    } else {
      return transpose(pos, 0, 0);
    }
  };
  var transposeContentAreaContainer = function (element, pos) {
    var containerPos = global$1.DOM.getPos(element);
    return transpose(pos, containerPos.x, containerPos.y);
  };
  var getPos = function (editor, e) {
    if (editor.inline) {
      return transposeUiContainer(getUiContainer(editor), fromPageXY(e));
    } else {
      var iframePos = transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
      return transposeUiContainer(getUiContainer(editor), iframePos);
    }
  };
  var $_712j2vagjh8lz007 = { getPos: getPos };

  var global$2 = tinymce.util.Tools.resolve('tinymce.ui.Factory');

  var global$3 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var renderMenu = function (editor, visibleState) {
    var menu, contextmenu;
    var items = [];
    contextmenu = $_gduzdnafjh8lz006.getContextMenu(editor);
    global$3.each(contextmenu.split(/[ ,]/), function (name) {
      var item = editor.menuItems[name];
      if (name === '|') {
        item = { text: name };
      }
      if (item) {
        item.shortcut = '';
        items.push(item);
      }
    });
    for (var i = 0; i < items.length; i++) {
      if (items[i].text === '|') {
        if (i === 0 || i === items.length - 1) {
          items.splice(i, 1);
        }
      }
    }
    menu = global$2.create('menu', {
      items: items,
      context: 'contextmenu',
      classes: 'contextmenu'
    });
    menu.uiContainer = getUiContainer(editor);
    menu.renderTo(getUiContainer(editor));
    menu.on('hide', function (e) {
      if (e.control === this) {
        visibleState.set(false);
      }
    });
    editor.on('remove', function () {
      menu.remove();
      menu = null;
    });
    return menu;
  };
  var show = function (editor, pos, visibleState, menu) {
    if (menu.get() === null) {
      menu.set(renderMenu(editor, visibleState));
    } else {
      menu.get().show();
    }
    menu.get().moveTo(pos.x, pos.y);
    visibleState.set(true);
  };
  var $_6to3u5ajjh8lz00c = { show: show };

  var isNativeOverrideKeyEvent = function (editor, e) {
    return e.ctrlKey && !$_gduzdnafjh8lz006.shouldNeverUseNative(editor);
  };
  var setup = function (editor, visibleState, menu) {
    editor.on('contextmenu', function (e) {
      if (isNativeOverrideKeyEvent(editor, e)) {
        return;
      }
      e.preventDefault();
      $_6to3u5ajjh8lz00c.show(editor, $_712j2vagjh8lz007.getPos(editor, e), visibleState, menu);
    });
  };
  var $_6rkqhnaejh8lz005 = { setup: setup };

  global.add('contextmenu', function (editor) {
    var menu = Cell(null), visibleState = Cell(false);
    $_6rkqhnaejh8lz005.setup(editor, visibleState, menu);
    return $_c2oibgadjh8lz004.get(visibleState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-directionality", ["tinymce"], function() {
  return (function() {
(function () {
var directionality = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var setDir = function (editor, dir) {
    var dom = editor.dom;
    var curDir;
    var blocks = editor.selection.getSelectedBlocks();
    if (blocks.length) {
      curDir = dom.getAttrib(blocks[0], 'dir');
      global$1.each(blocks, function (block) {
        if (!dom.getParent(block.parentNode, '*[dir="' + dir + '"]', dom.getRoot())) {
          dom.setAttrib(block, 'dir', curDir !== dir ? dir : null);
        }
      });
      editor.nodeChanged();
    }
  };
  var $_805jwcapjh8lz00w = { setDir: setDir };

  var register = function (editor) {
    editor.addCommand('mceDirectionLTR', function () {
      $_805jwcapjh8lz00w.setDir(editor, 'ltr');
    });
    editor.addCommand('mceDirectionRTL', function () {
      $_805jwcapjh8lz00w.setDir(editor, 'rtl');
    });
  };
  var $_bg4nrvaojh8lz00v = { register: register };

  var generateSelector = function (dir) {
    var selector = [];
    global$1.each('h1 h2 h3 h4 h5 h6 div p'.split(' '), function (name) {
      selector.push(name + '[dir=' + dir + ']');
    });
    return selector.join(',');
  };
  var register$1 = function (editor) {
    editor.addButton('ltr', {
      title: 'Left to right',
      cmd: 'mceDirectionLTR',
      stateSelector: generateSelector('ltr')
    });
    editor.addButton('rtl', {
      title: 'Right to left',
      cmd: 'mceDirectionRTL',
      stateSelector: generateSelector('rtl')
    });
  };
  var $_gcdqcharjh8lz015 = { register: register$1 };

  global.add('directionality', function (editor) {
    $_bg4nrvaojh8lz00v.register(editor);
    $_gcdqcharjh8lz015.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-emoticons", ["tinymce"], function() {
  return (function() {
(function () {
var emoticons = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var emoticons = [
    [
      'cool',
      'cry',
      'embarassed',
      'foot-in-mouth'
    ],
    [
      'frown',
      'innocent',
      'kiss',
      'laughing'
    ],
    [
      'money-mouth',
      'sealed',
      'smile',
      'surprised'
    ],
    [
      'tongue-out',
      'undecided',
      'wink',
      'yell'
    ]
  ];
  var getHtml = function (pluginUrl) {
    var emoticonsHtml;
    emoticonsHtml = '<table role="list" class="mce-grid">';
    global$1.each(emoticons, function (row) {
      emoticonsHtml += '<tr>';
      global$1.each(row, function (icon) {
        var emoticonUrl = pluginUrl + '/img/smiley-' + icon + '.gif';
        emoticonsHtml += '<td><a href="#" data-mce-url="' + emoticonUrl + '" data-mce-alt="' + icon + '" tabindex="-1" ' + 'role="option" aria-label="' + icon + '"><img src="' + emoticonUrl + '" style="width: 18px; height: 18px" role="presentation" /></a></td>';
      });
      emoticonsHtml += '</tr>';
    });
    emoticonsHtml += '</table>';
    return emoticonsHtml;
  };
  var $_1r8x6javjh8lz01h = { getHtml: getHtml };

  var insertEmoticon = function (editor, src, alt) {
    editor.insertContent(editor.dom.createHTML('img', {
      src: src,
      alt: alt
    }));
  };
  var register = function (editor, pluginUrl) {
    var panelHtml = $_1r8x6javjh8lz01h.getHtml(pluginUrl);
    editor.addButton('emoticons', {
      type: 'panelbutton',
      panel: {
        role: 'application',
        autohide: true,
        html: panelHtml,
        onclick: function (e) {
          var linkElm = editor.dom.getParent(e.target, 'a');
          if (linkElm) {
            insertEmoticon(editor, linkElm.getAttribute('data-mce-url'), linkElm.getAttribute('data-mce-alt'));
            this.hide();
          }
        }
      },
      tooltip: 'Emoticons'
    });
  };
  var $_eu4hs8aujh8lz01e = { register: register };

  global.add('emoticons', function (editor, pluginUrl) {
    $_eu4hs8aujh8lz01e.register(editor, pluginUrl);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-fullpage", ["tinymce"], function() {
  return (function() {
(function () {
var fullpage = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var global$2 = tinymce.util.Tools.resolve('tinymce.html.DomParser');

  var global$3 = tinymce.util.Tools.resolve('tinymce.html.Node');

  var global$4 = tinymce.util.Tools.resolve('tinymce.html.Serializer');

  var shouldHideInSourceView = function (editor) {
    return editor.getParam('fullpage_hide_in_source_view');
  };
  var getDefaultXmlPi = function (editor) {
    return editor.getParam('fullpage_default_xml_pi');
  };
  var getDefaultEncoding = function (editor) {
    return editor.getParam('fullpage_default_encoding');
  };
  var getDefaultFontFamily = function (editor) {
    return editor.getParam('fullpage_default_font_family');
  };
  var getDefaultFontSize = function (editor) {
    return editor.getParam('fullpage_default_font_size');
  };
  var getDefaultTextColor = function (editor) {
    return editor.getParam('fullpage_default_text_color');
  };
  var getDefaultTitle = function (editor) {
    return editor.getParam('fullpage_default_title');
  };
  var getDefaultDocType = function (editor) {
    return editor.getParam('fullpage_default_doctype', '<!DOCTYPE html>');
  };
  var $_g0xiuvbsjh8lz05n = {
    shouldHideInSourceView: shouldHideInSourceView,
    getDefaultXmlPi: getDefaultXmlPi,
    getDefaultEncoding: getDefaultEncoding,
    getDefaultFontFamily: getDefaultFontFamily,
    getDefaultFontSize: getDefaultFontSize,
    getDefaultTextColor: getDefaultTextColor,
    getDefaultTitle: getDefaultTitle,
    getDefaultDocType: getDefaultDocType
  };

  var parseHeader = function (head) {
    return global$2({
      validate: false,
      root_name: '#document'
    }).parse(head);
  };
  var htmlToData = function (editor, head) {
    var headerFragment = parseHeader(head);
    var data = {};
    var elm, matches;
    function getAttr(elm, name) {
      var value = elm.attr(name);
      return value || '';
    }
    data.fontface = $_g0xiuvbsjh8lz05n.getDefaultFontFamily(editor);
    data.fontsize = $_g0xiuvbsjh8lz05n.getDefaultFontSize(editor);
    elm = headerFragment.firstChild;
    if (elm.type === 7) {
      data.xml_pi = true;
      matches = /encoding="([^"]+)"/.exec(elm.value);
      if (matches) {
        data.docencoding = matches[1];
      }
    }
    elm = headerFragment.getAll('#doctype')[0];
    if (elm) {
      data.doctype = '<!DOCTYPE' + elm.value + '>';
    }
    elm = headerFragment.getAll('title')[0];
    if (elm && elm.firstChild) {
      data.title = elm.firstChild.value;
    }
    global$1.each(headerFragment.getAll('meta'), function (meta) {
      var name = meta.attr('name');
      var httpEquiv = meta.attr('http-equiv');
      var matches;
      if (name) {
        data[name.toLowerCase()] = meta.attr('content');
      } else if (httpEquiv === 'Content-Type') {
        matches = /charset\s*=\s*(.*)\s*/gi.exec(meta.attr('content'));
        if (matches) {
          data.docencoding = matches[1];
        }
      }
    });
    elm = headerFragment.getAll('html')[0];
    if (elm) {
      data.langcode = getAttr(elm, 'lang') || getAttr(elm, 'xml:lang');
    }
    data.stylesheets = [];
    global$1.each(headerFragment.getAll('link'), function (link) {
      if (link.attr('rel') === 'stylesheet') {
        data.stylesheets.push(link.attr('href'));
      }
    });
    elm = headerFragment.getAll('body')[0];
    if (elm) {
      data.langdir = getAttr(elm, 'dir');
      data.style = getAttr(elm, 'style');
      data.visited_color = getAttr(elm, 'vlink');
      data.link_color = getAttr(elm, 'link');
      data.active_color = getAttr(elm, 'alink');
    }
    return data;
  };
  var dataToHtml = function (editor, data, head) {
    var headerFragment, headElement, html, elm, value;
    var dom = editor.dom;
    function setAttr(elm, name, value) {
      elm.attr(name, value ? value : undefined);
    }
    function addHeadNode(node) {
      if (headElement.firstChild) {
        headElement.insert(node, headElement.firstChild);
      } else {
        headElement.append(node);
      }
    }
    headerFragment = parseHeader(head);
    headElement = headerFragment.getAll('head')[0];
    if (!headElement) {
      elm = headerFragment.getAll('html')[0];
      headElement = new global$3('head', 1);
      if (elm.firstChild) {
        elm.insert(headElement, elm.firstChild, true);
      } else {
        elm.append(headElement);
      }
    }
    elm = headerFragment.firstChild;
    if (data.xml_pi) {
      value = 'version="1.0"';
      if (data.docencoding) {
        value += ' encoding="' + data.docencoding + '"';
      }
      if (elm.type !== 7) {
        elm = new global$3('xml', 7);
        headerFragment.insert(elm, headerFragment.firstChild, true);
      }
      elm.value = value;
    } else if (elm && elm.type === 7) {
      elm.remove();
    }
    elm = headerFragment.getAll('#doctype')[0];
    if (data.doctype) {
      if (!elm) {
        elm = new global$3('#doctype', 10);
        if (data.xml_pi) {
          headerFragment.insert(elm, headerFragment.firstChild);
        } else {
          addHeadNode(elm);
        }
      }
      elm.value = data.doctype.substring(9, data.doctype.length - 1);
    } else if (elm) {
      elm.remove();
    }
    elm = null;
    global$1.each(headerFragment.getAll('meta'), function (meta) {
      if (meta.attr('http-equiv') === 'Content-Type') {
        elm = meta;
      }
    });
    if (data.docencoding) {
      if (!elm) {
        elm = new global$3('meta', 1);
        elm.attr('http-equiv', 'Content-Type');
        elm.shortEnded = true;
        addHeadNode(elm);
      }
      elm.attr('content', 'text/html; charset=' + data.docencoding);
    } else if (elm) {
      elm.remove();
    }
    elm = headerFragment.getAll('title')[0];
    if (data.title) {
      if (!elm) {
        elm = new global$3('title', 1);
        addHeadNode(elm);
      } else {
        elm.empty();
      }
      elm.append(new global$3('#text', 3)).value = data.title;
    } else if (elm) {
      elm.remove();
    }
    global$1.each('keywords,description,author,copyright,robots'.split(','), function (name) {
      var nodes = headerFragment.getAll('meta');
      var i, meta;
      var value = data[name];
      for (i = 0; i < nodes.length; i++) {
        meta = nodes[i];
        if (meta.attr('name') === name) {
          if (value) {
            meta.attr('content', value);
          } else {
            meta.remove();
          }
          return;
        }
      }
      if (value) {
        elm = new global$3('meta', 1);
        elm.attr('name', name);
        elm.attr('content', value);
        elm.shortEnded = true;
        addHeadNode(elm);
      }
    });
    var currentStyleSheetsMap = {};
    global$1.each(headerFragment.getAll('link'), function (stylesheet) {
      if (stylesheet.attr('rel') === 'stylesheet') {
        currentStyleSheetsMap[stylesheet.attr('href')] = stylesheet;
      }
    });
    global$1.each(data.stylesheets, function (stylesheet) {
      if (!currentStyleSheetsMap[stylesheet]) {
        elm = new global$3('link', 1);
        elm.attr({
          rel: 'stylesheet',
          text: 'text/css',
          href: stylesheet
        });
        elm.shortEnded = true;
        addHeadNode(elm);
      }
      delete currentStyleSheetsMap[stylesheet];
    });
    global$1.each(currentStyleSheetsMap, function (stylesheet) {
      stylesheet.remove();
    });
    elm = headerFragment.getAll('body')[0];
    if (elm) {
      setAttr(elm, 'dir', data.langdir);
      setAttr(elm, 'style', data.style);
      setAttr(elm, 'vlink', data.visited_color);
      setAttr(elm, 'link', data.link_color);
      setAttr(elm, 'alink', data.active_color);
      dom.setAttribs(editor.getBody(), {
        style: data.style,
        dir: data.dir,
        vLink: data.visited_color,
        link: data.link_color,
        aLink: data.active_color
      });
    }
    elm = headerFragment.getAll('html')[0];
    if (elm) {
      setAttr(elm, 'lang', data.langcode);
      setAttr(elm, 'xml:lang', data.langcode);
    }
    if (!headElement.firstChild) {
      headElement.remove();
    }
    html = global$4({
      validate: false,
      indent: true,
      apply_source_formatting: true,
      indent_before: 'head,html,body,meta,title,script,link,style',
      indent_after: 'head,html,body,meta,title,script,link,style'
    }).serialize(headerFragment);
    return html.substring(0, html.indexOf('</body>'));
  };
  var $_28en95bojh8lz05g = {
    parseHeader: parseHeader,
    htmlToData: htmlToData,
    dataToHtml: dataToHtml
  };

  var open = function (editor, headState) {
    var data = $_28en95bojh8lz05g.htmlToData(editor, headState.get());
    editor.windowManager.open({
      title: 'Document properties',
      data: data,
      defaults: {
        type: 'textbox',
        size: 40
      },
      body: [
        {
          name: 'title',
          label: 'Title'
        },
        {
          name: 'keywords',
          label: 'Keywords'
        },
        {
          name: 'description',
          label: 'Description'
        },
        {
          name: 'robots',
          label: 'Robots'
        },
        {
          name: 'author',
          label: 'Author'
        },
        {
          name: 'docencoding',
          label: 'Encoding'
        }
      ],
      onSubmit: function (e) {
        var headHtml = $_28en95bojh8lz05g.dataToHtml(editor, global$1.extend(data, e.data), headState.get());
        headState.set(headHtml);
      }
    });
  };
  var $_ekcxiubmjh8lz05d = { open: open };

  var register = function (editor, headState) {
    editor.addCommand('mceFullPageProperties', function () {
      $_ekcxiubmjh8lz05d.open(editor, headState);
    });
  };
  var $_8prs3sbljh8lz05c = { register: register };

  var protectHtml = function (protect, html) {
    global$1.each(protect, function (pattern) {
      html = html.replace(pattern, function (str) {
        return '<!--mce:protected ' + escape(str) + '-->';
      });
    });
    return html;
  };
  var unprotectHtml = function (html) {
    return html.replace(/<!--mce:protected ([\s\S]*?)-->/g, function (a, m) {
      return unescape(m);
    });
  };
  var $_e8blxibujh8lz05v = {
    protectHtml: protectHtml,
    unprotectHtml: unprotectHtml
  };

  var each = global$1.each;
  var low = function (s) {
    return s.replace(/<\/?[A-Z]+/g, function (a) {
      return a.toLowerCase();
    });
  };
  var handleSetContent = function (editor, headState, footState, evt) {
    var startPos, endPos, content, headerFragment, styles = '';
    var dom = editor.dom;
    var elm;
    if (evt.selection) {
      return;
    }
    content = $_e8blxibujh8lz05v.protectHtml(editor.settings.protect, evt.content);
    if (evt.format === 'raw' && headState.get()) {
      return;
    }
    if (evt.source_view && $_g0xiuvbsjh8lz05n.shouldHideInSourceView(editor)) {
      return;
    }
    if (content.length === 0 && !evt.source_view) {
      content = global$1.trim(headState.get()) + '\n' + global$1.trim(content) + '\n' + global$1.trim(footState.get());
    }
    content = content.replace(/<(\/?)BODY/gi, '<$1body');
    startPos = content.indexOf('<body');
    if (startPos !== -1) {
      startPos = content.indexOf('>', startPos);
      headState.set(low(content.substring(0, startPos + 1)));
      endPos = content.indexOf('</body', startPos);
      if (endPos === -1) {
        endPos = content.length;
      }
      evt.content = global$1.trim(content.substring(startPos + 1, endPos));
      footState.set(low(content.substring(endPos)));
    } else {
      headState.set(getDefaultHeader(editor));
      footState.set('\n</body>\n</html>');
    }
    headerFragment = $_28en95bojh8lz05g.parseHeader(headState.get());
    each(headerFragment.getAll('style'), function (node) {
      if (node.firstChild) {
        styles += node.firstChild.value;
      }
    });
    elm = headerFragment.getAll('body')[0];
    if (elm) {
      dom.setAttribs(editor.getBody(), {
        style: elm.attr('style') || '',
        dir: elm.attr('dir') || '',
        vLink: elm.attr('vlink') || '',
        link: elm.attr('link') || '',
        aLink: elm.attr('alink') || ''
      });
    }
    dom.remove('fullpage_styles');
    var headElm = editor.getDoc().getElementsByTagName('head')[0];
    if (styles) {
      dom.add(headElm, 'style', { id: 'fullpage_styles' }, styles);
      elm = dom.get('fullpage_styles');
      if (elm.styleSheet) {
        elm.styleSheet.cssText = styles;
      }
    }
    var currentStyleSheetsMap = {};
    global$1.each(headElm.getElementsByTagName('link'), function (stylesheet) {
      if (stylesheet.rel === 'stylesheet' && stylesheet.getAttribute('data-mce-fullpage')) {
        currentStyleSheetsMap[stylesheet.href] = stylesheet;
      }
    });
    global$1.each(headerFragment.getAll('link'), function (stylesheet) {
      var href = stylesheet.attr('href');
      if (!href) {
        return true;
      }
      if (!currentStyleSheetsMap[href] && stylesheet.attr('rel') === 'stylesheet') {
        dom.add(headElm, 'link', {
          'rel': 'stylesheet',
          'text': 'text/css',
          'href': href,
          'data-mce-fullpage': '1'
        });
      }
      delete currentStyleSheetsMap[href];
    });
    global$1.each(currentStyleSheetsMap, function (stylesheet) {
      stylesheet.parentNode.removeChild(stylesheet);
    });
  };
  var getDefaultHeader = function (editor) {
    var header = '', value, styles = '';
    if ($_g0xiuvbsjh8lz05n.getDefaultXmlPi(editor)) {
      var piEncoding = $_g0xiuvbsjh8lz05n.getDefaultEncoding(editor);
      header += '<?xml version="1.0" encoding="' + (piEncoding ? piEncoding : 'ISO-8859-1') + '" ?>\n';
    }
    header += $_g0xiuvbsjh8lz05n.getDefaultDocType(editor);
    header += '\n<html>\n<head>\n';
    if (value = $_g0xiuvbsjh8lz05n.getDefaultTitle(editor)) {
      header += '<title>' + value + '</title>\n';
    }
    if (value = $_g0xiuvbsjh8lz05n.getDefaultEncoding(editor)) {
      header += '<meta http-equiv="Content-Type" content="text/html; charset=' + value + '" />\n';
    }
    if (value = $_g0xiuvbsjh8lz05n.getDefaultFontFamily(editor)) {
      styles += 'font-family: ' + value + ';';
    }
    if (value = $_g0xiuvbsjh8lz05n.getDefaultFontSize(editor)) {
      styles += 'font-size: ' + value + ';';
    }
    if (value = $_g0xiuvbsjh8lz05n.getDefaultTextColor(editor)) {
      styles += 'color: ' + value + ';';
    }
    header += '</head>\n<body' + (styles ? ' style="' + styles + '"' : '') + '>\n';
    return header;
  };
  var handleGetContent = function (editor, head, foot, evt) {
    if (!evt.selection && (!evt.source_view || !$_g0xiuvbsjh8lz05n.shouldHideInSourceView(editor))) {
      evt.content = $_e8blxibujh8lz05v.unprotectHtml(global$1.trim(head) + '\n' + global$1.trim(evt.content) + '\n' + global$1.trim(foot));
    }
  };
  var setup = function (editor, headState, footState) {
    editor.on('BeforeSetContent', function (evt) {
      handleSetContent(editor, headState, footState, evt);
    });
    editor.on('GetContent', function (evt) {
      handleGetContent(editor, headState.get(), footState.get(), evt);
    });
  };
  var $_56p36sbtjh8lz05p = { setup: setup };

  var register$1 = function (editor) {
    editor.addButton('fullpage', {
      title: 'Document properties',
      cmd: 'mceFullPageProperties'
    });
    editor.addMenuItem('fullpage', {
      text: 'Document properties',
      cmd: 'mceFullPageProperties',
      context: 'file'
    });
  };
  var $_bqab8cbvjh8lz05w = { register: register$1 };

  global.add('fullpage', function (editor) {
    var headState = Cell(''), footState = Cell('');
    $_8prs3sbljh8lz05c.register(editor, headState);
    $_bqab8cbvjh8lz05w.register(editor);
    $_56p36sbtjh8lz05p.setup(editor, headState, footState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-fullscreen", ["tinymce"], function() {
  return (function() {
(function () {
var fullscreen = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var get = function (fullscreenState) {
    return {
      isFullscreen: function () {
        return fullscreenState.get() !== null;
      }
    };
  };
  var $_1rpb71bzjh8lz06v = { get: get };

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var fireFullscreenStateChanged = function (editor, state) {
    editor.fire('FullscreenStateChanged', { state: state });
  };
  var $_1d2nfac3jh8lz070 = { fireFullscreenStateChanged: fireFullscreenStateChanged };

  var DOM = global$1.DOM;
  var getWindowSize = function () {
    var w;
    var h;
    var win = window;
    var doc = document;
    var body = doc.body;
    if (body.offsetWidth) {
      w = body.offsetWidth;
      h = body.offsetHeight;
    }
    if (win.innerWidth && win.innerHeight) {
      w = win.innerWidth;
      h = win.innerHeight;
    }
    return {
      w: w,
      h: h
    };
  };
  var getScrollPos = function () {
    var vp = DOM.getViewPort();
    return {
      x: vp.x,
      y: vp.y
    };
  };
  var setScrollPos = function (pos) {
    window.scrollTo(pos.x, pos.y);
  };
  var toggleFullscreen = function (editor, fullscreenState) {
    var body = document.body;
    var documentElement = document.documentElement;
    var editorContainerStyle;
    var editorContainer, iframe, iframeStyle;
    var fullscreenInfo = fullscreenState.get();
    var resize = function () {
      DOM.setStyle(iframe, 'height', getWindowSize().h - (editorContainer.clientHeight - iframe.clientHeight));
    };
    var removeResize = function () {
      DOM.unbind(window, 'resize', resize);
    };
    editorContainer = editor.getContainer();
    editorContainerStyle = editorContainer.style;
    iframe = editor.getContentAreaContainer().firstChild;
    iframeStyle = iframe.style;
    if (!fullscreenInfo) {
      var newFullScreenInfo = {
        scrollPos: getScrollPos(),
        containerWidth: editorContainerStyle.width,
        containerHeight: editorContainerStyle.height,
        iframeWidth: iframeStyle.width,
        iframeHeight: iframeStyle.height,
        resizeHandler: resize,
        removeHandler: removeResize
      };
      iframeStyle.width = iframeStyle.height = '100%';
      editorContainerStyle.width = editorContainerStyle.height = '';
      DOM.addClass(body, 'mce-fullscreen');
      DOM.addClass(documentElement, 'mce-fullscreen');
      DOM.addClass(editorContainer, 'mce-fullscreen');
      DOM.bind(window, 'resize', resize);
      editor.on('remove', removeResize);
      resize();
      fullscreenState.set(newFullScreenInfo);
      $_1d2nfac3jh8lz070.fireFullscreenStateChanged(editor, true);
    } else {
      iframeStyle.width = fullscreenInfo.iframeWidth;
      iframeStyle.height = fullscreenInfo.iframeHeight;
      if (fullscreenInfo.containerWidth) {
        editorContainerStyle.width = fullscreenInfo.containerWidth;
      }
      if (fullscreenInfo.containerHeight) {
        editorContainerStyle.height = fullscreenInfo.containerHeight;
      }
      DOM.removeClass(body, 'mce-fullscreen');
      DOM.removeClass(documentElement, 'mce-fullscreen');
      DOM.removeClass(editorContainer, 'mce-fullscreen');
      setScrollPos(fullscreenInfo.scrollPos);
      DOM.unbind(window, 'resize', fullscreenInfo.resizeHandler);
      editor.off('remove', fullscreenInfo.removeHandler);
      fullscreenState.set(null);
      $_1d2nfac3jh8lz070.fireFullscreenStateChanged(editor, false);
    }
  };
  var $_7tc4jhc1jh8lz06x = { toggleFullscreen: toggleFullscreen };

  var register = function (editor, fullscreenState) {
    editor.addCommand('mceFullScreen', function () {
      $_7tc4jhc1jh8lz06x.toggleFullscreen(editor, fullscreenState);
    });
  };
  var $_em8om1c0jh8lz06w = { register: register };

  var postRender = function (editor) {
    return function (e) {
      var ctrl = e.control;
      editor.on('FullscreenStateChanged', function (e) {
        ctrl.active(e.state);
      });
    };
  };
  var register$1 = function (editor) {
    editor.addMenuItem('fullscreen', {
      text: 'Fullscreen',
      shortcut: 'Ctrl+Shift+F',
      selectable: true,
      cmd: 'mceFullScreen',
      onPostRender: postRender(editor),
      context: 'view'
    });
    editor.addButton('fullscreen', {
      active: false,
      tooltip: 'Fullscreen',
      cmd: 'mceFullScreen',
      onPostRender: postRender(editor)
    });
  };
  var $_f8ip0cc4jh8lz071 = { register: register$1 };

  global.add('fullscreen', function (editor) {
    var fullscreenState = Cell(null);
    if (editor.settings.inline) {
      return $_1rpb71bzjh8lz06v.get(fullscreenState);
    }
    $_em8om1c0jh8lz06w.register(editor, fullscreenState);
    $_f8ip0cc4jh8lz071.register(editor);
    editor.addShortcut('Ctrl+Shift+F', '', 'mceFullScreen');
    return $_1rpb71bzjh8lz06v.get(fullscreenState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-hr", ["tinymce"], function() {
  return (function() {
(function () {
var hr = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var register = function (editor) {
    editor.addCommand('InsertHorizontalRule', function () {
      editor.execCommand('mceInsertContent', false, '<hr />');
    });
  };
  var $_dxcs8yc7jh8lz07d = { register: register };

  var register$1 = function (editor) {
    editor.addButton('hr', {
      icon: 'hr',
      tooltip: 'Horizontal line',
      cmd: 'InsertHorizontalRule'
    });
    editor.addMenuItem('hr', {
      icon: 'hr',
      text: 'Horizontal line',
      cmd: 'InsertHorizontalRule',
      context: 'insert'
    });
  };
  var $_dmdtoxc8jh8lz07e = { register: register$1 };

  global.add('hr', function (editor) {
    $_dxcs8yc7jh8lz07d.register(editor);
    $_dmdtoxc8jh8lz07e.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-image", ["tinymce"], function() {
  return (function() {
(function () {
var image = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var hasDimensions = function (editor) {
    return editor.settings.image_dimensions === false ? false : true;
  };
  var hasAdvTab = function (editor) {
    return editor.settings.image_advtab === true ? true : false;
  };
  var getPrependUrl = function (editor) {
    return editor.getParam('image_prepend_url', '');
  };
  var getClassList = function (editor) {
    return editor.getParam('image_class_list');
  };
  var hasDescription = function (editor) {
    return editor.settings.image_description === false ? false : true;
  };
  var hasImageTitle = function (editor) {
    return editor.settings.image_title === true ? true : false;
  };
  var hasImageCaption = function (editor) {
    return editor.settings.image_caption === true ? true : false;
  };
  var getImageList = function (editor) {
    return editor.getParam('image_list', false);
  };
  var hasUploadUrl = function (editor) {
    return editor.getParam('images_upload_url', false);
  };
  var hasUploadHandler = function (editor) {
    return editor.getParam('images_upload_handler', false);
  };
  var getUploadUrl = function (editor) {
    return editor.getParam('images_upload_url');
  };
  var getUploadHandler = function (editor) {
    return editor.getParam('images_upload_handler');
  };
  var getUploadBasePath = function (editor) {
    return editor.getParam('images_upload_base_path');
  };
  var getUploadCredentials = function (editor) {
    return editor.getParam('images_upload_credentials');
  };
  var $_crxcnscdjh8lz07s = {
    hasDimensions: hasDimensions,
    hasAdvTab: hasAdvTab,
    getPrependUrl: getPrependUrl,
    getClassList: getClassList,
    hasDescription: hasDescription,
    hasImageTitle: hasImageTitle,
    hasImageCaption: hasImageCaption,
    getImageList: getImageList,
    hasUploadUrl: hasUploadUrl,
    hasUploadHandler: hasUploadHandler,
    getUploadUrl: getUploadUrl,
    getUploadHandler: getUploadHandler,
    getUploadBasePath: getUploadBasePath,
    getUploadCredentials: getUploadCredentials
  };

  var global$1 = typeof window !== 'undefined' ? window : Function('return this;')();

  var path = function (parts, scope) {
    var o = scope !== undefined && scope !== null ? scope : global$1;
    for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i)
      o = o[parts[i]];
    return o;
  };
  var resolve = function (p, scope) {
    var parts = p.split('.');
    return path(parts, scope);
  };
  var step = function (o, part) {
    if (o[part] === undefined || o[part] === null)
      o[part] = {};
    return o[part];
  };
  var forge = function (parts, target) {
    var o = target !== undefined ? target : global$1;
    for (var i = 0; i < parts.length; ++i)
      o = step(o, parts[i]);
    return o;
  };
  var namespace = function (name, target) {
    var parts = name.split('.');
    return forge(parts, target);
  };
  var $_9gheychjh8lz08c = {
    path: path,
    resolve: resolve,
    forge: forge,
    namespace: namespace
  };

  var unsafe = function (name, scope) {
    return $_9gheychjh8lz08c.resolve(name, scope);
  };
  var getOrDie = function (name, scope) {
    var actual = unsafe(name, scope);
    if (actual === undefined || actual === null)
      throw name + ' not available on this browser';
    return actual;
  };
  var $_8d9gbscgjh8lz089 = { getOrDie: getOrDie };

  function FileReader () {
    var f = $_8d9gbscgjh8lz089.getOrDie('FileReader');
    return new f();
  }

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Promise');

  var global$3 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var global$4 = tinymce.util.Tools.resolve('tinymce.util.XHR');

  var parseIntAndGetMax = function (val1, val2) {
    return Math.max(parseInt(val1, 10), parseInt(val2, 10));
  };
  var getImageSize = function (url, callback) {
    var img = document.createElement('img');
    function done(width, height) {
      if (img.parentNode) {
        img.parentNode.removeChild(img);
      }
      callback({
        width: width,
        height: height
      });
    }
    img.onload = function () {
      var width = parseIntAndGetMax(img.width, img.clientWidth);
      var height = parseIntAndGetMax(img.height, img.clientHeight);
      done(width, height);
    };
    img.onerror = function () {
      done(0, 0);
    };
    var style = img.style;
    style.visibility = 'hidden';
    style.position = 'fixed';
    style.bottom = style.left = '0px';
    style.width = style.height = 'auto';
    document.body.appendChild(img);
    img.src = url;
  };
  var buildListItems = function (inputList, itemCallback, startItems) {
    function appendItems(values, output) {
      output = output || [];
      global$3.each(values, function (item) {
        var menuItem = { text: item.text || item.title };
        if (item.menu) {
          menuItem.menu = appendItems(item.menu);
        } else {
          menuItem.value = item.value;
          itemCallback(menuItem);
        }
        output.push(menuItem);
      });
      return output;
    }
    return appendItems(inputList, startItems || []);
  };
  var removePixelSuffix = function (value) {
    if (value) {
      value = value.replace(/px$/, '');
    }
    return value;
  };
  var addPixelSuffix = function (value) {
    if (value.length > 0 && /^[0-9]+$/.test(value)) {
      value += 'px';
    }
    return value;
  };
  var mergeMargins = function (css) {
    if (css.margin) {
      var splitMargin = css.margin.split(' ');
      switch (splitMargin.length) {
      case 1:
        css['margin-top'] = css['margin-top'] || splitMargin[0];
        css['margin-right'] = css['margin-right'] || splitMargin[0];
        css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
        css['margin-left'] = css['margin-left'] || splitMargin[0];
        break;
      case 2:
        css['margin-top'] = css['margin-top'] || splitMargin[0];
        css['margin-right'] = css['margin-right'] || splitMargin[1];
        css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
        css['margin-left'] = css['margin-left'] || splitMargin[1];
        break;
      case 3:
        css['margin-top'] = css['margin-top'] || splitMargin[0];
        css['margin-right'] = css['margin-right'] || splitMargin[1];
        css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
        css['margin-left'] = css['margin-left'] || splitMargin[1];
        break;
      case 4:
        css['margin-top'] = css['margin-top'] || splitMargin[0];
        css['margin-right'] = css['margin-right'] || splitMargin[1];
        css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
        css['margin-left'] = css['margin-left'] || splitMargin[3];
      }
      delete css.margin;
    }
    return css;
  };
  var createImageList = function (editor, callback) {
    var imageList = $_crxcnscdjh8lz07s.getImageList(editor);
    if (typeof imageList === 'string') {
      global$4.send({
        url: imageList,
        success: function (text) {
          callback(JSON.parse(text));
        }
      });
    } else if (typeof imageList === 'function') {
      imageList(callback);
    } else {
      callback(imageList);
    }
  };
  var waitLoadImage = function (editor, data, imgElm) {
    function selectImage() {
      imgElm.onload = imgElm.onerror = null;
      if (editor.selection) {
        editor.selection.select(imgElm);
        editor.nodeChanged();
      }
    }
    imgElm.onload = function () {
      if (!data.width && !data.height && $_crxcnscdjh8lz07s.hasDimensions(editor)) {
        editor.dom.setAttribs(imgElm, {
          width: imgElm.clientWidth,
          height: imgElm.clientHeight
        });
      }
      selectImage();
    };
    imgElm.onerror = selectImage;
  };
  var blobToDataUri = function (blob) {
    return new global$2(function (resolve, reject) {
      var reader = new FileReader();
      reader.onload = function () {
        resolve(reader.result);
      };
      reader.onerror = function () {
        reject(FileReader.error.message);
      };
      reader.readAsDataURL(blob);
    });
  };
  var $_5m5ooacejh8lz07v = {
    getImageSize: getImageSize,
    buildListItems: buildListItems,
    removePixelSuffix: removePixelSuffix,
    addPixelSuffix: addPixelSuffix,
    mergeMargins: mergeMargins,
    createImageList: createImageList,
    waitLoadImage: waitLoadImage,
    blobToDataUri: blobToDataUri
  };

  var global$5 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var typeOf = function (x) {
    if (x === null)
      return 'null';
    var t = typeof x;
    if (t === 'object' && Array.prototype.isPrototypeOf(x))
      return 'array';
    if (t === 'object' && String.prototype.isPrototypeOf(x))
      return 'string';
    return t;
  };
  var isType = function (type) {
    return function (value) {
      return typeOf(value) === type;
    };
  };
  var $_8actkxcrjh8lz08z = {
    isString: isType('string'),
    isObject: isType('object'),
    isArray: isType('array'),
    isNull: isType('null'),
    isBoolean: isType('boolean'),
    isUndefined: isType('undefined'),
    isFunction: isType('function'),
    isNumber: isType('number')
  };

  var shallow = function (old, nu) {
    return nu;
  };
  var deep = function (old, nu) {
    var bothObjects = $_8actkxcrjh8lz08z.isObject(old) && $_8actkxcrjh8lz08z.isObject(nu);
    return bothObjects ? deepMerge(old, nu) : nu;
  };
  var baseMerge = function (merger) {
    return function () {
      var objects = new Array(arguments.length);
      for (var i = 0; i < objects.length; i++)
        objects[i] = arguments[i];
      if (objects.length === 0)
        throw new Error('Can\'t merge zero objects');
      var ret = {};
      for (var j = 0; j < objects.length; j++) {
        var curObject = objects[j];
        for (var key in curObject)
          if (curObject.hasOwnProperty(key)) {
            ret[key] = merger(ret[key], curObject[key]);
          }
      }
      return ret;
    };
  };
  var deepMerge = baseMerge(deep);
  var merge = baseMerge(shallow);
  var $_kivhlcqjh8lz08x = {
    deepMerge: deepMerge,
    merge: merge
  };

  var DOM = global$5.DOM;
  var getHspace = function (image) {
    if (image.style.marginLeft && image.style.marginRight && image.style.marginLeft === image.style.marginRight) {
      return $_5m5ooacejh8lz07v.removePixelSuffix(image.style.marginLeft);
    } else {
      return '';
    }
  };
  var getVspace = function (image) {
    if (image.style.marginTop && image.style.marginBottom && image.style.marginTop === image.style.marginBottom) {
      return $_5m5ooacejh8lz07v.removePixelSuffix(image.style.marginTop);
    } else {
      return '';
    }
  };
  var getBorder = function (image) {
    if (image.style.borderWidth) {
      return $_5m5ooacejh8lz07v.removePixelSuffix(image.style.borderWidth);
    } else {
      return '';
    }
  };
  var getAttrib = function (image, name) {
    if (image.hasAttribute(name)) {
      return image.getAttribute(name);
    } else {
      return '';
    }
  };
  var getStyle = function (image, name) {
    return image.style[name] ? image.style[name] : '';
  };
  var hasCaption = function (image) {
    return image.parentNode !== null && image.parentNode.nodeName === 'FIGURE';
  };
  var setAttrib = function (image, name, value) {
    image.setAttribute(name, value);
  };
  var wrapInFigure = function (image) {
    var figureElm = DOM.create('figure', { class: 'image' });
    DOM.insertAfter(figureElm, image);
    figureElm.appendChild(image);
    figureElm.appendChild(DOM.create('figcaption', { contentEditable: true }, 'Caption'));
    figureElm.contentEditable = 'false';
  };
  var removeFigure = function (image) {
    var figureElm = image.parentNode;
    DOM.insertAfter(image, figureElm);
    DOM.remove(figureElm);
  };
  var toggleCaption = function (image) {
    if (hasCaption(image)) {
      removeFigure(image);
    } else {
      wrapInFigure(image);
    }
  };
  var normalizeStyle = function (image, normalizeCss) {
    var attrValue = image.getAttribute('style');
    var value = normalizeCss(attrValue !== null ? attrValue : '');
    if (value.length > 0) {
      image.setAttribute('style', value);
      image.setAttribute('data-mce-style', value);
    } else {
      image.removeAttribute('style');
    }
  };
  var setSize = function (name, normalizeCss) {
    return function (image, name, value) {
      if (image.style[name]) {
        image.style[name] = $_5m5ooacejh8lz07v.addPixelSuffix(value);
        normalizeStyle(image, normalizeCss);
      } else {
        setAttrib(image, name, value);
      }
    };
  };
  var getSize = function (image, name) {
    if (image.style[name]) {
      return $_5m5ooacejh8lz07v.removePixelSuffix(image.style[name]);
    } else {
      return getAttrib(image, name);
    }
  };
  var setHspace = function (image, value) {
    var pxValue = $_5m5ooacejh8lz07v.addPixelSuffix(value);
    image.style.marginLeft = pxValue;
    image.style.marginRight = pxValue;
  };
  var setVspace = function (image, value) {
    var pxValue = $_5m5ooacejh8lz07v.addPixelSuffix(value);
    image.style.marginTop = pxValue;
    image.style.marginBottom = pxValue;
  };
  var setBorder = function (image, value) {
    var pxValue = $_5m5ooacejh8lz07v.addPixelSuffix(value);
    image.style.borderWidth = pxValue;
  };
  var setBorderStyle = function (image, value) {
    image.style.borderStyle = value;
  };
  var getBorderStyle = function (image) {
    return getStyle(image, 'borderStyle');
  };
  var isFigure = function (elm) {
    return elm.nodeName === 'FIGURE';
  };
  var defaultData = function () {
    return {
      src: '',
      alt: '',
      title: '',
      width: '',
      height: '',
      class: '',
      style: '',
      caption: false,
      hspace: '',
      vspace: '',
      border: '',
      borderStyle: ''
    };
  };
  var getStyleValue = function (normalizeCss, data) {
    var image = document.createElement('img');
    setAttrib(image, 'style', data.style);
    if (getHspace(image) || data.hspace !== '') {
      setHspace(image, data.hspace);
    }
    if (getVspace(image) || data.vspace !== '') {
      setVspace(image, data.vspace);
    }
    if (getBorder(image) || data.border !== '') {
      setBorder(image, data.border);
    }
    if (getBorderStyle(image) || data.borderStyle !== '') {
      setBorderStyle(image, data.borderStyle);
    }
    return normalizeCss(image.getAttribute('style'));
  };
  var create = function (normalizeCss, data) {
    var image = document.createElement('img');
    write(normalizeCss, $_kivhlcqjh8lz08x.merge(data, { caption: false }), image);
    setAttrib(image, 'alt', data.alt);
    if (data.caption) {
      var figure = DOM.create('figure', { class: 'image' });
      figure.appendChild(image);
      figure.appendChild(DOM.create('figcaption', { contentEditable: true }, 'Caption'));
      figure.contentEditable = 'false';
      return figure;
    } else {
      return image;
    }
  };
  var read = function (normalizeCss, image) {
    return {
      src: getAttrib(image, 'src'),
      alt: getAttrib(image, 'alt'),
      title: getAttrib(image, 'title'),
      width: getSize(image, 'width'),
      height: getSize(image, 'height'),
      class: getAttrib(image, 'class'),
      style: normalizeCss(getAttrib(image, 'style')),
      caption: hasCaption(image),
      hspace: getHspace(image),
      vspace: getVspace(image),
      border: getBorder(image),
      borderStyle: getStyle(image, 'borderStyle')
    };
  };
  var updateProp = function (image, oldData, newData, name, set) {
    if (newData[name] !== oldData[name]) {
      set(image, name, newData[name]);
    }
  };
  var normalized = function (set, normalizeCss) {
    return function (image, name, value) {
      set(image, value);
      normalizeStyle(image, normalizeCss);
    };
  };
  var write = function (normalizeCss, newData, image) {
    var oldData = read(normalizeCss, image);
    updateProp(image, oldData, newData, 'caption', function (image, _name, _value) {
      return toggleCaption(image);
    });
    updateProp(image, oldData, newData, 'src', setAttrib);
    updateProp(image, oldData, newData, 'alt', setAttrib);
    updateProp(image, oldData, newData, 'title', setAttrib);
    updateProp(image, oldData, newData, 'width', setSize('width', normalizeCss));
    updateProp(image, oldData, newData, 'height', setSize('height', normalizeCss));
    updateProp(image, oldData, newData, 'class', setAttrib);
    updateProp(image, oldData, newData, 'style', normalized(function (image, value) {
      return setAttrib(image, 'style', value);
    }, normalizeCss));
    updateProp(image, oldData, newData, 'hspace', normalized(setHspace, normalizeCss));
    updateProp(image, oldData, newData, 'vspace', normalized(setVspace, normalizeCss));
    updateProp(image, oldData, newData, 'border', normalized(setBorder, normalizeCss));
    updateProp(image, oldData, newData, 'borderStyle', normalized(setBorderStyle, normalizeCss));
  };

  var normalizeCss = function (editor, cssText) {
    var css = editor.dom.styles.parse(cssText);
    var mergedCss = $_5m5ooacejh8lz07v.mergeMargins(css);
    var compressed = editor.dom.styles.parse(editor.dom.styles.serialize(mergedCss));
    return editor.dom.styles.serialize(compressed);
  };
  var getSelectedImage = function (editor) {
    var imgElm = editor.selection.getNode();
    var figureElm = editor.dom.getParent(imgElm, 'figure.image');
    if (figureElm) {
      return editor.dom.select('img', figureElm)[0];
    }
    if (imgElm && (imgElm.nodeName !== 'IMG' || imgElm.getAttribute('data-mce-object') || imgElm.getAttribute('data-mce-placeholder'))) {
      return null;
    }
    return imgElm;
  };
  var splitTextBlock = function (editor, figure) {
    var dom = editor.dom;
    var textBlock = dom.getParent(figure.parentNode, function (node) {
      return editor.schema.getTextBlockElements()[node.nodeName];
    });
    if (textBlock) {
      return dom.split(textBlock, figure);
    } else {
      return figure;
    }
  };
  var readImageDataFromSelection = function (editor) {
    var image = getSelectedImage(editor);
    return image ? read(function (css) {
      return normalizeCss(editor, css);
    }, image) : defaultData();
  };
  var insertImageAtCaret = function (editor, data) {
    var elm = create(function (css) {
      return normalizeCss(editor, css);
    }, data);
    editor.dom.setAttrib(elm, 'data-mce-id', '__mcenew');
    editor.focus();
    editor.selection.setContent(elm.outerHTML);
    var insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0];
    editor.dom.setAttrib(insertedElm, 'data-mce-id', null);
    if (isFigure(insertedElm)) {
      var figure = splitTextBlock(editor, insertedElm);
      editor.selection.select(figure);
    } else {
      editor.selection.select(insertedElm);
    }
  };
  var syncSrcAttr = function (editor, image) {
    editor.dom.setAttrib(image, 'src', image.getAttribute('src'));
  };
  var deleteImage = function (editor, image) {
    if (image) {
      var elm = editor.dom.is(image.parentNode, 'figure.image') ? image.parentNode : image;
      editor.dom.remove(elm);
      editor.focus();
      editor.nodeChanged();
      if (editor.dom.isEmpty(editor.getBody())) {
        editor.setContent('');
        editor.selection.setCursorLocation();
      }
    }
  };
  var writeImageDataToSelection = function (editor, data) {
    var image = getSelectedImage(editor);
    write(function (css) {
      return normalizeCss(editor, css);
    }, data, image);
    syncSrcAttr(editor, image);
    if (isFigure(image.parentNode)) {
      var figure = image.parentNode;
      splitTextBlock(editor, figure);
      editor.selection.select(image.parentNode);
    } else {
      editor.selection.select(image);
      $_5m5ooacejh8lz07v.waitLoadImage(editor, data, image);
    }
  };
  var insertOrUpdateImage = function (editor, data) {
    var image = getSelectedImage(editor);
    if (image) {
      if (data.src) {
        writeImageDataToSelection(editor, data);
      } else {
        deleteImage(editor, image);
      }
    } else if (data.src) {
      insertImageAtCaret(editor, data);
    }
  };

  var updateVSpaceHSpaceBorder = function (editor) {
    return function (evt) {
      var dom = editor.dom;
      var rootControl = evt.control.rootControl;
      if (!$_crxcnscdjh8lz07s.hasAdvTab(editor)) {
        return;
      }
      var data = rootControl.toJSON();
      var css = dom.parseStyle(data.style);
      rootControl.find('#vspace').value('');
      rootControl.find('#hspace').value('');
      css = $_5m5ooacejh8lz07v.mergeMargins(css);
      if (css['margin-top'] && css['margin-bottom'] || css['margin-right'] && css['margin-left']) {
        if (css['margin-top'] === css['margin-bottom']) {
          rootControl.find('#vspace').value($_5m5ooacejh8lz07v.removePixelSuffix(css['margin-top']));
        } else {
          rootControl.find('#vspace').value('');
        }
        if (css['margin-right'] === css['margin-left']) {
          rootControl.find('#hspace').value($_5m5ooacejh8lz07v.removePixelSuffix(css['margin-right']));
        } else {
          rootControl.find('#hspace').value('');
        }
      }
      if (css['border-width']) {
        rootControl.find('#border').value($_5m5ooacejh8lz07v.removePixelSuffix(css['border-width']));
      } else {
        rootControl.find('#border').value('');
      }
      if (css['border-style']) {
        rootControl.find('#borderStyle').value(css['border-style']);
      } else {
        rootControl.find('#borderStyle').value('');
      }
      rootControl.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css))));
    };
  };
  var updateStyle = function (editor, win) {
    win.find('#style').each(function (ctrl) {
      var value = getStyleValue(function (css) {
        return normalizeCss(editor, css);
      }, $_kivhlcqjh8lz08x.merge(defaultData(), win.toJSON()));
      ctrl.value(value);
    });
  };
  var makeTab = function (editor) {
    return {
      title: 'Advanced',
      type: 'form',
      pack: 'start',
      items: [
        {
          label: 'Style',
          name: 'style',
          type: 'textbox',
          onchange: updateVSpaceHSpaceBorder(editor)
        },
        {
          type: 'form',
          layout: 'grid',
          packV: 'start',
          columns: 2,
          padding: 0,
          defaults: {
            type: 'textbox',
            maxWidth: 50,
            onchange: function (evt) {
              updateStyle(editor, evt.control.rootControl);
            }
          },
          items: [
            {
              label: 'Vertical space',
              name: 'vspace'
            },
            {
              label: 'Border width',
              name: 'border'
            },
            {
              label: 'Horizontal space',
              name: 'hspace'
            },
            {
              label: 'Border style',
              type: 'listbox',
              name: 'borderStyle',
              width: 90,
              maxWidth: 90,
              onselect: function (evt) {
                updateStyle(editor, evt.control.rootControl);
              },
              values: [
                {
                  text: 'Select...',
                  value: ''
                },
                {
                  text: 'Solid',
                  value: 'solid'
                },
                {
                  text: 'Dotted',
                  value: 'dotted'
                },
                {
                  text: 'Dashed',
                  value: 'dashed'
                },
                {
                  text: 'Double',
                  value: 'double'
                },
                {
                  text: 'Groove',
                  value: 'groove'
                },
                {
                  text: 'Ridge',
                  value: 'ridge'
                },
                {
                  text: 'Inset',
                  value: 'inset'
                },
                {
                  text: 'Outset',
                  value: 'outset'
                },
                {
                  text: 'None',
                  value: 'none'
                },
                {
                  text: 'Hidden',
                  value: 'hidden'
                }
              ]
            }
          ]
        }
      ]
    };
  };
  var $_546vuxcmjh8lz08g = { makeTab: makeTab };

  var doSyncSize = function (widthCtrl, heightCtrl) {
    widthCtrl.state.set('oldVal', widthCtrl.value());
    heightCtrl.state.set('oldVal', heightCtrl.value());
  };
  var doSizeControls = function (win, f) {
    var widthCtrl = win.find('#width')[0];
    var heightCtrl = win.find('#height')[0];
    var constrained = win.find('#constrain')[0];
    if (widthCtrl && heightCtrl && constrained) {
      f(widthCtrl, heightCtrl, constrained.checked());
    }
  };
  var doUpdateSize = function (widthCtrl, heightCtrl, isContrained) {
    var oldWidth = widthCtrl.state.get('oldVal');
    var oldHeight = heightCtrl.state.get('oldVal');
    var newWidth = widthCtrl.value();
    var newHeight = heightCtrl.value();
    if (isContrained && oldWidth && oldHeight && newWidth && newHeight) {
      if (newWidth !== oldWidth) {
        newHeight = Math.round(newWidth / oldWidth * newHeight);
        if (!isNaN(newHeight)) {
          heightCtrl.value(newHeight);
        }
      } else {
        newWidth = Math.round(newHeight / oldHeight * newWidth);
        if (!isNaN(newWidth)) {
          widthCtrl.value(newWidth);
        }
      }
    }
    doSyncSize(widthCtrl, heightCtrl);
  };
  var syncSize = function (win) {
    doSizeControls(win, doSyncSize);
  };
  var updateSize = function (win) {
    doSizeControls(win, doUpdateSize);
  };
  var createUi = function () {
    var recalcSize = function (evt) {
      updateSize(evt.control.rootControl);
    };
    return {
      type: 'container',
      label: 'Dimensions',
      layout: 'flex',
      align: 'center',
      spacing: 5,
      items: [
        {
          name: 'width',
          type: 'textbox',
          maxLength: 5,
          size: 5,
          onchange: recalcSize,
          ariaLabel: 'Width'
        },
        {
          type: 'label',
          text: 'x'
        },
        {
          name: 'height',
          type: 'textbox',
          maxLength: 5,
          size: 5,
          onchange: recalcSize,
          ariaLabel: 'Height'
        },
        {
          name: 'constrain',
          type: 'checkbox',
          checked: true,
          text: 'Constrain proportions'
        }
      ]
    };
  };
  var $_8agebqctjh8lz094 = {
    createUi: createUi,
    syncSize: syncSize,
    updateSize: updateSize
  };

  var onSrcChange = function (evt, editor) {
    var srcURL, prependURL, absoluteURLPattern;
    var meta = evt.meta || {};
    var control = evt.control;
    var rootControl = control.rootControl;
    var imageListCtrl = rootControl.find('#image-list')[0];
    if (imageListCtrl) {
      imageListCtrl.value(editor.convertURL(control.value(), 'src'));
    }
    global$3.each(meta, function (value, key) {
      rootControl.find('#' + key).value(value);
    });
    if (!meta.width && !meta.height) {
      srcURL = editor.convertURL(control.value(), 'src');
      prependURL = $_crxcnscdjh8lz07s.getPrependUrl(editor);
      absoluteURLPattern = new RegExp('^(?:[a-z]+:)?//', 'i');
      if (prependURL && !absoluteURLPattern.test(srcURL) && srcURL.substring(0, prependURL.length) !== prependURL) {
        srcURL = prependURL + srcURL;
      }
      control.value(srcURL);
      $_5m5ooacejh8lz07v.getImageSize(editor.documentBaseURI.toAbsolute(control.value()), function (data) {
        if (data.width && data.height && $_crxcnscdjh8lz07s.hasDimensions(editor)) {
          rootControl.find('#width').value(data.width);
          rootControl.find('#height').value(data.height);
          $_8agebqctjh8lz094.syncSize(rootControl);
        }
      });
    }
  };
  var onBeforeCall = function (evt) {
    evt.meta = evt.control.rootControl.toJSON();
  };
  var getGeneralItems = function (editor, imageListCtrl) {
    var generalFormItems = [
      {
        name: 'src',
        type: 'filepicker',
        filetype: 'image',
        label: 'Source',
        autofocus: true,
        onchange: function (evt) {
          onSrcChange(evt, editor);
        },
        onbeforecall: onBeforeCall
      },
      imageListCtrl
    ];
    if ($_crxcnscdjh8lz07s.hasDescription(editor)) {
      generalFormItems.push({
        name: 'alt',
        type: 'textbox',
        label: 'Image description'
      });
    }
    if ($_crxcnscdjh8lz07s.hasImageTitle(editor)) {
      generalFormItems.push({
        name: 'title',
        type: 'textbox',
        label: 'Image Title'
      });
    }
    if ($_crxcnscdjh8lz07s.hasDimensions(editor)) {
      generalFormItems.push($_8agebqctjh8lz094.createUi());
    }
    if ($_crxcnscdjh8lz07s.getClassList(editor)) {
      generalFormItems.push({
        name: 'class',
        type: 'listbox',
        label: 'Class',
        values: $_5m5ooacejh8lz07v.buildListItems($_crxcnscdjh8lz07s.getClassList(editor), function (item) {
          if (item.value) {
            item.textStyle = function () {
              return editor.formatter.getCssText({
                inline: 'img',
                classes: [item.value]
              });
            };
          }
        })
      });
    }
    if ($_crxcnscdjh8lz07s.hasImageCaption(editor)) {
      generalFormItems.push({
        name: 'caption',
        type: 'checkbox',
        label: 'Caption'
      });
    }
    return generalFormItems;
  };
  var makeTab$1 = function (editor, imageListCtrl) {
    return {
      title: 'General',
      type: 'form',
      items: getGeneralItems(editor, imageListCtrl)
    };
  };
  var $_586d0gcsjh8lz091 = {
    makeTab: makeTab$1,
    getGeneralItems: getGeneralItems
  };

  var url = function () {
    return $_8d9gbscgjh8lz089.getOrDie('URL');
  };
  var createObjectURL = function (blob) {
    return url().createObjectURL(blob);
  };
  var revokeObjectURL = function (u) {
    url().revokeObjectURL(u);
  };
  var $_61yp4wcvjh8lz09b = {
    createObjectURL: createObjectURL,
    revokeObjectURL: revokeObjectURL
  };

  var global$6 = tinymce.util.Tools.resolve('tinymce.ui.Factory');

  function XMLHttpRequest () {
    var f = $_8d9gbscgjh8lz089.getOrDie('XMLHttpRequest');
    return new f();
  }

  var noop = function () {
  };
  var pathJoin = function (path1, path2) {
    if (path1) {
      return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
    }
    return path2;
  };
  function Uploader (settings) {
    var defaultHandler = function (blobInfo, success, failure, progress) {
      var xhr, formData;
      xhr = new XMLHttpRequest();
      xhr.open('POST', settings.url);
      xhr.withCredentials = settings.credentials;
      xhr.upload.onprogress = function (e) {
        progress(e.loaded / e.total * 100);
      };
      xhr.onerror = function () {
        failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
      };
      xhr.onload = function () {
        var json;
        if (xhr.status < 200 || xhr.status >= 300) {
          failure('HTTP Error: ' + xhr.status);
          return;
        }
        json = JSON.parse(xhr.responseText);
        if (!json || typeof json.location !== 'string') {
          failure('Invalid JSON: ' + xhr.responseText);
          return;
        }
        success(pathJoin(settings.basePath, json.location));
      };
      formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());
      xhr.send(formData);
    };
    var uploadBlob = function (blobInfo, handler) {
      return new global$2(function (resolve, reject) {
        try {
          handler(blobInfo, resolve, reject, noop);
        } catch (ex) {
          reject(ex.message);
        }
      });
    };
    var isDefaultHandler = function (handler) {
      return handler === defaultHandler;
    };
    var upload = function (blobInfo) {
      return !settings.url && isDefaultHandler(settings.handler) ? global$2.reject('Upload url missing from the settings.') : uploadBlob(blobInfo, settings.handler);
    };
    settings = global$3.extend({
      credentials: false,
      handler: defaultHandler
    }, settings);
    return { upload: upload };
  }

  var onFileInput = function (editor) {
    return function (evt) {
      var Throbber = global$6.get('Throbber');
      var rootControl = evt.control.rootControl;
      var throbber = new Throbber(rootControl.getEl());
      var file = evt.control.value();
      var blobUri = $_61yp4wcvjh8lz09b.createObjectURL(file);
      var uploader = Uploader({
        url: $_crxcnscdjh8lz07s.getUploadUrl(editor),
        basePath: $_crxcnscdjh8lz07s.getUploadBasePath(editor),
        credentials: $_crxcnscdjh8lz07s.getUploadCredentials(editor),
        handler: $_crxcnscdjh8lz07s.getUploadHandler(editor)
      });
      var finalize = function () {
        throbber.hide();
        $_61yp4wcvjh8lz09b.revokeObjectURL(blobUri);
      };
      throbber.show();
      return $_5m5ooacejh8lz07v.blobToDataUri(file).then(function (dataUrl) {
        var blobInfo = editor.editorUpload.blobCache.create({
          blob: file,
          blobUri: blobUri,
          name: file.name ? file.name.replace(/\.[^\.]+$/, '') : null,
          base64: dataUrl.split(',')[1]
        });
        return uploader.upload(blobInfo).then(function (url) {
          var src = rootControl.find('#src');
          src.value(url);
          rootControl.find('tabpanel')[0].activateTab(0);
          src.fire('change');
          finalize();
          return url;
        });
      }).catch(function (err) {
        editor.windowManager.alert(err);
        finalize();
      });
    };
  };
  var acceptExts = '.jpg,.jpeg,.png,.gif';
  var makeTab$2 = function (editor) {
    return {
      title: 'Upload',
      type: 'form',
      layout: 'flex',
      direction: 'column',
      align: 'stretch',
      padding: '20 20 20 20',
      items: [
        {
          type: 'container',
          layout: 'flex',
          direction: 'column',
          align: 'center',
          spacing: 10,
          items: [
            {
              text: 'Browse for an image',
              type: 'browsebutton',
              accept: acceptExts,
              onchange: onFileInput(editor)
            },
            {
              text: 'OR',
              type: 'label'
            }
          ]
        },
        {
          text: 'Drop an image here',
          type: 'dropzone',
          accept: acceptExts,
          height: 100,
          onchange: onFileInput(editor)
        }
      ]
    };
  };
  var $_3w774acujh8lz097 = { makeTab: makeTab$2 };

  var noop$1 = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
  };
  var noarg = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return f();
    };
  };
  var compose = function (fa, fb) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return fa(fb.apply(null, arguments));
    };
  };
  var constant = function (value) {
    return function () {
      return value;
    };
  };
  var identity = function (x) {
    return x;
  };
  var tripleEquals = function (a, b) {
    return a === b;
  };
  var curry = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = new Array(arguments.length - 1);
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      var newArgs = new Array(arguments.length);
      for (var j = 0; j < newArgs.length; j++)
        newArgs[j] = arguments[j];
      var all = args.concat(newArgs);
      return f.apply(null, all);
    };
  };
  var not = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return !f.apply(null, arguments);
    };
  };
  var die = function (msg) {
    return function () {
      throw new Error(msg);
    };
  };
  var apply = function (f) {
    return f();
  };
  var call = function (f) {
    f();
  };
  var never = constant(false);
  var always = constant(true);
  var $_8rhdleczjh8lz09i = {
    noop: noop$1,
    noarg: noarg,
    compose: compose,
    constant: constant,
    identity: identity,
    tripleEquals: tripleEquals,
    curry: curry,
    not: not,
    die: die,
    apply: apply,
    call: call,
    never: never,
    always: always
  };

  var submitForm = function (editor, evt) {
    var win = evt.control.getRoot();
    $_8agebqctjh8lz094.updateSize(win);
    editor.undoManager.transact(function () {
      var data = $_kivhlcqjh8lz08x.merge(readImageDataFromSelection(editor), win.toJSON());
      insertOrUpdateImage(editor, data);
    });
    editor.editorUpload.uploadImagesAuto();
  };
  function Dialog (editor) {
    function showDialog(imageList) {
      var data = readImageDataFromSelection(editor);
      var win, imageListCtrl;
      if (imageList) {
        imageListCtrl = {
          type: 'listbox',
          label: 'Image list',
          name: 'image-list',
          values: $_5m5ooacejh8lz07v.buildListItems(imageList, function (item) {
            item.value = editor.convertURL(item.value || item.url, 'src');
          }, [{
              text: 'None',
              value: ''
            }]),
          value: data.src && editor.convertURL(data.src, 'src'),
          onselect: function (e) {
            var altCtrl = win.find('#alt');
            if (!altCtrl.value() || e.lastControl && altCtrl.value() === e.lastControl.text()) {
              altCtrl.value(e.control.text());
            }
            win.find('#src').value(e.control.value()).fire('change');
          },
          onPostRender: function () {
            imageListCtrl = this;
          }
        };
      }
      if ($_crxcnscdjh8lz07s.hasAdvTab(editor) || $_crxcnscdjh8lz07s.hasUploadUrl(editor) || $_crxcnscdjh8lz07s.hasUploadHandler(editor)) {
        var body = [$_586d0gcsjh8lz091.makeTab(editor, imageListCtrl)];
        if ($_crxcnscdjh8lz07s.hasAdvTab(editor)) {
          body.push($_546vuxcmjh8lz08g.makeTab(editor));
        }
        if ($_crxcnscdjh8lz07s.hasUploadUrl(editor) || $_crxcnscdjh8lz07s.hasUploadHandler(editor)) {
          body.push($_3w774acujh8lz097.makeTab(editor));
        }
        win = editor.windowManager.open({
          title: 'Insert/edit image',
          data: data,
          bodyType: 'tabpanel',
          body: body,
          onSubmit: $_8rhdleczjh8lz09i.curry(submitForm, editor)
        });
      } else {
        win = editor.windowManager.open({
          title: 'Insert/edit image',
          data: data,
          body: $_586d0gcsjh8lz091.getGeneralItems(editor, imageListCtrl),
          onSubmit: $_8rhdleczjh8lz09i.curry(submitForm, editor)
        });
      }
      $_8agebqctjh8lz094.syncSize(win);
    }
    function open() {
      $_5m5ooacejh8lz07v.createImageList(editor, showDialog);
    }
    return { open: open };
  }

  var register = function (editor) {
    editor.addCommand('mceImage', Dialog(editor).open);
  };
  var $_4g83a6cbjh8lz07k = { register: register };

  var hasImageClass = function (node) {
    var className = node.attr('class');
    return className && /\bimage\b/.test(className);
  };
  var toggleContentEditableState = function (state) {
    return function (nodes) {
      var i = nodes.length, node;
      var toggleContentEditable = function (node) {
        node.attr('contenteditable', state ? 'true' : null);
      };
      while (i--) {
        node = nodes[i];
        if (hasImageClass(node)) {
          node.attr('contenteditable', state ? 'false' : null);
          global$3.each(node.getAll('figcaption'), toggleContentEditable);
        }
      }
    };
  };
  var setup = function (editor) {
    editor.on('preInit', function () {
      editor.parser.addNodeFilter('figure', toggleContentEditableState(true));
      editor.serializer.addNodeFilter('figure', toggleContentEditableState(false));
    });
  };
  var $_1om65pd0jh8lz09k = { setup: setup };

  var register$1 = function (editor) {
    editor.addButton('image', {
      icon: 'image',
      tooltip: 'Insert/edit image',
      onclick: Dialog(editor).open,
      stateSelector: 'img:not([data-mce-object],[data-mce-placeholder]),figure.image'
    });
    editor.addMenuItem('image', {
      icon: 'image',
      text: 'Image',
      onclick: Dialog(editor).open,
      context: 'insert',
      prependToContext: true
    });
  };
  var $_df3mmtd1jh8lz09m = { register: register$1 };

  global.add('image', function (editor) {
    $_1om65pd0jh8lz09k.setup(editor);
    $_df3mmtd1jh8lz09m.register(editor);
    $_4g83a6cbjh8lz07k.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-importcss", ["tinymce"], function() {
  return (function() {
(function () {
var importcss = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$2 = tinymce.util.Tools.resolve('tinymce.EditorManager');

  var global$3 = tinymce.util.Tools.resolve('tinymce.Env');

  var global$4 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var shouldMergeClasses = function (editor) {
    return editor.getParam('importcss_merge_classes');
  };
  var shouldImportExclusive = function (editor) {
    return editor.getParam('importcss_exclusive');
  };
  var getSelectorConverter = function (editor) {
    return editor.getParam('importcss_selector_converter');
  };
  var getSelectorFilter = function (editor) {
    return editor.getParam('importcss_selector_filter');
  };
  var getCssGroups = function (editor) {
    return editor.getParam('importcss_groups');
  };
  var shouldAppend = function (editor) {
    return editor.getParam('importcss_append');
  };
  var getFileFilter = function (editor) {
    return editor.getParam('importcss_file_filter');
  };
  var $_988pjferjh8lz0nn = {
    shouldMergeClasses: shouldMergeClasses,
    shouldImportExclusive: shouldImportExclusive,
    getSelectorConverter: getSelectorConverter,
    getSelectorFilter: getSelectorFilter,
    getCssGroups: getCssGroups,
    shouldAppend: shouldAppend,
    getFileFilter: getFileFilter
  };

  var removeCacheSuffix = function (url) {
    var cacheSuffix = global$3.cacheSuffix;
    if (typeof url === 'string') {
      url = url.replace('?' + cacheSuffix, '').replace('&' + cacheSuffix, '');
    }
    return url;
  };
  var isSkinContentCss = function (editor, href) {
    var settings = editor.settings, skin = settings.skin !== false ? settings.skin || 'lightgray' : false;
    if (skin) {
      var skinUrl = settings.skin_url ? editor.documentBaseURI.toAbsolute(settings.skin_url) : global$2.baseURL + '/skins/' + skin;
      return href === skinUrl + '/content' + (editor.inline ? '.inline' : '') + '.min.css';
    }
    return false;
  };
  var compileFilter = function (filter) {
    if (typeof filter === 'string') {
      return function (value) {
        return value.indexOf(filter) !== -1;
      };
    } else if (filter instanceof RegExp) {
      return function (value) {
        return filter.test(value);
      };
    }
    return filter;
  };
  var getSelectors = function (editor, doc, fileFilter) {
    var selectors = [], contentCSSUrls = {};
    function append(styleSheet, imported) {
      var href = styleSheet.href, rules;
      href = removeCacheSuffix(href);
      if (!href || !fileFilter(href, imported) || isSkinContentCss(editor, href)) {
        return;
      }
      global$4.each(styleSheet.imports, function (styleSheet) {
        append(styleSheet, true);
      });
      try {
        rules = styleSheet.cssRules || styleSheet.rules;
      } catch (e) {
      }
      global$4.each(rules, function (cssRule) {
        if (cssRule.styleSheet) {
          append(cssRule.styleSheet, true);
        } else if (cssRule.selectorText) {
          global$4.each(cssRule.selectorText.split(','), function (selector) {
            selectors.push(global$4.trim(selector));
          });
        }
      });
    }
    global$4.each(editor.contentCSS, function (url) {
      contentCSSUrls[url] = true;
    });
    if (!fileFilter) {
      fileFilter = function (href, imported) {
        return imported || contentCSSUrls[href];
      };
    }
    try {
      global$4.each(doc.styleSheets, function (styleSheet) {
        append(styleSheet);
      });
    } catch (e) {
    }
    return selectors;
  };
  var defaultConvertSelectorToFormat = function (editor, selectorText) {
    var format;
    var selector = /^(?:([a-z0-9\-_]+))?(\.[a-z0-9_\-\.]+)$/i.exec(selectorText);
    if (!selector) {
      return;
    }
    var elementName = selector[1];
    var classes = selector[2].substr(1).split('.').join(' ');
    var inlineSelectorElements = global$4.makeMap('a,img');
    if (selector[1]) {
      format = { title: selectorText };
      if (editor.schema.getTextBlockElements()[elementName]) {
        format.block = elementName;
      } else if (editor.schema.getBlockElements()[elementName] || inlineSelectorElements[elementName.toLowerCase()]) {
        format.selector = elementName;
      } else {
        format.inline = elementName;
      }
    } else if (selector[2]) {
      format = {
        inline: 'span',
        title: selectorText.substr(1),
        classes: classes
      };
    }
    if ($_988pjferjh8lz0nn.shouldMergeClasses(editor) !== false) {
      format.classes = classes;
    } else {
      format.attributes = { class: classes };
    }
    return format;
  };
  var getGroupsBySelector = function (groups, selector) {
    return global$4.grep(groups, function (group) {
      return !group.filter || group.filter(selector);
    });
  };
  var compileUserDefinedGroups = function (groups) {
    return global$4.map(groups, function (group) {
      return global$4.extend({}, group, {
        original: group,
        selectors: {},
        filter: compileFilter(group.filter),
        item: {
          text: group.title,
          menu: []
        }
      });
    });
  };
  var isExclusiveMode = function (editor, group) {
    return group === null || $_988pjferjh8lz0nn.shouldImportExclusive(editor) !== false;
  };
  var isUniqueSelector = function (editor, selector, group, globallyUniqueSelectors) {
    return !(isExclusiveMode(editor, group) ? selector in globallyUniqueSelectors : selector in group.selectors);
  };
  var markUniqueSelector = function (editor, selector, group, globallyUniqueSelectors) {
    if (isExclusiveMode(editor, group)) {
      globallyUniqueSelectors[selector] = true;
    } else {
      group.selectors[selector] = true;
    }
  };
  var convertSelectorToFormat = function (editor, plugin, selector, group) {
    var selectorConverter;
    if (group && group.selector_converter) {
      selectorConverter = group.selector_converter;
    } else if ($_988pjferjh8lz0nn.getSelectorConverter(editor)) {
      selectorConverter = $_988pjferjh8lz0nn.getSelectorConverter(editor);
    } else {
      selectorConverter = function () {
        return defaultConvertSelectorToFormat(editor, selector);
      };
    }
    return selectorConverter.call(plugin, selector, group);
  };
  var setup = function (editor) {
    editor.on('renderFormatsMenu', function (e) {
      var globallyUniqueSelectors = {};
      var selectorFilter = compileFilter($_988pjferjh8lz0nn.getSelectorFilter(editor)), ctrl = e.control;
      var groups = compileUserDefinedGroups($_988pjferjh8lz0nn.getCssGroups(editor));
      var processSelector = function (selector, group) {
        if (isUniqueSelector(editor, selector, group, globallyUniqueSelectors)) {
          markUniqueSelector(editor, selector, group, globallyUniqueSelectors);
          var format = convertSelectorToFormat(editor, editor.plugins.importcss, selector, group);
          if (format) {
            var formatName = format.name || global$1.DOM.uniqueId();
            editor.formatter.register(formatName, format);
            return global$4.extend({}, ctrl.settings.itemDefaults, {
              text: format.title,
              format: formatName
            });
          }
        }
        return null;
      };
      if (!$_988pjferjh8lz0nn.shouldAppend(editor)) {
        ctrl.items().remove();
      }
      global$4.each(getSelectors(editor, e.doc || editor.getDoc(), compileFilter($_988pjferjh8lz0nn.getFileFilter(editor))), function (selector) {
        if (selector.indexOf('.mce-') === -1) {
          if (!selectorFilter || selectorFilter(selector)) {
            var selectorGroups = getGroupsBySelector(groups, selector);
            if (selectorGroups.length > 0) {
              global$4.each(selectorGroups, function (group) {
                var menuItem = processSelector(selector, group);
                if (menuItem) {
                  group.item.menu.push(menuItem);
                }
              });
            } else {
              var menuItem = processSelector(selector, null);
              if (menuItem) {
                ctrl.add(menuItem);
              }
            }
          }
        }
      });
      global$4.each(groups, function (group) {
        if (group.item.menu.length > 0) {
          ctrl.add(group.item);
        }
      });
      e.control.renderNew();
    });
  };
  var $_82ojngemjh8lz0ng = {
    defaultConvertSelectorToFormat: defaultConvertSelectorToFormat,
    setup: setup
  };

  var get = function (editor) {
    var convertSelectorToFormat = function (selectorText) {
      return $_82ojngemjh8lz0ng.defaultConvertSelectorToFormat(editor, selectorText);
    };
    return { convertSelectorToFormat: convertSelectorToFormat };
  };
  var $_9svv1eeljh8lz0ne = { get: get };

  global.add('importcss', function (editor) {
    $_82ojngemjh8lz0ng.setup(editor);
    return $_9svv1eeljh8lz0ne.get(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-insertdatetime", ["tinymce"], function() {
  return (function() {
(function () {
var insertdatetime = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var getDateFormat = function (editor) {
    return editor.getParam('insertdatetime_dateformat', editor.translate('%Y-%m-%d'));
  };
  var getTimeFormat = function (editor) {
    return editor.getParam('insertdatetime_timeformat', editor.translate('%H:%M:%S'));
  };
  var getFormats = function (editor) {
    return editor.getParam('insertdatetime_formats', [
      '%H:%M:%S',
      '%Y-%m-%d',
      '%I:%M:%S %p',
      '%D'
    ]);
  };
  var getDefaultDateTime = function (editor) {
    var formats = getFormats(editor);
    return formats.length > 0 ? formats[0] : getTimeFormat(editor);
  };
  var shouldInsertTimeElement = function (editor) {
    return editor.getParam('insertdatetime_element', false);
  };
  var $_dx1d2uewjh8lz0ob = {
    getDateFormat: getDateFormat,
    getTimeFormat: getTimeFormat,
    getFormats: getFormats,
    getDefaultDateTime: getDefaultDateTime,
    shouldInsertTimeElement: shouldInsertTimeElement
  };

  var daysShort = 'Sun Mon Tue Wed Thu Fri Sat Sun'.split(' ');
  var daysLong = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' ');
  var monthsShort = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
  var monthsLong = 'January February March April May June July August September October November December'.split(' ');
  var addZeros = function (value, len) {
    value = '' + value;
    if (value.length < len) {
      for (var i = 0; i < len - value.length; i++) {
        value = '0' + value;
      }
    }
    return value;
  };
  var getDateTime = function (editor, fmt, date) {
    date = date || new Date();
    fmt = fmt.replace('%D', '%m/%d/%Y');
    fmt = fmt.replace('%r', '%I:%M:%S %p');
    fmt = fmt.replace('%Y', '' + date.getFullYear());
    fmt = fmt.replace('%y', '' + date.getYear());
    fmt = fmt.replace('%m', addZeros(date.getMonth() + 1, 2));
    fmt = fmt.replace('%d', addZeros(date.getDate(), 2));
    fmt = fmt.replace('%H', '' + addZeros(date.getHours(), 2));
    fmt = fmt.replace('%M', '' + addZeros(date.getMinutes(), 2));
    fmt = fmt.replace('%S', '' + addZeros(date.getSeconds(), 2));
    fmt = fmt.replace('%I', '' + ((date.getHours() + 11) % 12 + 1));
    fmt = fmt.replace('%p', '' + (date.getHours() < 12 ? 'AM' : 'PM'));
    fmt = fmt.replace('%B', '' + editor.translate(monthsLong[date.getMonth()]));
    fmt = fmt.replace('%b', '' + editor.translate(monthsShort[date.getMonth()]));
    fmt = fmt.replace('%A', '' + editor.translate(daysLong[date.getDay()]));
    fmt = fmt.replace('%a', '' + editor.translate(daysShort[date.getDay()]));
    fmt = fmt.replace('%%', '%');
    return fmt;
  };
  var updateElement = function (editor, timeElm, computerTime, userTime) {
    var newTimeElm = editor.dom.create('time', { datetime: computerTime }, userTime);
    timeElm.parentNode.insertBefore(newTimeElm, timeElm);
    editor.dom.remove(timeElm);
    editor.selection.select(newTimeElm, true);
    editor.selection.collapse(false);
  };
  var insertDateTime = function (editor, format) {
    if ($_dx1d2uewjh8lz0ob.shouldInsertTimeElement(editor)) {
      var userTime = getDateTime(editor, format);
      var computerTime = void 0;
      if (/%[HMSIp]/.test(format)) {
        computerTime = getDateTime(editor, '%Y-%m-%dT%H:%M');
      } else {
        computerTime = getDateTime(editor, '%Y-%m-%d');
      }
      var timeElm = editor.dom.getParent(editor.selection.getStart(), 'time');
      if (timeElm) {
        updateElement(editor, timeElm, computerTime, userTime);
      } else {
        editor.insertContent('<time datetime="' + computerTime + '">' + userTime + '</time>');
      }
    } else {
      editor.insertContent(getDateTime(editor, format));
    }
  };
  var $_6jlqe7exjh8lz0oc = {
    insertDateTime: insertDateTime,
    getDateTime: getDateTime
  };

  var register = function (editor) {
    editor.addCommand('mceInsertDate', function () {
      $_6jlqe7exjh8lz0oc.insertDateTime(editor, $_dx1d2uewjh8lz0ob.getDateFormat(editor));
    });
    editor.addCommand('mceInsertTime', function () {
      $_6jlqe7exjh8lz0oc.insertDateTime(editor, $_dx1d2uewjh8lz0ob.getTimeFormat(editor));
    });
  };
  var $_asxg6pevjh8lz0oa = { register: register };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var createMenuItems = function (editor, lastFormatState) {
    var formats = $_dx1d2uewjh8lz0ob.getFormats(editor);
    return global$1.map(formats, function (fmt) {
      return {
        text: $_6jlqe7exjh8lz0oc.getDateTime(editor, fmt),
        onclick: function () {
          lastFormatState.set(fmt);
          $_6jlqe7exjh8lz0oc.insertDateTime(editor, fmt);
        }
      };
    });
  };
  var register$1 = function (editor, lastFormatState) {
    var menuItems = createMenuItems(editor, lastFormatState);
    editor.addButton('insertdatetime', {
      type: 'splitbutton',
      title: 'Insert date/time',
      menu: menuItems,
      onclick: function () {
        var lastFormat = lastFormatState.get();
        $_6jlqe7exjh8lz0oc.insertDateTime(editor, lastFormat ? lastFormat : $_dx1d2uewjh8lz0ob.getDefaultDateTime(editor));
      }
    });
    editor.addMenuItem('insertdatetime', {
      icon: 'date',
      text: 'Date/time',
      menu: menuItems,
      context: 'insert'
    });
  };
  var $_3qv4wheyjh8lz0of = { register: register$1 };

  global.add('insertdatetime', function (editor) {
    var lastFormatState = Cell(null);
    $_asxg6pevjh8lz0oa.register(editor);
    $_3qv4wheyjh8lz0of.register(editor, lastFormatState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-legacyoutput", ["tinymce"], function() {
  return (function() {
(function () {
var legacyoutput = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var overrideFormats = function (editor) {
    var alignElements = 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', fontSizes = global$1.explode(editor.settings.font_size_style_values), schema = editor.schema;
    editor.formatter.register({
      alignleft: {
        selector: alignElements,
        attributes: { align: 'left' }
      },
      aligncenter: {
        selector: alignElements,
        attributes: { align: 'center' }
      },
      alignright: {
        selector: alignElements,
        attributes: { align: 'right' }
      },
      alignjustify: {
        selector: alignElements,
        attributes: { align: 'justify' }
      },
      bold: [
        {
          inline: 'b',
          remove: 'all'
        },
        {
          inline: 'strong',
          remove: 'all'
        },
        {
          inline: 'span',
          styles: { fontWeight: 'bold' }
        }
      ],
      italic: [
        {
          inline: 'i',
          remove: 'all'
        },
        {
          inline: 'em',
          remove: 'all'
        },
        {
          inline: 'span',
          styles: { fontStyle: 'italic' }
        }
      ],
      underline: [
        {
          inline: 'u',
          remove: 'all'
        },
        {
          inline: 'span',
          styles: { textDecoration: 'underline' },
          exact: true
        }
      ],
      strikethrough: [
        {
          inline: 'strike',
          remove: 'all'
        },
        {
          inline: 'span',
          styles: { textDecoration: 'line-through' },
          exact: true
        }
      ],
      fontname: {
        inline: 'font',
        attributes: { face: '%value' }
      },
      fontsize: {
        inline: 'font',
        attributes: {
          size: function (vars) {
            return global$1.inArray(fontSizes, vars.value) + 1;
          }
        }
      },
      forecolor: {
        inline: 'font',
        attributes: { color: '%value' }
      },
      hilitecolor: {
        inline: 'font',
        styles: { backgroundColor: '%value' }
      }
    });
    global$1.each('b,i,u,strike'.split(','), function (name) {
      schema.addValidElements(name + '[*]');
    });
    if (!schema.getElementRule('font')) {
      schema.addValidElements('font[face|size|color|style]');
    }
    global$1.each(alignElements.split(','), function (name) {
      var rule = schema.getElementRule(name);
      if (rule) {
        if (!rule.attributes.align) {
          rule.attributes.align = {};
          rule.attributesOrder.push('align');
        }
      }
    });
  };
  var setup = function (editor) {
    editor.settings.inline_styles = false;
    editor.on('init', function () {
      overrideFormats(editor);
    });
  };
  var $_1u3icsf2jh8lz0ov = { setup: setup };

  var register = function (editor) {
    editor.addButton('fontsizeselect', function () {
      var items = [], defaultFontsizeFormats = '8pt=1 10pt=2 12pt=3 14pt=4 18pt=5 24pt=6 36pt=7';
      var fontsizeFormats = editor.settings.fontsizeFormats || defaultFontsizeFormats;
      editor.$.each(fontsizeFormats.split(' '), function (i, item) {
        var text = item, value = item;
        var values = item.split('=');
        if (values.length > 1) {
          text = values[0];
          value = values[1];
        }
        items.push({
          text: text,
          value: value
        });
      });
      return {
        type: 'listbox',
        text: 'Font Sizes',
        tooltip: 'Font Sizes',
        values: items,
        fixedWidth: true,
        onPostRender: function () {
          var self = this;
          editor.on('NodeChange', function () {
            var fontElm;
            fontElm = editor.dom.getParent(editor.selection.getNode(), 'font');
            if (fontElm) {
              self.value(fontElm.size);
            } else {
              self.value('');
            }
          });
        },
        onclick: function (e) {
          if (e.control.settings.value) {
            editor.execCommand('FontSize', false, e.control.settings.value);
          }
        }
      };
    });
    editor.addButton('fontselect', function () {
      function createFormats(formats) {
        formats = formats.replace(/;$/, '').split(';');
        var i = formats.length;
        while (i--) {
          formats[i] = formats[i].split('=');
        }
        return formats;
      }
      var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats';
      var items = [], fonts = createFormats(editor.settings.font_formats || defaultFontsFormats);
      editor.$.each(fonts, function (i, font) {
        items.push({
          text: { raw: font[0] },
          value: font[1],
          textStyle: font[1].indexOf('dings') === -1 ? 'font-family:' + font[1] : ''
        });
      });
      return {
        type: 'listbox',
        text: 'Font Family',
        tooltip: 'Font Family',
        values: items,
        fixedWidth: true,
        onPostRender: function () {
          var self = this;
          editor.on('NodeChange', function () {
            var fontElm;
            fontElm = editor.dom.getParent(editor.selection.getNode(), 'font');
            if (fontElm) {
              self.value(fontElm.face);
            } else {
              self.value('');
            }
          });
        },
        onselect: function (e) {
          if (e.control.settings.value) {
            editor.execCommand('FontName', false, e.control.settings.value);
          }
        }
      };
    });
  };
  var $_qhv2kf4jh8lz0oy = { register: register };

  global.add('legacyoutput', function (editor) {
    $_1u3icsf2jh8lz0ov.setup(editor);
    $_qhv2kf4jh8lz0oy.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-link", ["tinymce"], function() {
  return (function() {
(function () {
var link = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var assumeExternalTargets = function (editorSettings) {
    return typeof editorSettings.link_assume_external_targets === 'boolean' ? editorSettings.link_assume_external_targets : false;
  };
  var hasContextToolbar = function (editorSettings) {
    return typeof editorSettings.link_context_toolbar === 'boolean' ? editorSettings.link_context_toolbar : false;
  };
  var getLinkList = function (editorSettings) {
    return editorSettings.link_list;
  };
  var hasDefaultLinkTarget = function (editorSettings) {
    return typeof editorSettings.default_link_target === 'string';
  };
  var getDefaultLinkTarget = function (editorSettings) {
    return editorSettings.default_link_target;
  };
  var getTargetList = function (editorSettings) {
    return editorSettings.target_list;
  };
  var setTargetList = function (editor, list) {
    editor.settings.target_list = list;
  };
  var shouldShowTargetList = function (editorSettings) {
    return getTargetList(editorSettings) !== false;
  };
  var getRelList = function (editorSettings) {
    return editorSettings.rel_list;
  };
  var hasRelList = function (editorSettings) {
    return getRelList(editorSettings) !== undefined;
  };
  var getLinkClassList = function (editorSettings) {
    return editorSettings.link_class_list;
  };
  var hasLinkClassList = function (editorSettings) {
    return getLinkClassList(editorSettings) !== undefined;
  };
  var shouldShowLinkTitle = function (editorSettings) {
    return editorSettings.link_title !== false;
  };
  var allowUnsafeLinkTarget = function (editorSettings) {
    return typeof editorSettings.allow_unsafe_link_target === 'boolean' ? editorSettings.allow_unsafe_link_target : false;
  };
  var $_4854y3fajh8lz0pg = {
    assumeExternalTargets: assumeExternalTargets,
    hasContextToolbar: hasContextToolbar,
    getLinkList: getLinkList,
    hasDefaultLinkTarget: hasDefaultLinkTarget,
    getDefaultLinkTarget: getDefaultLinkTarget,
    getTargetList: getTargetList,
    setTargetList: setTargetList,
    shouldShowTargetList: shouldShowTargetList,
    getRelList: getRelList,
    hasRelList: hasRelList,
    getLinkClassList: getLinkClassList,
    hasLinkClassList: hasLinkClassList,
    shouldShowLinkTitle: shouldShowLinkTitle,
    allowUnsafeLinkTarget: allowUnsafeLinkTarget
  };

  var global$2 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$3 = tinymce.util.Tools.resolve('tinymce.Env');

  var appendClickRemove = function (link, evt) {
    document.body.appendChild(link);
    link.dispatchEvent(evt);
    document.body.removeChild(link);
  };
  var open = function (url) {
    if (!global$3.ie || global$3.ie > 10) {
      var link = document.createElement('a');
      link.target = '_blank';
      link.href = url;
      link.rel = 'noreferrer noopener';
      var evt = document.createEvent('MouseEvents');
      evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      appendClickRemove(link, evt);
    } else {
      var win = window.open('', '_blank');
      if (win) {
        win.opener = null;
        var doc = win.document;
        doc.open();
        doc.write('<meta http-equiv="refresh" content="0; url=' + global$2.DOM.encode(url) + '">');
        doc.close();
      }
    }
  };
  var $_1rtozzfbjh8lz0po = { open: open };

  var global$4 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var toggleTargetRules = function (rel, isUnsafe) {
    var rules = ['noopener'];
    var newRel = rel ? rel.split(/\s+/) : [];
    var toString = function (rel) {
      return global$4.trim(rel.sort().join(' '));
    };
    var addTargetRules = function (rel) {
      rel = removeTargetRules(rel);
      return rel.length ? rel.concat(rules) : rules;
    };
    var removeTargetRules = function (rel) {
      return rel.filter(function (val) {
        return global$4.inArray(rules, val) === -1;
      });
    };
    newRel = isUnsafe ? addTargetRules(newRel) : removeTargetRules(newRel);
    return newRel.length ? toString(newRel) : null;
  };
  var trimCaretContainers = function (text) {
    return text.replace(/\uFEFF/g, '');
  };
  var getAnchorElement = function (editor, selectedElm) {
    selectedElm = selectedElm || editor.selection.getNode();
    if (isImageFigure(selectedElm)) {
      return editor.dom.select('a[href]', selectedElm)[0];
    } else {
      return editor.dom.getParent(selectedElm, 'a[href]');
    }
  };
  var getAnchorText = function (selection, anchorElm) {
    var text = anchorElm ? anchorElm.innerText || anchorElm.textContent : selection.getContent({ format: 'text' });
    return trimCaretContainers(text);
  };
  var isLink = function (elm) {
    return elm && elm.nodeName === 'A' && elm.href;
  };
  var hasLinks = function (elements) {
    return global$4.grep(elements, isLink).length > 0;
  };
  var isOnlyTextSelected = function (html) {
    if (/</.test(html) && (!/^<a [^>]+>[^<]+<\/a>$/.test(html) || html.indexOf('href=') === -1)) {
      return false;
    }
    return true;
  };
  var isImageFigure = function (node) {
    return node && node.nodeName === 'FIGURE' && /\bimage\b/i.test(node.className);
  };
  var link = function (editor, attachState) {
    return function (data) {
      editor.undoManager.transact(function () {
        var selectedElm = editor.selection.getNode();
        var anchorElm = getAnchorElement(editor, selectedElm);
        var linkAttrs = {
          href: data.href,
          target: data.target ? data.target : null,
          rel: data.rel ? data.rel : null,
          class: data.class ? data.class : null,
          title: data.title ? data.title : null
        };
        if (!$_4854y3fajh8lz0pg.hasRelList(editor.settings) && $_4854y3fajh8lz0pg.allowUnsafeLinkTarget(editor.settings) === false) {
          linkAttrs.rel = toggleTargetRules(linkAttrs.rel, linkAttrs.target === '_blank');
        }
        if (data.href === attachState.href) {
          attachState.attach();
          attachState = {};
        }
        if (anchorElm) {
          editor.focus();
          if (data.hasOwnProperty('text')) {
            if ('innerText' in anchorElm) {
              anchorElm.innerText = data.text;
            } else {
              anchorElm.textContent = data.text;
            }
          }
          editor.dom.setAttribs(anchorElm, linkAttrs);
          editor.selection.select(anchorElm);
          editor.undoManager.add();
        } else {
          if (isImageFigure(selectedElm)) {
            linkImageFigure(editor, selectedElm, linkAttrs);
          } else if (data.hasOwnProperty('text')) {
            editor.insertContent(editor.dom.createHTML('a', linkAttrs, editor.dom.encode(data.text)));
          } else {
            editor.execCommand('mceInsertLink', false, linkAttrs);
          }
        }
      });
    };
  };
  var unlink = function (editor) {
    return function () {
      editor.undoManager.transact(function () {
        var node = editor.selection.getNode();
        if (isImageFigure(node)) {
          unlinkImageFigure(editor, node);
        } else {
          editor.execCommand('unlink');
        }
      });
    };
  };
  var unlinkImageFigure = function (editor, fig) {
    var a, img;
    img = editor.dom.select('img', fig)[0];
    if (img) {
      a = editor.dom.getParents(img, 'a[href]', fig)[0];
      if (a) {
        a.parentNode.insertBefore(img, a);
        editor.dom.remove(a);
      }
    }
  };
  var linkImageFigure = function (editor, fig, attrs) {
    var a, img;
    img = editor.dom.select('img', fig)[0];
    if (img) {
      a = editor.dom.create('a', attrs);
      img.parentNode.insertBefore(a, img);
      a.appendChild(img);
    }
  };
  var $_542aayfejh8lz0pr = {
    link: link,
    unlink: unlink,
    isLink: isLink,
    hasLinks: hasLinks,
    isOnlyTextSelected: isOnlyTextSelected,
    getAnchorElement: getAnchorElement,
    getAnchorText: getAnchorText,
    toggleTargetRules: toggleTargetRules
  };

  var global$5 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var global$6 = tinymce.util.Tools.resolve('tinymce.util.XHR');

  var attachState = {};
  var createLinkList = function (editor, callback) {
    var linkList = $_4854y3fajh8lz0pg.getLinkList(editor.settings);
    if (typeof linkList === 'string') {
      global$6.send({
        url: linkList,
        success: function (text) {
          callback(editor, JSON.parse(text));
        }
      });
    } else if (typeof linkList === 'function') {
      linkList(function (list) {
        callback(editor, list);
      });
    } else {
      callback(editor, linkList);
    }
  };
  var buildListItems = function (inputList, itemCallback, startItems) {
    var appendItems = function (values, output) {
      output = output || [];
      global$4.each(values, function (item) {
        var menuItem = { text: item.text || item.title };
        if (item.menu) {
          menuItem.menu = appendItems(item.menu);
        } else {
          menuItem.value = item.value;
          if (itemCallback) {
            itemCallback(menuItem);
          }
        }
        output.push(menuItem);
      });
      return output;
    };
    return appendItems(inputList, startItems || []);
  };
  var delayedConfirm = function (editor, message, callback) {
    var rng = editor.selection.getRng();
    global$5.setEditorTimeout(editor, function () {
      editor.windowManager.confirm(message, function (state) {
        editor.selection.setRng(rng);
        callback(state);
      });
    });
  };
  var showDialog = function (editor, linkList) {
    var data = {};
    var selection = editor.selection;
    var dom = editor.dom;
    var anchorElm, initialText;
    var win, onlyText, textListCtrl, linkListCtrl, relListCtrl, targetListCtrl, classListCtrl, linkTitleCtrl, value;
    var linkListChangeHandler = function (e) {
      var textCtrl = win.find('#text');
      if (!textCtrl.value() || e.lastControl && textCtrl.value() === e.lastControl.text()) {
        textCtrl.value(e.control.text());
      }
      win.find('#href').value(e.control.value());
    };
    var buildAnchorListControl = function (url) {
      var anchorList = [];
      global$4.each(editor.dom.select('a:not([href])'), function (anchor) {
        var id = anchor.name || anchor.id;
        if (id) {
          anchorList.push({
            text: id,
            value: '#' + id,
            selected: url.indexOf('#' + id) !== -1
          });
        }
      });
      if (anchorList.length) {
        anchorList.unshift({
          text: 'None',
          value: ''
        });
        return {
          name: 'anchor',
          type: 'listbox',
          label: 'Anchors',
          values: anchorList,
          onselect: linkListChangeHandler
        };
      }
    };
    var updateText = function () {
      if (!initialText && onlyText && !data.text) {
        this.parent().parent().find('#text')[0].value(this.value());
      }
    };
    var urlChange = function (e) {
      var meta = e.meta || {};
      if (linkListCtrl) {
        linkListCtrl.value(editor.convertURL(this.value(), 'href'));
      }
      global$4.each(e.meta, function (value, key) {
        var inp = win.find('#' + key);
        if (key === 'text') {
          if (initialText.length === 0) {
            inp.value(value);
            data.text = value;
          }
        } else {
          inp.value(value);
        }
      });
      if (meta.attach) {
        attachState = {
          href: this.value(),
          attach: meta.attach
        };
      }
      if (!meta.text) {
        updateText.call(this);
      }
    };
    var onBeforeCall = function (e) {
      e.meta = win.toJSON();
    };
    onlyText = $_542aayfejh8lz0pr.isOnlyTextSelected(selection.getContent());
    anchorElm = $_542aayfejh8lz0pr.getAnchorElement(editor);
    data.text = initialText = $_542aayfejh8lz0pr.getAnchorText(editor.selection, anchorElm);
    data.href = anchorElm ? dom.getAttrib(anchorElm, 'href') : '';
    if (anchorElm) {
      data.target = dom.getAttrib(anchorElm, 'target');
    } else if ($_4854y3fajh8lz0pg.hasDefaultLinkTarget(editor.settings)) {
      data.target = $_4854y3fajh8lz0pg.getDefaultLinkTarget(editor.settings);
    }
    if (value = dom.getAttrib(anchorElm, 'rel')) {
      data.rel = value;
    }
    if (value = dom.getAttrib(anchorElm, 'class')) {
      data.class = value;
    }
    if (value = dom.getAttrib(anchorElm, 'title')) {
      data.title = value;
    }
    if (onlyText) {
      textListCtrl = {
        name: 'text',
        type: 'textbox',
        size: 40,
        label: 'Text to display',
        onchange: function () {
          data.text = this.value();
        }
      };
    }
    if (linkList) {
      linkListCtrl = {
        type: 'listbox',
        label: 'Link list',
        values: buildListItems(linkList, function (item) {
          item.value = editor.convertURL(item.value || item.url, 'href');
        }, [{
            text: 'None',
            value: ''
          }]),
        onselect: linkListChangeHandler,
        value: editor.convertURL(data.href, 'href'),
        onPostRender: function () {
          linkListCtrl = this;
        }
      };
    }
    if ($_4854y3fajh8lz0pg.shouldShowTargetList(editor.settings)) {
      if ($_4854y3fajh8lz0pg.getTargetList(editor.settings) === undefined) {
        $_4854y3fajh8lz0pg.setTargetList(editor, [
          {
            text: 'None',
            value: ''
          },
          {
            text: 'New window',
            value: '_blank'
          }
        ]);
      }
      targetListCtrl = {
        name: 'target',
        type: 'listbox',
        label: 'Target',
        values: buildListItems($_4854y3fajh8lz0pg.getTargetList(editor.settings))
      };
    }
    if ($_4854y3fajh8lz0pg.hasRelList(editor.settings)) {
      relListCtrl = {
        name: 'rel',
        type: 'listbox',
        label: 'Rel',
        values: buildListItems($_4854y3fajh8lz0pg.getRelList(editor.settings), function (item) {
          if ($_4854y3fajh8lz0pg.allowUnsafeLinkTarget(editor.settings) === false) {
            item.value = $_542aayfejh8lz0pr.toggleTargetRules(item.value, data.target === '_blank');
          }
        })
      };
    }
    if ($_4854y3fajh8lz0pg.hasLinkClassList(editor.settings)) {
      classListCtrl = {
        name: 'class',
        type: 'listbox',
        label: 'Class',
        values: buildListItems($_4854y3fajh8lz0pg.getLinkClassList(editor.settings), function (item) {
          if (item.value) {
            item.textStyle = function () {
              return editor.formatter.getCssText({
                inline: 'a',
                classes: [item.value]
              });
            };
          }
        })
      };
    }
    if ($_4854y3fajh8lz0pg.shouldShowLinkTitle(editor.settings)) {
      linkTitleCtrl = {
        name: 'title',
        type: 'textbox',
        label: 'Title',
        value: data.title
      };
    }
    win = editor.windowManager.open({
      title: 'Insert link',
      data: data,
      body: [
        {
          name: 'href',
          type: 'filepicker',
          filetype: 'file',
          size: 40,
          autofocus: true,
          label: 'Url',
          onchange: urlChange,
          onkeyup: updateText,
          onpaste: updateText,
          onbeforecall: onBeforeCall
        },
        textListCtrl,
        linkTitleCtrl,
        buildAnchorListControl(data.href),
        linkListCtrl,
        relListCtrl,
        targetListCtrl,
        classListCtrl
      ],
      onSubmit: function (e) {
        var assumeExternalTargets = $_4854y3fajh8lz0pg.assumeExternalTargets(editor.settings);
        var insertLink = $_542aayfejh8lz0pr.link(editor, attachState);
        var removeLink = $_542aayfejh8lz0pr.unlink(editor);
        var resultData = global$4.extend({}, data, e.data);
        var href = resultData.href;
        if (!href) {
          removeLink();
          return;
        }
        if (!onlyText || resultData.text === initialText) {
          delete resultData.text;
        }
        if (href.indexOf('@') > 0 && href.indexOf('//') === -1 && href.indexOf('mailto:') === -1) {
          delayedConfirm(editor, 'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?', function (state) {
            if (state) {
              resultData.href = 'mailto:' + href;
            }
            insertLink(resultData);
          });
          return;
        }
        if (assumeExternalTargets === true && !/^\w+:/i.test(href) || assumeExternalTargets === false && /^\s*www[\.|\d\.]/i.test(href)) {
          delayedConfirm(editor, 'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?', function (state) {
            if (state) {
              resultData.href = 'http://' + href;
            }
            insertLink(resultData);
          });
          return;
        }
        insertLink(resultData);
      }
    });
  };
  var open$1 = function (editor) {
    createLinkList(editor, showDialog);
  };
  var $_bsp827fgjh8lz0pw = { open: open$1 };

  var getLink = function (editor, elm) {
    return editor.dom.getParent(elm, 'a[href]');
  };
  var getSelectedLink = function (editor) {
    return getLink(editor, editor.selection.getStart());
  };
  var getHref = function (elm) {
    var href = elm.getAttribute('data-mce-href');
    return href ? href : elm.getAttribute('href');
  };
  var isContextMenuVisible = function (editor) {
    var contextmenu = editor.plugins.contextmenu;
    return contextmenu ? contextmenu.isContextMenuVisible() : false;
  };
  var hasOnlyAltModifier = function (e) {
    return e.altKey === true && e.shiftKey === false && e.ctrlKey === false && e.metaKey === false;
  };
  var gotoLink = function (editor, a) {
    if (a) {
      var href = getHref(a);
      if (/^#/.test(href)) {
        var targetEl = editor.$(href);
        if (targetEl.length) {
          editor.selection.scrollIntoView(targetEl[0], true);
        }
      } else {
        $_1rtozzfbjh8lz0po.open(a.href);
      }
    }
  };
  var openDialog = function (editor) {
    return function () {
      $_bsp827fgjh8lz0pw.open(editor);
    };
  };
  var gotoSelectedLink = function (editor) {
    return function () {
      gotoLink(editor, getSelectedLink(editor));
    };
  };
  var leftClickedOnAHref = function (editor) {
    return function (elm) {
      var sel, rng, node;
      if ($_4854y3fajh8lz0pg.hasContextToolbar(editor.settings) && !isContextMenuVisible(editor) && $_542aayfejh8lz0pr.isLink(elm)) {
        sel = editor.selection;
        rng = sel.getRng();
        node = rng.startContainer;
        if (node.nodeType === 3 && sel.isCollapsed() && rng.startOffset > 0 && rng.startOffset < node.data.length) {
          return true;
        }
      }
      return false;
    };
  };
  var setupGotoLinks = function (editor) {
    editor.on('click', function (e) {
      var link = getLink(editor, e.target);
      if (link && global$1.metaKeyPressed(e)) {
        e.preventDefault();
        gotoLink(editor, link);
      }
    });
    editor.on('keydown', function (e) {
      var link = getSelectedLink(editor);
      if (link && e.keyCode === 13 && hasOnlyAltModifier(e)) {
        e.preventDefault();
        gotoLink(editor, link);
      }
    });
  };
  var toggleActiveState = function (editor) {
    return function () {
      var self = this;
      editor.on('nodechange', function (e) {
        self.active(!editor.readonly && !!$_542aayfejh8lz0pr.getAnchorElement(editor, e.element));
      });
    };
  };
  var toggleViewLinkState = function (editor) {
    return function () {
      var self = this;
      var toggleVisibility = function (e) {
        if ($_542aayfejh8lz0pr.hasLinks(e.parents)) {
          self.show();
        } else {
          self.hide();
        }
      };
      if (!$_542aayfejh8lz0pr.hasLinks(editor.dom.getParents(editor.selection.getStart()))) {
        self.hide();
      }
      editor.on('nodechange', toggleVisibility);
      self.on('remove', function () {
        editor.off('nodechange', toggleVisibility);
      });
    };
  };
  var $_8d8mxaf8jh8lz0pd = {
    openDialog: openDialog,
    gotoSelectedLink: gotoSelectedLink,
    leftClickedOnAHref: leftClickedOnAHref,
    setupGotoLinks: setupGotoLinks,
    toggleActiveState: toggleActiveState,
    toggleViewLinkState: toggleViewLinkState
  };

  var register = function (editor) {
    editor.addCommand('mceLink', $_8d8mxaf8jh8lz0pd.openDialog(editor));
  };
  var $_3527iyf7jh8lz0pb = { register: register };

  var setup = function (editor) {
    editor.addShortcut('Meta+K', '', $_8d8mxaf8jh8lz0pd.openDialog(editor));
  };
  var $_fpyya7fjjh8lz0q4 = { setup: setup };

  var setupButtons = function (editor) {
    editor.addButton('link', {
      active: false,
      icon: 'link',
      tooltip: 'Insert/edit link',
      onclick: $_8d8mxaf8jh8lz0pd.openDialog(editor),
      onpostrender: $_8d8mxaf8jh8lz0pd.toggleActiveState(editor)
    });
    editor.addButton('unlink', {
      active: false,
      icon: 'unlink',
      tooltip: 'Remove link',
      onclick: $_542aayfejh8lz0pr.unlink(editor),
      onpostrender: $_8d8mxaf8jh8lz0pd.toggleActiveState(editor)
    });
    if (editor.addContextToolbar) {
      editor.addButton('openlink', {
        icon: 'newtab',
        tooltip: 'Open link',
        onclick: $_8d8mxaf8jh8lz0pd.gotoSelectedLink(editor)
      });
    }
  };
  var setupMenuItems = function (editor) {
    editor.addMenuItem('openlink', {
      text: 'Open link',
      icon: 'newtab',
      onclick: $_8d8mxaf8jh8lz0pd.gotoSelectedLink(editor),
      onPostRender: $_8d8mxaf8jh8lz0pd.toggleViewLinkState(editor),
      prependToContext: true
    });
    editor.addMenuItem('link', {
      icon: 'link',
      text: 'Link',
      shortcut: 'Meta+K',
      onclick: $_8d8mxaf8jh8lz0pd.openDialog(editor),
      stateSelector: 'a[href]',
      context: 'insert',
      prependToContext: true
    });
    editor.addMenuItem('unlink', {
      icon: 'unlink',
      text: 'Remove link',
      onclick: $_542aayfejh8lz0pr.unlink(editor),
      stateSelector: 'a[href]'
    });
  };
  var setupContextToolbars = function (editor) {
    if (editor.addContextToolbar) {
      editor.addContextToolbar($_8d8mxaf8jh8lz0pd.leftClickedOnAHref(editor), 'openlink | link unlink');
    }
  };
  var $_f27siffkjh8lz0q5 = {
    setupButtons: setupButtons,
    setupMenuItems: setupMenuItems,
    setupContextToolbars: setupContextToolbars
  };

  global.add('link', function (editor) {
    $_f27siffkjh8lz0q5.setupButtons(editor);
    $_f27siffkjh8lz0q5.setupMenuItems(editor);
    $_f27siffkjh8lz0q5.setupContextToolbars(editor);
    $_8d8mxaf8jh8lz0pd.setupGotoLinks(editor);
    $_3527iyf7jh8lz0pb.register(editor);
    $_fpyya7fjjh8lz0q4.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-lists", ["tinymce"], function() {
  return (function() {
(function () {
var lists = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.RangeUtils');

  var global$2 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');

  var global$3 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var global$4 = tinymce.util.Tools.resolve('tinymce.dom.BookmarkManager');

  var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var global$6 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var isTextNode = function (node) {
    return node && node.nodeType === 3;
  };
  var isListNode = function (node) {
    return node && /^(OL|UL|DL)$/.test(node.nodeName);
  };
  var isListItemNode = function (node) {
    return node && /^(LI|DT|DD)$/.test(node.nodeName);
  };
  var isTableCellNode = function (node) {
    return node && /^(TH|TD)$/.test(node.nodeName);
  };
  var isBr = function (node) {
    return node && node.nodeName === 'BR';
  };
  var isFirstChild = function (node) {
    return node.parentNode.firstChild === node;
  };
  var isLastChild = function (node) {
    return node.parentNode.lastChild === node;
  };
  var isTextBlock = function (editor, node) {
    return node && !!editor.schema.getTextBlockElements()[node.nodeName];
  };
  var isBlock = function (node, blockElements) {
    return node && node.nodeName in blockElements;
  };
  var isBogusBr = function (dom, node) {
    if (!isBr(node)) {
      return false;
    }
    if (dom.isBlock(node.nextSibling) && !isBr(node.previousSibling)) {
      return true;
    }
    return false;
  };
  var isEmpty = function (dom, elm, keepBookmarks) {
    var empty = dom.isEmpty(elm);
    if (keepBookmarks && dom.select('span[data-mce-type=bookmark]', elm).length > 0) {
      return false;
    }
    return empty;
  };
  var isChildOfBody = function (dom, elm) {
    return dom.isChildOf(elm, dom.getRoot());
  };
  var $_zhglffzjh8lz0s2 = {
    isTextNode: isTextNode,
    isListNode: isListNode,
    isListItemNode: isListItemNode,
    isTableCellNode: isTableCellNode,
    isBr: isBr,
    isFirstChild: isFirstChild,
    isLastChild: isLastChild,
    isTextBlock: isTextBlock,
    isBlock: isBlock,
    isBogusBr: isBogusBr,
    isEmpty: isEmpty,
    isChildOfBody: isChildOfBody
  };

  var getNormalizedEndPoint = function (container, offset) {
    var node = global$1.getNode(container, offset);
    if ($_zhglffzjh8lz0s2.isListItemNode(container) && $_zhglffzjh8lz0s2.isTextNode(node)) {
      var textNodeOffset = offset >= container.childNodes.length ? node.data.length : 0;
      return {
        container: node,
        offset: textNodeOffset
      };
    }
    return {
      container: container,
      offset: offset
    };
  };
  var normalizeRange = function (rng) {
    var outRng = rng.cloneRange();
    var rangeStart = getNormalizedEndPoint(rng.startContainer, rng.startOffset);
    outRng.setStart(rangeStart.container, rangeStart.offset);
    var rangeEnd = getNormalizedEndPoint(rng.endContainer, rng.endOffset);
    outRng.setEnd(rangeEnd.container, rangeEnd.offset);
    return outRng;
  };
  var $_83g2fsfyjh8lz0s0 = {
    getNormalizedEndPoint: getNormalizedEndPoint,
    normalizeRange: normalizeRange
  };

  var DOM = global$6.DOM;
  var createBookmark = function (rng) {
    var bookmark = {};
    var setupEndPoint = function (start) {
      var offsetNode, container, offset;
      container = rng[start ? 'startContainer' : 'endContainer'];
      offset = rng[start ? 'startOffset' : 'endOffset'];
      if (container.nodeType === 1) {
        offsetNode = DOM.create('span', { 'data-mce-type': 'bookmark' });
        if (container.hasChildNodes()) {
          offset = Math.min(offset, container.childNodes.length - 1);
          if (start) {
            container.insertBefore(offsetNode, container.childNodes[offset]);
          } else {
            DOM.insertAfter(offsetNode, container.childNodes[offset]);
          }
        } else {
          container.appendChild(offsetNode);
        }
        container = offsetNode;
        offset = 0;
      }
      bookmark[start ? 'startContainer' : 'endContainer'] = container;
      bookmark[start ? 'startOffset' : 'endOffset'] = offset;
    };
    setupEndPoint(true);
    if (!rng.collapsed) {
      setupEndPoint();
    }
    return bookmark;
  };
  var resolveBookmark = function (bookmark) {
    function restoreEndPoint(start) {
      var container, offset, node;
      var nodeIndex = function (container) {
        var node = container.parentNode.firstChild, idx = 0;
        while (node) {
          if (node === container) {
            return idx;
          }
          if (node.nodeType !== 1 || node.getAttribute('data-mce-type') !== 'bookmark') {
            idx++;
          }
          node = node.nextSibling;
        }
        return -1;
      };
      container = node = bookmark[start ? 'startContainer' : 'endContainer'];
      offset = bookmark[start ? 'startOffset' : 'endOffset'];
      if (!container) {
        return;
      }
      if (container.nodeType === 1) {
        offset = nodeIndex(container);
        container = container.parentNode;
        DOM.remove(node);
        if (!container.hasChildNodes() && DOM.isBlock(container)) {
          container.appendChild(DOM.create('br'));
        }
      }
      bookmark[start ? 'startContainer' : 'endContainer'] = container;
      bookmark[start ? 'startOffset' : 'endOffset'] = offset;
    }
    restoreEndPoint(true);
    restoreEndPoint();
    var rng = DOM.createRng();
    rng.setStart(bookmark.startContainer, bookmark.startOffset);
    if (bookmark.endContainer) {
      rng.setEnd(bookmark.endContainer, bookmark.endOffset);
    }
    return $_83g2fsfyjh8lz0s0.normalizeRange(rng);
  };
  var $_99hdjifxjh8lz0rx = {
    createBookmark: createBookmark,
    resolveBookmark: resolveBookmark
  };

  var DOM$1 = global$6.DOM;
  var normalizeList = function (dom, ul) {
    var sibling;
    var parentNode = ul.parentNode;
    if (parentNode.nodeName === 'LI' && parentNode.firstChild === ul) {
      sibling = parentNode.previousSibling;
      if (sibling && sibling.nodeName === 'LI') {
        sibling.appendChild(ul);
        if ($_zhglffzjh8lz0s2.isEmpty(dom, parentNode)) {
          DOM$1.remove(parentNode);
        }
      } else {
        DOM$1.setStyle(parentNode, 'listStyleType', 'none');
      }
    }
    if ($_zhglffzjh8lz0s2.isListNode(parentNode)) {
      sibling = parentNode.previousSibling;
      if (sibling && sibling.nodeName === 'LI') {
        sibling.appendChild(ul);
      }
    }
  };
  var normalizeLists = function (dom, element) {
    global$5.each(global$5.grep(dom.select('ol,ul', element)), function (ul) {
      normalizeList(dom, ul);
    });
  };
  var $_emx2czg0jh8lz0s4 = {
    normalizeList: normalizeList,
    normalizeLists: normalizeLists
  };

  var global$7 = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');

  var getParentList = function (editor) {
    var selectionStart = editor.selection.getStart(true);
    return editor.dom.getParent(selectionStart, 'OL,UL,DL', getClosestListRootElm(editor, selectionStart));
  };
  var isParentListSelected = function (parentList, selectedBlocks) {
    return parentList && selectedBlocks.length === 1 && selectedBlocks[0] === parentList;
  };
  var findSubLists = function (parentList) {
    return global$5.grep(parentList.querySelectorAll('ol,ul,dl'), function (elm) {
      return $_zhglffzjh8lz0s2.isListNode(elm);
    });
  };
  var getSelectedSubLists = function (editor) {
    var parentList = getParentList(editor);
    var selectedBlocks = editor.selection.getSelectedBlocks();
    if (isParentListSelected(parentList, selectedBlocks)) {
      return findSubLists(parentList);
    } else {
      return global$5.grep(selectedBlocks, function (elm) {
        return $_zhglffzjh8lz0s2.isListNode(elm) && parentList !== elm;
      });
    }
  };
  var findParentListItemsNodes = function (editor, elms) {
    var listItemsElms = global$5.map(elms, function (elm) {
      var parentLi = editor.dom.getParent(elm, 'li,dd,dt', getClosestListRootElm(editor, elm));
      return parentLi ? parentLi : elm;
    });
    return global$7.unique(listItemsElms);
  };
  var getSelectedListItems = function (editor) {
    var selectedBlocks = editor.selection.getSelectedBlocks();
    return global$5.grep(findParentListItemsNodes(editor, selectedBlocks), function (block) {
      return $_zhglffzjh8lz0s2.isListItemNode(block);
    });
  };
  var getClosestListRootElm = function (editor, elm) {
    var parentTableCell = editor.dom.getParents(elm, 'TD,TH');
    var root = parentTableCell.length > 0 ? parentTableCell[0] : editor.getBody();
    return root;
  };
  var $_ukg72g1jh8lz0s6 = {
    getParentList: getParentList,
    getSelectedSubLists: getSelectedSubLists,
    getSelectedListItems: getSelectedListItems,
    getClosestListRootElm: getClosestListRootElm
  };

  var global$8 = tinymce.util.Tools.resolve('tinymce.Env');

  var DOM$2 = global$6.DOM;
  var createNewTextBlock = function (editor, contentNode, blockName) {
    var node, textBlock;
    var fragment = DOM$2.createFragment();
    var hasContentNode;
    var blockElements = editor.schema.getBlockElements();
    if (editor.settings.forced_root_block) {
      blockName = blockName || editor.settings.forced_root_block;
    }
    if (blockName) {
      textBlock = DOM$2.create(blockName);
      if (textBlock.tagName === editor.settings.forced_root_block) {
        DOM$2.setAttribs(textBlock, editor.settings.forced_root_block_attrs);
      }
      if (!$_zhglffzjh8lz0s2.isBlock(contentNode.firstChild, blockElements)) {
        fragment.appendChild(textBlock);
      }
    }
    if (contentNode) {
      while (node = contentNode.firstChild) {
        var nodeName = node.nodeName;
        if (!hasContentNode && (nodeName !== 'SPAN' || node.getAttribute('data-mce-type') !== 'bookmark')) {
          hasContentNode = true;
        }
        if ($_zhglffzjh8lz0s2.isBlock(node, blockElements)) {
          fragment.appendChild(node);
          textBlock = null;
        } else {
          if (blockName) {
            if (!textBlock) {
              textBlock = DOM$2.create(blockName);
              fragment.appendChild(textBlock);
            }
            textBlock.appendChild(node);
          } else {
            fragment.appendChild(node);
          }
        }
      }
    }
    if (!editor.settings.forced_root_block) {
      fragment.appendChild(DOM$2.create('br'));
    } else {
      if (!hasContentNode && (!global$8.ie || global$8.ie > 10)) {
        textBlock.appendChild(DOM$2.create('br', { 'data-mce-bogus': '1' }));
      }
    }
    return fragment;
  };
  var $_doauksg4jh8lz0sb = { createNewTextBlock: createNewTextBlock };

  var DOM$3 = global$6.DOM;
  var splitList = function (editor, ul, li, newBlock) {
    var tmpRng, fragment, bookmarks, node;
    var removeAndKeepBookmarks = function (targetNode) {
      global$5.each(bookmarks, function (node) {
        targetNode.parentNode.insertBefore(node, li.parentNode);
      });
      DOM$3.remove(targetNode);
    };
    bookmarks = DOM$3.select('span[data-mce-type="bookmark"]', ul);
    newBlock = newBlock || $_doauksg4jh8lz0sb.createNewTextBlock(editor, li);
    tmpRng = DOM$3.createRng();
    tmpRng.setStartAfter(li);
    tmpRng.setEndAfter(ul);
    fragment = tmpRng.extractContents();
    for (node = fragment.firstChild; node; node = node.firstChild) {
      if (node.nodeName === 'LI' && editor.dom.isEmpty(node)) {
        DOM$3.remove(node);
        break;
      }
    }
    if (!editor.dom.isEmpty(fragment)) {
      DOM$3.insertAfter(fragment, ul);
    }
    DOM$3.insertAfter(newBlock, ul);
    if ($_zhglffzjh8lz0s2.isEmpty(editor.dom, li.parentNode)) {
      removeAndKeepBookmarks(li.parentNode);
    }
    DOM$3.remove(li);
    if ($_zhglffzjh8lz0s2.isEmpty(editor.dom, ul)) {
      DOM$3.remove(ul);
    }
  };
  var $_2pwmf9g3jh8lz0s9 = { splitList: splitList };

  var DOM$4 = global$6.DOM;
  var removeEmptyLi = function (dom, li) {
    if ($_zhglffzjh8lz0s2.isEmpty(dom, li)) {
      DOM$4.remove(li);
    }
  };
  var outdent = function (editor, li) {
    var ul = li.parentNode;
    var ulParent, newBlock;
    if (ul) {
      ulParent = ul.parentNode;
    } else {
      removeEmptyLi(editor.dom, li);
      return true;
    }
    if (ul === editor.getBody()) {
      return true;
    }
    if (li.nodeName === 'DD') {
      DOM$4.rename(li, 'DT');
      return true;
    }
    if ($_zhglffzjh8lz0s2.isFirstChild(li) && $_zhglffzjh8lz0s2.isLastChild(li)) {
      if (ulParent.nodeName === 'LI') {
        DOM$4.insertAfter(li, ulParent);
        removeEmptyLi(editor.dom, ulParent);
        DOM$4.remove(ul);
      } else if ($_zhglffzjh8lz0s2.isListNode(ulParent)) {
        DOM$4.remove(ul, true);
      } else {
        ulParent.insertBefore($_doauksg4jh8lz0sb.createNewTextBlock(editor, li), ul);
        DOM$4.remove(ul);
      }
      return true;
    } else if ($_zhglffzjh8lz0s2.isFirstChild(li)) {
      if (ulParent.nodeName === 'LI') {
        DOM$4.insertAfter(li, ulParent);
        li.appendChild(ul);
        removeEmptyLi(editor.dom, ulParent);
      } else if ($_zhglffzjh8lz0s2.isListNode(ulParent)) {
        ulParent.insertBefore(li, ul);
      } else {
        ulParent.insertBefore($_doauksg4jh8lz0sb.createNewTextBlock(editor, li), ul);
        DOM$4.remove(li);
      }
      return true;
    } else if ($_zhglffzjh8lz0s2.isLastChild(li)) {
      if (ulParent.nodeName === 'LI') {
        DOM$4.insertAfter(li, ulParent);
      } else if ($_zhglffzjh8lz0s2.isListNode(ulParent)) {
        DOM$4.insertAfter(li, ul);
      } else {
        DOM$4.insertAfter($_doauksg4jh8lz0sb.createNewTextBlock(editor, li), ul);
        DOM$4.remove(li);
      }
      return true;
    }
    if (ulParent.nodeName === 'LI') {
      ul = ulParent;
      newBlock = $_doauksg4jh8lz0sb.createNewTextBlock(editor, li, 'LI');
    } else if ($_zhglffzjh8lz0s2.isListNode(ulParent)) {
      newBlock = $_doauksg4jh8lz0sb.createNewTextBlock(editor, li, 'LI');
    } else {
      newBlock = $_doauksg4jh8lz0sb.createNewTextBlock(editor, li);
    }
    $_2pwmf9g3jh8lz0s9.splitList(editor, ul, li, newBlock);
    $_emx2czg0jh8lz0s4.normalizeLists(editor.dom, ul.parentNode);
    return true;
  };
  var outdentSelection = function (editor) {
    var listElements = $_ukg72g1jh8lz0s6.getSelectedListItems(editor);
    if (listElements.length) {
      var bookmark = $_99hdjifxjh8lz0rx.createBookmark(editor.selection.getRng());
      var i = void 0, y = void 0;
      var root = $_ukg72g1jh8lz0s6.getClosestListRootElm(editor, editor.selection.getStart(true));
      i = listElements.length;
      while (i--) {
        var node = listElements[i].parentNode;
        while (node && node !== root) {
          y = listElements.length;
          while (y--) {
            if (listElements[y] === node) {
              listElements.splice(i, 1);
              break;
            }
          }
          node = node.parentNode;
        }
      }
      for (i = 0; i < listElements.length; i++) {
        if (!outdent(editor, listElements[i]) && i === 0) {
          break;
        }
      }
      editor.selection.setRng($_99hdjifxjh8lz0rx.resolveBookmark(bookmark));
      editor.nodeChanged();
      return true;
    }
  };
  var $_7womq3fvjh8lz0ru = {
    outdent: outdent,
    outdentSelection: outdentSelection
  };

  var updateListStyle = function (dom, el, detail) {
    var type = detail['list-style-type'] ? detail['list-style-type'] : null;
    dom.setStyle(el, 'list-style-type', type);
  };
  var setAttribs = function (elm, attrs) {
    global$5.each(attrs, function (value, key) {
      elm.setAttribute(key, value);
    });
  };
  var updateListAttrs = function (dom, el, detail) {
    setAttribs(el, detail['list-attributes']);
    global$5.each(dom.select('li', el), function (li) {
      setAttribs(li, detail['list-item-attributes']);
    });
  };
  var updateListWithDetails = function (dom, el, detail) {
    updateListStyle(dom, el, detail);
    updateListAttrs(dom, el, detail);
  };
  var removeStyles = function (dom, element, styles) {
    global$5.each(styles, function (style) {
      return dom.setStyle(element, (_a = {}, _a[style] = '', _a));
      var _a;
    });
  };
  var getEndPointNode = function (editor, rng, start, root) {
    var container, offset;
    container = rng[start ? 'startContainer' : 'endContainer'];
    offset = rng[start ? 'startOffset' : 'endOffset'];
    if (container.nodeType === 1) {
      container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
    }
    if (!start && $_zhglffzjh8lz0s2.isBr(container.nextSibling)) {
      container = container.nextSibling;
    }
    while (container.parentNode !== root) {
      if ($_zhglffzjh8lz0s2.isTextBlock(editor, container)) {
        return container;
      }
      if (/^(TD|TH)$/.test(container.parentNode.nodeName)) {
        return container;
      }
      container = container.parentNode;
    }
    return container;
  };
  var getSelectedTextBlocks = function (editor, rng, root) {
    var textBlocks = [], dom = editor.dom;
    var startNode = getEndPointNode(editor, rng, true, root);
    var endNode = getEndPointNode(editor, rng, false, root);
    var block;
    var siblings = [];
    for (var node = startNode; node; node = node.nextSibling) {
      siblings.push(node);
      if (node === endNode) {
        break;
      }
    }
    global$5.each(siblings, function (node) {
      if ($_zhglffzjh8lz0s2.isTextBlock(editor, node)) {
        textBlocks.push(node);
        block = null;
        return;
      }
      if (dom.isBlock(node) || $_zhglffzjh8lz0s2.isBr(node)) {
        if ($_zhglffzjh8lz0s2.isBr(node)) {
          dom.remove(node);
        }
        block = null;
        return;
      }
      var nextSibling = node.nextSibling;
      if (global$4.isBookmarkNode(node)) {
        if ($_zhglffzjh8lz0s2.isTextBlock(editor, nextSibling) || !nextSibling && node.parentNode === root) {
          block = null;
          return;
        }
      }
      if (!block) {
        block = dom.create('p');
        node.parentNode.insertBefore(block, node);
        textBlocks.push(block);
      }
      block.appendChild(node);
    });
    return textBlocks;
  };
  var hasCompatibleStyle = function (dom, sib, detail) {
    var sibStyle = dom.getStyle(sib, 'list-style-type');
    var detailStyle = detail ? detail['list-style-type'] : '';
    detailStyle = detailStyle === null ? '' : detailStyle;
    return sibStyle === detailStyle;
  };
  var applyList = function (editor, listName, detail) {
    if (detail === void 0) {
      detail = {};
    }
    var rng = editor.selection.getRng(true);
    var bookmark;
    var listItemName = 'LI';
    var root = $_ukg72g1jh8lz0s6.getClosestListRootElm(editor, editor.selection.getStart(true));
    var dom = editor.dom;
    if (dom.getContentEditable(editor.selection.getNode()) === 'false') {
      return;
    }
    listName = listName.toUpperCase();
    if (listName === 'DL') {
      listItemName = 'DT';
    }
    bookmark = $_99hdjifxjh8lz0rx.createBookmark(rng);
    global$5.each(getSelectedTextBlocks(editor, rng, root), function (block) {
      var listBlock, sibling;
      sibling = block.previousSibling;
      if (sibling && $_zhglffzjh8lz0s2.isListNode(sibling) && sibling.nodeName === listName && hasCompatibleStyle(dom, sibling, detail)) {
        listBlock = sibling;
        block = dom.rename(block, listItemName);
        sibling.appendChild(block);
      } else {
        listBlock = dom.create(listName);
        block.parentNode.insertBefore(listBlock, block);
        listBlock.appendChild(block);
        block = dom.rename(block, listItemName);
      }
      removeStyles(dom, block, [
        'margin',
        'margin-right',
        'margin-bottom',
        'margin-left',
        'margin-top',
        'padding',
        'padding-right',
        'padding-bottom',
        'padding-left',
        'padding-top'
      ]);
      updateListWithDetails(dom, listBlock, detail);
      mergeWithAdjacentLists(editor.dom, listBlock);
    });
    editor.selection.setRng($_99hdjifxjh8lz0rx.resolveBookmark(bookmark));
  };
  var removeList = function (editor) {
    var bookmark = $_99hdjifxjh8lz0rx.createBookmark(editor.selection.getRng(true));
    var root = $_ukg72g1jh8lz0s6.getClosestListRootElm(editor, editor.selection.getStart(true));
    var listItems = $_ukg72g1jh8lz0s6.getSelectedListItems(editor);
    var emptyListItems = global$5.grep(listItems, function (li) {
      return editor.dom.isEmpty(li);
    });
    listItems = global$5.grep(listItems, function (li) {
      return !editor.dom.isEmpty(li);
    });
    global$5.each(emptyListItems, function (li) {
      if ($_zhglffzjh8lz0s2.isEmpty(editor.dom, li)) {
        $_7womq3fvjh8lz0ru.outdent(editor, li);
        return;
      }
    });
    global$5.each(listItems, function (li) {
      var node, rootList;
      if (li.parentNode === editor.getBody()) {
        return;
      }
      for (node = li; node && node !== root; node = node.parentNode) {
        if ($_zhglffzjh8lz0s2.isListNode(node)) {
          rootList = node;
        }
      }
      $_2pwmf9g3jh8lz0s9.splitList(editor, rootList, li);
      $_emx2czg0jh8lz0s4.normalizeLists(editor.dom, rootList.parentNode);
    });
    editor.selection.setRng($_99hdjifxjh8lz0rx.resolveBookmark(bookmark));
  };
  var isValidLists = function (list1, list2) {
    return list1 && list2 && $_zhglffzjh8lz0s2.isListNode(list1) && list1.nodeName === list2.nodeName;
  };
  var hasSameListStyle = function (dom, list1, list2) {
    var targetStyle = dom.getStyle(list1, 'list-style-type', true);
    var style = dom.getStyle(list2, 'list-style-type', true);
    return targetStyle === style;
  };
  var hasSameClasses = function (elm1, elm2) {
    return elm1.className === elm2.className;
  };
  var shouldMerge = function (dom, list1, list2) {
    return isValidLists(list1, list2) && hasSameListStyle(dom, list1, list2) && hasSameClasses(list1, list2);
  };
  var mergeWithAdjacentLists = function (dom, listBlock) {
    var sibling, node;
    sibling = listBlock.nextSibling;
    if (shouldMerge(dom, listBlock, sibling)) {
      while (node = sibling.firstChild) {
        listBlock.appendChild(node);
      }
      dom.remove(sibling);
    }
    sibling = listBlock.previousSibling;
    if (shouldMerge(dom, listBlock, sibling)) {
      while (node = sibling.lastChild) {
        listBlock.insertBefore(node, listBlock.firstChild);
      }
      dom.remove(sibling);
    }
  };
  var updateList = function (dom, list, listName, detail) {
    if (list.nodeName !== listName) {
      var newList = dom.rename(list, listName);
      updateListWithDetails(dom, newList, detail);
    } else {
      updateListWithDetails(dom, list, detail);
    }
  };
  var toggleMultipleLists = function (editor, parentList, lists, listName, detail) {
    if (parentList.nodeName === listName && !hasListStyleDetail(detail)) {
      removeList(editor);
    } else {
      var bookmark = $_99hdjifxjh8lz0rx.createBookmark(editor.selection.getRng(true));
      global$5.each([parentList].concat(lists), function (elm) {
        updateList(editor.dom, elm, listName, detail);
      });
      editor.selection.setRng($_99hdjifxjh8lz0rx.resolveBookmark(bookmark));
    }
  };
  var hasListStyleDetail = function (detail) {
    return 'list-style-type' in detail;
  };
  var toggleSingleList = function (editor, parentList, listName, detail) {
    if (parentList === editor.getBody()) {
      return;
    }
    if (parentList) {
      if (parentList.nodeName === listName && !hasListStyleDetail(detail)) {
        removeList(editor);
      } else {
        var bookmark = $_99hdjifxjh8lz0rx.createBookmark(editor.selection.getRng(true));
        updateListWithDetails(editor.dom, parentList, detail);
        mergeWithAdjacentLists(editor.dom, editor.dom.rename(parentList, listName));
        editor.selection.setRng($_99hdjifxjh8lz0rx.resolveBookmark(bookmark));
      }
    } else {
      applyList(editor, listName, detail);
    }
  };
  var toggleList = function (editor, listName, detail) {
    var parentList = $_ukg72g1jh8lz0s6.getParentList(editor);
    var selectedSubLists = $_ukg72g1jh8lz0s6.getSelectedSubLists(editor);
    detail = detail ? detail : {};
    if (parentList && selectedSubLists.length > 0) {
      toggleMultipleLists(editor, parentList, selectedSubLists, listName, detail);
    } else {
      toggleSingleList(editor, parentList, listName, detail);
    }
  };
  var $_8t3z1mfsjh8lz0rl = {
    toggleList: toggleList,
    removeList: removeList,
    mergeWithAdjacentLists: mergeWithAdjacentLists
  };

  var findNextCaretContainer = function (editor, rng, isForward, root) {
    var node = rng.startContainer;
    var offset = rng.startOffset;
    var nonEmptyBlocks, walker;
    if (node.nodeType === 3 && (isForward ? offset < node.data.length : offset > 0)) {
      return node;
    }
    nonEmptyBlocks = editor.schema.getNonEmptyElements();
    if (node.nodeType === 1) {
      node = global$1.getNode(node, offset);
    }
    walker = new global$2(node, root);
    if (isForward) {
      if ($_zhglffzjh8lz0s2.isBogusBr(editor.dom, node)) {
        walker.next();
      }
    }
    while (node = walker[isForward ? 'next' : 'prev2']()) {
      if (node.nodeName === 'LI' && !node.hasChildNodes()) {
        return node;
      }
      if (nonEmptyBlocks[node.nodeName]) {
        return node;
      }
      if (node.nodeType === 3 && node.data.length > 0) {
        return node;
      }
    }
  };
  var hasOnlyOneBlockChild = function (dom, elm) {
    var childNodes = elm.childNodes;
    return childNodes.length === 1 && !$_zhglffzjh8lz0s2.isListNode(childNodes[0]) && dom.isBlock(childNodes[0]);
  };
  var unwrapSingleBlockChild = function (dom, elm) {
    if (hasOnlyOneBlockChild(dom, elm)) {
      dom.remove(elm.firstChild, true);
    }
  };
  var moveChildren = function (dom, fromElm, toElm) {
    var node, targetElm;
    targetElm = hasOnlyOneBlockChild(dom, toElm) ? toElm.firstChild : toElm;
    unwrapSingleBlockChild(dom, fromElm);
    if (!$_zhglffzjh8lz0s2.isEmpty(dom, fromElm, true)) {
      while (node = fromElm.firstChild) {
        targetElm.appendChild(node);
      }
    }
  };
  var mergeLiElements = function (dom, fromElm, toElm) {
    var node, listNode;
    var ul = fromElm.parentNode;
    if (!$_zhglffzjh8lz0s2.isChildOfBody(dom, fromElm) || !$_zhglffzjh8lz0s2.isChildOfBody(dom, toElm)) {
      return;
    }
    if ($_zhglffzjh8lz0s2.isListNode(toElm.lastChild)) {
      listNode = toElm.lastChild;
    }
    if (ul === toElm.lastChild) {
      if ($_zhglffzjh8lz0s2.isBr(ul.previousSibling)) {
        dom.remove(ul.previousSibling);
      }
    }
    node = toElm.lastChild;
    if (node && $_zhglffzjh8lz0s2.isBr(node) && fromElm.hasChildNodes()) {
      dom.remove(node);
    }
    if ($_zhglffzjh8lz0s2.isEmpty(dom, toElm, true)) {
      dom.$(toElm).empty();
    }
    moveChildren(dom, fromElm, toElm);
    if (listNode) {
      toElm.appendChild(listNode);
    }
    dom.remove(fromElm);
    if ($_zhglffzjh8lz0s2.isEmpty(dom, ul) && ul !== dom.getRoot()) {
      dom.remove(ul);
    }
  };
  var mergeIntoEmptyLi = function (editor, fromLi, toLi) {
    editor.dom.$(toLi).empty();
    mergeLiElements(editor.dom, fromLi, toLi);
    editor.selection.setCursorLocation(toLi);
  };
  var mergeForward = function (editor, rng, fromLi, toLi) {
    var dom = editor.dom;
    if (dom.isEmpty(toLi)) {
      mergeIntoEmptyLi(editor, fromLi, toLi);
    } else {
      var bookmark = $_99hdjifxjh8lz0rx.createBookmark(rng);
      mergeLiElements(dom, fromLi, toLi);
      editor.selection.setRng($_99hdjifxjh8lz0rx.resolveBookmark(bookmark));
    }
  };
  var mergeBackward = function (editor, rng, fromLi, toLi) {
    var bookmark = $_99hdjifxjh8lz0rx.createBookmark(rng);
    mergeLiElements(editor.dom, fromLi, toLi);
    var resolvedBookmark = $_99hdjifxjh8lz0rx.resolveBookmark(bookmark);
    editor.selection.setRng(resolvedBookmark);
  };
  var backspaceDeleteFromListToListCaret = function (editor, isForward) {
    var dom = editor.dom, selection = editor.selection;
    var selectionStartElm = selection.getStart();
    var root = $_ukg72g1jh8lz0s6.getClosestListRootElm(editor, selectionStartElm);
    var li = dom.getParent(selection.getStart(), 'LI', root);
    var ul, rng, otherLi;
    if (li) {
      ul = li.parentNode;
      if (ul === editor.getBody() && $_zhglffzjh8lz0s2.isEmpty(dom, ul)) {
        return true;
      }
      rng = $_83g2fsfyjh8lz0s0.normalizeRange(selection.getRng(true));
      otherLi = dom.getParent(findNextCaretContainer(editor, rng, isForward, root), 'LI', root);
      if (otherLi && otherLi !== li) {
        if (isForward) {
          mergeForward(editor, rng, otherLi, li);
        } else {
          mergeBackward(editor, rng, li, otherLi);
        }
        return true;
      } else if (!otherLi) {
        if (!isForward && $_8t3z1mfsjh8lz0rl.removeList(editor)) {
          return true;
        }
      }
    }
    return false;
  };
  var removeBlock = function (dom, block, root) {
    var parentBlock = dom.getParent(block.parentNode, dom.isBlock, root);
    dom.remove(block);
    if (parentBlock && dom.isEmpty(parentBlock)) {
      dom.remove(parentBlock);
    }
  };
  var backspaceDeleteIntoListCaret = function (editor, isForward) {
    var dom = editor.dom;
    var selectionStartElm = editor.selection.getStart();
    var root = $_ukg72g1jh8lz0s6.getClosestListRootElm(editor, selectionStartElm);
    var block = dom.getParent(selectionStartElm, dom.isBlock, root);
    if (block && dom.isEmpty(block)) {
      var rng = $_83g2fsfyjh8lz0s0.normalizeRange(editor.selection.getRng(true));
      var otherLi_1 = dom.getParent(findNextCaretContainer(editor, rng, isForward, root), 'LI', root);
      if (otherLi_1) {
        editor.undoManager.transact(function () {
          removeBlock(dom, block, root);
          $_8t3z1mfsjh8lz0rl.mergeWithAdjacentLists(dom, otherLi_1.parentNode);
          editor.selection.select(otherLi_1, true);
          editor.selection.collapse(isForward);
        });
        return true;
      }
    }
    return false;
  };
  var backspaceDeleteCaret = function (editor, isForward) {
    return backspaceDeleteFromListToListCaret(editor, isForward) || backspaceDeleteIntoListCaret(editor, isForward);
  };
  var backspaceDeleteRange = function (editor) {
    var selectionStartElm = editor.selection.getStart();
    var root = $_ukg72g1jh8lz0s6.getClosestListRootElm(editor, selectionStartElm);
    var startListParent = editor.dom.getParent(selectionStartElm, 'LI,DT,DD', root);
    if (startListParent || $_ukg72g1jh8lz0s6.getSelectedListItems(editor).length > 0) {
      editor.undoManager.transact(function () {
        editor.execCommand('Delete');
        $_emx2czg0jh8lz0s4.normalizeLists(editor.dom, editor.getBody());
      });
      return true;
    }
    return false;
  };
  var backspaceDelete = function (editor, isForward) {
    return editor.selection.isCollapsed() ? backspaceDeleteCaret(editor, isForward) : backspaceDeleteRange(editor);
  };
  var setup = function (editor) {
    editor.on('keydown', function (e) {
      if (e.keyCode === global$3.BACKSPACE) {
        if (backspaceDelete(editor, false)) {
          e.preventDefault();
        }
      } else if (e.keyCode === global$3.DELETE) {
        if (backspaceDelete(editor, true)) {
          e.preventDefault();
        }
      }
    });
  };
  var $_fl6g5dfojh8lz0re = {
    setup: setup,
    backspaceDelete: backspaceDelete
  };

  var get = function (editor) {
    return {
      backspaceDelete: function (isForward) {
        $_fl6g5dfojh8lz0re.backspaceDelete(editor, isForward);
      }
    };
  };
  var $_fad7jdfnjh8lz0rb = { get: get };

  var DOM$5 = global$6.DOM;
  var mergeLists = function (from, to) {
    var node;
    if ($_zhglffzjh8lz0s2.isListNode(from)) {
      while (node = from.firstChild) {
        to.appendChild(node);
      }
      DOM$5.remove(from);
    }
  };
  var indent = function (li) {
    var sibling, newList, listStyle;
    if (li.nodeName === 'DT') {
      DOM$5.rename(li, 'DD');
      return true;
    }
    sibling = li.previousSibling;
    if (sibling && $_zhglffzjh8lz0s2.isListNode(sibling)) {
      sibling.appendChild(li);
      return true;
    }
    if (sibling && sibling.nodeName === 'LI' && $_zhglffzjh8lz0s2.isListNode(sibling.lastChild)) {
      sibling.lastChild.appendChild(li);
      mergeLists(li.lastChild, sibling.lastChild);
      return true;
    }
    sibling = li.nextSibling;
    if (sibling && $_zhglffzjh8lz0s2.isListNode(sibling)) {
      sibling.insertBefore(li, sibling.firstChild);
      return true;
    }
    sibling = li.previousSibling;
    if (sibling && sibling.nodeName === 'LI') {
      newList = DOM$5.create(li.parentNode.nodeName);
      listStyle = DOM$5.getStyle(li.parentNode, 'listStyleType');
      if (listStyle) {
        DOM$5.setStyle(newList, 'listStyleType', listStyle);
      }
      sibling.appendChild(newList);
      newList.appendChild(li);
      mergeLists(li.lastChild, newList);
      return true;
    }
    return false;
  };
  var indentSelection = function (editor) {
    var listElements = $_ukg72g1jh8lz0s6.getSelectedListItems(editor);
    if (listElements.length) {
      var bookmark = $_99hdjifxjh8lz0rx.createBookmark(editor.selection.getRng(true));
      for (var i = 0; i < listElements.length; i++) {
        if (!indent(listElements[i]) && i === 0) {
          break;
        }
      }
      editor.selection.setRng($_99hdjifxjh8lz0rx.resolveBookmark(bookmark));
      editor.nodeChanged();
      return true;
    }
  };
  var $_4rsk3ng7jh8lz0sg = { indentSelection: indentSelection };

  var queryListCommandState = function (editor, listName) {
    return function () {
      var parentList = editor.dom.getParent(editor.selection.getStart(), 'UL,OL,DL');
      return parentList && parentList.nodeName === listName;
    };
  };
  var register = function (editor) {
    editor.on('BeforeExecCommand', function (e) {
      var cmd = e.command.toLowerCase();
      var isHandled;
      if (cmd === 'indent') {
        if ($_4rsk3ng7jh8lz0sg.indentSelection(editor)) {
          isHandled = true;
        }
      } else if (cmd === 'outdent') {
        if ($_7womq3fvjh8lz0ru.outdentSelection(editor)) {
          isHandled = true;
        }
      }
      if (isHandled) {
        editor.fire('ExecCommand', { command: e.command });
        e.preventDefault();
        return true;
      }
    });
    editor.addCommand('InsertUnorderedList', function (ui, detail) {
      $_8t3z1mfsjh8lz0rl.toggleList(editor, 'UL', detail);
    });
    editor.addCommand('InsertOrderedList', function (ui, detail) {
      $_8t3z1mfsjh8lz0rl.toggleList(editor, 'OL', detail);
    });
    editor.addCommand('InsertDefinitionList', function (ui, detail) {
      $_8t3z1mfsjh8lz0rl.toggleList(editor, 'DL', detail);
    });
    editor.addQueryStateHandler('InsertUnorderedList', queryListCommandState(editor, 'UL'));
    editor.addQueryStateHandler('InsertOrderedList', queryListCommandState(editor, 'OL'));
    editor.addQueryStateHandler('InsertDefinitionList', queryListCommandState(editor, 'DL'));
  };
  var $_1ley1og6jh8lz0se = { register: register };

  var shouldIndentOnTab = function (editor) {
    return editor.getParam('lists_indent_on_tab', true);
  };
  var $_bkr9ckg9jh8lz0sk = { shouldIndentOnTab: shouldIndentOnTab };

  var setupTabKey = function (editor) {
    editor.on('keydown', function (e) {
      if (e.keyCode !== global$3.TAB || global$3.metaKeyPressed(e)) {
        return;
      }
      if (editor.dom.getParent(editor.selection.getStart(), 'LI,DT,DD')) {
        e.preventDefault();
        if (e.shiftKey) {
          $_7womq3fvjh8lz0ru.outdentSelection(editor);
        } else {
          $_4rsk3ng7jh8lz0sg.indentSelection(editor);
        }
      }
    });
  };
  var setup$1 = function (editor) {
    if ($_bkr9ckg9jh8lz0sk.shouldIndentOnTab(editor)) {
      setupTabKey(editor);
    }
    $_fl6g5dfojh8lz0re.setup(editor);
  };
  var $_2piq8jg8jh8lz0sj = { setup: setup$1 };

  var findIndex = function (list, predicate) {
    for (var index = 0; index < list.length; index++) {
      var element = list[index];
      if (predicate(element)) {
        return index;
      }
    }
    return -1;
  };
  var listState = function (editor, listName) {
    return function (e) {
      var ctrl = e.control;
      editor.on('NodeChange', function (e) {
        var tableCellIndex = findIndex(e.parents, $_zhglffzjh8lz0s2.isTableCellNode);
        var parents = tableCellIndex !== -1 ? e.parents.slice(0, tableCellIndex) : e.parents;
        var lists = global$5.grep(parents, $_zhglffzjh8lz0s2.isListNode);
        ctrl.active(lists.length > 0 && lists[0].nodeName === listName);
      });
    };
  };
  var indentPostRender = function (editor) {
    return function (e) {
      var ctrl = e.control;
      editor.on('nodechange', function () {
        var listItemBlocks = $_ukg72g1jh8lz0s6.getSelectedListItems(editor);
        var disable = listItemBlocks.length > 0 && $_zhglffzjh8lz0s2.isFirstChild(listItemBlocks[0]);
        ctrl.disabled(disable);
      });
    };
  };
  var register$1 = function (editor) {
    var hasPlugin = function (editor, plugin) {
      var plugins = editor.settings.plugins ? editor.settings.plugins : '';
      return global$5.inArray(plugins.split(/[ ,]/), plugin) !== -1;
    };
    if (!hasPlugin(editor, 'advlist')) {
      editor.addButton('numlist', {
        active: false,
        title: 'Numbered list',
        cmd: 'InsertOrderedList',
        onPostRender: listState(editor, 'OL')
      });
      editor.addButton('bullist', {
        active: false,
        title: 'Bullet list',
        cmd: 'InsertUnorderedList',
        onPostRender: listState(editor, 'UL')
      });
    }
    editor.addButton('indent', {
      icon: 'indent',
      title: 'Increase indent',
      cmd: 'Indent',
      onPostRender: indentPostRender(editor)
    });
  };
  var $_60ls25gajh8lz0sl = { register: register$1 };

  global.add('lists', function (editor) {
    $_2piq8jg8jh8lz0sj.setup(editor);
    $_60ls25gajh8lz0sl.register(editor);
    $_1ley1og6jh8lz0se.register(editor);
    return $_fad7jdfnjh8lz0rb.get(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-media", ["tinymce"], function() {
  return (function() {
(function () {
var media = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.Env');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var getScripts = function (editor) {
    return editor.getParam('media_scripts');
  };
  var getAudioTemplateCallback = function (editor) {
    return editor.getParam('audio_template_callback');
  };
  var getVideoTemplateCallback = function (editor) {
    return editor.getParam('video_template_callback');
  };
  var hasLiveEmbeds = function (editor) {
    return editor.getParam('media_live_embeds', true);
  };
  var shouldFilterHtml = function (editor) {
    return editor.getParam('media_filter_html', true);
  };
  var getUrlResolver = function (editor) {
    return editor.getParam('media_url_resolver');
  };
  var hasAltSource = function (editor) {
    return editor.getParam('media_alt_source', true);
  };
  var hasPoster = function (editor) {
    return editor.getParam('media_poster', true);
  };
  var hasDimensions = function (editor) {
    return editor.getParam('media_dimensions', true);
  };
  var $_bcg8bpghjh8lz0ut = {
    getScripts: getScripts,
    getAudioTemplateCallback: getAudioTemplateCallback,
    getVideoTemplateCallback: getVideoTemplateCallback,
    hasLiveEmbeds: hasLiveEmbeds,
    shouldFilterHtml: shouldFilterHtml,
    getUrlResolver: getUrlResolver,
    hasAltSource: hasAltSource,
    hasPoster: hasPoster,
    hasDimensions: hasDimensions
  };

  var global$3 = tinymce.util.Tools.resolve('tinymce.html.SaxParser');

  var global$4 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var getVideoScriptMatch = function (prefixes, src) {
    if (prefixes) {
      for (var i = 0; i < prefixes.length; i++) {
        if (src.indexOf(prefixes[i].filter) !== -1) {
          return prefixes[i];
        }
      }
    }
  };
  var $_a6mt9vgljh8lz0uz = { getVideoScriptMatch: getVideoScriptMatch };

  var trimPx = function (value) {
    return value.replace(/px$/, '');
  };
  var addPx = function (value) {
    return /^[0-9.]+$/.test(value) ? value + 'px' : value;
  };
  var getSize = function (name) {
    return function (elm) {
      return elm ? trimPx(elm.style[name]) : '';
    };
  };
  var setSize = function (name) {
    return function (elm, value) {
      if (elm) {
        elm.style[name] = addPx(value);
      }
    };
  };
  var $_g4vsn9gmjh8lz0v1 = {
    getMaxWidth: getSize('maxWidth'),
    getMaxHeight: getSize('maxHeight'),
    setMaxWidth: setSize('maxWidth'),
    setMaxHeight: setSize('maxHeight')
  };

  var DOM = global$4.DOM;
  var getEphoxEmbedIri = function (elm) {
    return DOM.getAttrib(elm, 'data-ephox-embed-iri');
  };
  var isEphoxEmbed = function (html) {
    var fragment = DOM.createFragment(html);
    return getEphoxEmbedIri(fragment.firstChild) !== '';
  };
  var htmlToDataSax = function (prefixes, html) {
    var data = {};
    global$3({
      validate: false,
      allow_conditional_comments: true,
      special: 'script,noscript',
      start: function (name, attrs) {
        if (!data.source1 && name === 'param') {
          data.source1 = attrs.map.movie;
        }
        if (name === 'iframe' || name === 'object' || name === 'embed' || name === 'video' || name === 'audio') {
          if (!data.type) {
            data.type = name;
          }
          data = global$2.extend(attrs.map, data);
        }
        if (name === 'script') {
          var videoScript = $_a6mt9vgljh8lz0uz.getVideoScriptMatch(prefixes, attrs.map.src);
          if (!videoScript) {
            return;
          }
          data = {
            type: 'script',
            source1: attrs.map.src,
            width: videoScript.width,
            height: videoScript.height
          };
        }
        if (name === 'source') {
          if (!data.source1) {
            data.source1 = attrs.map.src;
          } else if (!data.source2) {
            data.source2 = attrs.map.src;
          }
        }
        if (name === 'img' && !data.poster) {
          data.poster = attrs.map.src;
        }
      }
    }).parse(html);
    data.source1 = data.source1 || data.src || data.data;
    data.source2 = data.source2 || '';
    data.poster = data.poster || '';
    return data;
  };
  var ephoxEmbedHtmlToData = function (html) {
    var fragment = DOM.createFragment(html);
    var div = fragment.firstChild;
    return {
      type: 'ephox-embed-iri',
      source1: getEphoxEmbedIri(div),
      source2: '',
      poster: '',
      width: $_g4vsn9gmjh8lz0v1.getMaxWidth(div),
      height: $_g4vsn9gmjh8lz0v1.getMaxHeight(div)
    };
  };
  var htmlToData = function (prefixes, html) {
    return isEphoxEmbed(html) ? ephoxEmbedHtmlToData(html) : htmlToDataSax(prefixes, html);
  };
  var $_3nrb4rgijh8lz0uw = { htmlToData: htmlToData };

  var global$5 = tinymce.util.Tools.resolve('tinymce.util.Promise');

  var guess = function (url) {
    var mimes = {
      mp3: 'audio/mpeg',
      wav: 'audio/wav',
      mp4: 'video/mp4',
      webm: 'video/webm',
      ogg: 'video/ogg',
      swf: 'application/x-shockwave-flash'
    };
    var fileEnd = url.toLowerCase().split('.').pop();
    var mime = mimes[fileEnd];
    return mime ? mime : '';
  };
  var $_fbk2jcgqjh8lz0v8 = { guess: guess };

  var global$6 = tinymce.util.Tools.resolve('tinymce.html.Writer');

  var global$7 = tinymce.util.Tools.resolve('tinymce.html.Schema');

  var DOM$1 = global$4.DOM;
  var setAttributes = function (attrs, updatedAttrs) {
    var name;
    var i;
    var value;
    var attr;
    for (name in updatedAttrs) {
      value = '' + updatedAttrs[name];
      if (attrs.map[name]) {
        i = attrs.length;
        while (i--) {
          attr = attrs[i];
          if (attr.name === name) {
            if (value) {
              attrs.map[name] = value;
              attr.value = value;
            } else {
              delete attrs.map[name];
              attrs.splice(i, 1);
            }
          }
        }
      } else if (value) {
        attrs.push({
          name: name,
          value: value
        });
        attrs.map[name] = value;
      }
    }
  };
  var normalizeHtml = function (html) {
    var writer = global$6();
    var parser = global$3(writer);
    parser.parse(html);
    return writer.getContent();
  };
  var updateHtmlSax = function (html, data, updateAll) {
    var writer = global$6();
    var sourceCount = 0;
    var hasImage;
    global$3({
      validate: false,
      allow_conditional_comments: true,
      special: 'script,noscript',
      comment: function (text) {
        writer.comment(text);
      },
      cdata: function (text) {
        writer.cdata(text);
      },
      text: function (text, raw) {
        writer.text(text, raw);
      },
      start: function (name, attrs, empty) {
        switch (name) {
        case 'video':
        case 'object':
        case 'embed':
        case 'img':
        case 'iframe':
          if (data.height !== undefined && data.width !== undefined) {
            setAttributes(attrs, {
              width: data.width,
              height: data.height
            });
          }
          break;
        }
        if (updateAll) {
          switch (name) {
          case 'video':
            setAttributes(attrs, {
              poster: data.poster,
              src: ''
            });
            if (data.source2) {
              setAttributes(attrs, { src: '' });
            }
            break;
          case 'iframe':
            setAttributes(attrs, { src: data.source1 });
            break;
          case 'source':
            sourceCount++;
            if (sourceCount <= 2) {
              setAttributes(attrs, {
                src: data['source' + sourceCount],
                type: data['source' + sourceCount + 'mime']
              });
              if (!data['source' + sourceCount]) {
                return;
              }
            }
            break;
          case 'img':
            if (!data.poster) {
              return;
            }
            hasImage = true;
            break;
          }
        }
        writer.start(name, attrs, empty);
      },
      end: function (name) {
        if (name === 'video' && updateAll) {
          for (var index = 1; index <= 2; index++) {
            if (data['source' + index]) {
              var attrs = [];
              attrs.map = {};
              if (sourceCount < index) {
                setAttributes(attrs, {
                  src: data['source' + index],
                  type: data['source' + index + 'mime']
                });
                writer.start('source', attrs, true);
              }
            }
          }
        }
        if (data.poster && name === 'object' && updateAll && !hasImage) {
          var imgAttrs = [];
          imgAttrs.map = {};
          setAttributes(imgAttrs, {
            src: data.poster,
            width: data.width,
            height: data.height
          });
          writer.start('img', imgAttrs, true);
        }
        writer.end(name);
      }
    }, global$7({})).parse(html);
    return writer.getContent();
  };
  var isEphoxEmbed$1 = function (html) {
    var fragment = DOM$1.createFragment(html);
    return DOM$1.getAttrib(fragment.firstChild, 'data-ephox-embed-iri') !== '';
  };
  var updateEphoxEmbed = function (html, data) {
    var fragment = DOM$1.createFragment(html);
    var div = fragment.firstChild;
    $_g4vsn9gmjh8lz0v1.setMaxWidth(div, data.width);
    $_g4vsn9gmjh8lz0v1.setMaxHeight(div, data.height);
    return normalizeHtml(div.outerHTML);
  };
  var updateHtml = function (html, data, updateAll) {
    return isEphoxEmbed$1(html) ? updateEphoxEmbed(html, data) : updateHtmlSax(html, data, updateAll);
  };
  var $_ec27xygrjh8lz0va = { updateHtml: updateHtml };

  var urlPatterns = [
    {
      regex: /youtu\.be\/([\w\-_\?&=.]+)/i,
      type: 'iframe',
      w: 560,
      h: 314,
      url: '//www.youtube.com/embed/$1',
      allowFullscreen: true
    },
    {
      regex: /youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?/i,
      type: 'iframe',
      w: 560,
      h: 314,
      url: '//www.youtube.com/embed/$2?$4',
      allowFullscreen: true
    },
    {
      regex: /youtube.com\/embed\/([a-z0-9\?&=\-_]+)/i,
      type: 'iframe',
      w: 560,
      h: 314,
      url: '//www.youtube.com/embed/$1',
      allowFullscreen: true
    },
    {
      regex: /vimeo\.com\/([0-9]+)/,
      type: 'iframe',
      w: 425,
      h: 350,
      url: '//player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc',
      allowFullscreen: true
    },
    {
      regex: /vimeo\.com\/(.*)\/([0-9]+)/,
      type: 'iframe',
      w: 425,
      h: 350,
      url: '//player.vimeo.com/video/$2?title=0&amp;byline=0',
      allowFullscreen: true
    },
    {
      regex: /maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/,
      type: 'iframe',
      w: 425,
      h: 350,
      url: '//maps.google.com/maps/ms?msid=$2&output=embed"',
      allowFullscreen: false
    },
    {
      regex: /dailymotion\.com\/video\/([^_]+)/,
      type: 'iframe',
      w: 480,
      h: 270,
      url: '//www.dailymotion.com/embed/video/$1',
      allowFullscreen: true
    },
    {
      regex: /dai\.ly\/([^_]+)/,
      type: 'iframe',
      w: 480,
      h: 270,
      url: '//www.dailymotion.com/embed/video/$1',
      allowFullscreen: true
    }
  ];
  var getUrl = function (pattern, url) {
    var match = pattern.regex.exec(url);
    var newUrl = pattern.url;
    var _loop_1 = function (i) {
      newUrl = newUrl.replace('$' + i, function () {
        return match[i] ? match[i] : '';
      });
    };
    for (var i = 0; i < match.length; i++) {
      _loop_1(i);
    }
    return newUrl.replace(/\?$/, '');
  };
  var matchPattern = function (url) {
    var pattern = urlPatterns.filter(function (pattern) {
      return pattern.regex.test(url);
    });
    if (pattern.length > 0) {
      return global$2.extend({}, pattern[0], { url: getUrl(pattern[0], url) });
    } else {
      return null;
    }
  };

  var getIframeHtml = function (data) {
    var allowFullscreen = data.allowFullscreen ? ' allowFullscreen="1"' : '';
    return '<iframe src="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '"' + allowFullscreen + '></iframe>';
  };
  var getFlashHtml = function (data) {
    var html = '<object data="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
    if (data.poster) {
      html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
    }
    html += '</object>';
    return html;
  };
  var getAudioHtml = function (data, audioTemplateCallback) {
    if (audioTemplateCallback) {
      return audioTemplateCallback(data);
    } else {
      return '<audio controls="controls" src="' + data.source1 + '">' + (data.source2 ? '\n<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') + '</audio>';
    }
  };
  var getVideoHtml = function (data, videoTemplateCallback) {
    if (videoTemplateCallback) {
      return videoTemplateCallback(data);
    } else {
      return '<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' + '<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' + (data.source2 ? '<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') + '</video>';
    }
  };
  var getScriptHtml = function (data) {
    return '<script src="' + data.source1 + '"></script>';
  };
  var dataToHtml = function (editor, dataIn) {
    var data = global$2.extend({}, dataIn);
    if (!data.source1) {
      global$2.extend(data, $_3nrb4rgijh8lz0uw.htmlToData($_bcg8bpghjh8lz0ut.getScripts(editor), data.embed));
      if (!data.source1) {
        return '';
      }
    }
    if (!data.source2) {
      data.source2 = '';
    }
    if (!data.poster) {
      data.poster = '';
    }
    data.source1 = editor.convertURL(data.source1, 'source');
    data.source2 = editor.convertURL(data.source2, 'source');
    data.source1mime = $_fbk2jcgqjh8lz0v8.guess(data.source1);
    data.source2mime = $_fbk2jcgqjh8lz0v8.guess(data.source2);
    data.poster = editor.convertURL(data.poster, 'poster');
    var pattern = matchPattern(data.source1);
    if (pattern) {
      data.source1 = pattern.url;
      data.type = pattern.type;
      data.allowFullscreen = pattern.allowFullscreen;
      data.width = data.width || pattern.w;
      data.height = data.height || pattern.h;
    }
    if (data.embed) {
      return $_ec27xygrjh8lz0va.updateHtml(data.embed, data, true);
    } else {
      var videoScript = $_a6mt9vgljh8lz0uz.getVideoScriptMatch($_bcg8bpghjh8lz0ut.getScripts(editor), data.source1);
      if (videoScript) {
        data.type = 'script';
        data.width = videoScript.width;
        data.height = videoScript.height;
      }
      var audioTemplateCallback = $_bcg8bpghjh8lz0ut.getAudioTemplateCallback(editor);
      var videoTemplateCallback = $_bcg8bpghjh8lz0ut.getVideoTemplateCallback(editor);
      data.width = data.width || 300;
      data.height = data.height || 150;
      global$2.each(data, function (value, key) {
        data[key] = editor.dom.encode(value);
      });
      if (data.type === 'iframe') {
        return getIframeHtml(data);
      } else if (data.source1mime === 'application/x-shockwave-flash') {
        return getFlashHtml(data);
      } else if (data.source1mime.indexOf('audio') !== -1) {
        return getAudioHtml(data, audioTemplateCallback);
      } else if (data.type === 'script') {
        return getScriptHtml(data);
      } else {
        return getVideoHtml(data, videoTemplateCallback);
      }
    }
  };
  var $_36z50bgpjh8lz0v5 = { dataToHtml: dataToHtml };

  var cache = {};
  var embedPromise = function (data, dataToHtml, handler) {
    return new global$5(function (res, rej) {
      var wrappedResolve = function (response) {
        if (response.html) {
          cache[data.source1] = response;
        }
        return res({
          url: data.source1,
          html: response.html ? response.html : dataToHtml(data)
        });
      };
      if (cache[data.source1]) {
        wrappedResolve(cache[data.source1]);
      } else {
        handler({ url: data.source1 }, wrappedResolve, rej);
      }
    });
  };
  var defaultPromise = function (data, dataToHtml) {
    return new global$5(function (res) {
      res({
        html: dataToHtml(data),
        url: data.source1
      });
    });
  };
  var loadedData = function (editor) {
    return function (data) {
      return $_36z50bgpjh8lz0v5.dataToHtml(editor, data);
    };
  };
  var getEmbedHtml = function (editor, data) {
    var embedHandler = $_bcg8bpghjh8lz0ut.getUrlResolver(editor);
    return embedHandler ? embedPromise(data, loadedData(editor), embedHandler) : defaultPromise(data, loadedData(editor));
  };
  var isCached = function (url) {
    return cache.hasOwnProperty(url);
  };
  var $_bqbbyvgnjh8lz0v2 = {
    getEmbedHtml: getEmbedHtml,
    isCached: isCached
  };

  var doSyncSize = function (widthCtrl, heightCtrl) {
    widthCtrl.state.set('oldVal', widthCtrl.value());
    heightCtrl.state.set('oldVal', heightCtrl.value());
  };
  var doSizeControls = function (win, f) {
    var widthCtrl = win.find('#width')[0];
    var heightCtrl = win.find('#height')[0];
    var constrained = win.find('#constrain')[0];
    if (widthCtrl && heightCtrl && constrained) {
      f(widthCtrl, heightCtrl, constrained.checked());
    }
  };
  var doUpdateSize = function (widthCtrl, heightCtrl, isContrained) {
    var oldWidth = widthCtrl.state.get('oldVal');
    var oldHeight = heightCtrl.state.get('oldVal');
    var newWidth = widthCtrl.value();
    var newHeight = heightCtrl.value();
    if (isContrained && oldWidth && oldHeight && newWidth && newHeight) {
      if (newWidth !== oldWidth) {
        newHeight = Math.round(newWidth / oldWidth * newHeight);
        if (!isNaN(newHeight)) {
          heightCtrl.value(newHeight);
        }
      } else {
        newWidth = Math.round(newHeight / oldHeight * newWidth);
        if (!isNaN(newWidth)) {
          widthCtrl.value(newWidth);
        }
      }
    }
    doSyncSize(widthCtrl, heightCtrl);
  };
  var syncSize = function (win) {
    doSizeControls(win, doSyncSize);
  };
  var updateSize = function (win) {
    doSizeControls(win, doUpdateSize);
  };
  var createUi = function (onChange) {
    var recalcSize = function () {
      onChange(function (win) {
        updateSize(win);
      });
    };
    return {
      type: 'container',
      label: 'Dimensions',
      layout: 'flex',
      align: 'center',
      spacing: 5,
      items: [
        {
          name: 'width',
          type: 'textbox',
          maxLength: 5,
          size: 5,
          onchange: recalcSize,
          ariaLabel: 'Width'
        },
        {
          type: 'label',
          text: 'x'
        },
        {
          name: 'height',
          type: 'textbox',
          maxLength: 5,
          size: 5,
          onchange: recalcSize,
          ariaLabel: 'Height'
        },
        {
          name: 'constrain',
          type: 'checkbox',
          checked: true,
          text: 'Constrain proportions'
        }
      ]
    };
  };
  var $_ctm8lcgvjh8lz0vo = {
    createUi: createUi,
    syncSize: syncSize,
    updateSize: updateSize
  };

  var embedChange = global$1.ie && global$1.ie <= 8 ? 'onChange' : 'onInput';
  var handleError = function (editor) {
    return function (error) {
      var errorMessage = error && error.msg ? 'Media embed handler error: ' + error.msg : 'Media embed handler threw unknown error.';
      editor.notificationManager.open({
        type: 'error',
        text: errorMessage
      });
    };
  };
  var getData = function (editor) {
    var element = editor.selection.getNode();
    var dataEmbed = element.getAttribute('data-ephox-embed-iri');
    if (dataEmbed) {
      return {
        'source1': dataEmbed,
        'data-ephox-embed-iri': dataEmbed,
        'width': $_g4vsn9gmjh8lz0v1.getMaxWidth(element),
        'height': $_g4vsn9gmjh8lz0v1.getMaxHeight(element)
      };
    }
    return element.getAttribute('data-mce-object') ? $_3nrb4rgijh8lz0uw.htmlToData($_bcg8bpghjh8lz0ut.getScripts(editor), editor.serializer.serialize(element, { selection: true })) : {};
  };
  var getSource = function (editor) {
    var elm = editor.selection.getNode();
    if (elm.getAttribute('data-mce-object') || elm.getAttribute('data-ephox-embed-iri')) {
      return editor.selection.getContent();
    }
  };
  var addEmbedHtml = function (win, editor) {
    return function (response) {
      var html = response.html;
      var embed = win.find('#embed')[0];
      var data = global$2.extend($_3nrb4rgijh8lz0uw.htmlToData($_bcg8bpghjh8lz0ut.getScripts(editor), html), { source1: response.url });
      win.fromJSON(data);
      if (embed) {
        embed.value(html);
        $_ctm8lcgvjh8lz0vo.updateSize(win);
      }
    };
  };
  var selectPlaceholder = function (editor, beforeObjects) {
    var i;
    var y;
    var afterObjects = editor.dom.select('img[data-mce-object]');
    for (i = 0; i < beforeObjects.length; i++) {
      for (y = afterObjects.length - 1; y >= 0; y--) {
        if (beforeObjects[i] === afterObjects[y]) {
          afterObjects.splice(y, 1);
        }
      }
    }
    editor.selection.select(afterObjects[0]);
  };
  var handleInsert = function (editor, html) {
    var beforeObjects = editor.dom.select('img[data-mce-object]');
    editor.insertContent(html);
    selectPlaceholder(editor, beforeObjects);
    editor.nodeChanged();
  };
  var submitForm = function (win, editor) {
    var data = win.toJSON();
    data.embed = $_ec27xygrjh8lz0va.updateHtml(data.embed, data);
    if (data.embed && $_bqbbyvgnjh8lz0v2.isCached(data.source1)) {
      handleInsert(editor, data.embed);
    } else {
      $_bqbbyvgnjh8lz0v2.getEmbedHtml(editor, data).then(function (response) {
        handleInsert(editor, response.html);
      }).catch(handleError(editor));
    }
  };
  var populateMeta = function (win, meta) {
    global$2.each(meta, function (value, key) {
      win.find('#' + key).value(value);
    });
  };
  var showDialog = function (editor) {
    var win;
    var data;
    var generalFormItems = [{
        name: 'source1',
        type: 'filepicker',
        filetype: 'media',
        size: 40,
        autofocus: true,
        label: 'Source',
        onpaste: function () {
          setTimeout(function () {
            $_bqbbyvgnjh8lz0v2.getEmbedHtml(editor, win.toJSON()).then(addEmbedHtml(win, editor)).catch(handleError(editor));
          }, 1);
        },
        onchange: function (e) {
          $_bqbbyvgnjh8lz0v2.getEmbedHtml(editor, win.toJSON()).then(addEmbedHtml(win, editor)).catch(handleError(editor));
          populateMeta(win, e.meta);
        },
        onbeforecall: function (e) {
          e.meta = win.toJSON();
        }
      }];
    var advancedFormItems = [];
    var reserialise = function (update) {
      update(win);
      data = win.toJSON();
      win.find('#embed').value($_ec27xygrjh8lz0va.updateHtml(data.embed, data));
    };
    if ($_bcg8bpghjh8lz0ut.hasAltSource(editor)) {
      advancedFormItems.push({
        name: 'source2',
        type: 'filepicker',
        filetype: 'media',
        size: 40,
        label: 'Alternative source'
      });
    }
    if ($_bcg8bpghjh8lz0ut.hasPoster(editor)) {
      advancedFormItems.push({
        name: 'poster',
        type: 'filepicker',
        filetype: 'image',
        size: 40,
        label: 'Poster'
      });
    }
    if ($_bcg8bpghjh8lz0ut.hasDimensions(editor)) {
      var control = $_ctm8lcgvjh8lz0vo.createUi(reserialise);
      generalFormItems.push(control);
    }
    data = getData(editor);
    var embedTextBox = {
      id: 'mcemediasource',
      type: 'textbox',
      flex: 1,
      name: 'embed',
      value: getSource(editor),
      multiline: true,
      rows: 5,
      label: 'Source'
    };
    var updateValueOnChange = function () {
      data = global$2.extend({}, $_3nrb4rgijh8lz0uw.htmlToData($_bcg8bpghjh8lz0ut.getScripts(editor), this.value()));
      this.parent().parent().fromJSON(data);
    };
    embedTextBox[embedChange] = updateValueOnChange;
    var body = [
      {
        title: 'General',
        type: 'form',
        items: generalFormItems
      },
      {
        title: 'Embed',
        type: 'container',
        layout: 'flex',
        direction: 'column',
        align: 'stretch',
        padding: 10,
        spacing: 10,
        items: [
          {
            type: 'label',
            text: 'Paste your embed code below:',
            forId: 'mcemediasource'
          },
          embedTextBox
        ]
      }
    ];
    if (advancedFormItems.length > 0) {
      body.push({
        title: 'Advanced',
        type: 'form',
        items: advancedFormItems
      });
    }
    win = editor.windowManager.open({
      title: 'Insert/edit media',
      data: data,
      bodyType: 'tabpanel',
      body: body,
      onSubmit: function () {
        $_ctm8lcgvjh8lz0vo.updateSize(win);
        submitForm(win, editor);
      }
    });
    $_ctm8lcgvjh8lz0vo.syncSize(win);
  };
  var $_3l3va1gejh8lz0uo = { showDialog: showDialog };

  var get = function (editor) {
    var showDialog = function () {
      $_3l3va1gejh8lz0uo.showDialog(editor);
    };
    return { showDialog: showDialog };
  };
  var $_baju01gdjh8lz0um = { get: get };

  var register = function (editor) {
    var showDialog = function () {
      $_3l3va1gejh8lz0uo.showDialog(editor);
    };
    editor.addCommand('mceMedia', showDialog);
  };
  var $_bp1t92gwjh8lz0vq = { register: register };

  var global$8 = tinymce.util.Tools.resolve('tinymce.html.Node');

  var sanitize = function (editor, html) {
    if ($_bcg8bpghjh8lz0ut.shouldFilterHtml(editor) === false) {
      return html;
    }
    var writer = global$6();
    var blocked;
    global$3({
      validate: false,
      allow_conditional_comments: false,
      special: 'script,noscript',
      comment: function (text) {
        writer.comment(text);
      },
      cdata: function (text) {
        writer.cdata(text);
      },
      text: function (text, raw) {
        writer.text(text, raw);
      },
      start: function (name, attrs, empty) {
        blocked = true;
        if (name === 'script' || name === 'noscript') {
          return;
        }
        for (var i = 0; i < attrs.length; i++) {
          if (attrs[i].name.indexOf('on') === 0) {
            return;
          }
          if (attrs[i].name === 'style') {
            attrs[i].value = editor.dom.serializeStyle(editor.dom.parseStyle(attrs[i].value), name);
          }
        }
        writer.start(name, attrs, empty);
        blocked = false;
      },
      end: function (name) {
        if (blocked) {
          return;
        }
        writer.end(name);
      }
    }, global$7({})).parse(html);
    return writer.getContent();
  };
  var $_6qsq2eh0jh8lz0vz = { sanitize: sanitize };

  var createPlaceholderNode = function (editor, node) {
    var placeHolder;
    var name = node.name;
    placeHolder = new global$8('img', 1);
    placeHolder.shortEnded = true;
    retainAttributesAndInnerHtml(editor, node, placeHolder);
    placeHolder.attr({
      'width': node.attr('width') || '300',
      'height': node.attr('height') || (name === 'audio' ? '30' : '150'),
      'style': node.attr('style'),
      'src': global$1.transparentSrc,
      'data-mce-object': name,
      'class': 'mce-object mce-object-' + name
    });
    return placeHolder;
  };
  var createPreviewIframeNode = function (editor, node) {
    var previewWrapper;
    var previewNode;
    var shimNode;
    var name = node.name;
    previewWrapper = new global$8('span', 1);
    previewWrapper.attr({
      'contentEditable': 'false',
      'style': node.attr('style'),
      'data-mce-object': name,
      'class': 'mce-preview-object mce-object-' + name
    });
    retainAttributesAndInnerHtml(editor, node, previewWrapper);
    previewNode = new global$8(name, 1);
    previewNode.attr({
      src: node.attr('src'),
      allowfullscreen: node.attr('allowfullscreen'),
      style: node.attr('style'),
      class: node.attr('class'),
      width: node.attr('width'),
      height: node.attr('height'),
      frameborder: '0'
    });
    shimNode = new global$8('span', 1);
    shimNode.attr('class', 'mce-shim');
    previewWrapper.append(previewNode);
    previewWrapper.append(shimNode);
    return previewWrapper;
  };
  var retainAttributesAndInnerHtml = function (editor, sourceNode, targetNode) {
    var attrName;
    var attrValue;
    var attribs;
    var ai;
    var innerHtml;
    attribs = sourceNode.attributes;
    ai = attribs.length;
    while (ai--) {
      attrName = attribs[ai].name;
      attrValue = attribs[ai].value;
      if (attrName !== 'width' && attrName !== 'height' && attrName !== 'style') {
        if (attrName === 'data' || attrName === 'src') {
          attrValue = editor.convertURL(attrValue, attrName);
        }
        targetNode.attr('data-mce-p-' + attrName, attrValue);
      }
    }
    innerHtml = sourceNode.firstChild && sourceNode.firstChild.value;
    if (innerHtml) {
      targetNode.attr('data-mce-html', escape($_6qsq2eh0jh8lz0vz.sanitize(editor, innerHtml)));
      targetNode.firstChild = null;
    }
  };
  var isWithinEphoxEmbed = function (node) {
    while (node = node.parent) {
      if (node.attr('data-ephox-embed-iri')) {
        return true;
      }
    }
    return false;
  };
  var placeHolderConverter = function (editor) {
    return function (nodes) {
      var i = nodes.length;
      var node;
      var videoScript;
      while (i--) {
        node = nodes[i];
        if (!node.parent) {
          continue;
        }
        if (node.parent.attr('data-mce-object')) {
          continue;
        }
        if (node.name === 'script') {
          videoScript = $_a6mt9vgljh8lz0uz.getVideoScriptMatch($_bcg8bpghjh8lz0ut.getScripts(editor), node.attr('src'));
          if (!videoScript) {
            continue;
          }
        }
        if (videoScript) {
          if (videoScript.width) {
            node.attr('width', videoScript.width.toString());
          }
          if (videoScript.height) {
            node.attr('height', videoScript.height.toString());
          }
        }
        if (node.name === 'iframe' && $_bcg8bpghjh8lz0ut.hasLiveEmbeds(editor) && global$1.ceFalse) {
          if (!isWithinEphoxEmbed(node)) {
            node.replace(createPreviewIframeNode(editor, node));
          }
        } else {
          if (!isWithinEphoxEmbed(node)) {
            node.replace(createPlaceholderNode(editor, node));
          }
        }
      }
    };
  };
  var $_avuyrbgzjh8lz0vv = {
    createPreviewIframeNode: createPreviewIframeNode,
    createPlaceholderNode: createPlaceholderNode,
    placeHolderConverter: placeHolderConverter
  };

  var setup = function (editor) {
    editor.on('preInit', function () {
      var specialElements = editor.schema.getSpecialElements();
      global$2.each('video audio iframe object'.split(' '), function (name) {
        specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
      });
      var boolAttrs = editor.schema.getBoolAttrs();
      global$2.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function (name) {
        boolAttrs[name] = {};
      });
      editor.parser.addNodeFilter('iframe,video,audio,object,embed,script', $_avuyrbgzjh8lz0vv.placeHolderConverter(editor));
      editor.serializer.addAttributeFilter('data-mce-object', function (nodes, name) {
        var i = nodes.length;
        var node;
        var realElm;
        var ai;
        var attribs;
        var innerHtml;
        var innerNode;
        var realElmName;
        var className;
        while (i--) {
          node = nodes[i];
          if (!node.parent) {
            continue;
          }
          realElmName = node.attr(name);
          realElm = new global$8(realElmName, 1);
          if (realElmName !== 'audio' && realElmName !== 'script') {
            className = node.attr('class');
            if (className && className.indexOf('mce-preview-object') !== -1) {
              realElm.attr({
                width: node.firstChild.attr('width'),
                height: node.firstChild.attr('height')
              });
            } else {
              realElm.attr({
                width: node.attr('width'),
                height: node.attr('height')
              });
            }
          }
          realElm.attr({ style: node.attr('style') });
          attribs = node.attributes;
          ai = attribs.length;
          while (ai--) {
            var attrName = attribs[ai].name;
            if (attrName.indexOf('data-mce-p-') === 0) {
              realElm.attr(attrName.substr(11), attribs[ai].value);
            }
          }
          if (realElmName === 'script') {
            realElm.attr('type', 'text/javascript');
          }
          innerHtml = node.attr('data-mce-html');
          if (innerHtml) {
            innerNode = new global$8('#text', 3);
            innerNode.raw = true;
            innerNode.value = $_6qsq2eh0jh8lz0vz.sanitize(editor, unescape(innerHtml));
            realElm.append(innerNode);
          }
          node.replace(realElm);
        }
      });
    });
    editor.on('setContent', function () {
      editor.$('span.mce-preview-object').each(function (index, elm) {
        var $elm = editor.$(elm);
        if ($elm.find('span.mce-shim', elm).length === 0) {
          $elm.append('<span class="mce-shim"></span>');
        }
      });
    });
  };
  var $_3u2masgxjh8lz0vs = { setup: setup };

  var setup$1 = function (editor) {
    editor.on('ResolveName', function (e) {
      var name;
      if (e.target.nodeType === 1 && (name = e.target.getAttribute('data-mce-object'))) {
        e.name = name;
      }
    });
  };
  var $_7e0f0eh1jh8lz0w1 = { setup: setup$1 };

  var setup$2 = function (editor) {
    editor.on('click keyup', function () {
      var selectedNode = editor.selection.getNode();
      if (selectedNode && editor.dom.hasClass(selectedNode, 'mce-preview-object')) {
        if (editor.dom.getAttrib(selectedNode, 'data-mce-selected')) {
          selectedNode.setAttribute('data-mce-selected', '2');
        }
      }
    });
    editor.on('ObjectSelected', function (e) {
      var objectType = e.target.getAttribute('data-mce-object');
      if (objectType === 'audio' || objectType === 'script') {
        e.preventDefault();
      }
    });
    editor.on('objectResized', function (e) {
      var target = e.target;
      var html;
      if (target.getAttribute('data-mce-object')) {
        html = target.getAttribute('data-mce-html');
        if (html) {
          html = unescape(html);
          target.setAttribute('data-mce-html', escape($_ec27xygrjh8lz0va.updateHtml(html, {
            width: e.width,
            height: e.height
          })));
        }
      }
    });
  };
  var $_firvch2jh8lz0w3 = { setup: setup$2 };

  var register$1 = function (editor) {
    editor.addButton('media', {
      tooltip: 'Insert/edit media',
      cmd: 'mceMedia',
      stateSelector: [
        'img[data-mce-object]',
        'span[data-mce-object]',
        'div[data-ephox-embed-iri]'
      ]
    });
    editor.addMenuItem('media', {
      icon: 'media',
      text: 'Media',
      cmd: 'mceMedia',
      context: 'insert',
      prependToContext: true
    });
  };
  var $_2oflieh3jh8lz0w4 = { register: register$1 };

  global.add('media', function (editor) {
    $_bp1t92gwjh8lz0vq.register(editor);
    $_2oflieh3jh8lz0w4.register(editor);
    $_7e0f0eh1jh8lz0w1.setup(editor);
    $_3u2masgxjh8lz0vs.setup(editor);
    $_firvch2jh8lz0w3.setup(editor);
    return $_baju01gdjh8lz0um.get(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-nonbreaking", ["tinymce"], function() {
  return (function() {
(function () {
var nonbreaking = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var stringRepeat = function (string, repeats) {
    var str = '';
    for (var index = 0; index < repeats; index++) {
      str += string;
    }
    return str;
  };
  var isVisualCharsEnabled = function (editor) {
    return editor.plugins.visualchars ? editor.plugins.visualchars.isEnabled() : false;
  };
  var insertNbsp = function (editor, times) {
    var nbsp = isVisualCharsEnabled(editor) ? '<span class="mce-nbsp">&nbsp;</span>' : '&nbsp;';
    editor.insertContent(stringRepeat(nbsp, times));
    editor.dom.setAttrib(editor.dom.select('span.mce-nbsp'), 'data-mce-bogus', '1');
  };
  var $_fpypash7jh8lz0y5 = { insertNbsp: insertNbsp };

  var register = function (editor) {
    editor.addCommand('mceNonBreaking', function () {
      $_fpypash7jh8lz0y5.insertNbsp(editor, 1);
    });
  };
  var $_45ppimh6jh8lz0y4 = { register: register };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var getKeyboardSpaces = function (editor) {
    var spaces = editor.getParam('nonbreaking_force_tab', 0);
    if (typeof spaces === 'boolean') {
      return spaces === true ? 3 : 0;
    } else {
      return spaces;
    }
  };
  var $_f73qmzhajh8lz0y7 = { getKeyboardSpaces: getKeyboardSpaces };

  var setup = function (editor) {
    var spaces = $_f73qmzhajh8lz0y7.getKeyboardSpaces(editor);
    if (spaces > 0) {
      editor.on('keydown', function (e) {
        if (e.keyCode === global$1.TAB && !e.isDefaultPrevented()) {
          if (e.shiftKey) {
            return;
          }
          e.preventDefault();
          e.stopImmediatePropagation();
          $_fpypash7jh8lz0y5.insertNbsp(editor, spaces);
        }
      });
    }
  };
  var $_8k27hmh8jh8lz0y6 = { setup: setup };

  var register$1 = function (editor) {
    editor.addButton('nonbreaking', {
      title: 'Nonbreaking space',
      cmd: 'mceNonBreaking'
    });
    editor.addMenuItem('nonbreaking', {
      icon: 'nonbreaking',
      text: 'Nonbreaking space',
      cmd: 'mceNonBreaking',
      context: 'insert'
    });
  };
  var $_2kco2nhbjh8lz0y9 = { register: register$1 };

  global.add('nonbreaking', function (editor) {
    $_45ppimh6jh8lz0y4.register(editor);
    $_2kco2nhbjh8lz0y9.register(editor);
    $_8k27hmh8jh8lz0y6.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-noneditable", ["tinymce"], function() {
  return (function() {
(function () {
var noneditable = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var getNonEditableClass = function (editor) {
    return editor.getParam('noneditable_noneditable_class', 'mceNonEditable');
  };
  var getEditableClass = function (editor) {
    return editor.getParam('noneditable_editable_class', 'mceEditable');
  };
  var getNonEditableRegExps = function (editor) {
    var nonEditableRegExps = editor.getParam('noneditable_regexp', []);
    if (nonEditableRegExps && nonEditableRegExps.constructor === RegExp) {
      return [nonEditableRegExps];
    } else {
      return nonEditableRegExps;
    }
  };
  var $_9u2u4bhgjh8lz0ym = {
    getNonEditableClass: getNonEditableClass,
    getEditableClass: getEditableClass,
    getNonEditableRegExps: getNonEditableRegExps
  };

  var hasClass = function (checkClassName) {
    return function (node) {
      return (' ' + node.attr('class') + ' ').indexOf(checkClassName) !== -1;
    };
  };
  var replaceMatchWithSpan = function (editor, content, cls) {
    return function (match) {
      var args = arguments, index = args[args.length - 2];
      var prevChar = index > 0 ? content.charAt(index - 1) : '';
      if (prevChar === '"') {
        return match;
      }
      if (prevChar === '>') {
        var findStartTagIndex = content.lastIndexOf('<', index);
        if (findStartTagIndex !== -1) {
          var tagHtml = content.substring(findStartTagIndex, index);
          if (tagHtml.indexOf('contenteditable="false"') !== -1) {
            return match;
          }
        }
      }
      return '<span class="' + cls + '" data-mce-content="' + editor.dom.encode(args[0]) + '">' + editor.dom.encode(typeof args[1] === 'string' ? args[1] : args[0]) + '</span>';
    };
  };
  var convertRegExpsToNonEditable = function (editor, nonEditableRegExps, e) {
    var i = nonEditableRegExps.length, content = e.content;
    if (e.format === 'raw') {
      return;
    }
    while (i--) {
      content = content.replace(nonEditableRegExps[i], replaceMatchWithSpan(editor, content, $_9u2u4bhgjh8lz0ym.getNonEditableClass(editor)));
    }
    e.content = content;
  };
  var setup = function (editor) {
    var editClass, nonEditClass;
    var contentEditableAttrName = 'contenteditable';
    editClass = ' ' + global$1.trim($_9u2u4bhgjh8lz0ym.getEditableClass(editor)) + ' ';
    nonEditClass = ' ' + global$1.trim($_9u2u4bhgjh8lz0ym.getNonEditableClass(editor)) + ' ';
    var hasEditClass = hasClass(editClass);
    var hasNonEditClass = hasClass(nonEditClass);
    var nonEditableRegExps = $_9u2u4bhgjh8lz0ym.getNonEditableRegExps(editor);
    editor.on('PreInit', function () {
      if (nonEditableRegExps.length > 0) {
        editor.on('BeforeSetContent', function (e) {
          convertRegExpsToNonEditable(editor, nonEditableRegExps, e);
        });
      }
      editor.parser.addAttributeFilter('class', function (nodes) {
        var i = nodes.length, node;
        while (i--) {
          node = nodes[i];
          if (hasEditClass(node)) {
            node.attr(contentEditableAttrName, 'true');
          } else if (hasNonEditClass(node)) {
            node.attr(contentEditableAttrName, 'false');
          }
        }
      });
      editor.serializer.addAttributeFilter(contentEditableAttrName, function (nodes) {
        var i = nodes.length, node;
        while (i--) {
          node = nodes[i];
          if (!hasEditClass(node) && !hasNonEditClass(node)) {
            continue;
          }
          if (nonEditableRegExps.length > 0 && node.attr('data-mce-content')) {
            node.name = '#text';
            node.type = 3;
            node.raw = true;
            node.value = node.attr('data-mce-content');
          } else {
            node.attr(contentEditableAttrName, null);
          }
        }
      });
    });
  };
  var $_bsp17lhejh8lz0yi = { setup: setup };

  global.add('noneditable', function (editor) {
    $_bsp17lhejh8lz0yi.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-pagebreak", ["tinymce"], function() {
  return (function() {
(function () {
var pagebreak = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.Env');

  var getSeparatorHtml = function (editor) {
    return editor.getParam('pagebreak_separator', '<!-- pagebreak -->');
  };
  var shouldSplitBlock = function (editor) {
    return editor.getParam('pagebreak_split_block', false);
  };
  var $_cfcp0ehmjh8lz0z6 = {
    getSeparatorHtml: getSeparatorHtml,
    shouldSplitBlock: shouldSplitBlock
  };

  var getPageBreakClass = function () {
    return 'mce-pagebreak';
  };
  var getPlaceholderHtml = function () {
    return '<img src="' + global$1.transparentSrc + '" class="' + getPageBreakClass() + '" data-mce-resize="false" data-mce-placeholder />';
  };
  var setup = function (editor) {
    var separatorHtml = $_cfcp0ehmjh8lz0z6.getSeparatorHtml(editor);
    var pageBreakSeparatorRegExp = new RegExp(separatorHtml.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function (a) {
      return '\\' + a;
    }), 'gi');
    editor.on('BeforeSetContent', function (e) {
      e.content = e.content.replace(pageBreakSeparatorRegExp, getPlaceholderHtml());
    });
    editor.on('PreInit', function () {
      editor.serializer.addNodeFilter('img', function (nodes) {
        var i = nodes.length, node, className;
        while (i--) {
          node = nodes[i];
          className = node.attr('class');
          if (className && className.indexOf('mce-pagebreak') !== -1) {
            var parentNode = node.parent;
            if (editor.schema.getBlockElements()[parentNode.name] && $_cfcp0ehmjh8lz0z6.shouldSplitBlock(editor)) {
              parentNode.type = 3;
              parentNode.value = separatorHtml;
              parentNode.raw = true;
              node.remove();
              continue;
            }
            node.type = 3;
            node.value = separatorHtml;
            node.raw = true;
          }
        }
      });
    });
  };
  var $_4nscs5hkjh8lz0z3 = {
    setup: setup,
    getPlaceholderHtml: getPlaceholderHtml,
    getPageBreakClass: getPageBreakClass
  };

  var register = function (editor) {
    editor.addCommand('mcePageBreak', function () {
      if (editor.settings.pagebreak_split_block) {
        editor.insertContent('<p>' + $_4nscs5hkjh8lz0z3.getPlaceholderHtml() + '</p>');
      } else {
        editor.insertContent($_4nscs5hkjh8lz0z3.getPlaceholderHtml());
      }
    });
  };
  var $_eeiv35hjjh8lz0z2 = { register: register };

  var setup$1 = function (editor) {
    editor.on('ResolveName', function (e) {
      if (e.target.nodeName === 'IMG' && editor.dom.hasClass(e.target, $_4nscs5hkjh8lz0z3.getPageBreakClass())) {
        e.name = 'pagebreak';
      }
    });
  };
  var $_4vaxechnjh8lz0z7 = { setup: setup$1 };

  var register$1 = function (editor) {
    editor.addButton('pagebreak', {
      title: 'Page break',
      cmd: 'mcePageBreak'
    });
    editor.addMenuItem('pagebreak', {
      text: 'Page break',
      icon: 'pagebreak',
      cmd: 'mcePageBreak',
      context: 'insert'
    });
  };
  var $_2d5h02hojh8lz0z8 = { register: register$1 };

  global.add('pagebreak', function (editor) {
    $_eeiv35hjjh8lz0z2.register(editor);
    $_2d5h02hojh8lz0z8.register(editor);
    $_4nscs5hkjh8lz0z3.setup(editor);
    $_4vaxechnjh8lz0z7.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-paste", ["tinymce"], function() {
  return (function() {
(function () {
var paste = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var hasProPlugin = function (editor) {
    if (/(^|[ ,])powerpaste([, ]|$)/.test(editor.settings.plugins) && global.get('powerpaste')) {
      if (typeof window.console !== 'undefined' && window.console.log) {
        window.console.log('PowerPaste is incompatible with Paste plugin! Remove \'paste\' from the \'plugins\' option.');
      }
      return true;
    } else {
      return false;
    }
  };
  var $_5zap27hsjh8lz0zl = { hasProPlugin: hasProPlugin };

  var get = function (clipboard, quirks) {
    return {
      clipboard: clipboard,
      quirks: quirks
    };
  };
  var $_b74kiihtjh8lz0zm = { get: get };

  var firePastePreProcess = function (editor, html, internal, isWordHtml) {
    return editor.fire('PastePreProcess', {
      content: html,
      internal: internal,
      wordContent: isWordHtml
    });
  };
  var firePastePostProcess = function (editor, node, internal, isWordHtml) {
    return editor.fire('PastePostProcess', {
      node: node,
      internal: internal,
      wordContent: isWordHtml
    });
  };
  var firePastePlainTextToggle = function (editor, state) {
    return editor.fire('PastePlainTextToggle', { state: state });
  };
  var firePaste = function (editor, ieFake) {
    return editor.fire('paste', { ieFake: ieFake });
  };
  var $_dotjevhwjh8lz0zq = {
    firePastePreProcess: firePastePreProcess,
    firePastePostProcess: firePastePostProcess,
    firePastePlainTextToggle: firePastePlainTextToggle,
    firePaste: firePaste
  };

  var shouldPlainTextInform = function (editor) {
    return editor.getParam('paste_plaintext_inform', true);
  };
  var shouldBlockDrop = function (editor) {
    return editor.getParam('paste_block_drop', false);
  };
  var shouldPasteDataImages = function (editor) {
    return editor.getParam('paste_data_images', false);
  };
  var shouldFilterDrop = function (editor) {
    return editor.getParam('paste_filter_drop', true);
  };
  var getPreProcess = function (editor) {
    return editor.getParam('paste_preprocess');
  };
  var getPostProcess = function (editor) {
    return editor.getParam('paste_postprocess');
  };
  var getWebkitStyles = function (editor) {
    return editor.getParam('paste_webkit_styles');
  };
  var shouldRemoveWebKitStyles = function (editor) {
    return editor.getParam('paste_remove_styles_if_webkit', true);
  };
  var shouldMergeFormats = function (editor) {
    return editor.getParam('paste_merge_formats', true);
  };
  var isSmartPasteEnabled = function (editor) {
    return editor.getParam('smart_paste', true);
  };
  var isPasteAsTextEnabled = function (editor) {
    return editor.getParam('paste_as_text', false);
  };
  var getRetainStyleProps = function (editor) {
    return editor.getParam('paste_retain_style_properties');
  };
  var getWordValidElements = function (editor) {
    var defaultValidElements = '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' + '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' + 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody';
    return editor.getParam('paste_word_valid_elements', defaultValidElements);
  };
  var shouldConvertWordFakeLists = function (editor) {
    return editor.getParam('paste_convert_word_fake_lists', true);
  };
  var shouldUseDefaultFilters = function (editor) {
    return editor.getParam('paste_enable_default_filters', true);
  };
  var $_59kbdnhxjh8lz0zr = {
    shouldPlainTextInform: shouldPlainTextInform,
    shouldBlockDrop: shouldBlockDrop,
    shouldPasteDataImages: shouldPasteDataImages,
    shouldFilterDrop: shouldFilterDrop,
    getPreProcess: getPreProcess,
    getPostProcess: getPostProcess,
    getWebkitStyles: getWebkitStyles,
    shouldRemoveWebKitStyles: shouldRemoveWebKitStyles,
    shouldMergeFormats: shouldMergeFormats,
    isSmartPasteEnabled: isSmartPasteEnabled,
    isPasteAsTextEnabled: isPasteAsTextEnabled,
    getRetainStyleProps: getRetainStyleProps,
    getWordValidElements: getWordValidElements,
    shouldConvertWordFakeLists: shouldConvertWordFakeLists,
    shouldUseDefaultFilters: shouldUseDefaultFilters
  };

  var shouldInformUserAboutPlainText = function (editor, userIsInformedState) {
    return userIsInformedState.get() === false && $_59kbdnhxjh8lz0zr.shouldPlainTextInform(editor);
  };
  var displayNotification = function (editor, message) {
    editor.notificationManager.open({
      text: editor.translate(message),
      type: 'info'
    });
  };
  var togglePlainTextPaste = function (editor, clipboard, userIsInformedState) {
    if (clipboard.pasteFormat.get() === 'text') {
      clipboard.pasteFormat.set('html');
      $_dotjevhwjh8lz0zq.firePastePlainTextToggle(editor, false);
    } else {
      clipboard.pasteFormat.set('text');
      $_dotjevhwjh8lz0zq.firePastePlainTextToggle(editor, true);
      if (shouldInformUserAboutPlainText(editor, userIsInformedState)) {
        displayNotification(editor, 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.');
        userIsInformedState.set(true);
      }
    }
    editor.focus();
  };
  var $_19uwahhvjh8lz0zo = { togglePlainTextPaste: togglePlainTextPaste };

  var register = function (editor, clipboard, userIsInformedState) {
    editor.addCommand('mceTogglePlainTextPaste', function () {
      $_19uwahhvjh8lz0zo.togglePlainTextPaste(editor, clipboard, userIsInformedState);
    });
    editor.addCommand('mceInsertClipboardContent', function (ui, value) {
      if (value.content) {
        clipboard.pasteHtml(value.content, value.internal);
      }
      if (value.text) {
        clipboard.pasteText(value.text);
      }
    });
  };
  var $_dw9jlohujh8lz0zn = { register: register };

  var global$1 = tinymce.util.Tools.resolve('tinymce.Env');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var global$3 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var global$4 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var internalMimeType = 'x-tinymce/html';
  var internalMark = '<!-- ' + internalMimeType + ' -->';
  var mark = function (html) {
    return internalMark + html;
  };
  var unmark = function (html) {
    return html.replace(internalMark, '');
  };
  var isMarked = function (html) {
    return html.indexOf(internalMark) !== -1;
  };
  var $_vdmj3i4jh8lz10b = {
    mark: mark,
    unmark: unmark,
    isMarked: isMarked,
    internalHtmlMime: function () {
      return internalMimeType;
    }
  };

  var global$5 = tinymce.util.Tools.resolve('tinymce.html.Entities');

  var isPlainText = function (text) {
    return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
  };
  var toBRs = function (text) {
    return text.replace(/\r?\n/g, '<br>');
  };
  var openContainer = function (rootTag, rootAttrs) {
    var key;
    var attrs = [];
    var tag = '<' + rootTag;
    if (typeof rootAttrs === 'object') {
      for (key in rootAttrs) {
        if (rootAttrs.hasOwnProperty(key)) {
          attrs.push(key + '="' + global$5.encodeAllRaw(rootAttrs[key]) + '"');
        }
      }
      if (attrs.length) {
        tag += ' ' + attrs.join(' ');
      }
    }
    return tag + '>';
  };
  var toBlockElements = function (text, rootTag, rootAttrs) {
    var blocks = text.split(/\n\n/);
    var tagOpen = openContainer(rootTag, rootAttrs);
    var tagClose = '</' + rootTag + '>';
    var paragraphs = global$3.map(blocks, function (p) {
      return p.split(/\n/).join('<br />');
    });
    var stitch = function (p) {
      return tagOpen + p + tagClose;
    };
    return paragraphs.length === 1 ? paragraphs[0] : global$3.map(paragraphs, stitch).join('');
  };
  var convert = function (text, rootTag, rootAttrs) {
    return rootTag ? toBlockElements(text, rootTag, rootAttrs) : toBRs(text);
  };
  var $_q5v7hi5jh8lz10d = {
    isPlainText: isPlainText,
    convert: convert,
    toBRs: toBRs,
    toBlockElements: toBlockElements
  };

  var global$6 = tinymce.util.Tools.resolve('tinymce.html.DomParser');

  var global$7 = tinymce.util.Tools.resolve('tinymce.html.Node');

  var global$8 = tinymce.util.Tools.resolve('tinymce.html.Schema');

  var global$9 = tinymce.util.Tools.resolve('tinymce.html.Serializer');

  function filter(content, items) {
    global$3.each(items, function (v) {
      if (v.constructor === RegExp) {
        content = content.replace(v, '');
      } else {
        content = content.replace(v[0], v[1]);
      }
    });
    return content;
  }
  function innerText(html) {
    var schema = global$8();
    var domParser = global$6({}, schema);
    var text = '';
    var shortEndedElements = schema.getShortEndedElements();
    var ignoreElements = global$3.makeMap('script noscript style textarea video audio iframe object', ' ');
    var blockElements = schema.getBlockElements();
    function walk(node) {
      var name = node.name, currentNode = node;
      if (name === 'br') {
        text += '\n';
        return;
      }
      if (shortEndedElements[name]) {
        text += ' ';
      }
      if (ignoreElements[name]) {
        text += ' ';
        return;
      }
      if (node.type === 3) {
        text += node.value;
      }
      if (!node.shortEnded) {
        if (node = node.firstChild) {
          do {
            walk(node);
          } while (node = node.next);
        }
      }
      if (blockElements[name] && currentNode.next) {
        text += '\n';
        if (name === 'p') {
          text += '\n';
        }
      }
    }
    html = filter(html, [/<!\[[^\]]+\]>/g]);
    walk(domParser.parse(html));
    return text;
  }
  function trimHtml(html) {
    function trimSpaces(all, s1, s2) {
      if (!s1 && !s2) {
        return ' ';
      }
      return '\xA0';
    }
    html = filter(html, [
      /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig,
      /<!--StartFragment-->|<!--EndFragment-->/g,
      [
        /( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g,
        trimSpaces
      ],
      /<br class="Apple-interchange-newline">/g,
      /<br>$/i
    ]);
    return html;
  }
  function createIdGenerator(prefix) {
    var count = 0;
    return function () {
      return prefix + count++;
    };
  }
  var isMsEdge = function () {
    return navigator.userAgent.indexOf(' Edge/') !== -1;
  };
  var $_exxhefidjh8lz10r = {
    filter: filter,
    innerText: innerText,
    trimHtml: trimHtml,
    createIdGenerator: createIdGenerator,
    isMsEdge: isMsEdge
  };

  function isWordContent(content) {
    return /<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i.test(content) || /class="OutlineElement/.test(content) || /id="?docs\-internal\-guid\-/.test(content);
  }
  function isNumericList(text) {
    var found, patterns;
    patterns = [
      /^[IVXLMCD]{1,2}\.[ \u00a0]/,
      /^[ivxlmcd]{1,2}\.[ \u00a0]/,
      /^[a-z]{1,2}[\.\)][ \u00a0]/,
      /^[A-Z]{1,2}[\.\)][ \u00a0]/,
      /^[0-9]+\.[ \u00a0]/,
      /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/,
      /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/
    ];
    text = text.replace(/^[\u00a0 ]+/, '');
    global$3.each(patterns, function (pattern) {
      if (pattern.test(text)) {
        found = true;
        return false;
      }
    });
    return found;
  }
  function isBulletList(text) {
    return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u25CF]\s*/.test(text);
  }
  function convertFakeListsToProperLists(node) {
    var currentListNode, prevListNode, lastLevel = 1;
    function getText(node) {
      var txt = '';
      if (node.type === 3) {
        return node.value;
      }
      if (node = node.firstChild) {
        do {
          txt += getText(node);
        } while (node = node.next);
      }
      return txt;
    }
    function trimListStart(node, regExp) {
      if (node.type === 3) {
        if (regExp.test(node.value)) {
          node.value = node.value.replace(regExp, '');
          return false;
        }
      }
      if (node = node.firstChild) {
        do {
          if (!trimListStart(node, regExp)) {
            return false;
          }
        } while (node = node.next);
      }
      return true;
    }
    function removeIgnoredNodes(node) {
      if (node._listIgnore) {
        node.remove();
        return;
      }
      if (node = node.firstChild) {
        do {
          removeIgnoredNodes(node);
        } while (node = node.next);
      }
    }
    function convertParagraphToLi(paragraphNode, listName, start) {
      var level = paragraphNode._listLevel || lastLevel;
      if (level !== lastLevel) {
        if (level < lastLevel) {
          if (currentListNode) {
            currentListNode = currentListNode.parent.parent;
          }
        } else {
          prevListNode = currentListNode;
          currentListNode = null;
        }
      }
      if (!currentListNode || currentListNode.name !== listName) {
        prevListNode = prevListNode || currentListNode;
        currentListNode = new global$7(listName, 1);
        if (start > 1) {
          currentListNode.attr('start', '' + start);
        }
        paragraphNode.wrap(currentListNode);
      } else {
        currentListNode.append(paragraphNode);
      }
      paragraphNode.name = 'li';
      if (level > lastLevel && prevListNode) {
        prevListNode.lastChild.append(currentListNode);
      }
      lastLevel = level;
      removeIgnoredNodes(paragraphNode);
      trimListStart(paragraphNode, /^\u00a0+/);
      trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
      trimListStart(paragraphNode, /^\u00a0+/);
    }
    var elements = [];
    var child = node.firstChild;
    while (typeof child !== 'undefined' && child !== null) {
      elements.push(child);
      child = child.walk();
      if (child !== null) {
        while (typeof child !== 'undefined' && child.parent !== node) {
          child = child.walk();
        }
      }
    }
    for (var i = 0; i < elements.length; i++) {
      node = elements[i];
      if (node.name === 'p' && node.firstChild) {
        var nodeText = getText(node);
        if (isBulletList(nodeText)) {
          convertParagraphToLi(node, 'ul');
          continue;
        }
        if (isNumericList(nodeText)) {
          var matches = /([0-9]+)\./.exec(nodeText);
          var start = 1;
          if (matches) {
            start = parseInt(matches[1], 10);
          }
          convertParagraphToLi(node, 'ol', start);
          continue;
        }
        if (node._listLevel) {
          convertParagraphToLi(node, 'ul', 1);
          continue;
        }
        currentListNode = null;
      } else {
        prevListNode = currentListNode;
        currentListNode = null;
      }
    }
  }
  function filterStyles(editor, validStyles, node, styleValue) {
    var outputStyles = {}, matches;
    var styles = editor.dom.parseStyle(styleValue);
    global$3.each(styles, function (value, name) {
      switch (name) {
      case 'mso-list':
        matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
        if (matches) {
          node._listLevel = parseInt(matches[1], 10);
        }
        if (/Ignore/i.test(value) && node.firstChild) {
          node._listIgnore = true;
          node.firstChild._listIgnore = true;
        }
        break;
      case 'horiz-align':
        name = 'text-align';
        break;
      case 'vert-align':
        name = 'vertical-align';
        break;
      case 'font-color':
      case 'mso-foreground':
        name = 'color';
        break;
      case 'mso-background':
      case 'mso-highlight':
        name = 'background';
        break;
      case 'font-weight':
      case 'font-style':
        if (value !== 'normal') {
          outputStyles[name] = value;
        }
        return;
      case 'mso-element':
        if (/^(comment|comment-list)$/i.test(value)) {
          node.remove();
          return;
        }
        break;
      }
      if (name.indexOf('mso-comment') === 0) {
        node.remove();
        return;
      }
      if (name.indexOf('mso-') === 0) {
        return;
      }
      if ($_59kbdnhxjh8lz0zr.getRetainStyleProps(editor) === 'all' || validStyles && validStyles[name]) {
        outputStyles[name] = value;
      }
    });
    if (/(bold)/i.test(outputStyles['font-weight'])) {
      delete outputStyles['font-weight'];
      node.wrap(new global$7('b', 1));
    }
    if (/(italic)/i.test(outputStyles['font-style'])) {
      delete outputStyles['font-style'];
      node.wrap(new global$7('i', 1));
    }
    outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
    if (outputStyles) {
      return outputStyles;
    }
    return null;
  }
  var filterWordContent = function (editor, content) {
    var retainStyleProperties, validStyles;
    retainStyleProperties = $_59kbdnhxjh8lz0zr.getRetainStyleProps(editor);
    if (retainStyleProperties) {
      validStyles = global$3.makeMap(retainStyleProperties.split(/[, ]/));
    }
    content = $_exxhefidjh8lz10r.filter(content, [
      /<br class="?Apple-interchange-newline"?>/gi,
      /<b[^>]+id="?docs-internal-[^>]*>/gi,
      /<!--[\s\S]+?-->/gi,
      /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
      [
        /<(\/?)s>/gi,
        '<$1strike>'
      ],
      [
        /&nbsp;/gi,
        '\xA0'
      ],
      [
        /<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
        function (str, spaces) {
          return spaces.length > 0 ? spaces.replace(/./, ' ').slice(Math.floor(spaces.length / 2)).split('').join('\xA0') : '';
        }
      ]
    ]);
    var validElements = $_59kbdnhxjh8lz0zr.getWordValidElements(editor);
    var schema = global$8({
      valid_elements: validElements,
      valid_children: '-li[p]'
    });
    global$3.each(schema.elements, function (rule) {
      if (!rule.attributes.class) {
        rule.attributes.class = {};
        rule.attributesOrder.push('class');
      }
      if (!rule.attributes.style) {
        rule.attributes.style = {};
        rule.attributesOrder.push('style');
      }
    });
    var domParser = global$6({}, schema);
    domParser.addAttributeFilter('style', function (nodes) {
      var i = nodes.length, node;
      while (i--) {
        node = nodes[i];
        node.attr('style', filterStyles(editor, validStyles, node, node.attr('style')));
        if (node.name === 'span' && node.parent && !node.attributes.length) {
          node.unwrap();
        }
      }
    });
    domParser.addAttributeFilter('class', function (nodes) {
      var i = nodes.length, node, className;
      while (i--) {
        node = nodes[i];
        className = node.attr('class');
        if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
          node.remove();
        }
        node.attr('class', null);
      }
    });
    domParser.addNodeFilter('del', function (nodes) {
      var i = nodes.length;
      while (i--) {
        nodes[i].remove();
      }
    });
    domParser.addNodeFilter('a', function (nodes) {
      var i = nodes.length, node, href, name;
      while (i--) {
        node = nodes[i];
        href = node.attr('href');
        name = node.attr('name');
        if (href && href.indexOf('#_msocom_') !== -1) {
          node.remove();
          continue;
        }
        if (href && href.indexOf('file://') === 0) {
          href = href.split('#')[1];
          if (href) {
            href = '#' + href;
          }
        }
        if (!href && !name) {
          node.unwrap();
        } else {
          if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
            node.unwrap();
            continue;
          }
          node.attr({
            href: href,
            name: name
          });
        }
      }
    });
    var rootNode = domParser.parse(content);
    if ($_59kbdnhxjh8lz0zr.shouldConvertWordFakeLists(editor)) {
      convertFakeListsToProperLists(rootNode);
    }
    content = global$9({ validate: editor.settings.validate }, schema).serialize(rootNode);
    return content;
  };
  var preProcess = function (editor, content) {
    return $_59kbdnhxjh8lz0zr.shouldUseDefaultFilters(editor) ? filterWordContent(editor, content) : content;
  };
  var $_d6zorbi8jh8lz10j = {
    preProcess: preProcess,
    isWordContent: isWordContent
  };

  var processResult = function (content, cancelled) {
    return {
      content: content,
      cancelled: cancelled
    };
  };
  var postProcessFilter = function (editor, html, internal, isWordHtml) {
    var tempBody = editor.dom.create('div', { style: 'display:none' }, html);
    var postProcessArgs = $_dotjevhwjh8lz0zq.firePastePostProcess(editor, tempBody, internal, isWordHtml);
    return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
  };
  var filterContent = function (editor, content, internal, isWordHtml) {
    var preProcessArgs = $_dotjevhwjh8lz0zq.firePastePreProcess(editor, content, internal, isWordHtml);
    if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) {
      return postProcessFilter(editor, preProcessArgs.content, internal, isWordHtml);
    } else {
      return processResult(preProcessArgs.content, preProcessArgs.isDefaultPrevented());
    }
  };
  var process = function (editor, html, internal) {
    var isWordHtml = $_d6zorbi8jh8lz10j.isWordContent(html);
    var content = isWordHtml ? $_d6zorbi8jh8lz10j.preProcess(editor, html) : html;
    return filterContent(editor, content, internal, isWordHtml);
  };
  var $_8pb2j8i7jh8lz10f = { process: process };

  var pasteHtml = function (editor, html) {
    editor.insertContent(html, {
      merge: $_59kbdnhxjh8lz0zr.shouldMergeFormats(editor),
      paste: true
    });
    return true;
  };
  var isAbsoluteUrl = function (url) {
    return /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url);
  };
  var isImageUrl = function (url) {
    return isAbsoluteUrl(url) && /.(gif|jpe?g|png)$/.test(url);
  };
  var createImage = function (editor, url, pasteHtmlFn) {
    editor.undoManager.extra(function () {
      pasteHtmlFn(editor, url);
    }, function () {
      editor.insertContent('<img src="' + url + '">');
    });
    return true;
  };
  var createLink = function (editor, url, pasteHtmlFn) {
    editor.undoManager.extra(function () {
      pasteHtmlFn(editor, url);
    }, function () {
      editor.execCommand('mceInsertLink', false, url);
    });
    return true;
  };
  var linkSelection = function (editor, html, pasteHtmlFn) {
    return editor.selection.isCollapsed() === false && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false;
  };
  var insertImage = function (editor, html, pasteHtmlFn) {
    return isImageUrl(html) ? createImage(editor, html, pasteHtmlFn) : false;
  };
  var smartInsertContent = function (editor, html) {
    global$3.each([
      linkSelection,
      insertImage,
      pasteHtml
    ], function (action) {
      return action(editor, html, pasteHtml) !== true;
    });
  };
  var insertContent = function (editor, html) {
    if ($_59kbdnhxjh8lz0zr.isSmartPasteEnabled(editor) === false) {
      pasteHtml(editor, html);
    } else {
      smartInsertContent(editor, html);
    }
  };
  var $_d0259ziejh8lz10u = {
    isImageUrl: isImageUrl,
    isAbsoluteUrl: isAbsoluteUrl,
    insertContent: insertContent
  };

  var pasteHtml$1 = function (editor, html, internalFlag) {
    var internal = internalFlag ? internalFlag : $_vdmj3i4jh8lz10b.isMarked(html);
    var args = $_8pb2j8i7jh8lz10f.process(editor, $_vdmj3i4jh8lz10b.unmark(html), internal);
    if (args.cancelled === false) {
      $_d0259ziejh8lz10u.insertContent(editor, args.content);
    }
  };
  var pasteText = function (editor, text) {
    text = editor.dom.encode(text).replace(/\r\n/g, '\n');
    text = $_q5v7hi5jh8lz10d.convert(text, editor.settings.forced_root_block, editor.settings.forced_root_block_attrs);
    pasteHtml$1(editor, text, false);
  };
  var getDataTransferItems = function (dataTransfer) {
    var items = {};
    var mceInternalUrlPrefix = 'data:text/mce-internal,';
    if (dataTransfer) {
      if (dataTransfer.getData) {
        var legacyText = dataTransfer.getData('Text');
        if (legacyText && legacyText.length > 0) {
          if (legacyText.indexOf(mceInternalUrlPrefix) === -1) {
            items['text/plain'] = legacyText;
          }
        }
      }
      if (dataTransfer.types) {
        for (var i = 0; i < dataTransfer.types.length; i++) {
          var contentType = dataTransfer.types[i];
          try {
            items[contentType] = dataTransfer.getData(contentType);
          } catch (ex) {
            items[contentType] = '';
          }
        }
      }
    }
    return items;
  };
  var getClipboardContent = function (editor, clipboardEvent) {
    var content = getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
    return $_exxhefidjh8lz10r.isMsEdge() ? global$3.extend(content, { 'text/html': '' }) : content;
  };
  var hasContentType = function (clipboardContent, mimeType) {
    return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
  };
  var hasHtmlOrText = function (content) {
    return hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
  };
  var getBase64FromUri = function (uri) {
    var idx;
    idx = uri.indexOf(',');
    if (idx !== -1) {
      return uri.substr(idx + 1);
    }
    return null;
  };
  var isValidDataUriImage = function (settings, imgElm) {
    return settings.images_dataimg_filter ? settings.images_dataimg_filter(imgElm) : true;
  };
  var extractFilename = function (editor, str) {
    var m = str.match(/([\s\S]+?)\.(?:jpeg|jpg|png|gif)$/i);
    return m ? editor.dom.encode(m[1]) : null;
  };
  var uniqueId = $_exxhefidjh8lz10r.createIdGenerator('mceclip');
  var pasteImage = function (editor, rng, reader, blob) {
    if (rng) {
      editor.selection.setRng(rng);
      rng = null;
    }
    var dataUri = reader.result;
    var base64 = getBase64FromUri(dataUri);
    var id = uniqueId();
    var name = editor.settings.images_reuse_filename && blob.name ? extractFilename(editor, blob.name) : id;
    var img = new Image();
    img.src = dataUri;
    if (isValidDataUriImage(editor.settings, img)) {
      var blobCache = editor.editorUpload.blobCache;
      var blobInfo = void 0, existingBlobInfo = void 0;
      existingBlobInfo = blobCache.findFirst(function (cachedBlobInfo) {
        return cachedBlobInfo.base64() === base64;
      });
      if (!existingBlobInfo) {
        blobInfo = blobCache.create(id, blob, base64, name);
        blobCache.add(blobInfo);
      } else {
        blobInfo = existingBlobInfo;
      }
      pasteHtml$1(editor, '<img src="' + blobInfo.blobUri() + '">', false);
    } else {
      pasteHtml$1(editor, '<img src="' + dataUri + '">', false);
    }
  };
  var isClipboardEvent = function (event) {
    return event.type === 'paste';
  };
  var pasteImageData = function (editor, e, rng) {
    var dataTransfer = isClipboardEvent(e) ? e.clipboardData : e.dataTransfer;
    function processItems(items) {
      var i, item, reader, hadImage = false;
      if (items) {
        for (i = 0; i < items.length; i++) {
          item = items[i];
          if (/^image\/(jpeg|png|gif|bmp)$/.test(item.type)) {
            var blob = item.getAsFile ? item.getAsFile() : item;
            reader = new window.FileReader();
            reader.onload = pasteImage.bind(null, editor, rng, reader, blob);
            reader.readAsDataURL(blob);
            e.preventDefault();
            hadImage = true;
          }
        }
      }
      return hadImage;
    }
    if (editor.settings.paste_data_images && dataTransfer) {
      return processItems(dataTransfer.items) || processItems(dataTransfer.files);
    }
  };
  var isBrokenAndroidClipboardEvent = function (e) {
    var clipboardData = e.clipboardData;
    return navigator.userAgent.indexOf('Android') !== -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
  };
  var isKeyboardPasteEvent = function (e) {
    return global$4.metaKeyPressed(e) && e.keyCode === 86 || e.shiftKey && e.keyCode === 45;
  };
  var registerEventHandlers = function (editor, pasteBin, pasteFormat) {
    var keyboardPasteTimeStamp = 0;
    var keyboardPastePlainTextState;
    editor.on('keydown', function (e) {
      function removePasteBinOnKeyUp(e) {
        if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
          pasteBin.remove();
        }
      }
      if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
        keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86;
        if (keyboardPastePlainTextState && global$1.webkit && navigator.userAgent.indexOf('Version/') !== -1) {
          return;
        }
        e.stopImmediatePropagation();
        keyboardPasteTimeStamp = new Date().getTime();
        if (global$1.ie && keyboardPastePlainTextState) {
          e.preventDefault();
          $_dotjevhwjh8lz0zq.firePaste(editor, true);
          return;
        }
        pasteBin.remove();
        pasteBin.create();
        editor.once('keyup', removePasteBinOnKeyUp);
        editor.once('paste', function () {
          editor.off('keyup', removePasteBinOnKeyUp);
        });
      }
    });
    function insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal) {
      var content, isPlainTextHtml;
      if (hasContentType(clipboardContent, 'text/html')) {
        content = clipboardContent['text/html'];
      } else {
        content = pasteBin.getHtml();
        internal = internal ? internal : $_vdmj3i4jh8lz10b.isMarked(content);
        if (pasteBin.isDefaultContent(content)) {
          plainTextMode = true;
        }
      }
      content = $_exxhefidjh8lz10r.trimHtml(content);
      pasteBin.remove();
      isPlainTextHtml = internal === false && $_q5v7hi5jh8lz10d.isPlainText(content);
      if (!content.length || isPlainTextHtml) {
        plainTextMode = true;
      }
      if (plainTextMode) {
        if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) {
          content = clipboardContent['text/plain'];
        } else {
          content = $_exxhefidjh8lz10r.innerText(content);
        }
      }
      if (pasteBin.isDefaultContent(content)) {
        if (!isKeyBoardPaste) {
          editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
        }
        return;
      }
      if (plainTextMode) {
        pasteText(editor, content);
      } else {
        pasteHtml$1(editor, content, internal);
      }
    }
    var getLastRng = function () {
      return pasteBin.getLastRng() || editor.selection.getRng();
    };
    editor.on('paste', function (e) {
      var clipboardTimer = new Date().getTime();
      var clipboardContent = getClipboardContent(editor, e);
      var clipboardDelay = new Date().getTime() - clipboardTimer;
      var isKeyBoardPaste = new Date().getTime() - keyboardPasteTimeStamp - clipboardDelay < 1000;
      var plainTextMode = pasteFormat.get() === 'text' || keyboardPastePlainTextState;
      var internal = hasContentType(clipboardContent, $_vdmj3i4jh8lz10b.internalHtmlMime());
      keyboardPastePlainTextState = false;
      if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
        pasteBin.remove();
        return;
      }
      if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e, getLastRng())) {
        pasteBin.remove();
        return;
      }
      if (!isKeyBoardPaste) {
        e.preventDefault();
      }
      if (global$1.ie && (!isKeyBoardPaste || e.ieFake) && !hasContentType(clipboardContent, 'text/html')) {
        pasteBin.create();
        editor.dom.bind(pasteBin.getEl(), 'paste', function (e) {
          e.stopPropagation();
        });
        editor.getDoc().execCommand('Paste', false, null);
        clipboardContent['text/html'] = pasteBin.getHtml();
      }
      if (hasContentType(clipboardContent, 'text/html')) {
        e.preventDefault();
        if (!internal) {
          internal = $_vdmj3i4jh8lz10b.isMarked(clipboardContent['text/html']);
        }
        insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
      } else {
        global$2.setEditorTimeout(editor, function () {
          insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
        }, 0);
      }
    });
  };
  var registerEventsAndFilters = function (editor, pasteBin, pasteFormat) {
    registerEventHandlers(editor, pasteBin, pasteFormat);
    var src;
    editor.parser.addNodeFilter('img', function (nodes, name, args) {
      var isPasteInsert = function (args) {
        return args.data && args.data.paste === true;
      };
      var remove = function (node) {
        if (!node.attr('data-mce-object') && src !== global$1.transparentSrc) {
          node.remove();
        }
      };
      var isWebKitFakeUrl = function (src) {
        return src.indexOf('webkit-fake-url') === 0;
      };
      var isDataUri = function (src) {
        return src.indexOf('data:') === 0;
      };
      if (!editor.settings.paste_data_images && isPasteInsert(args)) {
        var i = nodes.length;
        while (i--) {
          src = nodes[i].attributes.map.src;
          if (!src) {
            continue;
          }
          if (isWebKitFakeUrl(src)) {
            remove(nodes[i]);
          } else if (!editor.settings.allow_html_data_urls && isDataUri(src)) {
            remove(nodes[i]);
          }
        }
      }
    });
  };

  var getPasteBinParent = function (editor) {
    return global$1.ie && editor.inline ? document.body : editor.getBody();
  };
  var isExternalPasteBin = function (editor) {
    return getPasteBinParent(editor) !== editor.getBody();
  };
  var delegatePasteEvents = function (editor, pasteBinElm) {
    if (isExternalPasteBin(editor)) {
      editor.dom.bind(pasteBinElm, 'paste keyup', function (e) {
        setTimeout(function () {
          editor.fire('paste');
        }, 0);
      });
    }
  };
  var create = function (editor, lastRngCell, pasteBinDefaultContent) {
    var dom = editor.dom, body = editor.getBody();
    var pasteBinElm;
    lastRngCell.set(editor.selection.getRng());
    pasteBinElm = editor.dom.add(getPasteBinParent(editor), 'div', {
      'id': 'mcepastebin',
      'class': 'mce-pastebin',
      'contentEditable': true,
      'data-mce-bogus': 'all',
      'style': 'position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0'
    }, pasteBinDefaultContent);
    if (global$1.ie || global$1.gecko) {
      dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 65535 : -65535);
    }
    dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function (e) {
      e.stopPropagation();
    });
    delegatePasteEvents(editor, pasteBinElm);
    pasteBinElm.focus();
    editor.selection.select(pasteBinElm, true);
  };
  var remove = function (editor, lastRngCell) {
    if (getEl(editor)) {
      var pasteBinClone = void 0;
      var lastRng = lastRngCell.get();
      while (pasteBinClone = editor.dom.get('mcepastebin')) {
        editor.dom.remove(pasteBinClone);
        editor.dom.unbind(pasteBinClone);
      }
      if (lastRng) {
        editor.selection.setRng(lastRng);
      }
    }
    lastRngCell.set(null);
  };
  var getEl = function (editor) {
    return editor.dom.get('mcepastebin');
  };
  var getHtml = function (editor) {
    var pasteBinElm, pasteBinClones, i, dirtyWrappers, cleanWrapper;
    var copyAndRemove = function (toElm, fromElm) {
      toElm.appendChild(fromElm);
      editor.dom.remove(fromElm, true);
    };
    pasteBinClones = global$3.grep(getPasteBinParent(editor).childNodes, function (elm) {
      return elm.id === 'mcepastebin';
    });
    pasteBinElm = pasteBinClones.shift();
    global$3.each(pasteBinClones, function (pasteBinClone) {
      copyAndRemove(pasteBinElm, pasteBinClone);
    });
    dirtyWrappers = editor.dom.select('div[id=mcepastebin]', pasteBinElm);
    for (i = dirtyWrappers.length - 1; i >= 0; i--) {
      cleanWrapper = editor.dom.create('div');
      pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]);
      copyAndRemove(cleanWrapper, dirtyWrappers[i]);
    }
    return pasteBinElm ? pasteBinElm.innerHTML : '';
  };
  var getLastRng = function (lastRng) {
    return lastRng.get();
  };
  var isDefaultContent = function (pasteBinDefaultContent, content) {
    return content === pasteBinDefaultContent;
  };
  var isPasteBin = function (elm) {
    return elm && elm.id === 'mcepastebin';
  };
  var isDefault = function (editor, pasteBinDefaultContent) {
    var pasteBinElm = getEl(editor);
    return isPasteBin(pasteBinElm) && isDefaultContent(pasteBinDefaultContent, pasteBinElm.innerHTML);
  };
  var PasteBin = function (editor) {
    var lastRng = Cell(null);
    var pasteBinDefaultContent = '%MCEPASTEBIN%';
    return {
      create: function () {
        return create(editor, lastRng, pasteBinDefaultContent);
      },
      remove: function () {
        return remove(editor, lastRng);
      },
      getEl: function () {
        return getEl(editor);
      },
      getHtml: function () {
        return getHtml(editor);
      },
      getLastRng: function () {
        return getLastRng(lastRng);
      },
      isDefault: function () {
        return isDefault(editor, pasteBinDefaultContent);
      },
      isDefaultContent: function (content) {
        return isDefaultContent(pasteBinDefaultContent, content);
      }
    };
  };

  var Clipboard = function (editor, pasteFormat) {
    var pasteBin = PasteBin(editor);
    editor.on('preInit', function () {
      return registerEventsAndFilters(editor, pasteBin, pasteFormat);
    });
    return {
      pasteFormat: pasteFormat,
      pasteHtml: function (html, internalFlag) {
        return pasteHtml$1(editor, html, internalFlag);
      },
      pasteText: function (text) {
        return pasteText(editor, text);
      },
      pasteImageData: function (e, rng) {
        return pasteImageData(editor, e, rng);
      },
      getDataTransferItems: getDataTransferItems,
      hasHtmlOrText: hasHtmlOrText,
      hasContentType: hasContentType
    };
  };

  var noop = function () {
  };
  var hasWorkingClipboardApi = function (clipboardData) {
    return global$1.iOS === false && clipboardData !== undefined && typeof clipboardData.setData === 'function' && $_exxhefidjh8lz10r.isMsEdge() !== true;
  };
  var setHtml5Clipboard = function (clipboardData, html, text) {
    if (hasWorkingClipboardApi(clipboardData)) {
      try {
        clipboardData.clearData();
        clipboardData.setData('text/html', html);
        clipboardData.setData('text/plain', text);
        clipboardData.setData($_vdmj3i4jh8lz10b.internalHtmlMime(), html);
        return true;
      } catch (e) {
        return false;
      }
    } else {
      return false;
    }
  };
  var setClipboardData = function (evt, data, fallback, done) {
    if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
      evt.preventDefault();
      done();
    } else {
      fallback(data.html, done);
    }
  };
  var fallback = function (editor) {
    return function (html, done) {
      var markedHtml = $_vdmj3i4jh8lz10b.mark(html);
      var outer = editor.dom.create('div', {
        'contenteditable': 'false',
        'data-mce-bogus': 'all'
      });
      var inner = editor.dom.create('div', { contenteditable: 'true' }, markedHtml);
      editor.dom.setStyles(outer, {
        position: 'fixed',
        top: '0',
        left: '-3000px',
        width: '1000px',
        overflow: 'hidden'
      });
      outer.appendChild(inner);
      editor.dom.add(editor.getBody(), outer);
      var range = editor.selection.getRng();
      inner.focus();
      var offscreenRange = editor.dom.createRng();
      offscreenRange.selectNodeContents(inner);
      editor.selection.setRng(offscreenRange);
      setTimeout(function () {
        editor.selection.setRng(range);
        outer.parentNode.removeChild(outer);
        done();
      }, 0);
    };
  };
  var getData = function (editor) {
    return {
      html: editor.selection.getContent({ contextual: true }),
      text: editor.selection.getContent({ format: 'text' })
    };
  };
  var cut = function (editor) {
    return function (evt) {
      if (editor.selection.isCollapsed() === false) {
        setClipboardData(evt, getData(editor), fallback(editor), function () {
          setTimeout(function () {
            editor.execCommand('Delete');
          }, 0);
        });
      }
    };
  };
  var copy = function (editor) {
    return function (evt) {
      if (editor.selection.isCollapsed() === false) {
        setClipboardData(evt, getData(editor), fallback(editor), noop);
      }
    };
  };
  var register$1 = function (editor) {
    editor.on('cut', cut(editor));
    editor.on('copy', copy(editor));
  };
  var $_dic32vigjh8lz113 = { register: register$1 };

  var global$10 = tinymce.util.Tools.resolve('tinymce.dom.RangeUtils');

  var getCaretRangeFromEvent = function (editor, e) {
    return global$10.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc());
  };
  var isPlainTextFileUrl = function (content) {
    var plainTextContent = content['text/plain'];
    return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false;
  };
  var setFocusedRange = function (editor, rng) {
    editor.focus();
    editor.selection.setRng(rng);
  };
  var setup = function (editor, clipboard, draggingInternallyState) {
    if ($_59kbdnhxjh8lz0zr.shouldBlockDrop(editor)) {
      editor.on('dragend dragover draggesture dragdrop drop drag', function (e) {
        e.preventDefault();
        e.stopPropagation();
      });
    }
    if (!$_59kbdnhxjh8lz0zr.shouldPasteDataImages(editor)) {
      editor.on('drop', function (e) {
        var dataTransfer = e.dataTransfer;
        if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
          e.preventDefault();
        }
      });
    }
    editor.on('drop', function (e) {
      var dropContent, rng;
      rng = getCaretRangeFromEvent(editor, e);
      if (e.isDefaultPrevented() || draggingInternallyState.get()) {
        return;
      }
      dropContent = clipboard.getDataTransferItems(e.dataTransfer);
      var internal = clipboard.hasContentType(dropContent, $_vdmj3i4jh8lz10b.internalHtmlMime());
      if ((!clipboard.hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && clipboard.pasteImageData(e, rng)) {
        return;
      }
      if (rng && $_59kbdnhxjh8lz0zr.shouldFilterDrop(editor)) {
        var content_1 = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
        if (content_1) {
          e.preventDefault();
          global$2.setEditorTimeout(editor, function () {
            editor.undoManager.transact(function () {
              if (dropContent['mce-internal']) {
                editor.execCommand('Delete');
              }
              setFocusedRange(editor, rng);
              content_1 = $_exxhefidjh8lz10r.trimHtml(content_1);
              if (!dropContent['text/html']) {
                clipboard.pasteText(content_1);
              } else {
                clipboard.pasteHtml(content_1, internal);
              }
            });
          });
        }
      }
    });
    editor.on('dragstart', function (e) {
      draggingInternallyState.set(true);
    });
    editor.on('dragover dragend', function (e) {
      if ($_59kbdnhxjh8lz0zr.shouldPasteDataImages(editor) && draggingInternallyState.get() === false) {
        e.preventDefault();
        setFocusedRange(editor, getCaretRangeFromEvent(editor, e));
      }
      if (e.type === 'dragend') {
        draggingInternallyState.set(false);
      }
    });
  };
  var $_2b0t7zihjh8lz116 = { setup: setup };

  var setup$1 = function (editor) {
    var plugin = editor.plugins.paste;
    var preProcess = $_59kbdnhxjh8lz0zr.getPreProcess(editor);
    if (preProcess) {
      editor.on('PastePreProcess', function (e) {
        preProcess.call(plugin, plugin, e);
      });
    }
    var postProcess = $_59kbdnhxjh8lz0zr.getPostProcess(editor);
    if (postProcess) {
      editor.on('PastePostProcess', function (e) {
        postProcess.call(plugin, plugin, e);
      });
    }
  };
  var $_3fvf8sijjh8lz119 = { setup: setup$1 };

  function addPreProcessFilter(editor, filterFunc) {
    editor.on('PastePreProcess', function (e) {
      e.content = filterFunc(editor, e.content, e.internal, e.wordContent);
    });
  }
  function addPostProcessFilter(editor, filterFunc) {
    editor.on('PastePostProcess', function (e) {
      filterFunc(editor, e.node);
    });
  }
  function removeExplorerBrElementsAfterBlocks(editor, html) {
    if (!$_d6zorbi8jh8lz10j.isWordContent(html)) {
      return html;
    }
    var blockElements = [];
    global$3.each(editor.schema.getBlockElements(), function (block, blockName) {
      blockElements.push(blockName);
    });
    var explorerBlocksRegExp = new RegExp('(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*', 'g');
    html = $_exxhefidjh8lz10r.filter(html, [[
        explorerBlocksRegExp,
        '$1'
      ]]);
    html = $_exxhefidjh8lz10r.filter(html, [
      [
        /<br><br>/g,
        '<BR><BR>'
      ],
      [
        /<br>/g,
        ' '
      ],
      [
        /<BR><BR>/g,
        '<br>'
      ]
    ]);
    return html;
  }
  function removeWebKitStyles(editor, content, internal, isWordHtml) {
    if (isWordHtml || internal) {
      return content;
    }
    var webKitStylesSetting = $_59kbdnhxjh8lz0zr.getWebkitStyles(editor);
    var webKitStyles;
    if ($_59kbdnhxjh8lz0zr.shouldRemoveWebKitStyles(editor) === false || webKitStylesSetting === 'all') {
      return content;
    }
    if (webKitStylesSetting) {
      webKitStyles = webKitStylesSetting.split(/[, ]/);
    }
    if (webKitStyles) {
      var dom_1 = editor.dom, node_1 = editor.selection.getNode();
      content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function (all, before, value, after) {
        var inputStyles = dom_1.parseStyle(dom_1.decode(value));
        var outputStyles = {};
        if (webKitStyles === 'none') {
          return before + after;
        }
        for (var i = 0; i < webKitStyles.length; i++) {
          var inputValue = inputStyles[webKitStyles[i]], currentValue = dom_1.getStyle(node_1, webKitStyles[i], true);
          if (/color/.test(webKitStyles[i])) {
            inputValue = dom_1.toHex(inputValue);
            currentValue = dom_1.toHex(currentValue);
          }
          if (currentValue !== inputValue) {
            outputStyles[webKitStyles[i]] = inputValue;
          }
        }
        outputStyles = dom_1.serializeStyle(outputStyles, 'span');
        if (outputStyles) {
          return before + ' style="' + outputStyles + '"' + after;
        }
        return before + after;
      });
    } else {
      content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
    }
    content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function (all, before, value, after) {
      return before + ' style="' + value + '"' + after;
    });
    return content;
  }
  function removeUnderlineAndFontInAnchor(editor, root) {
    editor.$('a', root).find('font,u').each(function (i, node) {
      editor.dom.remove(node, true);
    });
  }
  var setup$2 = function (editor) {
    if (global$1.webkit) {
      addPreProcessFilter(editor, removeWebKitStyles);
    }
    if (global$1.ie) {
      addPreProcessFilter(editor, removeExplorerBrElementsAfterBlocks);
      addPostProcessFilter(editor, removeUnderlineAndFontInAnchor);
    }
  };
  var $_cmw2n5ikjh8lz11b = { setup: setup$2 };

  var noop$1 = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
  };
  var noarg = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return f();
    };
  };
  var compose = function (fa, fb) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return fa(fb.apply(null, arguments));
    };
  };
  var constant = function (value) {
    return function () {
      return value;
    };
  };
  var identity = function (x) {
    return x;
  };
  var tripleEquals = function (a, b) {
    return a === b;
  };
  var curry = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = new Array(arguments.length - 1);
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      var newArgs = new Array(arguments.length);
      for (var j = 0; j < newArgs.length; j++)
        newArgs[j] = arguments[j];
      var all = args.concat(newArgs);
      return f.apply(null, all);
    };
  };
  var not = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return !f.apply(null, arguments);
    };
  };
  var die = function (msg) {
    return function () {
      throw new Error(msg);
    };
  };
  var apply = function (f) {
    return f();
  };
  var call = function (f) {
    f();
  };
  var never = constant(false);
  var always = constant(true);
  var $_6je1ceimjh8lz11h = {
    noop: noop$1,
    noarg: noarg,
    compose: compose,
    constant: constant,
    identity: identity,
    tripleEquals: tripleEquals,
    curry: curry,
    not: not,
    die: die,
    apply: apply,
    call: call,
    never: never,
    always: always
  };

  var stateChange = function (editor, clipboard, e) {
    var ctrl = e.control;
    ctrl.active(clipboard.pasteFormat.get() === 'text');
    editor.on('PastePlainTextToggle', function (e) {
      ctrl.active(e.state);
    });
  };
  var register$2 = function (editor, clipboard) {
    var postRender = $_6je1ceimjh8lz11h.curry(stateChange, editor, clipboard);
    editor.addButton('pastetext', {
      active: false,
      icon: 'pastetext',
      tooltip: 'Paste as text',
      cmd: 'mceTogglePlainTextPaste',
      onPostRender: postRender
    });
    editor.addMenuItem('pastetext', {
      text: 'Paste as text',
      selectable: true,
      active: clipboard.pasteFormat,
      cmd: 'mceTogglePlainTextPaste',
      onPostRender: postRender
    });
  };
  var $_f92o70iljh8lz11e = { register: register$2 };

  global.add('paste', function (editor) {
    if ($_5zap27hsjh8lz0zl.hasProPlugin(editor) === false) {
      var userIsInformedState = Cell(false);
      var draggingInternallyState = Cell(false);
      var pasteFormat = Cell($_59kbdnhxjh8lz0zr.isPasteAsTextEnabled(editor) ? 'text' : 'html');
      var clipboard = Clipboard(editor, pasteFormat);
      var quirks = $_cmw2n5ikjh8lz11b.setup(editor);
      $_f92o70iljh8lz11e.register(editor, clipboard);
      $_dw9jlohujh8lz0zn.register(editor, clipboard, userIsInformedState);
      $_3fvf8sijjh8lz119.setup(editor);
      $_dic32vigjh8lz113.register(editor);
      $_2b0t7zihjh8lz116.setup(editor, clipboard, draggingInternallyState);
      return $_b74kiihtjh8lz0zm.get(clipboard, quirks);
    }
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-preview", ["tinymce"], function() {
  return (function() {
(function () {
var preview = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.Env');

  var getPreviewDialogWidth = function (editor) {
    return parseInt(editor.getParam('plugin_preview_width', '650'), 10);
  };
  var getPreviewDialogHeight = function (editor) {
    return parseInt(editor.getParam('plugin_preview_height', '500'), 10);
  };
  var getContentStyle = function (editor) {
    return editor.getParam('content_style', '');
  };
  var $_71hkk4isjh8lz146 = {
    getPreviewDialogWidth: getPreviewDialogWidth,
    getPreviewDialogHeight: getPreviewDialogHeight,
    getContentStyle: getContentStyle
  };

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var getPreviewHtml = function (editor) {
    var previewHtml;
    var headHtml = '';
    var encode = editor.dom.encode;
    var contentStyle = $_71hkk4isjh8lz146.getContentStyle(editor);
    headHtml += '<base href="' + encode(editor.documentBaseURI.getURI()) + '">';
    if (contentStyle) {
      headHtml += '<style type="text/css">' + contentStyle + '</style>';
    }
    global$2.each(editor.contentCSS, function (url) {
      headHtml += '<link type="text/css" rel="stylesheet" href="' + encode(editor.documentBaseURI.toAbsolute(url)) + '">';
    });
    var bodyId = editor.settings.body_id || 'tinymce';
    if (bodyId.indexOf('=') !== -1) {
      bodyId = editor.getParam('body_id', '', 'hash');
      bodyId = bodyId[editor.id] || bodyId;
    }
    var bodyClass = editor.settings.body_class || '';
    if (bodyClass.indexOf('=') !== -1) {
      bodyClass = editor.getParam('body_class', '', 'hash');
      bodyClass = bodyClass[editor.id] || '';
    }
    var preventClicksOnLinksScript = '<script>' + 'document.addEventListener && document.addEventListener("click", function(e) {' + 'for (var elm = e.target; elm; elm = elm.parentNode) {' + 'if (elm.nodeName === "A") {' + 'e.preventDefault();' + '}' + '}' + '}, false);' + '</script> ';
    var dirAttr = editor.settings.directionality ? ' dir="' + editor.settings.directionality + '"' : '';
    previewHtml = '<!DOCTYPE html>' + '<html>' + '<head>' + headHtml + '</head>' + '<body id="' + encode(bodyId) + '" class="mce-content-body ' + encode(bodyClass) + '"' + encode(dirAttr) + '>' + editor.getContent() + preventClicksOnLinksScript + '</body>' + '</html>';
    return previewHtml;
  };
  var injectIframeContent = function (editor, iframe, sandbox) {
    var previewHtml = getPreviewHtml(editor);
    if (!sandbox) {
      var doc = iframe.contentWindow.document;
      doc.open();
      doc.write(previewHtml);
      doc.close();
    } else {
      iframe.src = 'data:text/html;charset=utf-8,' + encodeURIComponent(previewHtml);
    }
  };
  var $_65q2xtitjh8lz147 = {
    getPreviewHtml: getPreviewHtml,
    injectIframeContent: injectIframeContent
  };

  var open = function (editor) {
    var sandbox = !global$1.ie;
    var dialogHtml = '<iframe src="" frameborder="0"' + (sandbox ? ' sandbox="allow-scripts"' : '') + '></iframe>';
    var dialogWidth = $_71hkk4isjh8lz146.getPreviewDialogWidth(editor);
    var dialogHeight = $_71hkk4isjh8lz146.getPreviewDialogHeight(editor);
    editor.windowManager.open({
      title: 'Preview',
      width: dialogWidth,
      height: dialogHeight,
      html: dialogHtml,
      buttons: {
        text: 'Close',
        onclick: function (e) {
          e.control.parent().parent().close();
        }
      },
      onPostRender: function (e) {
        var iframeElm = e.control.getEl('body').firstChild;
        $_65q2xtitjh8lz147.injectIframeContent(editor, iframeElm, sandbox);
      }
    });
  };
  var $_bncxn7iqjh8lz144 = { open: open };

  var register = function (editor) {
    editor.addCommand('mcePreview', function () {
      $_bncxn7iqjh8lz144.open(editor);
    });
  };
  var $_5cptv5ipjh8lz143 = { register: register };

  var register$1 = function (editor) {
    editor.addButton('preview', {
      title: 'Preview',
      cmd: 'mcePreview'
    });
    editor.addMenuItem('preview', {
      text: 'Preview',
      cmd: 'mcePreview',
      context: 'view'
    });
  };
  var $_fy0w72ivjh8lz14a = { register: register$1 };

  global.add('preview', function (editor) {
    $_5cptv5ipjh8lz143.register(editor);
    $_fy0w72ivjh8lz14a.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-print", ["tinymce"], function() {
  return (function() {
(function () {
var print = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var register = function (editor) {
    editor.addCommand('mcePrint', function () {
      editor.getWin().print();
    });
  };
  var $_62cei9iyjh8lz14q = { register: register };

  var register$1 = function (editor) {
    editor.addButton('print', {
      title: 'Print',
      cmd: 'mcePrint'
    });
    editor.addMenuItem('print', {
      text: 'Print',
      cmd: 'mcePrint',
      icon: 'print'
    });
  };
  var $_75d5qoizjh8lz14r = { register: register$1 };

  global.add('print', function (editor) {
    $_62cei9iyjh8lz14q.register(editor);
    $_75d5qoizjh8lz14r.register(editor);
    editor.addShortcut('Meta+P', '', 'mcePrint');
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-save", ["tinymce"], function() {
  return (function() {
(function () {
var save = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var enableWhenDirty = function (editor) {
    return editor.getParam('save_enablewhendirty', true);
  };
  var hasOnSaveCallback = function (editor) {
    return !!editor.getParam('save_onsavecallback');
  };
  var hasOnCancelCallback = function (editor) {
    return !!editor.getParam('save_oncancelcallback');
  };
  var $_8l09i7j6jh8lz151 = {
    enableWhenDirty: enableWhenDirty,
    hasOnSaveCallback: hasOnSaveCallback,
    hasOnCancelCallback: hasOnCancelCallback
  };

  var displayErrorMessage = function (editor, message) {
    editor.notificationManager.open({
      text: editor.translate(message),
      type: 'error'
    });
  };
  var save = function (editor) {
    var formObj;
    formObj = global$1.DOM.getParent(editor.id, 'form');
    if ($_8l09i7j6jh8lz151.enableWhenDirty(editor) && !editor.isDirty()) {
      return;
    }
    editor.save();
    if ($_8l09i7j6jh8lz151.hasOnSaveCallback(editor)) {
      editor.execCallback('save_onsavecallback', editor);
      editor.nodeChanged();
      return;
    }
    if (formObj) {
      editor.setDirty(false);
      if (!formObj.onsubmit || formObj.onsubmit()) {
        if (typeof formObj.submit === 'function') {
          formObj.submit();
        } else {
          displayErrorMessage(editor, 'Error: Form submit field collision.');
        }
      }
      editor.nodeChanged();
    } else {
      displayErrorMessage(editor, 'Error: No form element found.');
    }
  };
  var cancel = function (editor) {
    var h = global$2.trim(editor.startContent);
    if ($_8l09i7j6jh8lz151.hasOnCancelCallback(editor)) {
      editor.execCallback('save_oncancelcallback', editor);
      return;
    }
    editor.setContent(h);
    editor.undoManager.clear();
    editor.nodeChanged();
  };
  var $_9mbazj3jh8lz14y = {
    save: save,
    cancel: cancel
  };

  var register = function (editor) {
    editor.addCommand('mceSave', function () {
      $_9mbazj3jh8lz14y.save(editor);
    });
    editor.addCommand('mceCancel', function () {
      $_9mbazj3jh8lz14y.cancel(editor);
    });
  };
  var $_eyzj6nj2jh8lz14x = { register: register };

  var stateToggle = function (editor) {
    return function (e) {
      var ctrl = e.control;
      editor.on('nodeChange dirty', function () {
        ctrl.disabled($_8l09i7j6jh8lz151.enableWhenDirty(editor) && !editor.isDirty());
      });
    };
  };
  var register$1 = function (editor) {
    editor.addButton('save', {
      icon: 'save',
      text: 'Save',
      cmd: 'mceSave',
      disabled: true,
      onPostRender: stateToggle(editor)
    });
    editor.addButton('cancel', {
      text: 'Cancel',
      icon: false,
      cmd: 'mceCancel',
      disabled: true,
      onPostRender: stateToggle(editor)
    });
    editor.addShortcut('Meta+S', '', 'mceSave');
  };
  var $_3t71l4j7jh8lz152 = { register: register$1 };

  global.add('save', function (editor) {
    $_3t71l4j7jh8lz152.register(editor);
    $_eyzj6nj2jh8lz14x.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-searchreplace", ["tinymce"], function() {
  return (function() {
(function () {
var searchreplace = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  function isContentEditableFalse(node) {
    return node && node.nodeType === 1 && node.contentEditable === 'false';
  }
  function findAndReplaceDOMText(regex, node, replacementNode, captureGroup, schema) {
    var m;
    var matches = [];
    var text, count = 0, doc;
    var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap;
    doc = node.ownerDocument;
    blockElementsMap = schema.getBlockElements();
    hiddenTextElementsMap = schema.getWhiteSpaceElements();
    shortEndedElementsMap = schema.getShortEndedElements();
    function getMatchIndexes(m, captureGroup) {
      captureGroup = captureGroup || 0;
      if (!m[0]) {
        throw new Error('findAndReplaceDOMText cannot handle zero-length matches');
      }
      var index = m.index;
      if (captureGroup > 0) {
        var cg = m[captureGroup];
        if (!cg) {
          throw new Error('Invalid capture group');
        }
        index += m[0].indexOf(cg);
        m[0] = cg;
      }
      return [
        index,
        index + m[0].length,
        [m[0]]
      ];
    }
    function getText(node) {
      var txt;
      if (node.nodeType === 3) {
        return node.data;
      }
      if (hiddenTextElementsMap[node.nodeName] && !blockElementsMap[node.nodeName]) {
        return '';
      }
      txt = '';
      if (isContentEditableFalse(node)) {
        return '\n';
      }
      if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) {
        txt += '\n';
      }
      if (node = node.firstChild) {
        do {
          txt += getText(node);
        } while (node = node.nextSibling);
      }
      return txt;
    }
    function stepThroughMatches(node, matches, replaceFn) {
      var startNode, endNode, startNodeIndex, endNodeIndex, innerNodes = [], atIndex = 0, curNode = node, matchLocation = matches.shift(), matchIndex = 0;
      out:
        while (true) {
          if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName] || isContentEditableFalse(curNode)) {
            atIndex++;
          }
          if (curNode.nodeType === 3) {
            if (!endNode && curNode.length + atIndex >= matchLocation[1]) {
              endNode = curNode;
              endNodeIndex = matchLocation[1] - atIndex;
            } else if (startNode) {
              innerNodes.push(curNode);
            }
            if (!startNode && curNode.length + atIndex > matchLocation[0]) {
              startNode = curNode;
              startNodeIndex = matchLocation[0] - atIndex;
            }
            atIndex += curNode.length;
          }
          if (startNode && endNode) {
            curNode = replaceFn({
              startNode: startNode,
              startNodeIndex: startNodeIndex,
              endNode: endNode,
              endNodeIndex: endNodeIndex,
              innerNodes: innerNodes,
              match: matchLocation[2],
              matchIndex: matchIndex
            });
            atIndex -= endNode.length - endNodeIndex;
            startNode = null;
            endNode = null;
            innerNodes = [];
            matchLocation = matches.shift();
            matchIndex++;
            if (!matchLocation) {
              break;
            }
          } else if ((!hiddenTextElementsMap[curNode.nodeName] || blockElementsMap[curNode.nodeName]) && curNode.firstChild) {
            if (!isContentEditableFalse(curNode)) {
              curNode = curNode.firstChild;
              continue;
            }
          } else if (curNode.nextSibling) {
            curNode = curNode.nextSibling;
            continue;
          }
          while (true) {
            if (curNode.nextSibling) {
              curNode = curNode.nextSibling;
              break;
            } else if (curNode.parentNode !== node) {
              curNode = curNode.parentNode;
            } else {
              break out;
            }
          }
        }
    }
    function genReplacer(nodeName) {
      var makeReplacementNode;
      if (typeof nodeName !== 'function') {
        var stencilNode_1 = nodeName.nodeType ? nodeName : doc.createElement(nodeName);
        makeReplacementNode = function (fill, matchIndex) {
          var clone = stencilNode_1.cloneNode(false);
          clone.setAttribute('data-mce-index', matchIndex);
          if (fill) {
            clone.appendChild(doc.createTextNode(fill));
          }
          return clone;
        };
      } else {
        makeReplacementNode = nodeName;
      }
      return function (range) {
        var before;
        var after;
        var parentNode;
        var startNode = range.startNode;
        var endNode = range.endNode;
        var matchIndex = range.matchIndex;
        if (startNode === endNode) {
          var node_1 = startNode;
          parentNode = node_1.parentNode;
          if (range.startNodeIndex > 0) {
            before = doc.createTextNode(node_1.data.substring(0, range.startNodeIndex));
            parentNode.insertBefore(before, node_1);
          }
          var el = makeReplacementNode(range.match[0], matchIndex);
          parentNode.insertBefore(el, node_1);
          if (range.endNodeIndex < node_1.length) {
            after = doc.createTextNode(node_1.data.substring(range.endNodeIndex));
            parentNode.insertBefore(after, node_1);
          }
          node_1.parentNode.removeChild(node_1);
          return el;
        }
        before = doc.createTextNode(startNode.data.substring(0, range.startNodeIndex));
        after = doc.createTextNode(endNode.data.substring(range.endNodeIndex));
        var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex);
        var innerEls = [];
        for (var i = 0, l = range.innerNodes.length; i < l; ++i) {
          var innerNode = range.innerNodes[i];
          var innerEl = makeReplacementNode(innerNode.data, matchIndex);
          innerNode.parentNode.replaceChild(innerEl, innerNode);
          innerEls.push(innerEl);
        }
        var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex);
        parentNode = startNode.parentNode;
        parentNode.insertBefore(before, startNode);
        parentNode.insertBefore(elA, startNode);
        parentNode.removeChild(startNode);
        parentNode = endNode.parentNode;
        parentNode.insertBefore(elB, endNode);
        parentNode.insertBefore(after, endNode);
        parentNode.removeChild(endNode);
        return elB;
      };
    }
    text = getText(node);
    if (!text) {
      return;
    }
    if (regex.global) {
      while (m = regex.exec(text)) {
        matches.push(getMatchIndexes(m, captureGroup));
      }
    } else {
      m = text.match(regex);
      matches.push(getMatchIndexes(m, captureGroup));
    }
    if (matches.length) {
      count = matches.length;
      stepThroughMatches(node, matches, genReplacer(replacementNode));
    }
    return count;
  }
  var $_fsoyimjejh8lz15q = { findAndReplaceDOMText: findAndReplaceDOMText };

  var getElmIndex = function (elm) {
    var value = elm.getAttribute('data-mce-index');
    if (typeof value === 'number') {
      return '' + value;
    }
    return value;
  };
  var markAllMatches = function (editor, currentIndexState, regex) {
    var node, marker;
    marker = editor.dom.create('span', { 'data-mce-bogus': 1 });
    marker.className = 'mce-match-marker';
    node = editor.getBody();
    done(editor, currentIndexState, false);
    return $_fsoyimjejh8lz15q.findAndReplaceDOMText(regex, node, marker, false, editor.schema);
  };
  var unwrap = function (node) {
    var parentNode = node.parentNode;
    if (node.firstChild) {
      parentNode.insertBefore(node.firstChild, node);
    }
    node.parentNode.removeChild(node);
  };
  var findSpansByIndex = function (editor, index) {
    var nodes;
    var spans = [];
    nodes = global$1.toArray(editor.getBody().getElementsByTagName('span'));
    if (nodes.length) {
      for (var i = 0; i < nodes.length; i++) {
        var nodeIndex = getElmIndex(nodes[i]);
        if (nodeIndex === null || !nodeIndex.length) {
          continue;
        }
        if (nodeIndex === index.toString()) {
          spans.push(nodes[i]);
        }
      }
    }
    return spans;
  };
  var moveSelection = function (editor, currentIndexState, forward) {
    var testIndex = currentIndexState.get();
    var dom = editor.dom;
    forward = forward !== false;
    if (forward) {
      testIndex++;
    } else {
      testIndex--;
    }
    dom.removeClass(findSpansByIndex(editor, currentIndexState.get()), 'mce-match-marker-selected');
    var spans = findSpansByIndex(editor, testIndex);
    if (spans.length) {
      dom.addClass(findSpansByIndex(editor, testIndex), 'mce-match-marker-selected');
      editor.selection.scrollIntoView(spans[0]);
      return testIndex;
    }
    return -1;
  };
  var removeNode = function (dom, node) {
    var parent = node.parentNode;
    dom.remove(node);
    if (dom.isEmpty(parent)) {
      dom.remove(parent);
    }
  };
  var find = function (editor, currentIndexState, text, matchCase, wholeWord) {
    text = text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
    text = text.replace(/\s/g, '\\s');
    text = wholeWord ? '\\b' + text + '\\b' : text;
    var count = markAllMatches(editor, currentIndexState, new RegExp(text, matchCase ? 'g' : 'gi'));
    if (count) {
      currentIndexState.set(-1);
      currentIndexState.set(moveSelection(editor, currentIndexState, true));
    }
    return count;
  };
  var next = function (editor, currentIndexState) {
    var index = moveSelection(editor, currentIndexState, true);
    if (index !== -1) {
      currentIndexState.set(index);
    }
  };
  var prev = function (editor, currentIndexState) {
    var index = moveSelection(editor, currentIndexState, false);
    if (index !== -1) {
      currentIndexState.set(index);
    }
  };
  var isMatchSpan = function (node) {
    var matchIndex = getElmIndex(node);
    return matchIndex !== null && matchIndex.length > 0;
  };
  var replace = function (editor, currentIndexState, text, forward, all) {
    var i, nodes, node, matchIndex, currentMatchIndex, nextIndex = currentIndexState.get(), hasMore;
    forward = forward !== false;
    node = editor.getBody();
    nodes = global$1.grep(global$1.toArray(node.getElementsByTagName('span')), isMatchSpan);
    for (i = 0; i < nodes.length; i++) {
      var nodeIndex = getElmIndex(nodes[i]);
      matchIndex = currentMatchIndex = parseInt(nodeIndex, 10);
      if (all || matchIndex === currentIndexState.get()) {
        if (text.length) {
          nodes[i].firstChild.nodeValue = text;
          unwrap(nodes[i]);
        } else {
          removeNode(editor.dom, nodes[i]);
        }
        while (nodes[++i]) {
          matchIndex = parseInt(getElmIndex(nodes[i]), 10);
          if (matchIndex === currentMatchIndex) {
            removeNode(editor.dom, nodes[i]);
          } else {
            i--;
            break;
          }
        }
        if (forward) {
          nextIndex--;
        }
      } else if (currentMatchIndex > currentIndexState.get()) {
        nodes[i].setAttribute('data-mce-index', currentMatchIndex - 1);
      }
    }
    currentIndexState.set(nextIndex);
    if (forward) {
      hasMore = hasNext(editor, currentIndexState);
      next(editor, currentIndexState);
    } else {
      hasMore = hasPrev(editor, currentIndexState);
      prev(editor, currentIndexState);
    }
    return !all && hasMore;
  };
  var done = function (editor, currentIndexState, keepEditorSelection) {
    var i, nodes, startContainer, endContainer;
    nodes = global$1.toArray(editor.getBody().getElementsByTagName('span'));
    for (i = 0; i < nodes.length; i++) {
      var nodeIndex = getElmIndex(nodes[i]);
      if (nodeIndex !== null && nodeIndex.length) {
        if (nodeIndex === currentIndexState.get().toString()) {
          if (!startContainer) {
            startContainer = nodes[i].firstChild;
          }
          endContainer = nodes[i].firstChild;
        }
        unwrap(nodes[i]);
      }
    }
    if (startContainer && endContainer) {
      var rng = editor.dom.createRng();
      rng.setStart(startContainer, 0);
      rng.setEnd(endContainer, endContainer.data.length);
      if (keepEditorSelection !== false) {
        editor.selection.setRng(rng);
      }
      return rng;
    }
  };
  var hasNext = function (editor, currentIndexState) {
    return findSpansByIndex(editor, currentIndexState.get() + 1).length > 0;
  };
  var hasPrev = function (editor, currentIndexState) {
    return findSpansByIndex(editor, currentIndexState.get() - 1).length > 0;
  };
  var $_84lfczjcjh8lz15j = {
    done: done,
    find: find,
    next: next,
    prev: prev,
    replace: replace,
    hasNext: hasNext,
    hasPrev: hasPrev
  };

  var get = function (editor, currentIndexState) {
    var done = function (keepEditorSelection) {
      return $_84lfczjcjh8lz15j.done(editor, currentIndexState, keepEditorSelection);
    };
    var find = function (text, matchCase, wholeWord) {
      return $_84lfczjcjh8lz15j.find(editor, currentIndexState, text, matchCase, wholeWord);
    };
    var next = function () {
      return $_84lfczjcjh8lz15j.next(editor, currentIndexState);
    };
    var prev = function () {
      return $_84lfczjcjh8lz15j.prev(editor, currentIndexState);
    };
    var replace = function (text, forward, all) {
      return $_84lfczjcjh8lz15j.replace(editor, currentIndexState, text, forward, all);
    };
    return {
      done: done,
      find: find,
      next: next,
      prev: prev,
      replace: replace
    };
  };
  var $_9m9g6ojbjh8lz15h = { get: get };

  var open = function (editor, currentIndexState) {
    var last = {}, selectedText;
    editor.undoManager.add();
    selectedText = global$1.trim(editor.selection.getContent({ format: 'text' }));
    function updateButtonStates() {
      win.statusbar.find('#next').disabled($_84lfczjcjh8lz15j.hasNext(editor, currentIndexState) === false);
      win.statusbar.find('#prev').disabled($_84lfczjcjh8lz15j.hasPrev(editor, currentIndexState) === false);
    }
    function notFoundAlert() {
      editor.windowManager.alert('Could not find the specified string.', function () {
        win.find('#find')[0].focus();
      });
    }
    var win = editor.windowManager.open({
      layout: 'flex',
      pack: 'center',
      align: 'center',
      onClose: function () {
        editor.focus();
        $_84lfczjcjh8lz15j.done(editor, currentIndexState);
        editor.undoManager.add();
      },
      onSubmit: function (e) {
        var count, caseState, text, wholeWord;
        e.preventDefault();
        caseState = win.find('#case').checked();
        wholeWord = win.find('#words').checked();
        text = win.find('#find').value();
        if (!text.length) {
          $_84lfczjcjh8lz15j.done(editor, currentIndexState, false);
          win.statusbar.items().slice(1).disabled(true);
          return;
        }
        if (last.text === text && last.caseState === caseState && last.wholeWord === wholeWord) {
          if (!$_84lfczjcjh8lz15j.hasNext(editor, currentIndexState)) {
            notFoundAlert();
            return;
          }
          $_84lfczjcjh8lz15j.next(editor, currentIndexState);
          updateButtonStates();
          return;
        }
        count = $_84lfczjcjh8lz15j.find(editor, currentIndexState, text, caseState, wholeWord);
        if (!count) {
          notFoundAlert();
        }
        win.statusbar.items().slice(1).disabled(count === 0);
        updateButtonStates();
        last = {
          text: text,
          caseState: caseState,
          wholeWord: wholeWord
        };
      },
      buttons: [
        {
          text: 'Find',
          subtype: 'primary',
          onclick: function () {
            win.submit();
          }
        },
        {
          text: 'Replace',
          disabled: true,
          onclick: function () {
            if (!$_84lfczjcjh8lz15j.replace(editor, currentIndexState, win.find('#replace').value())) {
              win.statusbar.items().slice(1).disabled(true);
              currentIndexState.set(-1);
              last = {};
            }
          }
        },
        {
          text: 'Replace all',
          disabled: true,
          onclick: function () {
            $_84lfczjcjh8lz15j.replace(editor, currentIndexState, win.find('#replace').value(), true, true);
            win.statusbar.items().slice(1).disabled(true);
            last = {};
          }
        },
        {
          type: 'spacer',
          flex: 1
        },
        {
          text: 'Prev',
          name: 'prev',
          disabled: true,
          onclick: function () {
            $_84lfczjcjh8lz15j.prev(editor, currentIndexState);
            updateButtonStates();
          }
        },
        {
          text: 'Next',
          name: 'next',
          disabled: true,
          onclick: function () {
            $_84lfczjcjh8lz15j.next(editor, currentIndexState);
            updateButtonStates();
          }
        }
      ],
      title: 'Find and replace',
      items: {
        type: 'form',
        padding: 20,
        labelGap: 30,
        spacing: 10,
        items: [
          {
            type: 'textbox',
            name: 'find',
            size: 40,
            label: 'Find',
            value: selectedText
          },
          {
            type: 'textbox',
            name: 'replace',
            size: 40,
            label: 'Replace with'
          },
          {
            type: 'checkbox',
            name: 'case',
            text: 'Match case',
            label: ' '
          },
          {
            type: 'checkbox',
            name: 'words',
            text: 'Whole words',
            label: ' '
          }
        ]
      }
    });
  };
  var $_14sx6wjgjh8lz15v = { open: open };

  var register = function (editor, currentIndexState) {
    editor.addCommand('SearchReplace', function () {
      $_14sx6wjgjh8lz15v.open(editor, currentIndexState);
    });
  };
  var $_80q66sjfjh8lz15u = { register: register };

  var showDialog = function (editor, currentIndexState) {
    return function () {
      $_14sx6wjgjh8lz15v.open(editor, currentIndexState);
    };
  };
  var register$1 = function (editor, currentIndexState) {
    editor.addMenuItem('searchreplace', {
      text: 'Find and replace',
      shortcut: 'Meta+F',
      onclick: showDialog(editor, currentIndexState),
      separator: 'before',
      context: 'edit'
    });
    editor.addButton('searchreplace', {
      tooltip: 'Find and replace',
      onclick: showDialog(editor, currentIndexState)
    });
    editor.shortcuts.add('Meta+F', '', showDialog(editor, currentIndexState));
  };
  var $_b8zyomjhjh8lz15y = { register: register$1 };

  global.add('searchreplace', function (editor) {
    var currentIndexState = Cell(-1);
    $_80q66sjfjh8lz15u.register(editor, currentIndexState);
    $_b8zyomjhjh8lz15y.register(editor, currentIndexState);
    return $_9m9g6ojbjh8lz15h.get(editor, currentIndexState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-spellchecker", ["tinymce"], function() {
  return (function() {
(function () {
var spellchecker = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var hasProPlugin = function (editor) {
    if (/(^|[ ,])tinymcespellchecker([, ]|$)/.test(editor.settings.plugins) && global.get('tinymcespellchecker')) {
      if (typeof window.console !== 'undefined' && window.console.log) {
        window.console.log('Spell Checker Pro is incompatible with Spell Checker plugin! ' + 'Remove \'spellchecker\' from the \'plugins\' option.');
      }
      return true;
    } else {
      return false;
    }
  };
  var $_2a4jkrjljh8lz172 = { hasProPlugin: hasProPlugin };

  var getLanguages = function (editor) {
    var defaultLanguages = 'English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr_FR,German=de,Italian=it,Polish=pl,Portuguese=pt_BR,Spanish=es,Swedish=sv';
    return editor.getParam('spellchecker_languages', defaultLanguages);
  };
  var getLanguage = function (editor) {
    var defaultLanguage = editor.getParam('language', 'en');
    return editor.getParam('spellchecker_language', defaultLanguage);
  };
  var getRpcUrl = function (editor) {
    return editor.getParam('spellchecker_rpc_url');
  };
  var getSpellcheckerCallback = function (editor) {
    return editor.getParam('spellchecker_callback');
  };
  var getSpellcheckerWordcharPattern = function (editor) {
    var defaultPattern = new RegExp('[^' + '\\s!"#$%&()*+,-./:;<=>?@[\\]^_{|}`' + '\xA7\xA9\xAB\xAE\xB1\xB6\xB7\xB8\xBB' + '\xBC\xBD\xBE\xBF\xD7\xF7\xA4\u201D\u201C\u201E\xA0\u2002\u2003\u2009' + ']+', 'g');
    return editor.getParam('spellchecker_wordchar_pattern', defaultPattern);
  };
  var $_g0597ajnjh8lz176 = {
    getLanguages: getLanguages,
    getLanguage: getLanguage,
    getRpcUrl: getRpcUrl,
    getSpellcheckerCallback: getSpellcheckerCallback,
    getSpellcheckerWordcharPattern: getSpellcheckerWordcharPattern
  };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.URI');

  var global$3 = tinymce.util.Tools.resolve('tinymce.util.XHR');

  var fireSpellcheckStart = function (editor) {
    return editor.fire('SpellcheckStart');
  };
  var fireSpellcheckEnd = function (editor) {
    return editor.fire('SpellcheckEnd');
  };
  var $_91lf17jsjh8lz17g = {
    fireSpellcheckStart: fireSpellcheckStart,
    fireSpellcheckEnd: fireSpellcheckEnd
  };

  function isContentEditableFalse(node) {
    return node && node.nodeType === 1 && node.contentEditable === 'false';
  }
  var DomTextMatcher = function (node, editor) {
    var m, matches = [], text;
    var dom = editor.dom;
    var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap;
    blockElementsMap = editor.schema.getBlockElements();
    hiddenTextElementsMap = editor.schema.getWhiteSpaceElements();
    shortEndedElementsMap = editor.schema.getShortEndedElements();
    function createMatch(m, data) {
      if (!m[0]) {
        throw new Error('findAndReplaceDOMText cannot handle zero-length matches');
      }
      return {
        start: m.index,
        end: m.index + m[0].length,
        text: m[0],
        data: data
      };
    }
    function getText(node) {
      var txt;
      if (node.nodeType === 3) {
        return node.data;
      }
      if (hiddenTextElementsMap[node.nodeName] && !blockElementsMap[node.nodeName]) {
        return '';
      }
      if (isContentEditableFalse(node)) {
        return '\n';
      }
      txt = '';
      if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) {
        txt += '\n';
      }
      if (node = node.firstChild) {
        do {
          txt += getText(node);
        } while (node = node.nextSibling);
      }
      return txt;
    }
    function stepThroughMatches(node, matches, replaceFn) {
      var startNode, endNode, startNodeIndex, endNodeIndex, innerNodes = [], atIndex = 0, curNode = node, matchLocation, matchIndex = 0;
      matches = matches.slice(0);
      matches.sort(function (a, b) {
        return a.start - b.start;
      });
      matchLocation = matches.shift();
      out:
        while (true) {
          if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName] || isContentEditableFalse(curNode)) {
            atIndex++;
          }
          if (curNode.nodeType === 3) {
            if (!endNode && curNode.length + atIndex >= matchLocation.end) {
              endNode = curNode;
              endNodeIndex = matchLocation.end - atIndex;
            } else if (startNode) {
              innerNodes.push(curNode);
            }
            if (!startNode && curNode.length + atIndex > matchLocation.start) {
              startNode = curNode;
              startNodeIndex = matchLocation.start - atIndex;
            }
            atIndex += curNode.length;
          }
          if (startNode && endNode) {
            curNode = replaceFn({
              startNode: startNode,
              startNodeIndex: startNodeIndex,
              endNode: endNode,
              endNodeIndex: endNodeIndex,
              innerNodes: innerNodes,
              match: matchLocation.text,
              matchIndex: matchIndex
            });
            atIndex -= endNode.length - endNodeIndex;
            startNode = null;
            endNode = null;
            innerNodes = [];
            matchLocation = matches.shift();
            matchIndex++;
            if (!matchLocation) {
              break;
            }
          } else if ((!hiddenTextElementsMap[curNode.nodeName] || blockElementsMap[curNode.nodeName]) && curNode.firstChild) {
            if (!isContentEditableFalse(curNode)) {
              curNode = curNode.firstChild;
              continue;
            }
          } else if (curNode.nextSibling) {
            curNode = curNode.nextSibling;
            continue;
          }
          while (true) {
            if (curNode.nextSibling) {
              curNode = curNode.nextSibling;
              break;
            } else if (curNode.parentNode !== node) {
              curNode = curNode.parentNode;
            } else {
              break out;
            }
          }
        }
    }
    function genReplacer(callback) {
      function makeReplacementNode(fill, matchIndex) {
        var match = matches[matchIndex];
        if (!match.stencil) {
          match.stencil = callback(match);
        }
        var clone = match.stencil.cloneNode(false);
        clone.setAttribute('data-mce-index', matchIndex);
        if (fill) {
          clone.appendChild(dom.doc.createTextNode(fill));
        }
        return clone;
      }
      return function (range) {
        var before;
        var after;
        var parentNode;
        var startNode = range.startNode;
        var endNode = range.endNode;
        var matchIndex = range.matchIndex;
        var doc = dom.doc;
        if (startNode === endNode) {
          var node_1 = startNode;
          parentNode = node_1.parentNode;
          if (range.startNodeIndex > 0) {
            before = doc.createTextNode(node_1.data.substring(0, range.startNodeIndex));
            parentNode.insertBefore(before, node_1);
          }
          var el = makeReplacementNode(range.match, matchIndex);
          parentNode.insertBefore(el, node_1);
          if (range.endNodeIndex < node_1.length) {
            after = doc.createTextNode(node_1.data.substring(range.endNodeIndex));
            parentNode.insertBefore(after, node_1);
          }
          node_1.parentNode.removeChild(node_1);
          return el;
        }
        before = doc.createTextNode(startNode.data.substring(0, range.startNodeIndex));
        after = doc.createTextNode(endNode.data.substring(range.endNodeIndex));
        var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex);
        var innerEls = [];
        for (var i = 0, l = range.innerNodes.length; i < l; ++i) {
          var innerNode = range.innerNodes[i];
          var innerEl = makeReplacementNode(innerNode.data, matchIndex);
          innerNode.parentNode.replaceChild(innerEl, innerNode);
          innerEls.push(innerEl);
        }
        var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex);
        parentNode = startNode.parentNode;
        parentNode.insertBefore(before, startNode);
        parentNode.insertBefore(elA, startNode);
        parentNode.removeChild(startNode);
        parentNode = endNode.parentNode;
        parentNode.insertBefore(elB, endNode);
        parentNode.insertBefore(after, endNode);
        parentNode.removeChild(endNode);
        return elB;
      };
    }
    function unwrapElement(element) {
      var parentNode = element.parentNode;
      parentNode.insertBefore(element.firstChild, element);
      element.parentNode.removeChild(element);
    }
    function hasClass(elm) {
      return elm.className.indexOf('mce-spellchecker-word') !== -1;
    }
    function getWrappersByIndex(index) {
      var elements = node.getElementsByTagName('*'), wrappers = [];
      index = typeof index === 'number' ? '' + index : null;
      for (var i = 0; i < elements.length; i++) {
        var element = elements[i], dataIndex = element.getAttribute('data-mce-index');
        if (dataIndex !== null && dataIndex.length && hasClass(element)) {
          if (dataIndex === index || index === null) {
            wrappers.push(element);
          }
        }
      }
      return wrappers;
    }
    function indexOf(match) {
      var i = matches.length;
      while (i--) {
        if (matches[i] === match) {
          return i;
        }
      }
      return -1;
    }
    function filter(callback) {
      var filteredMatches = [];
      each(function (match, i) {
        if (callback(match, i)) {
          filteredMatches.push(match);
        }
      });
      matches = filteredMatches;
      return this;
    }
    function each(callback) {
      for (var i = 0, l = matches.length; i < l; i++) {
        if (callback(matches[i], i) === false) {
          break;
        }
      }
      return this;
    }
    function wrap(callback) {
      if (matches.length) {
        stepThroughMatches(node, matches, genReplacer(callback));
      }
      return this;
    }
    function find(regex, data) {
      if (text && regex.global) {
        while (m = regex.exec(text)) {
          matches.push(createMatch(m, data));
        }
      }
      return this;
    }
    function unwrap(match) {
      var i;
      var elements = getWrappersByIndex(match ? indexOf(match) : null);
      i = elements.length;
      while (i--) {
        unwrapElement(elements[i]);
      }
      return this;
    }
    function matchFromElement(element) {
      return matches[element.getAttribute('data-mce-index')];
    }
    function elementFromMatch(match) {
      return getWrappersByIndex(indexOf(match))[0];
    }
    function add(start, length, data) {
      matches.push({
        start: start,
        end: start + length,
        text: text.substr(start, length),
        data: data
      });
      return this;
    }
    function rangeFromMatch(match) {
      var wrappers = getWrappersByIndex(indexOf(match));
      var rng = editor.dom.createRng();
      rng.setStartBefore(wrappers[0]);
      rng.setEndAfter(wrappers[wrappers.length - 1]);
      return rng;
    }
    function replace(match, text) {
      var rng = rangeFromMatch(match);
      rng.deleteContents();
      if (text.length > 0) {
        rng.insertNode(editor.dom.doc.createTextNode(text));
      }
      return rng;
    }
    function reset() {
      matches.splice(0, matches.length);
      unwrap();
      return this;
    }
    text = getText(node);
    return {
      text: text,
      matches: matches,
      each: each,
      filter: filter,
      reset: reset,
      matchFromElement: matchFromElement,
      elementFromMatch: elementFromMatch,
      find: find,
      add: add,
      wrap: wrap,
      unwrap: unwrap,
      replace: replace,
      rangeFromMatch: rangeFromMatch,
      indexOf: indexOf
    };
  };

  var getTextMatcher = function (editor, textMatcherState) {
    if (!textMatcherState.get()) {
      var textMatcher = DomTextMatcher(editor.getBody(), editor);
      textMatcherState.set(textMatcher);
    }
    return textMatcherState.get();
  };
  var isEmpty = function (obj) {
    for (var _ in obj) {
      return false;
    }
    return true;
  };
  var defaultSpellcheckCallback = function (editor, pluginUrl, currentLanguageState) {
    return function (method, text, doneCallback, errorCallback) {
      var data = {
        method: method,
        lang: currentLanguageState.get()
      };
      var postData = '';
      data[method === 'addToDictionary' ? 'word' : 'text'] = text;
      global$1.each(data, function (value, key) {
        if (postData) {
          postData += '&';
        }
        postData += key + '=' + encodeURIComponent(value);
      });
      global$3.send({
        url: new global$2(pluginUrl).toAbsolute($_g0597ajnjh8lz176.getRpcUrl(editor)),
        type: 'post',
        content_type: 'application/x-www-form-urlencoded',
        data: postData,
        success: function (result) {
          result = JSON.parse(result);
          if (!result) {
            var message = editor.translate('Server response wasn\'t proper JSON.');
            errorCallback(message);
          } else if (result.error) {
            errorCallback(result.error);
          } else {
            doneCallback(result);
          }
        },
        error: function () {
          var message = editor.translate('The spelling service was not found: (') + $_g0597ajnjh8lz176.getRpcUrl(editor) + editor.translate(')');
          errorCallback(message);
        }
      });
    };
  };
  var sendRpcCall = function (editor, pluginUrl, currentLanguageState, name, data, successCallback, errorCallback) {
    var userSpellcheckCallback = $_g0597ajnjh8lz176.getSpellcheckerCallback(editor);
    var spellCheckCallback = userSpellcheckCallback ? userSpellcheckCallback : defaultSpellcheckCallback(editor, pluginUrl, currentLanguageState);
    spellCheckCallback.call(editor.plugins.spellchecker, name, data, successCallback, errorCallback);
  };
  var spellcheck = function (editor, pluginUrl, startedState, textMatcherState, lastSuggestionsState, currentLanguageState) {
    if (finish(editor, startedState, textMatcherState)) {
      return;
    }
    var errorCallback = function (message) {
      editor.notificationManager.open({
        text: message,
        type: 'error'
      });
      editor.setProgressState(false);
      finish(editor, startedState, textMatcherState);
    };
    var successCallback = function (data) {
      markErrors(editor, startedState, textMatcherState, lastSuggestionsState, data);
    };
    editor.setProgressState(true);
    sendRpcCall(editor, pluginUrl, currentLanguageState, 'spellcheck', getTextMatcher(editor, textMatcherState).text, successCallback, errorCallback);
    editor.focus();
  };
  var checkIfFinished = function (editor, startedState, textMatcherState) {
    if (!editor.dom.select('span.mce-spellchecker-word').length) {
      finish(editor, startedState, textMatcherState);
    }
  };
  var addToDictionary = function (editor, pluginUrl, startedState, textMatcherState, currentLanguageState, word, spans) {
    editor.setProgressState(true);
    sendRpcCall(editor, pluginUrl, currentLanguageState, 'addToDictionary', word, function () {
      editor.setProgressState(false);
      editor.dom.remove(spans, true);
      checkIfFinished(editor, startedState, textMatcherState);
    }, function (message) {
      editor.notificationManager.open({
        text: message,
        type: 'error'
      });
      editor.setProgressState(false);
    });
  };
  var ignoreWord = function (editor, startedState, textMatcherState, word, spans, all) {
    editor.selection.collapse();
    if (all) {
      global$1.each(editor.dom.select('span.mce-spellchecker-word'), function (span) {
        if (span.getAttribute('data-mce-word') === word) {
          editor.dom.remove(span, true);
        }
      });
    } else {
      editor.dom.remove(spans, true);
    }
    checkIfFinished(editor, startedState, textMatcherState);
  };
  var finish = function (editor, startedState, textMatcherState) {
    getTextMatcher(editor, textMatcherState).reset();
    textMatcherState.set(null);
    if (startedState.get()) {
      startedState.set(false);
      $_91lf17jsjh8lz17g.fireSpellcheckEnd(editor);
      return true;
    }
  };
  var getElmIndex = function (elm) {
    var value = elm.getAttribute('data-mce-index');
    if (typeof value === 'number') {
      return '' + value;
    }
    return value;
  };
  var findSpansByIndex = function (editor, index) {
    var nodes;
    var spans = [];
    nodes = global$1.toArray(editor.getBody().getElementsByTagName('span'));
    if (nodes.length) {
      for (var i = 0; i < nodes.length; i++) {
        var nodeIndex = getElmIndex(nodes[i]);
        if (nodeIndex === null || !nodeIndex.length) {
          continue;
        }
        if (nodeIndex === index.toString()) {
          spans.push(nodes[i]);
        }
      }
    }
    return spans;
  };
  var markErrors = function (editor, startedState, textMatcherState, lastSuggestionsState, data) {
    var suggestions, hasDictionarySupport;
    if (typeof data !== 'string' && data.words) {
      hasDictionarySupport = !!data.dictionary;
      suggestions = data.words;
    } else {
      suggestions = data;
    }
    editor.setProgressState(false);
    if (isEmpty(suggestions)) {
      var message = editor.translate('No misspellings found.');
      editor.notificationManager.open({
        text: message,
        type: 'info'
      });
      startedState.set(false);
      return;
    }
    lastSuggestionsState.set({
      suggestions: suggestions,
      hasDictionarySupport: hasDictionarySupport
    });
    getTextMatcher(editor, textMatcherState).find($_g0597ajnjh8lz176.getSpellcheckerWordcharPattern(editor)).filter(function (match) {
      return !!suggestions[match.text];
    }).wrap(function (match) {
      return editor.dom.create('span', {
        'class': 'mce-spellchecker-word',
        'data-mce-bogus': 1,
        'data-mce-word': match.text
      });
    });
    startedState.set(true);
    $_91lf17jsjh8lz17g.fireSpellcheckStart(editor);
  };
  var $_cw8e2ojojh8lz17a = {
    spellcheck: spellcheck,
    checkIfFinished: checkIfFinished,
    addToDictionary: addToDictionary,
    ignoreWord: ignoreWord,
    findSpansByIndex: findSpansByIndex,
    getElmIndex: getElmIndex,
    markErrors: markErrors
  };

  var get = function (editor, startedState, lastSuggestionsState, textMatcherState, currentLanguageState, url) {
    var getLanguage = function () {
      return currentLanguageState.get();
    };
    var getWordCharPattern = function () {
      return $_g0597ajnjh8lz176.getSpellcheckerWordcharPattern(editor);
    };
    var markErrors = function (data) {
      $_cw8e2ojojh8lz17a.markErrors(editor, startedState, textMatcherState, lastSuggestionsState, data);
    };
    var getTextMatcher = function () {
      return textMatcherState.get();
    };
    return {
      getTextMatcher: getTextMatcher,
      getWordCharPattern: getWordCharPattern,
      markErrors: markErrors,
      getLanguage: getLanguage
    };
  };
  var $_6c6maajmjh8lz174 = { get: get };

  var register = function (editor, pluginUrl, startedState, textMatcherState, lastSuggestionsState, currentLanguageState) {
    editor.addCommand('mceSpellCheck', function () {
      $_cw8e2ojojh8lz17a.spellcheck(editor, pluginUrl, startedState, textMatcherState, lastSuggestionsState, currentLanguageState);
    });
  };
  var $_2adncojujh8lz17o = { register: register };

  var buildMenuItems = function (listName, languageValues) {
    var items = [];
    global$1.each(languageValues, function (languageValue) {
      items.push({
        selectable: true,
        text: languageValue.name,
        data: languageValue.value
      });
    });
    return items;
  };
  var updateSelection = function (editor, currentLanguageState) {
    return function (e) {
      var selectedLanguage = currentLanguageState.get();
      e.control.items().each(function (ctrl) {
        ctrl.active(ctrl.settings.data === selectedLanguage);
      });
    };
  };
  var getItems = function (editor) {
    return global$1.map($_g0597ajnjh8lz176.getLanguages(editor).split(','), function (langPair) {
      langPair = langPair.split('=');
      return {
        name: langPair[0],
        value: langPair[1]
      };
    });
  };
  var register$1 = function (editor, pluginUrl, startedState, textMatcherState, currentLanguageState, lastSuggestionsState) {
    var languageMenuItems = buildMenuItems('Language', getItems(editor));
    var startSpellchecking = function () {
      $_cw8e2ojojh8lz17a.spellcheck(editor, pluginUrl, startedState, textMatcherState, lastSuggestionsState, currentLanguageState);
    };
    var buttonArgs = {
      tooltip: 'Spellcheck',
      onclick: startSpellchecking,
      onPostRender: function (e) {
        var ctrl = e.control;
        editor.on('SpellcheckStart SpellcheckEnd', function () {
          ctrl.active(startedState.get());
        });
      }
    };
    if (languageMenuItems.length > 1) {
      buttonArgs.type = 'splitbutton';
      buttonArgs.menu = languageMenuItems;
      buttonArgs.onshow = updateSelection(editor, currentLanguageState);
      buttonArgs.onselect = function (e) {
        currentLanguageState.set(e.control.settings.data);
      };
    }
    editor.addButton('spellchecker', buttonArgs);
    editor.addMenuItem('spellchecker', {
      text: 'Spellcheck',
      context: 'tools',
      onclick: startSpellchecking,
      selectable: true,
      onPostRender: function () {
        var self = this;
        self.active(startedState.get());
        editor.on('SpellcheckStart SpellcheckEnd', function () {
          self.active(startedState.get());
        });
      }
    });
  };
  var $_14j9gfjvjh8lz17p = { register: register$1 };

  var global$4 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$5 = tinymce.util.Tools.resolve('tinymce.ui.Factory');

  var suggestionsMenu;
  var showSuggestions = function (editor, pluginUrl, lastSuggestionsState, startedState, textMatcherState, currentLanguageState, word, spans) {
    var items = [], suggestions = lastSuggestionsState.get().suggestions[word];
    global$1.each(suggestions, function (suggestion) {
      items.push({
        text: suggestion,
        onclick: function () {
          editor.insertContent(editor.dom.encode(suggestion));
          editor.dom.remove(spans);
          $_cw8e2ojojh8lz17a.checkIfFinished(editor, startedState, textMatcherState);
        }
      });
    });
    items.push({ text: '-' });
    var hasDictionarySupport = lastSuggestionsState.get().hasDictionarySupport;
    if (hasDictionarySupport) {
      items.push({
        text: 'Add to Dictionary',
        onclick: function () {
          $_cw8e2ojojh8lz17a.addToDictionary(editor, pluginUrl, startedState, textMatcherState, currentLanguageState, word, spans);
        }
      });
    }
    items.push.apply(items, [
      {
        text: 'Ignore',
        onclick: function () {
          $_cw8e2ojojh8lz17a.ignoreWord(editor, startedState, textMatcherState, word, spans);
        }
      },
      {
        text: 'Ignore all',
        onclick: function () {
          $_cw8e2ojojh8lz17a.ignoreWord(editor, startedState, textMatcherState, word, spans, true);
        }
      }
    ]);
    suggestionsMenu = global$5.create('menu', {
      items: items,
      context: 'contextmenu',
      onautohide: function (e) {
        if (e.target.className.indexOf('spellchecker') !== -1) {
          e.preventDefault();
        }
      },
      onhide: function () {
        suggestionsMenu.remove();
        suggestionsMenu = null;
      }
    });
    suggestionsMenu.renderTo(document.body);
    var pos = global$4.DOM.getPos(editor.getContentAreaContainer());
    var targetPos = editor.dom.getPos(spans[0]);
    var root = editor.dom.getRoot();
    if (root.nodeName === 'BODY') {
      targetPos.x -= root.ownerDocument.documentElement.scrollLeft || root.scrollLeft;
      targetPos.y -= root.ownerDocument.documentElement.scrollTop || root.scrollTop;
    } else {
      targetPos.x -= root.scrollLeft;
      targetPos.y -= root.scrollTop;
    }
    pos.x += targetPos.x;
    pos.y += targetPos.y;
    suggestionsMenu.moveTo(pos.x, pos.y + spans[0].offsetHeight);
  };
  var setup = function (editor, pluginUrl, lastSuggestionsState, startedState, textMatcherState, currentLanguageState) {
    editor.on('click', function (e) {
      var target = e.target;
      if (target.className === 'mce-spellchecker-word') {
        e.preventDefault();
        var spans = $_cw8e2ojojh8lz17a.findSpansByIndex(editor, $_cw8e2ojojh8lz17a.getElmIndex(target));
        if (spans.length > 0) {
          var rng = editor.dom.createRng();
          rng.setStartBefore(spans[0]);
          rng.setEndAfter(spans[spans.length - 1]);
          editor.selection.setRng(rng);
          showSuggestions(editor, pluginUrl, lastSuggestionsState, startedState, textMatcherState, currentLanguageState, target.getAttribute('data-mce-word'), spans);
        }
      }
    });
  };
  var $_6ic81cjwjh8lz181 = { setup: setup };

  global.add('spellchecker', function (editor, pluginUrl) {
    if ($_2a4jkrjljh8lz172.hasProPlugin(editor) === false) {
      var startedState = Cell(false);
      var currentLanguageState = Cell($_g0597ajnjh8lz176.getLanguage(editor));
      var textMatcherState = Cell(null);
      var lastSuggestionsState = Cell(null);
      $_14j9gfjvjh8lz17p.register(editor, pluginUrl, startedState, textMatcherState, currentLanguageState, lastSuggestionsState);
      $_6ic81cjwjh8lz181.setup(editor, pluginUrl, lastSuggestionsState, startedState, textMatcherState, currentLanguageState);
      $_2adncojujh8lz17o.register(editor, pluginUrl, startedState, textMatcherState, lastSuggestionsState, currentLanguageState);
      return $_6c6maajmjh8lz174.get(editor, startedState, lastSuggestionsState, textMatcherState, currentLanguageState, pluginUrl);
    }
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-tabfocus", ["tinymce"], function() {
  return (function() {
(function () {
var tabfocus = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$2 = tinymce.util.Tools.resolve('tinymce.EditorManager');

  var global$3 = tinymce.util.Tools.resolve('tinymce.Env');

  var global$4 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var global$6 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var getTabFocusElements = function (editor) {
    return editor.getParam('tabfocus_elements', ':prev,:next');
  };
  var getTabFocus = function (editor) {
    return editor.getParam('tab_focus', getTabFocusElements(editor));
  };
  var $_949n7ik8jh8lz19m = { getTabFocus: getTabFocus };

  var DOM = global$1.DOM;
  var tabCancel = function (e) {
    if (e.keyCode === global$6.TAB && !e.ctrlKey && !e.altKey && !e.metaKey) {
      e.preventDefault();
    }
  };
  var setup = function (editor) {
    function tabHandler(e) {
      var x, el, v, i;
      if (e.keyCode !== global$6.TAB || e.ctrlKey || e.altKey || e.metaKey || e.isDefaultPrevented()) {
        return;
      }
      function find(direction) {
        el = DOM.select(':input:enabled,*[tabindex]:not(iframe)');
        function canSelectRecursive(e) {
          return e.nodeName === 'BODY' || e.type !== 'hidden' && e.style.display !== 'none' && e.style.visibility !== 'hidden' && canSelectRecursive(e.parentNode);
        }
        function canSelect(el) {
          return /INPUT|TEXTAREA|BUTTON/.test(el.tagName) && global$2.get(e.id) && el.tabIndex !== -1 && canSelectRecursive(el);
        }
        global$5.each(el, function (e, i) {
          if (e.id === editor.id) {
            x = i;
            return false;
          }
        });
        if (direction > 0) {
          for (i = x + 1; i < el.length; i++) {
            if (canSelect(el[i])) {
              return el[i];
            }
          }
        } else {
          for (i = x - 1; i >= 0; i--) {
            if (canSelect(el[i])) {
              return el[i];
            }
          }
        }
        return null;
      }
      v = global$5.explode($_949n7ik8jh8lz19m.getTabFocus(editor));
      if (v.length === 1) {
        v[1] = v[0];
        v[0] = ':prev';
      }
      if (e.shiftKey) {
        if (v[0] === ':prev') {
          el = find(-1);
        } else {
          el = DOM.get(v[0]);
        }
      } else {
        if (v[1] === ':next') {
          el = find(1);
        } else {
          el = DOM.get(v[1]);
        }
      }
      if (el) {
        var focusEditor = global$2.get(el.id || el.name);
        if (el.id && focusEditor) {
          focusEditor.focus();
        } else {
          global$4.setTimeout(function () {
            if (!global$3.webkit) {
              window.focus();
            }
            el.focus();
          }, 10);
        }
        e.preventDefault();
      }
    }
    editor.on('init', function () {
      if (editor.inline) {
        DOM.setAttrib(editor.getBody(), 'tabIndex', null);
      }
      editor.on('keyup', tabCancel);
      if (global$3.gecko) {
        editor.on('keypress keydown', tabHandler);
      } else {
        editor.on('keydown', tabHandler);
      }
    });
  };
  var $_5hsd2hk1jh8lz19f = { setup: setup };

  global.add('tabfocus', function (editor) {
    $_5hsd2hk1jh8lz19f.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-table", ["tinymce"], function() {
  return (function() {
(function () {
var table = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var noop = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
  };
  var noarg = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return f();
    };
  };
  var compose = function (fa, fb) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return fa(fb.apply(null, arguments));
    };
  };
  var constant = function (value) {
    return function () {
      return value;
    };
  };
  var identity = function (x) {
    return x;
  };
  var tripleEquals = function (a, b) {
    return a === b;
  };
  var curry = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = new Array(arguments.length - 1);
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      var newArgs = new Array(arguments.length);
      for (var j = 0; j < newArgs.length; j++)
        newArgs[j] = arguments[j];
      var all = args.concat(newArgs);
      return f.apply(null, all);
    };
  };
  var not = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return !f.apply(null, arguments);
    };
  };
  var die = function (msg) {
    return function () {
      throw new Error(msg);
    };
  };
  var apply = function (f) {
    return f();
  };
  var call = function (f) {
    f();
  };
  var never = constant(false);
  var always = constant(true);
  var $_bgyjg9kejh8lz1ax = {
    noop: noop,
    noarg: noarg,
    compose: compose,
    constant: constant,
    identity: identity,
    tripleEquals: tripleEquals,
    curry: curry,
    not: not,
    die: die,
    apply: apply,
    call: call,
    never: never,
    always: always
  };

  var never$1 = $_bgyjg9kejh8lz1ax.never;
  var always$1 = $_bgyjg9kejh8lz1ax.always;
  var none = function () {
    return NONE;
  };
  var NONE = function () {
    var eq = function (o) {
      return o.isNone();
    };
    var call = function (thunk) {
      return thunk();
    };
    var id = function (n) {
      return n;
    };
    var noop = function () {
    };
    var me = {
      fold: function (n, s) {
        return n();
      },
      is: never$1,
      isSome: never$1,
      isNone: always$1,
      getOr: id,
      getOrThunk: call,
      getOrDie: function (msg) {
        throw new Error(msg || 'error: getOrDie called on none.');
      },
      or: id,
      orThunk: call,
      map: none,
      ap: none,
      each: noop,
      bind: none,
      flatten: none,
      exists: never$1,
      forall: always$1,
      filter: none,
      equals: eq,
      equals_: eq,
      toArray: function () {
        return [];
      },
      toString: $_bgyjg9kejh8lz1ax.constant('none()')
    };
    if (Object.freeze)
      Object.freeze(me);
    return me;
  }();
  var some = function (a) {
    var constant_a = function () {
      return a;
    };
    var self = function () {
      return me;
    };
    var map = function (f) {
      return some(f(a));
    };
    var bind = function (f) {
      return f(a);
    };
    var me = {
      fold: function (n, s) {
        return s(a);
      },
      is: function (v) {
        return a === v;
      },
      isSome: always$1,
      isNone: never$1,
      getOr: constant_a,
      getOrThunk: constant_a,
      getOrDie: constant_a,
      or: self,
      orThunk: self,
      map: map,
      ap: function (optfab) {
        return optfab.fold(none, function (fab) {
          return some(fab(a));
        });
      },
      each: function (f) {
        f(a);
      },
      bind: bind,
      flatten: constant_a,
      exists: bind,
      forall: bind,
      filter: function (f) {
        return f(a) ? me : NONE;
      },
      equals: function (o) {
        return o.is(a);
      },
      equals_: function (o, elementEq) {
        return o.fold(never$1, function (b) {
          return elementEq(a, b);
        });
      },
      toArray: function () {
        return [a];
      },
      toString: function () {
        return 'some(' + a + ')';
      }
    };
    return me;
  };
  var from = function (value) {
    return value === null || value === undefined ? NONE : some(value);
  };
  var Option = {
    some: some,
    none: none,
    from: from
  };

  var typeOf = function (x) {
    if (x === null)
      return 'null';
    var t = typeof x;
    if (t === 'object' && Array.prototype.isPrototypeOf(x))
      return 'array';
    if (t === 'object' && String.prototype.isPrototypeOf(x))
      return 'string';
    return t;
  };
  var isType = function (type) {
    return function (value) {
      return typeOf(value) === type;
    };
  };
  var $_d1kyz8kfjh8lz1az = {
    isString: isType('string'),
    isObject: isType('object'),
    isArray: isType('array'),
    isNull: isType('null'),
    isBoolean: isType('boolean'),
    isUndefined: isType('undefined'),
    isFunction: isType('function'),
    isNumber: isType('number')
  };

  var rawIndexOf = function () {
    var pIndexOf = Array.prototype.indexOf;
    var fastIndex = function (xs, x) {
      return pIndexOf.call(xs, x);
    };
    var slowIndex = function (xs, x) {
      return slowIndexOf(xs, x);
    };
    return pIndexOf === undefined ? slowIndex : fastIndex;
  }();
  var indexOf = function (xs, x) {
    var r = rawIndexOf(xs, x);
    return r === -1 ? Option.none() : Option.some(r);
  };
  var contains = function (xs, x) {
    return rawIndexOf(xs, x) > -1;
  };
  var exists = function (xs, pred) {
    return findIndex(xs, pred).isSome();
  };
  var range = function (num, f) {
    var r = [];
    for (var i = 0; i < num; i++) {
      r.push(f(i));
    }
    return r;
  };
  var chunk = function (array, size) {
    var r = [];
    for (var i = 0; i < array.length; i += size) {
      var s = array.slice(i, i + size);
      r.push(s);
    }
    return r;
  };
  var map = function (xs, f) {
    var len = xs.length;
    var r = new Array(len);
    for (var i = 0; i < len; i++) {
      var x = xs[i];
      r[i] = f(x, i, xs);
    }
    return r;
  };
  var each = function (xs, f) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var eachr = function (xs, f) {
    for (var i = xs.length - 1; i >= 0; i--) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var partition = function (xs, pred) {
    var pass = [];
    var fail = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      var arr = pred(x, i, xs) ? pass : fail;
      arr.push(x);
    }
    return {
      pass: pass,
      fail: fail
    };
  };
  var filter = function (xs, pred) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        r.push(x);
      }
    }
    return r;
  };
  var groupBy = function (xs, f) {
    if (xs.length === 0) {
      return [];
    } else {
      var wasType = f(xs[0]);
      var r = [];
      var group = [];
      for (var i = 0, len = xs.length; i < len; i++) {
        var x = xs[i];
        var type = f(x);
        if (type !== wasType) {
          r.push(group);
          group = [];
        }
        wasType = type;
        group.push(x);
      }
      if (group.length !== 0) {
        r.push(group);
      }
      return r;
    }
  };
  var foldr = function (xs, f, acc) {
    eachr(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var foldl = function (xs, f, acc) {
    each(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var find = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(x);
      }
    }
    return Option.none();
  };
  var findIndex = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(i);
      }
    }
    return Option.none();
  };
  var slowIndexOf = function (xs, x) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (xs[i] === x) {
        return i;
      }
    }
    return -1;
  };
  var push = Array.prototype.push;
  var flatten = function (xs) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (!Array.prototype.isPrototypeOf(xs[i]))
        throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
      push.apply(r, xs[i]);
    }
    return r;
  };
  var bind = function (xs, f) {
    var output = map(xs, f);
    return flatten(output);
  };
  var forall = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      var x = xs[i];
      if (pred(x, i, xs) !== true) {
        return false;
      }
    }
    return true;
  };
  var equal = function (a1, a2) {
    return a1.length === a2.length && forall(a1, function (x, i) {
      return x === a2[i];
    });
  };
  var slice = Array.prototype.slice;
  var reverse = function (xs) {
    var r = slice.call(xs, 0);
    r.reverse();
    return r;
  };
  var difference = function (a1, a2) {
    return filter(a1, function (x) {
      return !contains(a2, x);
    });
  };
  var mapToObject = function (xs, f) {
    var r = {};
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      r[String(x)] = f(x, i);
    }
    return r;
  };
  var pure = function (x) {
    return [x];
  };
  var sort = function (xs, comparator) {
    var copy = slice.call(xs, 0);
    copy.sort(comparator);
    return copy;
  };
  var head = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  };
  var last = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  };
  var from$1 = $_d1kyz8kfjh8lz1az.isFunction(Array.from) ? Array.from : function (x) {
    return slice.call(x);
  };
  var $_6b0spykcjh8lz1ao = {
    map: map,
    each: each,
    eachr: eachr,
    partition: partition,
    filter: filter,
    groupBy: groupBy,
    indexOf: indexOf,
    foldr: foldr,
    foldl: foldl,
    find: find,
    findIndex: findIndex,
    flatten: flatten,
    bind: bind,
    forall: forall,
    exists: exists,
    contains: contains,
    equal: equal,
    reverse: reverse,
    chunk: chunk,
    difference: difference,
    mapToObject: mapToObject,
    pure: pure,
    sort: sort,
    range: range,
    head: head,
    last: last,
    from: from$1
  };

  var keys = function () {
    var fastKeys = Object.keys;
    var slowKeys = function (o) {
      var r = [];
      for (var i in o) {
        if (o.hasOwnProperty(i)) {
          r.push(i);
        }
      }
      return r;
    };
    return fastKeys === undefined ? slowKeys : fastKeys;
  }();
  var each$1 = function (obj, f) {
    var props = keys(obj);
    for (var k = 0, len = props.length; k < len; k++) {
      var i = props[k];
      var x = obj[i];
      f(x, i, obj);
    }
  };
  var objectMap = function (obj, f) {
    return tupleMap(obj, function (x, i, obj) {
      return {
        k: i,
        v: f(x, i, obj)
      };
    });
  };
  var tupleMap = function (obj, f) {
    var r = {};
    each$1(obj, function (x, i) {
      var tuple = f(x, i, obj);
      r[tuple.k] = tuple.v;
    });
    return r;
  };
  var bifilter = function (obj, pred) {
    var t = {};
    var f = {};
    each$1(obj, function (x, i) {
      var branch = pred(x, i) ? t : f;
      branch[i] = x;
    });
    return {
      t: t,
      f: f
    };
  };
  var mapToArray = function (obj, f) {
    var r = [];
    each$1(obj, function (value, name) {
      r.push(f(value, name));
    });
    return r;
  };
  var find$1 = function (obj, pred) {
    var props = keys(obj);
    for (var k = 0, len = props.length; k < len; k++) {
      var i = props[k];
      var x = obj[i];
      if (pred(x, i, obj)) {
        return Option.some(x);
      }
    }
    return Option.none();
  };
  var values = function (obj) {
    return mapToArray(obj, function (v) {
      return v;
    });
  };
  var size = function (obj) {
    return values(obj).length;
  };
  var $_8kti2hkhjh8lz1bt = {
    bifilter: bifilter,
    each: each$1,
    map: objectMap,
    mapToArray: mapToArray,
    tupleMap: tupleMap,
    find: find$1,
    keys: keys,
    values: values,
    size: size
  };

  function Immutable () {
    var fields = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      fields[_i] = arguments[_i];
    }
    return function () {
      var values = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        values[_i] = arguments[_i];
      }
      if (fields.length !== values.length) {
        throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
      }
      var struct = {};
      $_6b0spykcjh8lz1ao.each(fields, function (name, i) {
        struct[name] = $_bgyjg9kejh8lz1ax.constant(values[i]);
      });
      return struct;
    };
  }

  var sort$1 = function (arr) {
    return arr.slice(0).sort();
  };
  var reqMessage = function (required, keys) {
    throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
  };
  var unsuppMessage = function (unsupported) {
    throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
  };
  var validateStrArr = function (label, array) {
    if (!$_d1kyz8kfjh8lz1az.isArray(array))
      throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
    $_6b0spykcjh8lz1ao.each(array, function (a) {
      if (!$_d1kyz8kfjh8lz1az.isString(a))
        throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
    });
  };
  var invalidTypeMessage = function (incorrect, type) {
    throw new Error('All values need to be of type: ' + type + '. Keys (' + sort$1(incorrect).join(', ') + ') were not.');
  };
  var checkDupes = function (everything) {
    var sorted = sort$1(everything);
    var dupe = $_6b0spykcjh8lz1ao.find(sorted, function (s, i) {
      return i < sorted.length - 1 && s === sorted[i + 1];
    });
    dupe.each(function (d) {
      throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
    });
  };
  var $_9ogtmjkljh8lz1c0 = {
    sort: sort$1,
    reqMessage: reqMessage,
    unsuppMessage: unsuppMessage,
    validateStrArr: validateStrArr,
    invalidTypeMessage: invalidTypeMessage,
    checkDupes: checkDupes
  };

  function MixedBag (required, optional) {
    var everything = required.concat(optional);
    if (everything.length === 0)
      throw new Error('You must specify at least one required or optional field.');
    $_9ogtmjkljh8lz1c0.validateStrArr('required', required);
    $_9ogtmjkljh8lz1c0.validateStrArr('optional', optional);
    $_9ogtmjkljh8lz1c0.checkDupes(everything);
    return function (obj) {
      var keys = $_8kti2hkhjh8lz1bt.keys(obj);
      var allReqd = $_6b0spykcjh8lz1ao.forall(required, function (req) {
        return $_6b0spykcjh8lz1ao.contains(keys, req);
      });
      if (!allReqd)
        $_9ogtmjkljh8lz1c0.reqMessage(required, keys);
      var unsupported = $_6b0spykcjh8lz1ao.filter(keys, function (key) {
        return !$_6b0spykcjh8lz1ao.contains(everything, key);
      });
      if (unsupported.length > 0)
        $_9ogtmjkljh8lz1c0.unsuppMessage(unsupported);
      var r = {};
      $_6b0spykcjh8lz1ao.each(required, function (req) {
        r[req] = $_bgyjg9kejh8lz1ax.constant(obj[req]);
      });
      $_6b0spykcjh8lz1ao.each(optional, function (opt) {
        r[opt] = $_bgyjg9kejh8lz1ax.constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
      });
      return r;
    };
  }

  var $_d2ojjnkijh8lz1bv = {
    immutable: Immutable,
    immutableBag: MixedBag
  };

  var dimensions = $_d2ojjnkijh8lz1bv.immutable('width', 'height');
  var grid = $_d2ojjnkijh8lz1bv.immutable('rows', 'columns');
  var address = $_d2ojjnkijh8lz1bv.immutable('row', 'column');
  var coords = $_d2ojjnkijh8lz1bv.immutable('x', 'y');
  var detail = $_d2ojjnkijh8lz1bv.immutable('element', 'rowspan', 'colspan');
  var detailnew = $_d2ojjnkijh8lz1bv.immutable('element', 'rowspan', 'colspan', 'isNew');
  var extended = $_d2ojjnkijh8lz1bv.immutable('element', 'rowspan', 'colspan', 'row', 'column');
  var rowdata = $_d2ojjnkijh8lz1bv.immutable('element', 'cells', 'section');
  var elementnew = $_d2ojjnkijh8lz1bv.immutable('element', 'isNew');
  var rowdatanew = $_d2ojjnkijh8lz1bv.immutable('element', 'cells', 'section', 'isNew');
  var rowcells = $_d2ojjnkijh8lz1bv.immutable('cells', 'section');
  var rowdetails = $_d2ojjnkijh8lz1bv.immutable('details', 'section');
  var bounds = $_d2ojjnkijh8lz1bv.immutable('startRow', 'startCol', 'finishRow', 'finishCol');
  var $_g424vknjh8lz1cd = {
    dimensions: dimensions,
    grid: grid,
    address: address,
    coords: coords,
    extended: extended,
    detail: detail,
    detailnew: detailnew,
    rowdata: rowdata,
    elementnew: elementnew,
    rowdatanew: rowdatanew,
    rowcells: rowcells,
    rowdetails: rowdetails,
    bounds: bounds
  };

  var fromHtml = function (html, scope) {
    var doc = scope || document;
    var div = doc.createElement('div');
    div.innerHTML = html;
    if (!div.hasChildNodes() || div.childNodes.length > 1) {
      console.error('HTML does not have a single root node', html);
      throw 'HTML must have a single root node';
    }
    return fromDom(div.childNodes[0]);
  };
  var fromTag = function (tag, scope) {
    var doc = scope || document;
    var node = doc.createElement(tag);
    return fromDom(node);
  };
  var fromText = function (text, scope) {
    var doc = scope || document;
    var node = doc.createTextNode(text);
    return fromDom(node);
  };
  var fromDom = function (node) {
    if (node === null || node === undefined)
      throw new Error('Node cannot be null or undefined');
    return { dom: $_bgyjg9kejh8lz1ax.constant(node) };
  };
  var fromPoint = function (doc, x, y) {
    return Option.from(doc.dom().elementFromPoint(x, y)).map(fromDom);
  };
  var $_6vo9a4krjh8lz1do = {
    fromHtml: fromHtml,
    fromTag: fromTag,
    fromText: fromText,
    fromDom: fromDom,
    fromPoint: fromPoint
  };

  var $_e4k979ksjh8lz1dt = {
    ATTRIBUTE: 2,
    CDATA_SECTION: 4,
    COMMENT: 8,
    DOCUMENT: 9,
    DOCUMENT_TYPE: 10,
    DOCUMENT_FRAGMENT: 11,
    ELEMENT: 1,
    TEXT: 3,
    PROCESSING_INSTRUCTION: 7,
    ENTITY_REFERENCE: 5,
    ENTITY: 6,
    NOTATION: 12
  };

  var ELEMENT = $_e4k979ksjh8lz1dt.ELEMENT;
  var DOCUMENT = $_e4k979ksjh8lz1dt.DOCUMENT;
  var is = function (element, selector) {
    var elem = element.dom();
    if (elem.nodeType !== ELEMENT)
      return false;
    else if (elem.matches !== undefined)
      return elem.matches(selector);
    else if (elem.msMatchesSelector !== undefined)
      return elem.msMatchesSelector(selector);
    else if (elem.webkitMatchesSelector !== undefined)
      return elem.webkitMatchesSelector(selector);
    else if (elem.mozMatchesSelector !== undefined)
      return elem.mozMatchesSelector(selector);
    else
      throw new Error('Browser lacks native selectors');
  };
  var bypassSelector = function (dom) {
    return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT || dom.childElementCount === 0;
  };
  var all = function (selector, scope) {
    var base = scope === undefined ? document : scope.dom();
    return bypassSelector(base) ? [] : $_6b0spykcjh8lz1ao.map(base.querySelectorAll(selector), $_6vo9a4krjh8lz1do.fromDom);
  };
  var one = function (selector, scope) {
    var base = scope === undefined ? document : scope.dom();
    return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map($_6vo9a4krjh8lz1do.fromDom);
  };
  var $_62so4qkqjh8lz1di = {
    all: all,
    is: is,
    one: one
  };

  var toArray = function (target, f) {
    var r = [];
    var recurse = function (e) {
      r.push(e);
      return f(e);
    };
    var cur = f(target);
    do {
      cur = cur.bind(recurse);
    } while (cur.isSome());
    return r;
  };
  var $_4g1y8akujh8lz1e7 = { toArray: toArray };

  var global$1 = typeof window !== 'undefined' ? window : Function('return this;')();

  var path = function (parts, scope) {
    var o = scope !== undefined && scope !== null ? scope : global$1;
    for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i)
      o = o[parts[i]];
    return o;
  };
  var resolve = function (p, scope) {
    var parts = p.split('.');
    return path(parts, scope);
  };
  var step = function (o, part) {
    if (o[part] === undefined || o[part] === null)
      o[part] = {};
    return o[part];
  };
  var forge = function (parts, target) {
    var o = target !== undefined ? target : global$1;
    for (var i = 0; i < parts.length; ++i)
      o = step(o, parts[i]);
    return o;
  };
  var namespace = function (name, target) {
    var parts = name.split('.');
    return forge(parts, target);
  };
  var $_4ek05lkyjh8lz1en = {
    path: path,
    resolve: resolve,
    forge: forge,
    namespace: namespace
  };

  var unsafe = function (name, scope) {
    return $_4ek05lkyjh8lz1en.resolve(name, scope);
  };
  var getOrDie = function (name, scope) {
    var actual = unsafe(name, scope);
    if (actual === undefined || actual === null)
      throw name + ' not available on this browser';
    return actual;
  };
  var $_f53sa7kxjh8lz1ek = { getOrDie: getOrDie };

  var node = function () {
    var f = $_f53sa7kxjh8lz1ek.getOrDie('Node');
    return f;
  };
  var compareDocumentPosition = function (a, b, match) {
    return (a.compareDocumentPosition(b) & match) !== 0;
  };
  var documentPositionPreceding = function (a, b) {
    return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_PRECEDING);
  };
  var documentPositionContainedBy = function (a, b) {
    return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_CONTAINED_BY);
  };
  var $_1bck1kkwjh8lz1ej = {
    documentPositionPreceding: documentPositionPreceding,
    documentPositionContainedBy: documentPositionContainedBy
  };

  var cached = function (f) {
    var called = false;
    var r;
    return function () {
      if (!called) {
        called = true;
        r = f.apply(null, arguments);
      }
      return r;
    };
  };
  var $_aela9fl1jh8lz1es = { cached: cached };

  var firstMatch = function (regexes, s) {
    for (var i = 0; i < regexes.length; i++) {
      var x = regexes[i];
      if (x.test(s))
        return x;
    }
    return undefined;
  };
  var find$2 = function (regexes, agent) {
    var r = firstMatch(regexes, agent);
    if (!r)
      return {
        major: 0,
        minor: 0
      };
    var group = function (i) {
      return Number(agent.replace(r, '$' + i));
    };
    return nu(group(1), group(2));
  };
  var detect = function (versionRegexes, agent) {
    var cleanedAgent = String(agent).toLowerCase();
    if (versionRegexes.length === 0)
      return unknown();
    return find$2(versionRegexes, cleanedAgent);
  };
  var unknown = function () {
    return nu(0, 0);
  };
  var nu = function (major, minor) {
    return {
      major: major,
      minor: minor
    };
  };
  var $_90grizl4jh8lz1ex = {
    nu: nu,
    detect: detect,
    unknown: unknown
  };

  var edge = 'Edge';
  var chrome = 'Chrome';
  var ie = 'IE';
  var opera = 'Opera';
  var firefox = 'Firefox';
  var safari = 'Safari';
  var isBrowser = function (name, current) {
    return function () {
      return current === name;
    };
  };
  var unknown$1 = function () {
    return nu$1({
      current: undefined,
      version: $_90grizl4jh8lz1ex.unknown()
    });
  };
  var nu$1 = function (info) {
    var current = info.current;
    var version = info.version;
    return {
      current: current,
      version: version,
      isEdge: isBrowser(edge, current),
      isChrome: isBrowser(chrome, current),
      isIE: isBrowser(ie, current),
      isOpera: isBrowser(opera, current),
      isFirefox: isBrowser(firefox, current),
      isSafari: isBrowser(safari, current)
    };
  };
  var $_bu3ikfl3jh8lz1eu = {
    unknown: unknown$1,
    nu: nu$1,
    edge: $_bgyjg9kejh8lz1ax.constant(edge),
    chrome: $_bgyjg9kejh8lz1ax.constant(chrome),
    ie: $_bgyjg9kejh8lz1ax.constant(ie),
    opera: $_bgyjg9kejh8lz1ax.constant(opera),
    firefox: $_bgyjg9kejh8lz1ax.constant(firefox),
    safari: $_bgyjg9kejh8lz1ax.constant(safari)
  };

  var windows = 'Windows';
  var ios = 'iOS';
  var android = 'Android';
  var linux = 'Linux';
  var osx = 'OSX';
  var solaris = 'Solaris';
  var freebsd = 'FreeBSD';
  var isOS = function (name, current) {
    return function () {
      return current === name;
    };
  };
  var unknown$2 = function () {
    return nu$2({
      current: undefined,
      version: $_90grizl4jh8lz1ex.unknown()
    });
  };
  var nu$2 = function (info) {
    var current = info.current;
    var version = info.version;
    return {
      current: current,
      version: version,
      isWindows: isOS(windows, current),
      isiOS: isOS(ios, current),
      isAndroid: isOS(android, current),
      isOSX: isOS(osx, current),
      isLinux: isOS(linux, current),
      isSolaris: isOS(solaris, current),
      isFreeBSD: isOS(freebsd, current)
    };
  };
  var $_3hjylpl5jh8lz1ez = {
    unknown: unknown$2,
    nu: nu$2,
    windows: $_bgyjg9kejh8lz1ax.constant(windows),
    ios: $_bgyjg9kejh8lz1ax.constant(ios),
    android: $_bgyjg9kejh8lz1ax.constant(android),
    linux: $_bgyjg9kejh8lz1ax.constant(linux),
    osx: $_bgyjg9kejh8lz1ax.constant(osx),
    solaris: $_bgyjg9kejh8lz1ax.constant(solaris),
    freebsd: $_bgyjg9kejh8lz1ax.constant(freebsd)
  };

  function DeviceType (os, browser, userAgent) {
    var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
    var isiPhone = os.isiOS() && !isiPad;
    var isAndroid3 = os.isAndroid() && os.version.major === 3;
    var isAndroid4 = os.isAndroid() && os.version.major === 4;
    var isTablet = isiPad || isAndroid3 || isAndroid4 && /mobile/i.test(userAgent) === true;
    var isTouch = os.isiOS() || os.isAndroid();
    var isPhone = isTouch && !isTablet;
    var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
    return {
      isiPad: $_bgyjg9kejh8lz1ax.constant(isiPad),
      isiPhone: $_bgyjg9kejh8lz1ax.constant(isiPhone),
      isTablet: $_bgyjg9kejh8lz1ax.constant(isTablet),
      isPhone: $_bgyjg9kejh8lz1ax.constant(isPhone),
      isTouch: $_bgyjg9kejh8lz1ax.constant(isTouch),
      isAndroid: os.isAndroid,
      isiOS: os.isiOS,
      isWebView: $_bgyjg9kejh8lz1ax.constant(iOSwebview)
    };
  }

  var detect$1 = function (candidates, userAgent) {
    var agent = String(userAgent).toLowerCase();
    return $_6b0spykcjh8lz1ao.find(candidates, function (candidate) {
      return candidate.search(agent);
    });
  };
  var detectBrowser = function (browsers, userAgent) {
    return detect$1(browsers, userAgent).map(function (browser) {
      var version = $_90grizl4jh8lz1ex.detect(browser.versionRegexes, userAgent);
      return {
        current: browser.name,
        version: version
      };
    });
  };
  var detectOs = function (oses, userAgent) {
    return detect$1(oses, userAgent).map(function (os) {
      var version = $_90grizl4jh8lz1ex.detect(os.versionRegexes, userAgent);
      return {
        current: os.name,
        version: version
      };
    });
  };
  var $_ai99afl7jh8lz1f5 = {
    detectBrowser: detectBrowser,
    detectOs: detectOs
  };

  var addToStart = function (str, prefix) {
    return prefix + str;
  };
  var addToEnd = function (str, suffix) {
    return str + suffix;
  };
  var removeFromStart = function (str, numChars) {
    return str.substring(numChars);
  };
  var removeFromEnd = function (str, numChars) {
    return str.substring(0, str.length - numChars);
  };
  var $_cciq56lajh8lz1fm = {
    addToStart: addToStart,
    addToEnd: addToEnd,
    removeFromStart: removeFromStart,
    removeFromEnd: removeFromEnd
  };

  var first = function (str, count) {
    return str.substr(0, count);
  };
  var last$1 = function (str, count) {
    return str.substr(str.length - count, str.length);
  };
  var head$1 = function (str) {
    return str === '' ? Option.none() : Option.some(str.substr(0, 1));
  };
  var tail = function (str) {
    return str === '' ? Option.none() : Option.some(str.substring(1));
  };
  var $_c66x3zlbjh8lz1fo = {
    first: first,
    last: last$1,
    head: head$1,
    tail: tail
  };

  var checkRange = function (str, substr, start) {
    if (substr === '')
      return true;
    if (str.length < substr.length)
      return false;
    var x = str.substr(start, start + substr.length);
    return x === substr;
  };
  var supplant = function (str, obj) {
    var isStringOrNumber = function (a) {
      var t = typeof a;
      return t === 'string' || t === 'number';
    };
    return str.replace(/\${([^{}]*)}/g, function (a, b) {
      var value = obj[b];
      return isStringOrNumber(value) ? value : a;
    });
  };
  var removeLeading = function (str, prefix) {
    return startsWith(str, prefix) ? $_cciq56lajh8lz1fm.removeFromStart(str, prefix.length) : str;
  };
  var removeTrailing = function (str, prefix) {
    return endsWith(str, prefix) ? $_cciq56lajh8lz1fm.removeFromEnd(str, prefix.length) : str;
  };
  var ensureLeading = function (str, prefix) {
    return startsWith(str, prefix) ? str : $_cciq56lajh8lz1fm.addToStart(str, prefix);
  };
  var ensureTrailing = function (str, prefix) {
    return endsWith(str, prefix) ? str : $_cciq56lajh8lz1fm.addToEnd(str, prefix);
  };
  var contains$1 = function (str, substr) {
    return str.indexOf(substr) !== -1;
  };
  var capitalize = function (str) {
    return $_c66x3zlbjh8lz1fo.head(str).bind(function (head) {
      return $_c66x3zlbjh8lz1fo.tail(str).map(function (tail) {
        return head.toUpperCase() + tail;
      });
    }).getOr(str);
  };
  var startsWith = function (str, prefix) {
    return checkRange(str, prefix, 0);
  };
  var endsWith = function (str, suffix) {
    return checkRange(str, suffix, str.length - suffix.length);
  };
  var trim = function (str) {
    return str.replace(/^\s+|\s+$/g, '');
  };
  var lTrim = function (str) {
    return str.replace(/^\s+/g, '');
  };
  var rTrim = function (str) {
    return str.replace(/\s+$/g, '');
  };
  var $_34vbjol9jh8lz1fk = {
    supplant: supplant,
    startsWith: startsWith,
    removeLeading: removeLeading,
    removeTrailing: removeTrailing,
    ensureLeading: ensureLeading,
    ensureTrailing: ensureTrailing,
    endsWith: endsWith,
    contains: contains$1,
    trim: trim,
    lTrim: lTrim,
    rTrim: rTrim,
    capitalize: capitalize
  };

  var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  var checkContains = function (target) {
    return function (uastring) {
      return $_34vbjol9jh8lz1fk.contains(uastring, target);
    };
  };
  var browsers = [
    {
      name: 'Edge',
      versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
      search: function (uastring) {
        var monstrosity = $_34vbjol9jh8lz1fk.contains(uastring, 'edge/') && $_34vbjol9jh8lz1fk.contains(uastring, 'chrome') && $_34vbjol9jh8lz1fk.contains(uastring, 'safari') && $_34vbjol9jh8lz1fk.contains(uastring, 'applewebkit');
        return monstrosity;
      }
    },
    {
      name: 'Chrome',
      versionRegexes: [
        /.*?chrome\/([0-9]+)\.([0-9]+).*/,
        normalVersionRegex
      ],
      search: function (uastring) {
        return $_34vbjol9jh8lz1fk.contains(uastring, 'chrome') && !$_34vbjol9jh8lz1fk.contains(uastring, 'chromeframe');
      }
    },
    {
      name: 'IE',
      versionRegexes: [
        /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
        /.*?rv:([0-9]+)\.([0-9]+).*/
      ],
      search: function (uastring) {
        return $_34vbjol9jh8lz1fk.contains(uastring, 'msie') || $_34vbjol9jh8lz1fk.contains(uastring, 'trident');
      }
    },
    {
      name: 'Opera',
      versionRegexes: [
        normalVersionRegex,
        /.*?opera\/([0-9]+)\.([0-9]+).*/
      ],
      search: checkContains('opera')
    },
    {
      name: 'Firefox',
      versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
      search: checkContains('firefox')
    },
    {
      name: 'Safari',
      versionRegexes: [
        normalVersionRegex,
        /.*?cpu os ([0-9]+)_([0-9]+).*/
      ],
      search: function (uastring) {
        return ($_34vbjol9jh8lz1fk.contains(uastring, 'safari') || $_34vbjol9jh8lz1fk.contains(uastring, 'mobile/')) && $_34vbjol9jh8lz1fk.contains(uastring, 'applewebkit');
      }
    }
  ];
  var oses = [
    {
      name: 'Windows',
      search: checkContains('win'),
      versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
    },
    {
      name: 'iOS',
      search: function (uastring) {
        return $_34vbjol9jh8lz1fk.contains(uastring, 'iphone') || $_34vbjol9jh8lz1fk.contains(uastring, 'ipad');
      },
      versionRegexes: [
        /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
        /.*cpu os ([0-9]+)_([0-9]+).*/,
        /.*cpu iphone os ([0-9]+)_([0-9]+).*/
      ]
    },
    {
      name: 'Android',
      search: checkContains('android'),
      versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
    },
    {
      name: 'OSX',
      search: checkContains('os x'),
      versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
    },
    {
      name: 'Linux',
      search: checkContains('linux'),
      versionRegexes: []
    },
    {
      name: 'Solaris',
      search: checkContains('sunos'),
      versionRegexes: []
    },
    {
      name: 'FreeBSD',
      search: checkContains('freebsd'),
      versionRegexes: []
    }
  ];
  var $_b5ruc3l8jh8lz1fe = {
    browsers: $_bgyjg9kejh8lz1ax.constant(browsers),
    oses: $_bgyjg9kejh8lz1ax.constant(oses)
  };

  var detect$2 = function (userAgent) {
    var browsers = $_b5ruc3l8jh8lz1fe.browsers();
    var oses = $_b5ruc3l8jh8lz1fe.oses();
    var browser = $_ai99afl7jh8lz1f5.detectBrowser(browsers, userAgent).fold($_bu3ikfl3jh8lz1eu.unknown, $_bu3ikfl3jh8lz1eu.nu);
    var os = $_ai99afl7jh8lz1f5.detectOs(oses, userAgent).fold($_3hjylpl5jh8lz1ez.unknown, $_3hjylpl5jh8lz1ez.nu);
    var deviceType = DeviceType(os, browser, userAgent);
    return {
      browser: browser,
      os: os,
      deviceType: deviceType
    };
  };
  var $_dgywb9l2jh8lz1et = { detect: detect$2 };

  var detect$3 = $_aela9fl1jh8lz1es.cached(function () {
    var userAgent = navigator.userAgent;
    return $_dgywb9l2jh8lz1et.detect(userAgent);
  });
  var $_a6om0dl0jh8lz1ep = { detect: detect$3 };

  var eq = function (e1, e2) {
    return e1.dom() === e2.dom();
  };
  var isEqualNode = function (e1, e2) {
    return e1.dom().isEqualNode(e2.dom());
  };
  var member = function (element, elements) {
    return $_6b0spykcjh8lz1ao.exists(elements, $_bgyjg9kejh8lz1ax.curry(eq, element));
  };
  var regularContains = function (e1, e2) {
    var d1 = e1.dom(), d2 = e2.dom();
    return d1 === d2 ? false : d1.contains(d2);
  };
  var ieContains = function (e1, e2) {
    return $_1bck1kkwjh8lz1ej.documentPositionContainedBy(e1.dom(), e2.dom());
  };
  var browser = $_a6om0dl0jh8lz1ep.detect().browser;
  var contains$2 = browser.isIE() ? ieContains : regularContains;
  var $_2eywnlkvjh8lz1e8 = {
    eq: eq,
    isEqualNode: isEqualNode,
    member: member,
    contains: contains$2,
    is: $_62so4qkqjh8lz1di.is
  };

  var owner = function (element) {
    return $_6vo9a4krjh8lz1do.fromDom(element.dom().ownerDocument);
  };
  var documentElement = function (element) {
    var doc = owner(element);
    return $_6vo9a4krjh8lz1do.fromDom(doc.dom().documentElement);
  };
  var defaultView = function (element) {
    var el = element.dom();
    var defaultView = el.ownerDocument.defaultView;
    return $_6vo9a4krjh8lz1do.fromDom(defaultView);
  };
  var parent = function (element) {
    var dom = element.dom();
    return Option.from(dom.parentNode).map($_6vo9a4krjh8lz1do.fromDom);
  };
  var findIndex$1 = function (element) {
    return parent(element).bind(function (p) {
      var kin = children(p);
      return $_6b0spykcjh8lz1ao.findIndex(kin, function (elem) {
        return $_2eywnlkvjh8lz1e8.eq(element, elem);
      });
    });
  };
  var parents = function (element, isRoot) {
    var stop = $_d1kyz8kfjh8lz1az.isFunction(isRoot) ? isRoot : $_bgyjg9kejh8lz1ax.constant(false);
    var dom = element.dom();
    var ret = [];
    while (dom.parentNode !== null && dom.parentNode !== undefined) {
      var rawParent = dom.parentNode;
      var parent = $_6vo9a4krjh8lz1do.fromDom(rawParent);
      ret.push(parent);
      if (stop(parent) === true)
        break;
      else
        dom = rawParent;
    }
    return ret;
  };
  var siblings = function (element) {
    var filterSelf = function (elements) {
      return $_6b0spykcjh8lz1ao.filter(elements, function (x) {
        return !$_2eywnlkvjh8lz1e8.eq(element, x);
      });
    };
    return parent(element).map(children).map(filterSelf).getOr([]);
  };
  var offsetParent = function (element) {
    var dom = element.dom();
    return Option.from(dom.offsetParent).map($_6vo9a4krjh8lz1do.fromDom);
  };
  var prevSibling = function (element) {
    var dom = element.dom();
    return Option.from(dom.previousSibling).map($_6vo9a4krjh8lz1do.fromDom);
  };
  var nextSibling = function (element) {
    var dom = element.dom();
    return Option.from(dom.nextSibling).map($_6vo9a4krjh8lz1do.fromDom);
  };
  var prevSiblings = function (element) {
    return $_6b0spykcjh8lz1ao.reverse($_4g1y8akujh8lz1e7.toArray(element, prevSibling));
  };
  var nextSiblings = function (element) {
    return $_4g1y8akujh8lz1e7.toArray(element, nextSibling);
  };
  var children = function (element) {
    var dom = element.dom();
    return $_6b0spykcjh8lz1ao.map(dom.childNodes, $_6vo9a4krjh8lz1do.fromDom);
  };
  var child = function (element, index) {
    var children = element.dom().childNodes;
    return Option.from(children[index]).map($_6vo9a4krjh8lz1do.fromDom);
  };
  var firstChild = function (element) {
    return child(element, 0);
  };
  var lastChild = function (element) {
    return child(element, element.dom().childNodes.length - 1);
  };
  var childNodesCount = function (element) {
    return element.dom().childNodes.length;
  };
  var hasChildNodes = function (element) {
    return element.dom().hasChildNodes();
  };
  var spot = $_d2ojjnkijh8lz1bv.immutable('element', 'offset');
  var leaf = function (element, offset) {
    var cs = children(element);
    return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  };
  var $_4hc7u2ktjh8lz1dv = {
    owner: owner,
    defaultView: defaultView,
    documentElement: documentElement,
    parent: parent,
    findIndex: findIndex$1,
    parents: parents,
    siblings: siblings,
    prevSibling: prevSibling,
    offsetParent: offsetParent,
    prevSiblings: prevSiblings,
    nextSibling: nextSibling,
    nextSiblings: nextSiblings,
    children: children,
    child: child,
    firstChild: firstChild,
    lastChild: lastChild,
    childNodesCount: childNodesCount,
    hasChildNodes: hasChildNodes,
    leaf: leaf
  };

  var firstLayer = function (scope, selector) {
    return filterFirstLayer(scope, selector, $_bgyjg9kejh8lz1ax.constant(true));
  };
  var filterFirstLayer = function (scope, selector, predicate) {
    return $_6b0spykcjh8lz1ao.bind($_4hc7u2ktjh8lz1dv.children(scope), function (x) {
      return $_62so4qkqjh8lz1di.is(x, selector) ? predicate(x) ? [x] : [] : filterFirstLayer(x, selector, predicate);
    });
  };
  var $_egd9zbkpjh8lz1d3 = {
    firstLayer: firstLayer,
    filterFirstLayer: filterFirstLayer
  };

  var name = function (element) {
    var r = element.dom().nodeName;
    return r.toLowerCase();
  };
  var type = function (element) {
    return element.dom().nodeType;
  };
  var value = function (element) {
    return element.dom().nodeValue;
  };
  var isType$1 = function (t) {
    return function (element) {
      return type(element) === t;
    };
  };
  var isComment = function (element) {
    return type(element) === $_e4k979ksjh8lz1dt.COMMENT || name(element) === '#comment';
  };
  var isElement = isType$1($_e4k979ksjh8lz1dt.ELEMENT);
  var isText = isType$1($_e4k979ksjh8lz1dt.TEXT);
  var isDocument = isType$1($_e4k979ksjh8lz1dt.DOCUMENT);
  var $_a3izpgldjh8lz1fy = {
    name: name,
    type: type,
    value: value,
    isElement: isElement,
    isText: isText,
    isDocument: isDocument,
    isComment: isComment
  };

  var rawSet = function (dom, key, value) {
    if ($_d1kyz8kfjh8lz1az.isString(value) || $_d1kyz8kfjh8lz1az.isBoolean(value) || $_d1kyz8kfjh8lz1az.isNumber(value)) {
      dom.setAttribute(key, value + '');
    } else {
      console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
      throw new Error('Attribute value was not simple');
    }
  };
  var set = function (element, key, value) {
    rawSet(element.dom(), key, value);
  };
  var setAll = function (element, attrs) {
    var dom = element.dom();
    $_8kti2hkhjh8lz1bt.each(attrs, function (v, k) {
      rawSet(dom, k, v);
    });
  };
  var get = function (element, key) {
    var v = element.dom().getAttribute(key);
    return v === null ? undefined : v;
  };
  var has = function (element, key) {
    var dom = element.dom();
    return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  };
  var remove = function (element, key) {
    element.dom().removeAttribute(key);
  };
  var hasNone = function (element) {
    var attrs = element.dom().attributes;
    return attrs === undefined || attrs === null || attrs.length === 0;
  };
  var clone = function (element) {
    return $_6b0spykcjh8lz1ao.foldl(element.dom().attributes, function (acc, attr) {
      acc[attr.name] = attr.value;
      return acc;
    }, {});
  };
  var transferOne = function (source, destination, attr) {
    if (has(source, attr) && !has(destination, attr))
      set(destination, attr, get(source, attr));
  };
  var transfer = function (source, destination, attrs) {
    if (!$_a3izpgldjh8lz1fy.isElement(source) || !$_a3izpgldjh8lz1fy.isElement(destination))
      return;
    $_6b0spykcjh8lz1ao.each(attrs, function (attr) {
      transferOne(source, destination, attr);
    });
  };
  var $_1mp8lglcjh8lz1fq = {
    clone: clone,
    set: set,
    setAll: setAll,
    get: get,
    has: has,
    remove: remove,
    hasNone: hasNone,
    transfer: transfer
  };

  var inBody = function (element) {
    var dom = $_a3izpgldjh8lz1fy.isText(element) ? element.dom().parentNode : element.dom();
    return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  };
  var body = $_aela9fl1jh8lz1es.cached(function () {
    return getBody($_6vo9a4krjh8lz1do.fromDom(document));
  });
  var getBody = function (doc) {
    var body = doc.dom().body;
    if (body === null || body === undefined)
      throw 'Body is not available yet';
    return $_6vo9a4krjh8lz1do.fromDom(body);
  };
  var $_brbde9lgjh8lz1g4 = {
    body: body,
    getBody: getBody,
    inBody: inBody
  };

  var all$1 = function (predicate) {
    return descendants($_brbde9lgjh8lz1g4.body(), predicate);
  };
  var ancestors = function (scope, predicate, isRoot) {
    return $_6b0spykcjh8lz1ao.filter($_4hc7u2ktjh8lz1dv.parents(scope, isRoot), predicate);
  };
  var siblings$1 = function (scope, predicate) {
    return $_6b0spykcjh8lz1ao.filter($_4hc7u2ktjh8lz1dv.siblings(scope), predicate);
  };
  var children$1 = function (scope, predicate) {
    return $_6b0spykcjh8lz1ao.filter($_4hc7u2ktjh8lz1dv.children(scope), predicate);
  };
  var descendants = function (scope, predicate) {
    var result = [];
    $_6b0spykcjh8lz1ao.each($_4hc7u2ktjh8lz1dv.children(scope), function (x) {
      if (predicate(x)) {
        result = result.concat([x]);
      }
      result = result.concat(descendants(x, predicate));
    });
    return result;
  };
  var $_5a2t82lfjh8lz1g0 = {
    all: all$1,
    ancestors: ancestors,
    siblings: siblings$1,
    children: children$1,
    descendants: descendants
  };

  var all$2 = function (selector) {
    return $_62so4qkqjh8lz1di.all(selector);
  };
  var ancestors$1 = function (scope, selector, isRoot) {
    return $_5a2t82lfjh8lz1g0.ancestors(scope, function (e) {
      return $_62so4qkqjh8lz1di.is(e, selector);
    }, isRoot);
  };
  var siblings$2 = function (scope, selector) {
    return $_5a2t82lfjh8lz1g0.siblings(scope, function (e) {
      return $_62so4qkqjh8lz1di.is(e, selector);
    });
  };
  var children$2 = function (scope, selector) {
    return $_5a2t82lfjh8lz1g0.children(scope, function (e) {
      return $_62so4qkqjh8lz1di.is(e, selector);
    });
  };
  var descendants$1 = function (scope, selector) {
    return $_62so4qkqjh8lz1di.all(selector, scope);
  };
  var $_coxlualejh8lz1fz = {
    all: all$2,
    ancestors: ancestors$1,
    siblings: siblings$2,
    children: children$2,
    descendants: descendants$1
  };

  function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
    return is(scope, a) ? Option.some(scope) : $_d1kyz8kfjh8lz1az.isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  }

  var first$1 = function (predicate) {
    return descendant($_brbde9lgjh8lz1g4.body(), predicate);
  };
  var ancestor = function (scope, predicate, isRoot) {
    var element = scope.dom();
    var stop = $_d1kyz8kfjh8lz1az.isFunction(isRoot) ? isRoot : $_bgyjg9kejh8lz1ax.constant(false);
    while (element.parentNode) {
      element = element.parentNode;
      var el = $_6vo9a4krjh8lz1do.fromDom(element);
      if (predicate(el))
        return Option.some(el);
      else if (stop(el))
        break;
    }
    return Option.none();
  };
  var closest = function (scope, predicate, isRoot) {
    var is = function (scope) {
      return predicate(scope);
    };
    return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  };
  var sibling = function (scope, predicate) {
    var element = scope.dom();
    if (!element.parentNode)
      return Option.none();
    return child$1($_6vo9a4krjh8lz1do.fromDom(element.parentNode), function (x) {
      return !$_2eywnlkvjh8lz1e8.eq(scope, x) && predicate(x);
    });
  };
  var child$1 = function (scope, predicate) {
    var result = $_6b0spykcjh8lz1ao.find(scope.dom().childNodes, $_bgyjg9kejh8lz1ax.compose(predicate, $_6vo9a4krjh8lz1do.fromDom));
    return result.map($_6vo9a4krjh8lz1do.fromDom);
  };
  var descendant = function (scope, predicate) {
    var descend = function (element) {
      for (var i = 0; i < element.childNodes.length; i++) {
        if (predicate($_6vo9a4krjh8lz1do.fromDom(element.childNodes[i])))
          return Option.some($_6vo9a4krjh8lz1do.fromDom(element.childNodes[i]));
        var res = descend(element.childNodes[i]);
        if (res.isSome())
          return res;
      }
      return Option.none();
    };
    return descend(scope.dom());
  };
  var $_aykj0glijh8lz1g9 = {
    first: first$1,
    ancestor: ancestor,
    closest: closest,
    sibling: sibling,
    child: child$1,
    descendant: descendant
  };

  var first$2 = function (selector) {
    return $_62so4qkqjh8lz1di.one(selector);
  };
  var ancestor$1 = function (scope, selector, isRoot) {
    return $_aykj0glijh8lz1g9.ancestor(scope, function (e) {
      return $_62so4qkqjh8lz1di.is(e, selector);
    }, isRoot);
  };
  var sibling$1 = function (scope, selector) {
    return $_aykj0glijh8lz1g9.sibling(scope, function (e) {
      return $_62so4qkqjh8lz1di.is(e, selector);
    });
  };
  var child$2 = function (scope, selector) {
    return $_aykj0glijh8lz1g9.child(scope, function (e) {
      return $_62so4qkqjh8lz1di.is(e, selector);
    });
  };
  var descendant$1 = function (scope, selector) {
    return $_62so4qkqjh8lz1di.one(selector, scope);
  };
  var closest$1 = function (scope, selector, isRoot) {
    return ClosestOrAncestor($_62so4qkqjh8lz1di.is, ancestor$1, scope, selector, isRoot);
  };
  var $_fiygddlhjh8lz1g7 = {
    first: first$2,
    ancestor: ancestor$1,
    sibling: sibling$1,
    child: child$2,
    descendant: descendant$1,
    closest: closest$1
  };

  var lookup = function (tags, element, _isRoot) {
    var isRoot = _isRoot !== undefined ? _isRoot : $_bgyjg9kejh8lz1ax.constant(false);
    if (isRoot(element))
      return Option.none();
    if ($_6b0spykcjh8lz1ao.contains(tags, $_a3izpgldjh8lz1fy.name(element)))
      return Option.some(element);
    var isRootOrUpperTable = function (element) {
      return $_62so4qkqjh8lz1di.is(element, 'table') || isRoot(element);
    };
    return $_fiygddlhjh8lz1g7.ancestor(element, tags.join(','), isRootOrUpperTable);
  };
  var cell = function (element, isRoot) {
    return lookup([
      'td',
      'th'
    ], element, isRoot);
  };
  var cells = function (ancestor) {
    return $_egd9zbkpjh8lz1d3.firstLayer(ancestor, 'th,td');
  };
  var notCell = function (element, isRoot) {
    return lookup([
      'caption',
      'tr',
      'tbody',
      'tfoot',
      'thead'
    ], element, isRoot);
  };
  var neighbours = function (selector, element) {
    return $_4hc7u2ktjh8lz1dv.parent(element).map(function (parent) {
      return $_coxlualejh8lz1fz.children(parent, selector);
    });
  };
  var neighbourCells = $_bgyjg9kejh8lz1ax.curry(neighbours, 'th,td');
  var neighbourRows = $_bgyjg9kejh8lz1ax.curry(neighbours, 'tr');
  var firstCell = function (ancestor) {
    return $_fiygddlhjh8lz1g7.descendant(ancestor, 'th,td');
  };
  var table = function (element, isRoot) {
    return $_fiygddlhjh8lz1g7.closest(element, 'table', isRoot);
  };
  var row = function (element, isRoot) {
    return lookup(['tr'], element, isRoot);
  };
  var rows = function (ancestor) {
    return $_egd9zbkpjh8lz1d3.firstLayer(ancestor, 'tr');
  };
  var attr = function (element, property) {
    return parseInt($_1mp8lglcjh8lz1fq.get(element, property), 10);
  };
  var grid$1 = function (element, rowProp, colProp) {
    var rows = attr(element, rowProp);
    var cols = attr(element, colProp);
    return $_g424vknjh8lz1cd.grid(rows, cols);
  };
  var $_ee8pmfkojh8lz1ch = {
    cell: cell,
    firstCell: firstCell,
    cells: cells,
    neighbourCells: neighbourCells,
    table: table,
    row: row,
    rows: rows,
    notCell: notCell,
    neighbourRows: neighbourRows,
    attr: attr,
    grid: grid$1
  };

  var fromTable = function (table) {
    var rows = $_ee8pmfkojh8lz1ch.rows(table);
    return $_6b0spykcjh8lz1ao.map(rows, function (row) {
      var element = row;
      var parent = $_4hc7u2ktjh8lz1dv.parent(element);
      var parentSection = parent.bind(function (parent) {
        var parentName = $_a3izpgldjh8lz1fy.name(parent);
        return parentName === 'tfoot' || parentName === 'thead' || parentName === 'tbody' ? parentName : 'tbody';
      });
      var cells = $_6b0spykcjh8lz1ao.map($_ee8pmfkojh8lz1ch.cells(row), function (cell) {
        var rowspan = $_1mp8lglcjh8lz1fq.has(cell, 'rowspan') ? parseInt($_1mp8lglcjh8lz1fq.get(cell, 'rowspan'), 10) : 1;
        var colspan = $_1mp8lglcjh8lz1fq.has(cell, 'colspan') ? parseInt($_1mp8lglcjh8lz1fq.get(cell, 'colspan'), 10) : 1;
        return $_g424vknjh8lz1cd.detail(cell, rowspan, colspan);
      });
      return $_g424vknjh8lz1cd.rowdata(element, cells, parentSection);
    });
  };
  var fromPastedRows = function (rows, example) {
    return $_6b0spykcjh8lz1ao.map(rows, function (row) {
      var cells = $_6b0spykcjh8lz1ao.map($_ee8pmfkojh8lz1ch.cells(row), function (cell) {
        var rowspan = $_1mp8lglcjh8lz1fq.has(cell, 'rowspan') ? parseInt($_1mp8lglcjh8lz1fq.get(cell, 'rowspan'), 10) : 1;
        var colspan = $_1mp8lglcjh8lz1fq.has(cell, 'colspan') ? parseInt($_1mp8lglcjh8lz1fq.get(cell, 'colspan'), 10) : 1;
        return $_g424vknjh8lz1cd.detail(cell, rowspan, colspan);
      });
      return $_g424vknjh8lz1cd.rowdata(row, cells, example.section());
    });
  };
  var $_ff1h20kmjh8lz1c3 = {
    fromTable: fromTable,
    fromPastedRows: fromPastedRows
  };

  var key = function (row, column) {
    return row + ',' + column;
  };
  var getAt = function (warehouse, row, column) {
    var raw = warehouse.access()[key(row, column)];
    return raw !== undefined ? Option.some(raw) : Option.none();
  };
  var findItem = function (warehouse, item, comparator) {
    var filtered = filterItems(warehouse, function (detail) {
      return comparator(item, detail.element());
    });
    return filtered.length > 0 ? Option.some(filtered[0]) : Option.none();
  };
  var filterItems = function (warehouse, predicate) {
    var all = $_6b0spykcjh8lz1ao.bind(warehouse.all(), function (r) {
      return r.cells();
    });
    return $_6b0spykcjh8lz1ao.filter(all, predicate);
  };
  var generate = function (list) {
    var access = {};
    var cells = [];
    var maxRows = list.length;
    var maxColumns = 0;
    $_6b0spykcjh8lz1ao.each(list, function (details, r) {
      var currentRow = [];
      $_6b0spykcjh8lz1ao.each(details.cells(), function (detail, c) {
        var start = 0;
        while (access[key(r, start)] !== undefined) {
          start++;
        }
        var current = $_g424vknjh8lz1cd.extended(detail.element(), detail.rowspan(), detail.colspan(), r, start);
        for (var i = 0; i < detail.colspan(); i++) {
          for (var j = 0; j < detail.rowspan(); j++) {
            var cr = r + j;
            var cc = start + i;
            var newpos = key(cr, cc);
            access[newpos] = current;
            maxColumns = Math.max(maxColumns, cc + 1);
          }
        }
        currentRow.push(current);
      });
      cells.push($_g424vknjh8lz1cd.rowdata(details.element(), currentRow, details.section()));
    });
    var grid = $_g424vknjh8lz1cd.grid(maxRows, maxColumns);
    return {
      grid: $_bgyjg9kejh8lz1ax.constant(grid),
      access: $_bgyjg9kejh8lz1ax.constant(access),
      all: $_bgyjg9kejh8lz1ax.constant(cells)
    };
  };
  var justCells = function (warehouse) {
    var rows = $_6b0spykcjh8lz1ao.map(warehouse.all(), function (w) {
      return w.cells();
    });
    return $_6b0spykcjh8lz1ao.flatten(rows);
  };
  var $_fxwupplkjh8lz1go = {
    generate: generate,
    getAt: getAt,
    findItem: findItem,
    filterItems: filterItems,
    justCells: justCells
  };

  var isSupported = function (dom) {
    return dom.style !== undefined;
  };
  var $_3r8yz1lmjh8lz1hf = { isSupported: isSupported };

  var internalSet = function (dom, property, value) {
    if (!$_d1kyz8kfjh8lz1az.isString(value)) {
      console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
      throw new Error('CSS value must be a string: ' + value);
    }
    if ($_3r8yz1lmjh8lz1hf.isSupported(dom))
      dom.style.setProperty(property, value);
  };
  var internalRemove = function (dom, property) {
    if ($_3r8yz1lmjh8lz1hf.isSupported(dom))
      dom.style.removeProperty(property);
  };
  var set$1 = function (element, property, value) {
    var dom = element.dom();
    internalSet(dom, property, value);
  };
  var setAll$1 = function (element, css) {
    var dom = element.dom();
    $_8kti2hkhjh8lz1bt.each(css, function (v, k) {
      internalSet(dom, k, v);
    });
  };
  var setOptions = function (element, css) {
    var dom = element.dom();
    $_8kti2hkhjh8lz1bt.each(css, function (v, k) {
      v.fold(function () {
        internalRemove(dom, k);
      }, function (value) {
        internalSet(dom, k, value);
      });
    });
  };
  var get$1 = function (element, property) {
    var dom = element.dom();
    var styles = window.getComputedStyle(dom);
    var r = styles.getPropertyValue(property);
    var v = r === '' && !$_brbde9lgjh8lz1g4.inBody(element) ? getUnsafeProperty(dom, property) : r;
    return v === null ? undefined : v;
  };
  var getUnsafeProperty = function (dom, property) {
    return $_3r8yz1lmjh8lz1hf.isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  };
  var getRaw = function (element, property) {
    var dom = element.dom();
    var raw = getUnsafeProperty(dom, property);
    return Option.from(raw).filter(function (r) {
      return r.length > 0;
    });
  };
  var getAllRaw = function (element) {
    var css = {};
    var dom = element.dom();
    if ($_3r8yz1lmjh8lz1hf.isSupported(dom)) {
      for (var i = 0; i < dom.style.length; i++) {
        var ruleName = dom.style.item(i);
        css[ruleName] = dom.style[ruleName];
      }
    }
    return css;
  };
  var isValidValue = function (tag, property, value) {
    var element = $_6vo9a4krjh8lz1do.fromTag(tag);
    set$1(element, property, value);
    var style = getRaw(element, property);
    return style.isSome();
  };
  var remove$1 = function (element, property) {
    var dom = element.dom();
    internalRemove(dom, property);
    if ($_1mp8lglcjh8lz1fq.has(element, 'style') && $_34vbjol9jh8lz1fk.trim($_1mp8lglcjh8lz1fq.get(element, 'style')) === '') {
      $_1mp8lglcjh8lz1fq.remove(element, 'style');
    }
  };
  var preserve = function (element, f) {
    var oldStyles = $_1mp8lglcjh8lz1fq.get(element, 'style');
    var result = f(element);
    var restore = oldStyles === undefined ? $_1mp8lglcjh8lz1fq.remove : $_1mp8lglcjh8lz1fq.set;
    restore(element, 'style', oldStyles);
    return result;
  };
  var copy = function (source, target) {
    var sourceDom = source.dom();
    var targetDom = target.dom();
    if ($_3r8yz1lmjh8lz1hf.isSupported(sourceDom) && $_3r8yz1lmjh8lz1hf.isSupported(targetDom)) {
      targetDom.style.cssText = sourceDom.style.cssText;
    }
  };
  var reflow = function (e) {
    return e.dom().offsetWidth;
  };
  var transferOne$1 = function (source, destination, style) {
    getRaw(source, style).each(function (value) {
      if (getRaw(destination, style).isNone())
        set$1(destination, style, value);
    });
  };
  var transfer$1 = function (source, destination, styles) {
    if (!$_a3izpgldjh8lz1fy.isElement(source) || !$_a3izpgldjh8lz1fy.isElement(destination))
      return;
    $_6b0spykcjh8lz1ao.each(styles, function (style) {
      transferOne$1(source, destination, style);
    });
  };
  var $_3ory84lljh8lz1gx = {
    copy: copy,
    set: set$1,
    preserve: preserve,
    setAll: setAll$1,
    setOptions: setOptions,
    remove: remove$1,
    get: get$1,
    getRaw: getRaw,
    getAllRaw: getAllRaw,
    isValidValue: isValidValue,
    reflow: reflow,
    transfer: transfer$1
  };

  var before = function (marker, element) {
    var parent = $_4hc7u2ktjh8lz1dv.parent(marker);
    parent.each(function (v) {
      v.dom().insertBefore(element.dom(), marker.dom());
    });
  };
  var after = function (marker, element) {
    var sibling = $_4hc7u2ktjh8lz1dv.nextSibling(marker);
    sibling.fold(function () {
      var parent = $_4hc7u2ktjh8lz1dv.parent(marker);
      parent.each(function (v) {
        append(v, element);
      });
    }, function (v) {
      before(v, element);
    });
  };
  var prepend = function (parent, element) {
    var firstChild = $_4hc7u2ktjh8lz1dv.firstChild(parent);
    firstChild.fold(function () {
      append(parent, element);
    }, function (v) {
      parent.dom().insertBefore(element.dom(), v.dom());
    });
  };
  var append = function (parent, element) {
    parent.dom().appendChild(element.dom());
  };
  var appendAt = function (parent, element, index) {
    $_4hc7u2ktjh8lz1dv.child(parent, index).fold(function () {
      append(parent, element);
    }, function (v) {
      before(v, element);
    });
  };
  var wrap = function (element, wrapper) {
    before(element, wrapper);
    append(wrapper, element);
  };
  var $_6qqu1alnjh8lz1hg = {
    before: before,
    after: after,
    prepend: prepend,
    append: append,
    appendAt: appendAt,
    wrap: wrap
  };

  var before$1 = function (marker, elements) {
    $_6b0spykcjh8lz1ao.each(elements, function (x) {
      $_6qqu1alnjh8lz1hg.before(marker, x);
    });
  };
  var after$1 = function (marker, elements) {
    $_6b0spykcjh8lz1ao.each(elements, function (x, i) {
      var e = i === 0 ? marker : elements[i - 1];
      $_6qqu1alnjh8lz1hg.after(e, x);
    });
  };
  var prepend$1 = function (parent, elements) {
    $_6b0spykcjh8lz1ao.each(elements.slice().reverse(), function (x) {
      $_6qqu1alnjh8lz1hg.prepend(parent, x);
    });
  };
  var append$1 = function (parent, elements) {
    $_6b0spykcjh8lz1ao.each(elements, function (x) {
      $_6qqu1alnjh8lz1hg.append(parent, x);
    });
  };
  var $_d7tq5mlpjh8lz1hl = {
    before: before$1,
    after: after$1,
    prepend: prepend$1,
    append: append$1
  };

  var empty = function (element) {
    element.dom().textContent = '';
    $_6b0spykcjh8lz1ao.each($_4hc7u2ktjh8lz1dv.children(element), function (rogue) {
      remove$2(rogue);
    });
  };
  var remove$2 = function (element) {
    var dom = element.dom();
    if (dom.parentNode !== null)
      dom.parentNode.removeChild(dom);
  };
  var unwrap = function (wrapper) {
    var children = $_4hc7u2ktjh8lz1dv.children(wrapper);
    if (children.length > 0)
      $_d7tq5mlpjh8lz1hl.before(wrapper, children);
    remove$2(wrapper);
  };
  var $_f2hny0lojh8lz1hi = {
    empty: empty,
    remove: remove$2,
    unwrap: unwrap
  };

  var stats = $_d2ojjnkijh8lz1bv.immutable('minRow', 'minCol', 'maxRow', 'maxCol');
  var findSelectedStats = function (house, isSelected) {
    var totalColumns = house.grid().columns();
    var totalRows = house.grid().rows();
    var minRow = totalRows;
    var minCol = totalColumns;
    var maxRow = 0;
    var maxCol = 0;
    $_8kti2hkhjh8lz1bt.each(house.access(), function (detail) {
      if (isSelected(detail)) {
        var startRow = detail.row();
        var endRow = startRow + detail.rowspan() - 1;
        var startCol = detail.column();
        var endCol = startCol + detail.colspan() - 1;
        if (startRow < minRow)
          minRow = startRow;
        else if (endRow > maxRow)
          maxRow = endRow;
        if (startCol < minCol)
          minCol = startCol;
        else if (endCol > maxCol)
          maxCol = endCol;
      }
    });
    return stats(minRow, minCol, maxRow, maxCol);
  };
  var makeCell = function (list, seenSelected, rowIndex) {
    var row = list[rowIndex].element();
    var td = $_6vo9a4krjh8lz1do.fromTag('td');
    $_6qqu1alnjh8lz1hg.append(td, $_6vo9a4krjh8lz1do.fromTag('br'));
    var f = seenSelected ? $_6qqu1alnjh8lz1hg.append : $_6qqu1alnjh8lz1hg.prepend;
    f(row, td);
  };
  var fillInGaps = function (list, house, stats, isSelected) {
    var totalColumns = house.grid().columns();
    var totalRows = house.grid().rows();
    for (var i = 0; i < totalRows; i++) {
      var seenSelected = false;
      for (var j = 0; j < totalColumns; j++) {
        if (!(i < stats.minRow() || i > stats.maxRow() || j < stats.minCol() || j > stats.maxCol())) {
          var needCell = $_fxwupplkjh8lz1go.getAt(house, i, j).filter(isSelected).isNone();
          if (needCell)
            makeCell(list, seenSelected, i);
          else
            seenSelected = true;
        }
      }
    }
  };
  var clean = function (table, stats) {
    var emptyRows = $_6b0spykcjh8lz1ao.filter($_egd9zbkpjh8lz1d3.firstLayer(table, 'tr'), function (row) {
      return row.dom().childElementCount === 0;
    });
    $_6b0spykcjh8lz1ao.each(emptyRows, $_f2hny0lojh8lz1hi.remove);
    if (stats.minCol() === stats.maxCol() || stats.minRow() === stats.maxRow()) {
      $_6b0spykcjh8lz1ao.each($_egd9zbkpjh8lz1d3.firstLayer(table, 'th,td'), function (cell) {
        $_1mp8lglcjh8lz1fq.remove(cell, 'rowspan');
        $_1mp8lglcjh8lz1fq.remove(cell, 'colspan');
      });
    }
    $_1mp8lglcjh8lz1fq.remove(table, 'width');
    $_1mp8lglcjh8lz1fq.remove(table, 'height');
    $_3ory84lljh8lz1gx.remove(table, 'width');
    $_3ory84lljh8lz1gx.remove(table, 'height');
  };
  var extract = function (table, selectedSelector) {
    var isSelected = function (detail) {
      return $_62so4qkqjh8lz1di.is(detail.element(), selectedSelector);
    };
    var list = $_ff1h20kmjh8lz1c3.fromTable(table);
    var house = $_fxwupplkjh8lz1go.generate(list);
    var stats = findSelectedStats(house, isSelected);
    var selector = 'th:not(' + selectedSelector + ')' + ',td:not(' + selectedSelector + ')';
    var unselectedCells = $_egd9zbkpjh8lz1d3.filterFirstLayer(table, 'th,td', function (cell) {
      return $_62so4qkqjh8lz1di.is(cell, selector);
    });
    $_6b0spykcjh8lz1ao.each(unselectedCells, $_f2hny0lojh8lz1hi.remove);
    fillInGaps(list, house, stats, isSelected);
    clean(table, stats);
    return table;
  };
  var $_dj8mm1kgjh8lz1b3 = { extract: extract };

  var clone$1 = function (original, deep) {
    return $_6vo9a4krjh8lz1do.fromDom(original.dom().cloneNode(deep));
  };
  var shallow = function (original) {
    return clone$1(original, false);
  };
  var deep = function (original) {
    return clone$1(original, true);
  };
  var shallowAs = function (original, tag) {
    var nu = $_6vo9a4krjh8lz1do.fromTag(tag);
    var attributes = $_1mp8lglcjh8lz1fq.clone(original);
    $_1mp8lglcjh8lz1fq.setAll(nu, attributes);
    return nu;
  };
  var copy$1 = function (original, tag) {
    var nu = shallowAs(original, tag);
    var cloneChildren = $_4hc7u2ktjh8lz1dv.children(deep(original));
    $_d7tq5mlpjh8lz1hl.append(nu, cloneChildren);
    return nu;
  };
  var mutate = function (original, tag) {
    var nu = shallowAs(original, tag);
    $_6qqu1alnjh8lz1hg.before(original, nu);
    var children = $_4hc7u2ktjh8lz1dv.children(original);
    $_d7tq5mlpjh8lz1hl.append(nu, children);
    $_f2hny0lojh8lz1hi.remove(original);
    return nu;
  };
  var $_zeqq4lrjh8lz1id = {
    shallow: shallow,
    shallowAs: shallowAs,
    deep: deep,
    copy: copy$1,
    mutate: mutate
  };

  function NodeValue (is, name) {
    var get = function (element) {
      if (!is(element))
        throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
      return getOption(element).getOr('');
    };
    var getOptionIE10 = function (element) {
      try {
        return getOptionSafe(element);
      } catch (e) {
        return Option.none();
      }
    };
    var getOptionSafe = function (element) {
      return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
    };
    var browser = $_a6om0dl0jh8lz1ep.detect().browser;
    var getOption = browser.isIE() && browser.version.major === 10 ? getOptionIE10 : getOptionSafe;
    var set = function (element, value) {
      if (!is(element))
        throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
      element.dom().nodeValue = value;
    };
    return {
      get: get,
      getOption: getOption,
      set: set
    };
  }

  var api = NodeValue($_a3izpgldjh8lz1fy.isText, 'text');
  var get$2 = function (element) {
    return api.get(element);
  };
  var getOption = function (element) {
    return api.getOption(element);
  };
  var set$2 = function (element, value) {
    api.set(element, value);
  };
  var $_bri5anlujh8lz1in = {
    get: get$2,
    getOption: getOption,
    set: set$2
  };

  var getEnd = function (element) {
    return $_a3izpgldjh8lz1fy.name(element) === 'img' ? 1 : $_bri5anlujh8lz1in.getOption(element).fold(function () {
      return $_4hc7u2ktjh8lz1dv.children(element).length;
    }, function (v) {
      return v.length;
    });
  };
  var isEnd = function (element, offset) {
    return getEnd(element) === offset;
  };
  var isStart = function (element, offset) {
    return offset === 0;
  };
  var NBSP = '\xA0';
  var isTextNodeWithCursorPosition = function (el) {
    return $_bri5anlujh8lz1in.getOption(el).filter(function (text) {
      return text.trim().length !== 0 || text.indexOf(NBSP) > -1;
    }).isSome();
  };
  var elementsWithCursorPosition = [
    'img',
    'br'
  ];
  var isCursorPosition = function (elem) {
    var hasCursorPosition = isTextNodeWithCursorPosition(elem);
    return hasCursorPosition || $_6b0spykcjh8lz1ao.contains(elementsWithCursorPosition, $_a3izpgldjh8lz1fy.name(elem));
  };
  var $_6759o9ltjh8lz1ij = {
    getEnd: getEnd,
    isEnd: isEnd,
    isStart: isStart,
    isCursorPosition: isCursorPosition
  };

  var first$3 = function (element) {
    return $_aykj0glijh8lz1g9.descendant(element, $_6759o9ltjh8lz1ij.isCursorPosition);
  };
  var last$2 = function (element) {
    return descendantRtl(element, $_6759o9ltjh8lz1ij.isCursorPosition);
  };
  var descendantRtl = function (scope, predicate) {
    var descend = function (element) {
      var children = $_4hc7u2ktjh8lz1dv.children(element);
      for (var i = children.length - 1; i >= 0; i--) {
        var child = children[i];
        if (predicate(child))
          return Option.some(child);
        var res = descend(child);
        if (res.isSome())
          return res;
      }
      return Option.none();
    };
    return descend(scope);
  };
  var $_fpdn73lsjh8lz1ig = {
    first: first$3,
    last: last$2
  };

  var cell$1 = function () {
    var td = $_6vo9a4krjh8lz1do.fromTag('td');
    $_6qqu1alnjh8lz1hg.append(td, $_6vo9a4krjh8lz1do.fromTag('br'));
    return td;
  };
  var replace = function (cell, tag, attrs) {
    var replica = $_zeqq4lrjh8lz1id.copy(cell, tag);
    $_8kti2hkhjh8lz1bt.each(attrs, function (v, k) {
      if (v === null)
        $_1mp8lglcjh8lz1fq.remove(replica, k);
      else
        $_1mp8lglcjh8lz1fq.set(replica, k, v);
    });
    return replica;
  };
  var pasteReplace = function (cellContent) {
    return cellContent;
  };
  var newRow = function (doc) {
    return function () {
      return $_6vo9a4krjh8lz1do.fromTag('tr', doc.dom());
    };
  };
  var cloneFormats = function (oldCell, newCell, formats) {
    var first = $_fpdn73lsjh8lz1ig.first(oldCell);
    return first.map(function (firstText) {
      var formatSelector = formats.join(',');
      var parents = $_coxlualejh8lz1fz.ancestors(firstText, formatSelector, function (element) {
        return $_2eywnlkvjh8lz1e8.eq(element, oldCell);
      });
      return $_6b0spykcjh8lz1ao.foldr(parents, function (last, parent) {
        var clonedFormat = $_zeqq4lrjh8lz1id.shallow(parent);
        $_6qqu1alnjh8lz1hg.append(last, clonedFormat);
        return clonedFormat;
      }, newCell);
    }).getOr(newCell);
  };
  var cellOperations = function (mutate, doc, formatsToClone) {
    var newCell = function (prev) {
      var doc = $_4hc7u2ktjh8lz1dv.owner(prev.element());
      var td = $_6vo9a4krjh8lz1do.fromTag($_a3izpgldjh8lz1fy.name(prev.element()), doc.dom());
      var formats = formatsToClone.getOr([
        'strong',
        'em',
        'b',
        'i',
        'span',
        'font',
        'h1',
        'h2',
        'h3',
        'h4',
        'h5',
        'h6',
        'p',
        'div'
      ]);
      var lastNode = formats.length > 0 ? cloneFormats(prev.element(), td, formats) : td;
      $_6qqu1alnjh8lz1hg.append(lastNode, $_6vo9a4krjh8lz1do.fromTag('br'));
      $_3ory84lljh8lz1gx.copy(prev.element(), td);
      $_3ory84lljh8lz1gx.remove(td, 'height');
      if (prev.colspan() !== 1)
        $_3ory84lljh8lz1gx.remove(prev.element(), 'width');
      mutate(prev.element(), td);
      return td;
    };
    return {
      row: newRow(doc),
      cell: newCell,
      replace: replace,
      gap: cell$1
    };
  };
  var paste = function (doc) {
    return {
      row: newRow(doc),
      cell: cell$1,
      replace: pasteReplace,
      gap: cell$1
    };
  };
  var $_3fxw02lqjh8lz1hp = {
    cellOperations: cellOperations,
    paste: paste
  };

  var fromHtml$1 = function (html, scope) {
    var doc = scope || document;
    var div = doc.createElement('div');
    div.innerHTML = html;
    return $_4hc7u2ktjh8lz1dv.children($_6vo9a4krjh8lz1do.fromDom(div));
  };
  var fromTags = function (tags, scope) {
    return $_6b0spykcjh8lz1ao.map(tags, function (x) {
      return $_6vo9a4krjh8lz1do.fromTag(x, scope);
    });
  };
  var fromText$1 = function (texts, scope) {
    return $_6b0spykcjh8lz1ao.map(texts, function (x) {
      return $_6vo9a4krjh8lz1do.fromText(x, scope);
    });
  };
  var fromDom$1 = function (nodes) {
    return $_6b0spykcjh8lz1ao.map(nodes, $_6vo9a4krjh8lz1do.fromDom);
  };
  var $_200no5lwjh8lz1iy = {
    fromHtml: fromHtml$1,
    fromTags: fromTags,
    fromText: fromText$1,
    fromDom: fromDom$1
  };

  var TagBoundaries = [
    'body',
    'p',
    'div',
    'article',
    'aside',
    'figcaption',
    'figure',
    'footer',
    'header',
    'nav',
    'section',
    'ol',
    'ul',
    'li',
    'table',
    'thead',
    'tbody',
    'tfoot',
    'caption',
    'tr',
    'td',
    'th',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'blockquote',
    'pre',
    'address'
  ];

  function DomUniverse () {
    var clone = function (element) {
      return $_6vo9a4krjh8lz1do.fromDom(element.dom().cloneNode(false));
    };
    var isBoundary = function (element) {
      if (!$_a3izpgldjh8lz1fy.isElement(element))
        return false;
      if ($_a3izpgldjh8lz1fy.name(element) === 'body')
        return true;
      return $_6b0spykcjh8lz1ao.contains(TagBoundaries, $_a3izpgldjh8lz1fy.name(element));
    };
    var isEmptyTag = function (element) {
      if (!$_a3izpgldjh8lz1fy.isElement(element))
        return false;
      return $_6b0spykcjh8lz1ao.contains([
        'br',
        'img',
        'hr',
        'input'
      ], $_a3izpgldjh8lz1fy.name(element));
    };
    var comparePosition = function (element, other) {
      return element.dom().compareDocumentPosition(other.dom());
    };
    var copyAttributesTo = function (source, destination) {
      var as = $_1mp8lglcjh8lz1fq.clone(source);
      $_1mp8lglcjh8lz1fq.setAll(destination, as);
    };
    return {
      up: $_bgyjg9kejh8lz1ax.constant({
        selector: $_fiygddlhjh8lz1g7.ancestor,
        closest: $_fiygddlhjh8lz1g7.closest,
        predicate: $_aykj0glijh8lz1g9.ancestor,
        all: $_4hc7u2ktjh8lz1dv.parents
      }),
      down: $_bgyjg9kejh8lz1ax.constant({
        selector: $_coxlualejh8lz1fz.descendants,
        predicate: $_5a2t82lfjh8lz1g0.descendants
      }),
      styles: $_bgyjg9kejh8lz1ax.constant({
        get: $_3ory84lljh8lz1gx.get,
        getRaw: $_3ory84lljh8lz1gx.getRaw,
        set: $_3ory84lljh8lz1gx.set,
        remove: $_3ory84lljh8lz1gx.remove
      }),
      attrs: $_bgyjg9kejh8lz1ax.constant({
        get: $_1mp8lglcjh8lz1fq.get,
        set: $_1mp8lglcjh8lz1fq.set,
        remove: $_1mp8lglcjh8lz1fq.remove,
        copyTo: copyAttributesTo
      }),
      insert: $_bgyjg9kejh8lz1ax.constant({
        before: $_6qqu1alnjh8lz1hg.before,
        after: $_6qqu1alnjh8lz1hg.after,
        afterAll: $_d7tq5mlpjh8lz1hl.after,
        append: $_6qqu1alnjh8lz1hg.append,
        appendAll: $_d7tq5mlpjh8lz1hl.append,
        prepend: $_6qqu1alnjh8lz1hg.prepend,
        wrap: $_6qqu1alnjh8lz1hg.wrap
      }),
      remove: $_bgyjg9kejh8lz1ax.constant({
        unwrap: $_f2hny0lojh8lz1hi.unwrap,
        remove: $_f2hny0lojh8lz1hi.remove
      }),
      create: $_bgyjg9kejh8lz1ax.constant({
        nu: $_6vo9a4krjh8lz1do.fromTag,
        clone: clone,
        text: $_6vo9a4krjh8lz1do.fromText
      }),
      query: $_bgyjg9kejh8lz1ax.constant({
        comparePosition: comparePosition,
        prevSibling: $_4hc7u2ktjh8lz1dv.prevSibling,
        nextSibling: $_4hc7u2ktjh8lz1dv.nextSibling
      }),
      property: $_bgyjg9kejh8lz1ax.constant({
        children: $_4hc7u2ktjh8lz1dv.children,
        name: $_a3izpgldjh8lz1fy.name,
        parent: $_4hc7u2ktjh8lz1dv.parent,
        isText: $_a3izpgldjh8lz1fy.isText,
        isComment: $_a3izpgldjh8lz1fy.isComment,
        isElement: $_a3izpgldjh8lz1fy.isElement,
        getText: $_bri5anlujh8lz1in.get,
        setText: $_bri5anlujh8lz1in.set,
        isBoundary: isBoundary,
        isEmptyTag: isEmptyTag
      }),
      eq: $_2eywnlkvjh8lz1e8.eq,
      is: $_2eywnlkvjh8lz1e8.is
    };
  }

  var leftRight = $_d2ojjnkijh8lz1bv.immutable('left', 'right');
  var bisect = function (universe, parent, child) {
    var children = universe.property().children(parent);
    var index = $_6b0spykcjh8lz1ao.findIndex(children, $_bgyjg9kejh8lz1ax.curry(universe.eq, child));
    return index.map(function (ind) {
      return {
        before: $_bgyjg9kejh8lz1ax.constant(children.slice(0, ind)),
        after: $_bgyjg9kejh8lz1ax.constant(children.slice(ind + 1))
      };
    });
  };
  var breakToRight = function (universe, parent, child) {
    return bisect(universe, parent, child).map(function (parts) {
      var second = universe.create().clone(parent);
      universe.insert().appendAll(second, parts.after());
      universe.insert().after(parent, second);
      return leftRight(parent, second);
    });
  };
  var breakToLeft = function (universe, parent, child) {
    return bisect(universe, parent, child).map(function (parts) {
      var prior = universe.create().clone(parent);
      universe.insert().appendAll(prior, parts.before().concat([child]));
      universe.insert().appendAll(parent, parts.after());
      universe.insert().before(parent, prior);
      return leftRight(prior, parent);
    });
  };
  var breakPath = function (universe, item, isTop, breaker) {
    var result = $_d2ojjnkijh8lz1bv.immutable('first', 'second', 'splits');
    var next = function (child, group, splits) {
      var fallback = result(child, Option.none(), splits);
      if (isTop(child))
        return result(child, group, splits);
      else {
        return universe.property().parent(child).bind(function (parent) {
          return breaker(universe, parent, child).map(function (breakage) {
            var extra = [{
                first: breakage.left,
                second: breakage.right
              }];
            var nextChild = isTop(parent) ? parent : breakage.left();
            return next(nextChild, Option.some(breakage.right()), splits.concat(extra));
          }).getOr(fallback);
        });
      }
    };
    return next(item, Option.none(), []);
  };
  var $_6javmwm5jh8lz1lp = {
    breakToLeft: breakToLeft,
    breakToRight: breakToRight,
    breakPath: breakPath
  };

  var all$3 = function (universe, look, elements, f) {
    var head = elements[0];
    var tail = elements.slice(1);
    return f(universe, look, head, tail);
  };
  var oneAll = function (universe, look, elements) {
    return elements.length > 0 ? all$3(universe, look, elements, unsafeOne) : Option.none();
  };
  var unsafeOne = function (universe, look, head, tail) {
    var start = look(universe, head);
    return $_6b0spykcjh8lz1ao.foldr(tail, function (b, a) {
      var current = look(universe, a);
      return commonElement(universe, b, current);
    }, start);
  };
  var commonElement = function (universe, start, end) {
    return start.bind(function (s) {
      return end.filter($_bgyjg9kejh8lz1ax.curry(universe.eq, s));
    });
  };
  var $_f59pclm6jh8lz1lz = { oneAll: oneAll };

  var eq$1 = function (universe, item) {
    return $_bgyjg9kejh8lz1ax.curry(universe.eq, item);
  };
  var unsafeSubset = function (universe, common, ps1, ps2) {
    var children = universe.property().children(common);
    if (universe.eq(common, ps1[0]))
      return Option.some([ps1[0]]);
    if (universe.eq(common, ps2[0]))
      return Option.some([ps2[0]]);
    var finder = function (ps) {
      var topDown = $_6b0spykcjh8lz1ao.reverse(ps);
      var index = $_6b0spykcjh8lz1ao.findIndex(topDown, eq$1(universe, common)).getOr(-1);
      var item = index < topDown.length - 1 ? topDown[index + 1] : topDown[index];
      return $_6b0spykcjh8lz1ao.findIndex(children, eq$1(universe, item));
    };
    var startIndex = finder(ps1);
    var endIndex = finder(ps2);
    return startIndex.bind(function (sIndex) {
      return endIndex.map(function (eIndex) {
        var first = Math.min(sIndex, eIndex);
        var last = Math.max(sIndex, eIndex);
        return children.slice(first, last + 1);
      });
    });
  };
  var ancestors$2 = function (universe, start, end, _isRoot) {
    var isRoot = _isRoot !== undefined ? _isRoot : $_bgyjg9kejh8lz1ax.constant(false);
    var ps1 = [start].concat(universe.up().all(start));
    var ps2 = [end].concat(universe.up().all(end));
    var prune = function (path) {
      var index = $_6b0spykcjh8lz1ao.findIndex(path, isRoot);
      return index.fold(function () {
        return path;
      }, function (ind) {
        return path.slice(0, ind + 1);
      });
    };
    var pruned1 = prune(ps1);
    var pruned2 = prune(ps2);
    var shared = $_6b0spykcjh8lz1ao.find(pruned1, function (x) {
      return $_6b0spykcjh8lz1ao.exists(pruned2, eq$1(universe, x));
    });
    return {
      firstpath: $_bgyjg9kejh8lz1ax.constant(pruned1),
      secondpath: $_bgyjg9kejh8lz1ax.constant(pruned2),
      shared: $_bgyjg9kejh8lz1ax.constant(shared)
    };
  };
  var subset = function (universe, start, end) {
    var ancs = ancestors$2(universe, start, end);
    return ancs.shared().bind(function (shared) {
      return unsafeSubset(universe, shared, ancs.firstpath(), ancs.secondpath());
    });
  };
  var $_53b8yjm7jh8lz1m7 = {
    subset: subset,
    ancestors: ancestors$2
  };

  var sharedOne = function (universe, look, elements) {
    return $_f59pclm6jh8lz1lz.oneAll(universe, look, elements);
  };
  var subset$1 = function (universe, start, finish) {
    return $_53b8yjm7jh8lz1m7.subset(universe, start, finish);
  };
  var ancestors$3 = function (universe, start, finish, _isRoot) {
    return $_53b8yjm7jh8lz1m7.ancestors(universe, start, finish, _isRoot);
  };
  var breakToLeft$1 = function (universe, parent, child) {
    return $_6javmwm5jh8lz1lp.breakToLeft(universe, parent, child);
  };
  var breakToRight$1 = function (universe, parent, child) {
    return $_6javmwm5jh8lz1lp.breakToRight(universe, parent, child);
  };
  var breakPath$1 = function (universe, child, isTop, breaker) {
    return $_6javmwm5jh8lz1lp.breakPath(universe, child, isTop, breaker);
  };
  var $_dkt9bum4jh8lz1ln = {
    sharedOne: sharedOne,
    subset: subset$1,
    ancestors: ancestors$3,
    breakToLeft: breakToLeft$1,
    breakToRight: breakToRight$1,
    breakPath: breakPath$1
  };

  var universe = DomUniverse();
  var sharedOne$1 = function (look, elements) {
    return $_dkt9bum4jh8lz1ln.sharedOne(universe, function (universe, element) {
      return look(element);
    }, elements);
  };
  var subset$2 = function (start, finish) {
    return $_dkt9bum4jh8lz1ln.subset(universe, start, finish);
  };
  var ancestors$4 = function (start, finish, _isRoot) {
    return $_dkt9bum4jh8lz1ln.ancestors(universe, start, finish, _isRoot);
  };
  var breakToLeft$2 = function (parent, child) {
    return $_dkt9bum4jh8lz1ln.breakToLeft(universe, parent, child);
  };
  var breakToRight$2 = function (parent, child) {
    return $_dkt9bum4jh8lz1ln.breakToRight(universe, parent, child);
  };
  var breakPath$2 = function (child, isTop, breaker) {
    return $_dkt9bum4jh8lz1ln.breakPath(universe, child, isTop, function (u, p, c) {
      return breaker(p, c);
    });
  };
  var $_5glne7m1jh8lz1kg = {
    sharedOne: sharedOne$1,
    subset: subset$2,
    ancestors: ancestors$4,
    breakToLeft: breakToLeft$2,
    breakToRight: breakToRight$2,
    breakPath: breakPath$2
  };

  var inSelection = function (bounds, detail) {
    var leftEdge = detail.column();
    var rightEdge = detail.column() + detail.colspan() - 1;
    var topEdge = detail.row();
    var bottomEdge = detail.row() + detail.rowspan() - 1;
    return leftEdge <= bounds.finishCol() && rightEdge >= bounds.startCol() && (topEdge <= bounds.finishRow() && bottomEdge >= bounds.startRow());
  };
  var isWithin = function (bounds, detail) {
    return detail.column() >= bounds.startCol() && detail.column() + detail.colspan() - 1 <= bounds.finishCol() && detail.row() >= bounds.startRow() && detail.row() + detail.rowspan() - 1 <= bounds.finishRow();
  };
  var isRectangular = function (warehouse, bounds) {
    var isRect = true;
    var detailIsWithin = $_bgyjg9kejh8lz1ax.curry(isWithin, bounds);
    for (var i = bounds.startRow(); i <= bounds.finishRow(); i++) {
      for (var j = bounds.startCol(); j <= bounds.finishCol(); j++) {
        isRect = isRect && $_fxwupplkjh8lz1go.getAt(warehouse, i, j).exists(detailIsWithin);
      }
    }
    return isRect ? Option.some(bounds) : Option.none();
  };
  var $_bx09g1majh8lz1mt = {
    inSelection: inSelection,
    isWithin: isWithin,
    isRectangular: isRectangular
  };

  var getBounds = function (detailA, detailB) {
    return $_g424vknjh8lz1cd.bounds(Math.min(detailA.row(), detailB.row()), Math.min(detailA.column(), detailB.column()), Math.max(detailA.row() + detailA.rowspan() - 1, detailB.row() + detailB.rowspan() - 1), Math.max(detailA.column() + detailA.colspan() - 1, detailB.column() + detailB.colspan() - 1));
  };
  var getAnyBox = function (warehouse, startCell, finishCell) {
    var startCoords = $_fxwupplkjh8lz1go.findItem(warehouse, startCell, $_2eywnlkvjh8lz1e8.eq);
    var finishCoords = $_fxwupplkjh8lz1go.findItem(warehouse, finishCell, $_2eywnlkvjh8lz1e8.eq);
    return startCoords.bind(function (sc) {
      return finishCoords.map(function (fc) {
        return getBounds(sc, fc);
      });
    });
  };
  var getBox = function (warehouse, startCell, finishCell) {
    return getAnyBox(warehouse, startCell, finishCell).bind(function (bounds) {
      return $_bx09g1majh8lz1mt.isRectangular(warehouse, bounds);
    });
  };
  var $_dsxu28mbjh8lz1mz = {
    getAnyBox: getAnyBox,
    getBox: getBox
  };

  var moveBy = function (warehouse, cell, row, column) {
    return $_fxwupplkjh8lz1go.findItem(warehouse, cell, $_2eywnlkvjh8lz1e8.eq).bind(function (detail) {
      var startRow = row > 0 ? detail.row() + detail.rowspan() - 1 : detail.row();
      var startCol = column > 0 ? detail.column() + detail.colspan() - 1 : detail.column();
      var dest = $_fxwupplkjh8lz1go.getAt(warehouse, startRow + row, startCol + column);
      return dest.map(function (d) {
        return d.element();
      });
    });
  };
  var intercepts = function (warehouse, start, finish) {
    return $_dsxu28mbjh8lz1mz.getAnyBox(warehouse, start, finish).map(function (bounds) {
      var inside = $_fxwupplkjh8lz1go.filterItems(warehouse, $_bgyjg9kejh8lz1ax.curry($_bx09g1majh8lz1mt.inSelection, bounds));
      return $_6b0spykcjh8lz1ao.map(inside, function (detail) {
        return detail.element();
      });
    });
  };
  var parentCell = function (warehouse, innerCell) {
    var isContainedBy = function (c1, c2) {
      return $_2eywnlkvjh8lz1e8.contains(c2, c1);
    };
    return $_fxwupplkjh8lz1go.findItem(warehouse, innerCell, isContainedBy).bind(function (detail) {
      return detail.element();
    });
  };
  var $_cwtr9hm9jh8lz1mm = {
    moveBy: moveBy,
    intercepts: intercepts,
    parentCell: parentCell
  };

  var moveBy$1 = function (cell, deltaRow, deltaColumn) {
    return $_ee8pmfkojh8lz1ch.table(cell).bind(function (table) {
      var warehouse = getWarehouse(table);
      return $_cwtr9hm9jh8lz1mm.moveBy(warehouse, cell, deltaRow, deltaColumn);
    });
  };
  var intercepts$1 = function (table, first, last) {
    var warehouse = getWarehouse(table);
    return $_cwtr9hm9jh8lz1mm.intercepts(warehouse, first, last);
  };
  var nestedIntercepts = function (table, first, firstTable, last, lastTable) {
    var warehouse = getWarehouse(table);
    var startCell = $_2eywnlkvjh8lz1e8.eq(table, firstTable) ? first : $_cwtr9hm9jh8lz1mm.parentCell(warehouse, first);
    var lastCell = $_2eywnlkvjh8lz1e8.eq(table, lastTable) ? last : $_cwtr9hm9jh8lz1mm.parentCell(warehouse, last);
    return $_cwtr9hm9jh8lz1mm.intercepts(warehouse, startCell, lastCell);
  };
  var getBox$1 = function (table, first, last) {
    var warehouse = getWarehouse(table);
    return $_dsxu28mbjh8lz1mz.getBox(warehouse, first, last);
  };
  var getWarehouse = function (table) {
    var list = $_ff1h20kmjh8lz1c3.fromTable(table);
    return $_fxwupplkjh8lz1go.generate(list);
  };
  var $_7f2vlpm8jh8lz1mf = {
    moveBy: moveBy$1,
    intercepts: intercepts$1,
    nestedIntercepts: nestedIntercepts,
    getBox: getBox$1
  };

  var lookupTable = function (container, isRoot) {
    return $_fiygddlhjh8lz1g7.ancestor(container, 'table');
  };
  var identified = $_d2ojjnkijh8lz1bv.immutableBag([
    'boxes',
    'start',
    'finish'
  ], []);
  var identify = function (start, finish, isRoot) {
    var getIsRoot = function (rootTable) {
      return function (element) {
        return isRoot(element) || $_2eywnlkvjh8lz1e8.eq(element, rootTable);
      };
    };
    if ($_2eywnlkvjh8lz1e8.eq(start, finish)) {
      return Option.some(identified({
        boxes: Option.some([start]),
        start: start,
        finish: finish
      }));
    } else {
      return lookupTable(start, isRoot).bind(function (startTable) {
        return lookupTable(finish, isRoot).bind(function (finishTable) {
          if ($_2eywnlkvjh8lz1e8.eq(startTable, finishTable)) {
            return Option.some(identified({
              boxes: $_7f2vlpm8jh8lz1mf.intercepts(startTable, start, finish),
              start: start,
              finish: finish
            }));
          } else if ($_2eywnlkvjh8lz1e8.contains(startTable, finishTable)) {
            var ancestorCells = $_coxlualejh8lz1fz.ancestors(finish, 'td,th', getIsRoot(startTable));
            var finishCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : finish;
            return Option.some(identified({
              boxes: $_7f2vlpm8jh8lz1mf.nestedIntercepts(startTable, start, startTable, finish, finishTable),
              start: start,
              finish: finishCell
            }));
          } else if ($_2eywnlkvjh8lz1e8.contains(finishTable, startTable)) {
            var ancestorCells = $_coxlualejh8lz1fz.ancestors(start, 'td,th', getIsRoot(finishTable));
            var startCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : start;
            return Option.some(identified({
              boxes: $_7f2vlpm8jh8lz1mf.nestedIntercepts(finishTable, start, startTable, finish, finishTable),
              start: start,
              finish: startCell
            }));
          } else {
            return $_5glne7m1jh8lz1kg.ancestors(start, finish).shared().bind(function (lca) {
              return $_fiygddlhjh8lz1g7.closest(lca, 'table', isRoot).bind(function (lcaTable) {
                var finishAncestorCells = $_coxlualejh8lz1fz.ancestors(finish, 'td,th', getIsRoot(lcaTable));
                var finishCell = finishAncestorCells.length > 0 ? finishAncestorCells[finishAncestorCells.length - 1] : finish;
                var startAncestorCells = $_coxlualejh8lz1fz.ancestors(start, 'td,th', getIsRoot(lcaTable));
                var startCell = startAncestorCells.length > 0 ? startAncestorCells[startAncestorCells.length - 1] : start;
                return Option.some(identified({
                  boxes: $_7f2vlpm8jh8lz1mf.nestedIntercepts(lcaTable, start, startTable, finish, finishTable),
                  start: startCell,
                  finish: finishCell
                }));
              });
            });
          }
        });
      });
    }
  };
  var retrieve = function (container, selector) {
    var sels = $_coxlualejh8lz1fz.descendants(container, selector);
    return sels.length > 0 ? Option.some(sels) : Option.none();
  };
  var getLast = function (boxes, lastSelectedSelector) {
    return $_6b0spykcjh8lz1ao.find(boxes, function (box) {
      return $_62so4qkqjh8lz1di.is(box, lastSelectedSelector);
    });
  };
  var getEdges = function (container, firstSelectedSelector, lastSelectedSelector) {
    return $_fiygddlhjh8lz1g7.descendant(container, firstSelectedSelector).bind(function (first) {
      return $_fiygddlhjh8lz1g7.descendant(container, lastSelectedSelector).bind(function (last) {
        return $_5glne7m1jh8lz1kg.sharedOne(lookupTable, [
          first,
          last
        ]).map(function (tbl) {
          return {
            first: $_bgyjg9kejh8lz1ax.constant(first),
            last: $_bgyjg9kejh8lz1ax.constant(last),
            table: $_bgyjg9kejh8lz1ax.constant(tbl)
          };
        });
      });
    });
  };
  var expandTo = function (finish, firstSelectedSelector) {
    return $_fiygddlhjh8lz1g7.ancestor(finish, 'table').bind(function (table) {
      return $_fiygddlhjh8lz1g7.descendant(table, firstSelectedSelector).bind(function (start) {
        return identify(start, finish).bind(function (identified) {
          return identified.boxes().map(function (boxes) {
            return {
              boxes: $_bgyjg9kejh8lz1ax.constant(boxes),
              start: $_bgyjg9kejh8lz1ax.constant(identified.start()),
              finish: $_bgyjg9kejh8lz1ax.constant(identified.finish())
            };
          });
        });
      });
    });
  };
  var shiftSelection = function (boxes, deltaRow, deltaColumn, firstSelectedSelector, lastSelectedSelector) {
    return getLast(boxes, lastSelectedSelector).bind(function (last) {
      return $_7f2vlpm8jh8lz1mf.moveBy(last, deltaRow, deltaColumn).bind(function (finish) {
        return expandTo(finish, firstSelectedSelector);
      });
    });
  };
  var $_5tpv0tm0jh8lz1jt = {
    identify: identify,
    retrieve: retrieve,
    shiftSelection: shiftSelection,
    getEdges: getEdges
  };

  var retrieve$1 = function (container, selector) {
    return $_5tpv0tm0jh8lz1jt.retrieve(container, selector);
  };
  var retrieveBox = function (container, firstSelectedSelector, lastSelectedSelector) {
    return $_5tpv0tm0jh8lz1jt.getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(function (edges) {
      var isRoot = function (ancestor) {
        return $_2eywnlkvjh8lz1e8.eq(container, ancestor);
      };
      var firstAncestor = $_fiygddlhjh8lz1g7.ancestor(edges.first(), 'thead,tfoot,tbody,table', isRoot);
      var lastAncestor = $_fiygddlhjh8lz1g7.ancestor(edges.last(), 'thead,tfoot,tbody,table', isRoot);
      return firstAncestor.bind(function (fA) {
        return lastAncestor.bind(function (lA) {
          return $_2eywnlkvjh8lz1e8.eq(fA, lA) ? $_7f2vlpm8jh8lz1mf.getBox(edges.table(), edges.first(), edges.last()) : Option.none();
        });
      });
    });
  };
  var $_21toytlzjh8lz1jj = {
    retrieve: retrieve$1,
    retrieveBox: retrieveBox
  };

  var selected = 'data-mce-selected';
  var selectedSelector = 'td[' + selected + '],th[' + selected + ']';
  var attributeSelector = '[' + selected + ']';
  var firstSelected = 'data-mce-first-selected';
  var firstSelectedSelector = 'td[' + firstSelected + '],th[' + firstSelected + ']';
  var lastSelected = 'data-mce-last-selected';
  var lastSelectedSelector = 'td[' + lastSelected + '],th[' + lastSelected + ']';
  var $_2yroczmcjh8lz1n4 = {
    selected: $_bgyjg9kejh8lz1ax.constant(selected),
    selectedSelector: $_bgyjg9kejh8lz1ax.constant(selectedSelector),
    attributeSelector: $_bgyjg9kejh8lz1ax.constant(attributeSelector),
    firstSelected: $_bgyjg9kejh8lz1ax.constant(firstSelected),
    firstSelectedSelector: $_bgyjg9kejh8lz1ax.constant(firstSelectedSelector),
    lastSelected: $_bgyjg9kejh8lz1ax.constant(lastSelected),
    lastSelectedSelector: $_bgyjg9kejh8lz1ax.constant(lastSelectedSelector)
  };

  var generate$1 = function (cases) {
    if (!$_d1kyz8kfjh8lz1az.isArray(cases)) {
      throw new Error('cases must be an array');
    }
    if (cases.length === 0) {
      throw new Error('there must be at least one case');
    }
    var constructors = [];
    var adt = {};
    $_6b0spykcjh8lz1ao.each(cases, function (acase, count) {
      var keys = $_8kti2hkhjh8lz1bt.keys(acase);
      if (keys.length !== 1) {
        throw new Error('one and only one name per case');
      }
      var key = keys[0];
      var value = acase[key];
      if (adt[key] !== undefined) {
        throw new Error('duplicate key detected:' + key);
      } else if (key === 'cata') {
        throw new Error('cannot have a case named cata (sorry)');
      } else if (!$_d1kyz8kfjh8lz1az.isArray(value)) {
        throw new Error('case arguments must be an array');
      }
      constructors.push(key);
      adt[key] = function () {
        var argLength = arguments.length;
        if (argLength !== value.length) {
          throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
        }
        var args = new Array(argLength);
        for (var i = 0; i < args.length; i++)
          args[i] = arguments[i];
        var match = function (branches) {
          var branchKeys = $_8kti2hkhjh8lz1bt.keys(branches);
          if (constructors.length !== branchKeys.length) {
            throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
          }
          var allReqd = $_6b0spykcjh8lz1ao.forall(constructors, function (reqKey) {
            return $_6b0spykcjh8lz1ao.contains(branchKeys, reqKey);
          });
          if (!allReqd)
            throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
          return branches[key].apply(null, args);
        };
        return {
          fold: function () {
            if (arguments.length !== cases.length) {
              throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
            }
            var target = arguments[count];
            return target.apply(null, args);
          },
          match: match,
          log: function (label) {
            console.log(label, {
              constructors: constructors,
              constructor: key,
              params: args
            });
          }
        };
      };
    });
    return adt;
  };
  var $_659si2mejh8lz1n9 = { generate: generate$1 };

  var type$1 = $_659si2mejh8lz1n9.generate([
    { none: [] },
    { multiple: ['elements'] },
    { single: ['selection'] }
  ]);
  var cata = function (subject, onNone, onMultiple, onSingle) {
    return subject.fold(onNone, onMultiple, onSingle);
  };
  var $_crzziemdjh8lz1n7 = {
    cata: cata,
    none: type$1.none,
    multiple: type$1.multiple,
    single: type$1.single
  };

  var selection = function (cell, selections) {
    return $_crzziemdjh8lz1n7.cata(selections.get(), $_bgyjg9kejh8lz1ax.constant([]), $_bgyjg9kejh8lz1ax.identity, $_bgyjg9kejh8lz1ax.constant([cell]));
  };
  var unmergable = function (cell, selections) {
    var hasSpan = function (elem) {
      return $_1mp8lglcjh8lz1fq.has(elem, 'rowspan') && parseInt($_1mp8lglcjh8lz1fq.get(elem, 'rowspan'), 10) > 1 || $_1mp8lglcjh8lz1fq.has(elem, 'colspan') && parseInt($_1mp8lglcjh8lz1fq.get(elem, 'colspan'), 10) > 1;
    };
    var candidates = selection(cell, selections);
    return candidates.length > 0 && $_6b0spykcjh8lz1ao.forall(candidates, hasSpan) ? Option.some(candidates) : Option.none();
  };
  var mergable = function (table, selections) {
    return $_crzziemdjh8lz1n7.cata(selections.get(), Option.none, function (cells, _env) {
      if (cells.length === 0) {
        return Option.none();
      }
      return $_21toytlzjh8lz1jj.retrieveBox(table, $_2yroczmcjh8lz1n4.firstSelectedSelector(), $_2yroczmcjh8lz1n4.lastSelectedSelector()).bind(function (bounds) {
        return cells.length > 1 ? Option.some({
          bounds: $_bgyjg9kejh8lz1ax.constant(bounds),
          cells: $_bgyjg9kejh8lz1ax.constant(cells)
        }) : Option.none();
      });
    }, Option.none);
  };
  var $_59in44lyjh8lz1j8 = {
    mergable: mergable,
    unmergable: unmergable,
    selection: selection
  };

  var noMenu = function (cell) {
    return {
      element: $_bgyjg9kejh8lz1ax.constant(cell),
      mergable: Option.none,
      unmergable: Option.none,
      selection: $_bgyjg9kejh8lz1ax.constant([cell])
    };
  };
  var forMenu = function (selections, table, cell) {
    return {
      element: $_bgyjg9kejh8lz1ax.constant(cell),
      mergable: $_bgyjg9kejh8lz1ax.constant($_59in44lyjh8lz1j8.mergable(table, selections)),
      unmergable: $_bgyjg9kejh8lz1ax.constant($_59in44lyjh8lz1j8.unmergable(cell, selections)),
      selection: $_bgyjg9kejh8lz1ax.constant($_59in44lyjh8lz1j8.selection(cell, selections))
    };
  };
  var notCell$1 = function (element) {
    return noMenu(element);
  };
  var paste$1 = $_d2ojjnkijh8lz1bv.immutable('element', 'clipboard', 'generators');
  var pasteRows = function (selections, table, cell, clipboard, generators) {
    return {
      element: $_bgyjg9kejh8lz1ax.constant(cell),
      mergable: Option.none,
      unmergable: Option.none,
      selection: $_bgyjg9kejh8lz1ax.constant($_59in44lyjh8lz1j8.selection(cell, selections)),
      clipboard: $_bgyjg9kejh8lz1ax.constant(clipboard),
      generators: $_bgyjg9kejh8lz1ax.constant(generators)
    };
  };
  var $_3xfj7olxjh8lz1j2 = {
    noMenu: noMenu,
    forMenu: forMenu,
    notCell: notCell$1,
    paste: paste$1,
    pasteRows: pasteRows
  };

  var extractSelected = function (cells) {
    return $_ee8pmfkojh8lz1ch.table(cells[0]).map($_zeqq4lrjh8lz1id.deep).map(function (replica) {
      return [$_dj8mm1kgjh8lz1b3.extract(replica, $_2yroczmcjh8lz1n4.attributeSelector())];
    });
  };
  var serializeElement = function (editor, elm) {
    return editor.selection.serializer.serialize(elm.dom(), {});
  };
  var registerEvents = function (editor, selections, actions, cellSelection) {
    editor.on('BeforeGetContent', function (e) {
      var multiCellContext = function (cells) {
        e.preventDefault();
        extractSelected(cells).each(function (elements) {
          e.content = $_6b0spykcjh8lz1ao.map(elements, function (elm) {
            return serializeElement(editor, elm);
          }).join('');
        });
      };
      if (e.selection === true) {
        $_crzziemdjh8lz1n7.cata(selections.get(), $_bgyjg9kejh8lz1ax.noop, multiCellContext, $_bgyjg9kejh8lz1ax.noop);
      }
    });
    editor.on('BeforeSetContent', function (e) {
      if (e.selection === true && e.paste === true) {
        var cellOpt = Option.from(editor.dom.getParent(editor.selection.getStart(), 'th,td'));
        cellOpt.each(function (domCell) {
          var cell = $_6vo9a4krjh8lz1do.fromDom(domCell);
          var table = $_ee8pmfkojh8lz1ch.table(cell);
          table.bind(function (table) {
            var elements = $_6b0spykcjh8lz1ao.filter($_200no5lwjh8lz1iy.fromHtml(e.content), function (content) {
              return $_a3izpgldjh8lz1fy.name(content) !== 'meta';
            });
            if (elements.length === 1 && $_a3izpgldjh8lz1fy.name(elements[0]) === 'table') {
              e.preventDefault();
              var doc = $_6vo9a4krjh8lz1do.fromDom(editor.getDoc());
              var generators = $_3fxw02lqjh8lz1hp.paste(doc);
              var targets = $_3xfj7olxjh8lz1j2.paste(cell, elements[0], generators);
              actions.pasteCells(table, targets).each(function (rng) {
                editor.selection.setRng(rng);
                editor.focus();
                cellSelection.clear(table);
              });
            }
          });
        });
      }
    });
  };
  var $_3x42x9kbjh8lz1a2 = { registerEvents: registerEvents };

  function Dimension (name, getOffset) {
    var set = function (element, h) {
      if (!$_d1kyz8kfjh8lz1az.isNumber(h) && !h.match(/^[0-9]+$/))
        throw name + '.set accepts only positive integer values. Value was ' + h;
      var dom = element.dom();
      if ($_3r8yz1lmjh8lz1hf.isSupported(dom))
        dom.style[name] = h + 'px';
    };
    var get = function (element) {
      var r = getOffset(element);
      if (r <= 0 || r === null) {
        var css = $_3ory84lljh8lz1gx.get(element, name);
        return parseFloat(css) || 0;
      }
      return r;
    };
    var getOuter = get;
    var aggregate = function (element, properties) {
      return $_6b0spykcjh8lz1ao.foldl(properties, function (acc, property) {
        var val = $_3ory84lljh8lz1gx.get(element, property);
        var value = val === undefined ? 0 : parseInt(val, 10);
        return isNaN(value) ? acc : acc + value;
      }, 0);
    };
    var max = function (element, value, properties) {
      var cumulativeInclusions = aggregate(element, properties);
      var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
      return absoluteMax;
    };
    return {
      set: set,
      get: get,
      getOuter: getOuter,
      aggregate: aggregate,
      max: max
    };
  }

  var api$1 = Dimension('height', function (element) {
    return $_brbde9lgjh8lz1g4.inBody(element) ? element.dom().getBoundingClientRect().height : element.dom().offsetHeight;
  });
  var set$3 = function (element, h) {
    api$1.set(element, h);
  };
  var get$3 = function (element) {
    return api$1.get(element);
  };
  var getOuter = function (element) {
    return api$1.getOuter(element);
  };
  var setMax = function (element, value) {
    var inclusions = [
      'margin-top',
      'border-top-width',
      'padding-top',
      'padding-bottom',
      'border-bottom-width',
      'margin-bottom'
    ];
    var absMax = api$1.max(element, value, inclusions);
    $_3ory84lljh8lz1gx.set(element, 'max-height', absMax + 'px');
  };
  var $_dc45zsmjjh8lz1or = {
    set: set$3,
    get: get$3,
    getOuter: getOuter,
    setMax: setMax
  };

  var api$2 = Dimension('width', function (element) {
    return element.dom().offsetWidth;
  });
  var set$4 = function (element, h) {
    api$2.set(element, h);
  };
  var get$4 = function (element) {
    return api$2.get(element);
  };
  var getOuter$1 = function (element) {
    return api$2.getOuter(element);
  };
  var setMax$1 = function (element, value) {
    var inclusions = [
      'margin-left',
      'border-left-width',
      'padding-left',
      'padding-right',
      'border-right-width',
      'margin-right'
    ];
    var absMax = api$2.max(element, value, inclusions);
    $_3ory84lljh8lz1gx.set(element, 'max-width', absMax + 'px');
  };
  var $_fu3j58mljh8lz1oz = {
    set: set$4,
    get: get$4,
    getOuter: getOuter$1,
    setMax: setMax$1
  };

  var platform = $_a6om0dl0jh8lz1ep.detect();
  var needManualCalc = function () {
    return platform.browser.isIE() || platform.browser.isEdge();
  };
  var toNumber = function (px, fallback) {
    var num = parseFloat(px);
    return isNaN(num) ? fallback : num;
  };
  var getProp = function (elm, name, fallback) {
    return toNumber($_3ory84lljh8lz1gx.get(elm, name), fallback);
  };
  var getCalculatedHeight = function (cell) {
    var paddingTop = getProp(cell, 'padding-top', 0);
    var paddingBottom = getProp(cell, 'padding-bottom', 0);
    var borderTop = getProp(cell, 'border-top-width', 0);
    var borderBottom = getProp(cell, 'border-bottom-width', 0);
    var height = cell.dom().getBoundingClientRect().height;
    var boxSizing = $_3ory84lljh8lz1gx.get(cell, 'box-sizing');
    var borders = borderTop + borderBottom;
    return boxSizing === 'border-box' ? height : height - paddingTop - paddingBottom - borders;
  };
  var getWidth = function (cell) {
    return getProp(cell, 'width', $_fu3j58mljh8lz1oz.get(cell));
  };
  var getHeight = function (cell) {
    return needManualCalc() ? getCalculatedHeight(cell) : getProp(cell, 'height', $_dc45zsmjjh8lz1or.get(cell));
  };
  var $_4n3vr6mijh8lz1oi = {
    getWidth: getWidth,
    getHeight: getHeight
  };

  var genericSizeRegex = /(\d+(\.\d+)?)(\w|%)*/;
  var percentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
  var pixelBasedSizeRegex = /(\d+(\.\d+)?)px|em/;
  var setPixelWidth = function (cell, amount) {
    $_3ory84lljh8lz1gx.set(cell, 'width', amount + 'px');
  };
  var setPercentageWidth = function (cell, amount) {
    $_3ory84lljh8lz1gx.set(cell, 'width', amount + '%');
  };
  var setHeight = function (cell, amount) {
    $_3ory84lljh8lz1gx.set(cell, 'height', amount + 'px');
  };
  var getHeightValue = function (cell) {
    return $_3ory84lljh8lz1gx.getRaw(cell, 'height').getOrThunk(function () {
      return $_4n3vr6mijh8lz1oi.getHeight(cell) + 'px';
    });
  };
  var convert = function (cell, number, getter, setter) {
    var newSize = $_ee8pmfkojh8lz1ch.table(cell).map(function (table) {
      var total = getter(table);
      return Math.floor(number / 100 * total);
    }).getOr(number);
    setter(cell, newSize);
    return newSize;
  };
  var normalizePixelSize = function (value, cell, getter, setter) {
    var number = parseInt(value, 10);
    return $_34vbjol9jh8lz1fk.endsWith(value, '%') && $_a3izpgldjh8lz1fy.name(cell) !== 'table' ? convert(cell, number, getter, setter) : number;
  };
  var getTotalHeight = function (cell) {
    var value = getHeightValue(cell);
    if (!value)
      return $_dc45zsmjjh8lz1or.get(cell);
    return normalizePixelSize(value, cell, $_dc45zsmjjh8lz1or.get, setHeight);
  };
  var get$5 = function (cell, type, f) {
    var v = f(cell);
    var span = getSpan(cell, type);
    return v / span;
  };
  var getSpan = function (cell, type) {
    return $_1mp8lglcjh8lz1fq.has(cell, type) ? parseInt($_1mp8lglcjh8lz1fq.get(cell, type), 10) : 1;
  };
  var getRawWidth = function (element) {
    var cssWidth = $_3ory84lljh8lz1gx.getRaw(element, 'width');
    return cssWidth.fold(function () {
      return Option.from($_1mp8lglcjh8lz1fq.get(element, 'width'));
    }, function (width) {
      return Option.some(width);
    });
  };
  var normalizePercentageWidth = function (cellWidth, tableSize) {
    return cellWidth / tableSize.pixelWidth() * 100;
  };
  var choosePercentageSize = function (element, width, tableSize) {
    if (percentageBasedSizeRegex.test(width)) {
      var percentMatch = percentageBasedSizeRegex.exec(width);
      return parseFloat(percentMatch[1]);
    } else {
      var fallbackWidth = $_fu3j58mljh8lz1oz.get(element);
      var intWidth = parseInt(fallbackWidth, 10);
      return normalizePercentageWidth(intWidth, tableSize);
    }
  };
  var getPercentageWidth = function (cell, tableSize) {
    var width = getRawWidth(cell);
    return width.fold(function () {
      var width = $_fu3j58mljh8lz1oz.get(cell);
      var intWidth = parseInt(width, 10);
      return normalizePercentageWidth(intWidth, tableSize);
    }, function (width) {
      return choosePercentageSize(cell, width, tableSize);
    });
  };
  var normalizePixelWidth = function (cellWidth, tableSize) {
    return cellWidth / 100 * tableSize.pixelWidth();
  };
  var choosePixelSize = function (element, width, tableSize) {
    if (pixelBasedSizeRegex.test(width)) {
      var pixelMatch = pixelBasedSizeRegex.exec(width);
      return parseInt(pixelMatch[1], 10);
    } else if (percentageBasedSizeRegex.test(width)) {
      var percentMatch = percentageBasedSizeRegex.exec(width);
      var floatWidth = parseFloat(percentMatch[1]);
      return normalizePixelWidth(floatWidth, tableSize);
    } else {
      var fallbackWidth = $_fu3j58mljh8lz1oz.get(element);
      return parseInt(fallbackWidth, 10);
    }
  };
  var getPixelWidth = function (cell, tableSize) {
    var width = getRawWidth(cell);
    return width.fold(function () {
      var width = $_fu3j58mljh8lz1oz.get(cell);
      var intWidth = parseInt(width, 10);
      return intWidth;
    }, function (width) {
      return choosePixelSize(cell, width, tableSize);
    });
  };
  var getHeight$1 = function (cell) {
    return get$5(cell, 'rowspan', getTotalHeight);
  };
  var getGenericWidth = function (cell) {
    var width = getRawWidth(cell);
    return width.bind(function (width) {
      if (genericSizeRegex.test(width)) {
        var match = genericSizeRegex.exec(width);
        return Option.some({
          width: $_bgyjg9kejh8lz1ax.constant(match[1]),
          unit: $_bgyjg9kejh8lz1ax.constant(match[3])
        });
      } else {
        return Option.none();
      }
    });
  };
  var setGenericWidth = function (cell, amount, unit) {
    $_3ory84lljh8lz1gx.set(cell, 'width', amount + unit);
  };
  var $_i2xtsmhjh8lz1nv = {
    percentageBasedSizeRegex: $_bgyjg9kejh8lz1ax.constant(percentageBasedSizeRegex),
    pixelBasedSizeRegex: $_bgyjg9kejh8lz1ax.constant(pixelBasedSizeRegex),
    setPixelWidth: setPixelWidth,
    setPercentageWidth: setPercentageWidth,
    setHeight: setHeight,
    getPixelWidth: getPixelWidth,
    getPercentageWidth: getPercentageWidth,
    getGenericWidth: getGenericWidth,
    setGenericWidth: setGenericWidth,
    getHeight: getHeight$1,
    getRawWidth: getRawWidth
  };

  var halve = function (main, other) {
    var width = $_i2xtsmhjh8lz1nv.getGenericWidth(main);
    width.each(function (width) {
      var newWidth = width.width() / 2;
      $_i2xtsmhjh8lz1nv.setGenericWidth(main, newWidth, width.unit());
      $_i2xtsmhjh8lz1nv.setGenericWidth(other, newWidth, width.unit());
    });
  };
  var $_36r49rmgjh8lz1nt = { halve: halve };

  var attached = function (element, scope) {
    var doc = scope || $_6vo9a4krjh8lz1do.fromDom(document.documentElement);
    return $_aykj0glijh8lz1g9.ancestor(element, $_bgyjg9kejh8lz1ax.curry($_2eywnlkvjh8lz1e8.eq, doc)).isSome();
  };
  var windowOf = function (element) {
    var dom = element.dom();
    if (dom === dom.window)
      return element;
    return $_a3izpgldjh8lz1fy.isDocument(element) ? dom.defaultView || dom.parentWindow : null;
  };
  var $_d04mvbmqjh8lz1pi = {
    attached: attached,
    windowOf: windowOf
  };

  var r = function (left, top) {
    var translate = function (x, y) {
      return r(left + x, top + y);
    };
    return {
      left: $_bgyjg9kejh8lz1ax.constant(left),
      top: $_bgyjg9kejh8lz1ax.constant(top),
      translate: translate
    };
  };

  var boxPosition = function (dom) {
    var box = dom.getBoundingClientRect();
    return r(box.left, box.top);
  };
  var firstDefinedOrZero = function (a, b) {
    return a !== undefined ? a : b !== undefined ? b : 0;
  };
  var absolute = function (element) {
    var doc = element.dom().ownerDocument;
    var body = doc.body;
    var win = $_d04mvbmqjh8lz1pi.windowOf($_6vo9a4krjh8lz1do.fromDom(doc));
    var html = doc.documentElement;
    var scrollTop = firstDefinedOrZero(win.pageYOffset, html.scrollTop);
    var scrollLeft = firstDefinedOrZero(win.pageXOffset, html.scrollLeft);
    var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
    var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
    return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  };
  var relative = function (element) {
    var dom = element.dom();
    return r(dom.offsetLeft, dom.offsetTop);
  };
  var viewport = function (element) {
    var dom = element.dom();
    var doc = dom.ownerDocument;
    var body = doc.body;
    var html = $_6vo9a4krjh8lz1do.fromDom(doc.documentElement);
    if (body === dom)
      return r(body.offsetLeft, body.offsetTop);
    if (!$_d04mvbmqjh8lz1pi.attached(element, html))
      return r(0, 0);
    return boxPosition(dom);
  };
  var $_6xc5idmpjh8lz1ph = {
    absolute: absolute,
    relative: relative,
    viewport: viewport
  };

  var rowInfo = $_d2ojjnkijh8lz1bv.immutable('row', 'y');
  var colInfo = $_d2ojjnkijh8lz1bv.immutable('col', 'x');
  var rtlEdge = function (cell) {
    var pos = $_6xc5idmpjh8lz1ph.absolute(cell);
    return pos.left() + $_fu3j58mljh8lz1oz.getOuter(cell);
  };
  var ltrEdge = function (cell) {
    return $_6xc5idmpjh8lz1ph.absolute(cell).left();
  };
  var getLeftEdge = function (index, cell) {
    return colInfo(index, ltrEdge(cell));
  };
  var getRightEdge = function (index, cell) {
    return colInfo(index, rtlEdge(cell));
  };
  var getTop = function (cell) {
    return $_6xc5idmpjh8lz1ph.absolute(cell).top();
  };
  var getTopEdge = function (index, cell) {
    return rowInfo(index, getTop(cell));
  };
  var getBottomEdge = function (index, cell) {
    return rowInfo(index, getTop(cell) + $_dc45zsmjjh8lz1or.getOuter(cell));
  };
  var findPositions = function (getInnerEdge, getOuterEdge, array) {
    if (array.length === 0)
      return [];
    var lines = $_6b0spykcjh8lz1ao.map(array.slice(1), function (cellOption, index) {
      return cellOption.map(function (cell) {
        return getInnerEdge(index, cell);
      });
    });
    var lastLine = array[array.length - 1].map(function (cell) {
      return getOuterEdge(array.length - 1, cell);
    });
    return lines.concat([lastLine]);
  };
  var negate = function (step, _table) {
    return -step;
  };
  var height = {
    delta: $_bgyjg9kejh8lz1ax.identity,
    positions: $_bgyjg9kejh8lz1ax.curry(findPositions, getTopEdge, getBottomEdge),
    edge: getTop
  };
  var ltr = {
    delta: $_bgyjg9kejh8lz1ax.identity,
    edge: ltrEdge,
    positions: $_bgyjg9kejh8lz1ax.curry(findPositions, getLeftEdge, getRightEdge)
  };
  var rtl = {
    delta: negate,
    edge: rtlEdge,
    positions: $_bgyjg9kejh8lz1ax.curry(findPositions, getRightEdge, getLeftEdge)
  };
  var $_sdnutmojh8lz1p3 = {
    height: height,
    rtl: rtl,
    ltr: ltr
  };

  var $_7vn0kzmnjh8lz1p2 = {
    ltr: $_sdnutmojh8lz1p3.ltr,
    rtl: $_sdnutmojh8lz1p3.rtl
  };

  function TableDirection (directionAt) {
    var auto = function (table) {
      return directionAt(table).isRtl() ? $_7vn0kzmnjh8lz1p2.rtl : $_7vn0kzmnjh8lz1p2.ltr;
    };
    var delta = function (amount, table) {
      return auto(table).delta(amount, table);
    };
    var positions = function (cols, table) {
      return auto(table).positions(cols, table);
    };
    var edge = function (cell) {
      return auto(cell).edge(cell);
    };
    return {
      delta: delta,
      edge: edge,
      positions: positions
    };
  }

  var getGridSize = function (table) {
    var input = $_ff1h20kmjh8lz1c3.fromTable(table);
    var warehouse = $_fxwupplkjh8lz1go.generate(input);
    return warehouse.grid();
  };
  var $_fpjoz7msjh8lz1pq = { getGridSize: getGridSize };

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var base = function (handleUnsupported, required) {
    return baseWith(handleUnsupported, required, {
      validate: $_d1kyz8kfjh8lz1az.isFunction,
      label: 'function'
    });
  };
  var baseWith = function (handleUnsupported, required, pred) {
    if (required.length === 0)
      throw new Error('You must specify at least one required field.');
    $_9ogtmjkljh8lz1c0.validateStrArr('required', required);
    $_9ogtmjkljh8lz1c0.checkDupes(required);
    return function (obj) {
      var keys = $_8kti2hkhjh8lz1bt.keys(obj);
      var allReqd = $_6b0spykcjh8lz1ao.forall(required, function (req) {
        return $_6b0spykcjh8lz1ao.contains(keys, req);
      });
      if (!allReqd)
        $_9ogtmjkljh8lz1c0.reqMessage(required, keys);
      handleUnsupported(required, keys);
      var invalidKeys = $_6b0spykcjh8lz1ao.filter(required, function (key) {
        return !pred.validate(obj[key], key);
      });
      if (invalidKeys.length > 0)
        $_9ogtmjkljh8lz1c0.invalidTypeMessage(invalidKeys, pred.label);
      return obj;
    };
  };
  var handleExact = function (required, keys) {
    var unsupported = $_6b0spykcjh8lz1ao.filter(keys, function (key) {
      return !$_6b0spykcjh8lz1ao.contains(required, key);
    });
    if (unsupported.length > 0)
      $_9ogtmjkljh8lz1c0.unsuppMessage(unsupported);
  };
  var allowExtra = $_bgyjg9kejh8lz1ax.noop;
  var $_2qijvhmwjh8lz1qv = {
    exactly: $_bgyjg9kejh8lz1ax.curry(base, handleExact),
    ensure: $_bgyjg9kejh8lz1ax.curry(base, allowExtra),
    ensureWith: $_bgyjg9kejh8lz1ax.curry(baseWith, allowExtra)
  };

  var elementToData = function (element) {
    var colspan = $_1mp8lglcjh8lz1fq.has(element, 'colspan') ? parseInt($_1mp8lglcjh8lz1fq.get(element, 'colspan'), 10) : 1;
    var rowspan = $_1mp8lglcjh8lz1fq.has(element, 'rowspan') ? parseInt($_1mp8lglcjh8lz1fq.get(element, 'rowspan'), 10) : 1;
    return {
      element: $_bgyjg9kejh8lz1ax.constant(element),
      colspan: $_bgyjg9kejh8lz1ax.constant(colspan),
      rowspan: $_bgyjg9kejh8lz1ax.constant(rowspan)
    };
  };
  var modification = function (generators, _toData) {
    contract(generators);
    var position = Cell(Option.none());
    var toData = _toData !== undefined ? _toData : elementToData;
    var nu = function (data) {
      return generators.cell(data);
    };
    var nuFrom = function (element) {
      var data = toData(element);
      return nu(data);
    };
    var add = function (element) {
      var replacement = nuFrom(element);
      if (position.get().isNone())
        position.set(Option.some(replacement));
      recent = Option.some({
        item: element,
        replacement: replacement
      });
      return replacement;
    };
    var recent = Option.none();
    var getOrInit = function (element, comparator) {
      return recent.fold(function () {
        return add(element);
      }, function (p) {
        return comparator(element, p.item) ? p.replacement : add(element);
      });
    };
    return {
      getOrInit: getOrInit,
      cursor: position.get
    };
  };
  var transform = function (scope, tag) {
    return function (generators) {
      var position = Cell(Option.none());
      contract(generators);
      var list = [];
      var find = function (element, comparator) {
        return $_6b0spykcjh8lz1ao.find(list, function (x) {
          return comparator(x.item, element);
        });
      };
      var makeNew = function (element) {
        var cell = generators.replace(element, tag, { scope: scope });
        list.push({
          item: element,
          sub: cell
        });
        if (position.get().isNone())
          position.set(Option.some(cell));
        return cell;
      };
      var replaceOrInit = function (element, comparator) {
        return find(element, comparator).fold(function () {
          return makeNew(element);
        }, function (p) {
          return comparator(element, p.item) ? p.sub : makeNew(element);
        });
      };
      return {
        replaceOrInit: replaceOrInit,
        cursor: position.get
      };
    };
  };
  var merging = function (generators) {
    contract(generators);
    var position = Cell(Option.none());
    var combine = function (cell) {
      if (position.get().isNone())
        position.set(Option.some(cell));
      return function () {
        var raw = generators.cell({
          element: $_bgyjg9kejh8lz1ax.constant(cell),
          colspan: $_bgyjg9kejh8lz1ax.constant(1),
          rowspan: $_bgyjg9kejh8lz1ax.constant(1)
        });
        $_3ory84lljh8lz1gx.remove(raw, 'width');
        $_3ory84lljh8lz1gx.remove(cell, 'width');
        return raw;
      };
    };
    return {
      combine: combine,
      cursor: position.get
    };
  };
  var contract = $_2qijvhmwjh8lz1qv.exactly([
    'cell',
    'row',
    'replace',
    'gap'
  ]);
  var $_46iqoomujh8lz1qf = {
    modification: modification,
    transform: transform,
    merging: merging
  };

  var blockList = [
    'body',
    'p',
    'div',
    'article',
    'aside',
    'figcaption',
    'figure',
    'footer',
    'header',
    'nav',
    'section',
    'ol',
    'ul',
    'table',
    'thead',
    'tfoot',
    'tbody',
    'caption',
    'tr',
    'td',
    'th',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'blockquote',
    'pre',
    'address'
  ];
  var isList = function (universe, item) {
    var tagName = universe.property().name(item);
    return $_6b0spykcjh8lz1ao.contains([
      'ol',
      'ul'
    ], tagName);
  };
  var isBlock = function (universe, item) {
    var tagName = universe.property().name(item);
    return $_6b0spykcjh8lz1ao.contains(blockList, tagName);
  };
  var isFormatting = function (universe, item) {
    var tagName = universe.property().name(item);
    return $_6b0spykcjh8lz1ao.contains([
      'address',
      'pre',
      'p',
      'h1',
      'h2',
      'h3',
      'h4',
      'h5',
      'h6'
    ], tagName);
  };
  var isHeading = function (universe, item) {
    var tagName = universe.property().name(item);
    return $_6b0spykcjh8lz1ao.contains([
      'h1',
      'h2',
      'h3',
      'h4',
      'h5',
      'h6'
    ], tagName);
  };
  var isContainer = function (universe, item) {
    return $_6b0spykcjh8lz1ao.contains([
      'div',
      'li',
      'td',
      'th',
      'blockquote',
      'body',
      'caption'
    ], universe.property().name(item));
  };
  var isEmptyTag = function (universe, item) {
    return $_6b0spykcjh8lz1ao.contains([
      'br',
      'img',
      'hr',
      'input'
    ], universe.property().name(item));
  };
  var isFrame = function (universe, item) {
    return universe.property().name(item) === 'iframe';
  };
  var isInline = function (universe, item) {
    return !(isBlock(universe, item) || isEmptyTag(universe, item)) && universe.property().name(item) !== 'li';
  };
  var $_77qm98mzjh8lz1ro = {
    isBlock: isBlock,
    isList: isList,
    isFormatting: isFormatting,
    isHeading: isHeading,
    isContainer: isContainer,
    isEmptyTag: isEmptyTag,
    isFrame: isFrame,
    isInline: isInline
  };

  var universe$1 = DomUniverse();
  var isBlock$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isBlock(universe$1, element);
  };
  var isList$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isList(universe$1, element);
  };
  var isFormatting$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isFormatting(universe$1, element);
  };
  var isHeading$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isHeading(universe$1, element);
  };
  var isContainer$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isContainer(universe$1, element);
  };
  var isEmptyTag$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isEmptyTag(universe$1, element);
  };
  var isFrame$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isFrame(universe$1, element);
  };
  var isInline$1 = function (element) {
    return $_77qm98mzjh8lz1ro.isInline(universe$1, element);
  };
  var $_39l7z3myjh8lz1rk = {
    isBlock: isBlock$1,
    isList: isList$1,
    isFormatting: isFormatting$1,
    isHeading: isHeading$1,
    isContainer: isContainer$1,
    isEmptyTag: isEmptyTag$1,
    isFrame: isFrame$1,
    isInline: isInline$1
  };

  var merge = function (cells) {
    var isBr = function (el) {
      return $_a3izpgldjh8lz1fy.name(el) === 'br';
    };
    var advancedBr = function (children) {
      return $_6b0spykcjh8lz1ao.forall(children, function (c) {
        return isBr(c) || $_a3izpgldjh8lz1fy.isText(c) && $_bri5anlujh8lz1in.get(c).trim().length === 0;
      });
    };
    var isListItem = function (el) {
      return $_a3izpgldjh8lz1fy.name(el) === 'li' || $_aykj0glijh8lz1g9.ancestor(el, $_39l7z3myjh8lz1rk.isList).isSome();
    };
    var siblingIsBlock = function (el) {
      return $_4hc7u2ktjh8lz1dv.nextSibling(el).map(function (rightSibling) {
        if ($_39l7z3myjh8lz1rk.isBlock(rightSibling))
          return true;
        if ($_39l7z3myjh8lz1rk.isEmptyTag(rightSibling)) {
          return $_a3izpgldjh8lz1fy.name(rightSibling) === 'img' ? false : true;
        }
      }).getOr(false);
    };
    var markCell = function (cell) {
      return $_fpdn73lsjh8lz1ig.last(cell).bind(function (rightEdge) {
        var rightSiblingIsBlock = siblingIsBlock(rightEdge);
        return $_4hc7u2ktjh8lz1dv.parent(rightEdge).map(function (parent) {
          return rightSiblingIsBlock === true || isListItem(parent) || isBr(rightEdge) || $_39l7z3myjh8lz1rk.isBlock(parent) && !$_2eywnlkvjh8lz1e8.eq(cell, parent) ? [] : [$_6vo9a4krjh8lz1do.fromTag('br')];
        });
      }).getOr([]);
    };
    var markContent = function () {
      var content = $_6b0spykcjh8lz1ao.bind(cells, function (cell) {
        var children = $_4hc7u2ktjh8lz1dv.children(cell);
        return advancedBr(children) ? [] : children.concat(markCell(cell));
      });
      return content.length === 0 ? [$_6vo9a4krjh8lz1do.fromTag('br')] : content;
    };
    var contents = markContent();
    $_f2hny0lojh8lz1hi.empty(cells[0]);
    $_d7tq5mlpjh8lz1hl.append(cells[0], contents);
  };
  var $_9305lemxjh8lz1qy = { merge: merge };

  var shallow$1 = function (old, nu) {
    return nu;
  };
  var deep$1 = function (old, nu) {
    var bothObjects = $_d1kyz8kfjh8lz1az.isObject(old) && $_d1kyz8kfjh8lz1az.isObject(nu);
    return bothObjects ? deepMerge(old, nu) : nu;
  };
  var baseMerge = function (merger) {
    return function () {
      var objects = new Array(arguments.length);
      for (var i = 0; i < objects.length; i++)
        objects[i] = arguments[i];
      if (objects.length === 0)
        throw new Error('Can\'t merge zero objects');
      var ret = {};
      for (var j = 0; j < objects.length; j++) {
        var curObject = objects[j];
        for (var key in curObject)
          if (curObject.hasOwnProperty(key)) {
            ret[key] = merger(ret[key], curObject[key]);
          }
      }
      return ret;
    };
  };
  var deepMerge = baseMerge(deep$1);
  var merge$1 = baseMerge(shallow$1);
  var $_b4x7eon1jh8lz1se = {
    deepMerge: deepMerge,
    merge: merge$1
  };

  var cat = function (arr) {
    var r = [];
    var push = function (x) {
      r.push(x);
    };
    for (var i = 0; i < arr.length; i++) {
      arr[i].each(push);
    }
    return r;
  };
  var findMap = function (arr, f) {
    for (var i = 0; i < arr.length; i++) {
      var r = f(arr[i], i);
      if (r.isSome()) {
        return r;
      }
    }
    return Option.none();
  };
  var liftN = function (arr, f) {
    var r = [];
    for (var i = 0; i < arr.length; i++) {
      var x = arr[i];
      if (x.isSome()) {
        r.push(x.getOrDie());
      } else {
        return Option.none();
      }
    }
    return Option.some(f.apply(null, r));
  };
  var $_clgylhn2jh8lz1sg = {
    cat: cat,
    findMap: findMap,
    liftN: liftN
  };

  var addCell = function (gridRow, index, cell) {
    var cells = gridRow.cells();
    var before = cells.slice(0, index);
    var after = cells.slice(index);
    var newCells = before.concat([cell]).concat(after);
    return setCells(gridRow, newCells);
  };
  var mutateCell = function (gridRow, index, cell) {
    var cells = gridRow.cells();
    cells[index] = cell;
  };
  var setCells = function (gridRow, cells) {
    return $_g424vknjh8lz1cd.rowcells(cells, gridRow.section());
  };
  var mapCells = function (gridRow, f) {
    var cells = gridRow.cells();
    var r = $_6b0spykcjh8lz1ao.map(cells, f);
    return $_g424vknjh8lz1cd.rowcells(r, gridRow.section());
  };
  var getCell = function (gridRow, index) {
    return gridRow.cells()[index];
  };
  var getCellElement = function (gridRow, index) {
    return getCell(gridRow, index).element();
  };
  var cellLength = function (gridRow) {
    return gridRow.cells().length;
  };
  var $_cndk32n5jh8lz1ss = {
    addCell: addCell,
    setCells: setCells,
    mutateCell: mutateCell,
    getCell: getCell,
    getCellElement: getCellElement,
    mapCells: mapCells,
    cellLength: cellLength
  };

  var getColumn = function (grid, index) {
    return $_6b0spykcjh8lz1ao.map(grid, function (row) {
      return $_cndk32n5jh8lz1ss.getCell(row, index);
    });
  };
  var getRow = function (grid, index) {
    return grid[index];
  };
  var findDiff = function (xs, comp) {
    if (xs.length === 0)
      return 0;
    var first = xs[0];
    var index = $_6b0spykcjh8lz1ao.findIndex(xs, function (x) {
      return !comp(first.element(), x.element());
    });
    return index.fold(function () {
      return xs.length;
    }, function (ind) {
      return ind;
    });
  };
  var subgrid = function (grid, row, column, comparator) {
    var restOfRow = getRow(grid, row).cells().slice(column);
    var endColIndex = findDiff(restOfRow, comparator);
    var restOfColumn = getColumn(grid, column).slice(row);
    var endRowIndex = findDiff(restOfColumn, comparator);
    return {
      colspan: $_bgyjg9kejh8lz1ax.constant(endColIndex),
      rowspan: $_bgyjg9kejh8lz1ax.constant(endRowIndex)
    };
  };
  var $_6s0r2pn4jh8lz1sn = { subgrid: subgrid };

  var toDetails = function (grid, comparator) {
    var seen = $_6b0spykcjh8lz1ao.map(grid, function (row, ri) {
      return $_6b0spykcjh8lz1ao.map(row.cells(), function (col, ci) {
        return false;
      });
    });
    var updateSeen = function (ri, ci, rowspan, colspan) {
      for (var r = ri; r < ri + rowspan; r++) {
        for (var c = ci; c < ci + colspan; c++) {
          seen[r][c] = true;
        }
      }
    };
    return $_6b0spykcjh8lz1ao.map(grid, function (row, ri) {
      var details = $_6b0spykcjh8lz1ao.bind(row.cells(), function (cell, ci) {
        if (seen[ri][ci] === false) {
          var result = $_6s0r2pn4jh8lz1sn.subgrid(grid, ri, ci, comparator);
          updateSeen(ri, ci, result.rowspan(), result.colspan());
          return [$_g424vknjh8lz1cd.detailnew(cell.element(), result.rowspan(), result.colspan(), cell.isNew())];
        } else {
          return [];
        }
      });
      return $_g424vknjh8lz1cd.rowdetails(details, row.section());
    });
  };
  var toGrid = function (warehouse, generators, isNew) {
    var grid = [];
    for (var i = 0; i < warehouse.grid().rows(); i++) {
      var rowCells = [];
      for (var j = 0; j < warehouse.grid().columns(); j++) {
        var element = $_fxwupplkjh8lz1go.getAt(warehouse, i, j).map(function (item) {
          return $_g424vknjh8lz1cd.elementnew(item.element(), isNew);
        }).getOrThunk(function () {
          return $_g424vknjh8lz1cd.elementnew(generators.gap(), true);
        });
        rowCells.push(element);
      }
      var row = $_g424vknjh8lz1cd.rowcells(rowCells, warehouse.all()[i].section());
      grid.push(row);
    }
    return grid;
  };
  var $_7a3bzon3jh8lz1si = {
    toDetails: toDetails,
    toGrid: toGrid
  };

  var setIfNot = function (element, property, value, ignore) {
    if (value === ignore)
      $_1mp8lglcjh8lz1fq.remove(element, property);
    else
      $_1mp8lglcjh8lz1fq.set(element, property, value);
  };
  var render = function (table, grid) {
    var newRows = [];
    var newCells = [];
    var renderSection = function (gridSection, sectionName) {
      var section = $_fiygddlhjh8lz1g7.child(table, sectionName).getOrThunk(function () {
        var tb = $_6vo9a4krjh8lz1do.fromTag(sectionName, $_4hc7u2ktjh8lz1dv.owner(table).dom());
        $_6qqu1alnjh8lz1hg.append(table, tb);
        return tb;
      });
      $_f2hny0lojh8lz1hi.empty(section);
      var rows = $_6b0spykcjh8lz1ao.map(gridSection, function (row) {
        if (row.isNew()) {
          newRows.push(row.element());
        }
        var tr = row.element();
        $_f2hny0lojh8lz1hi.empty(tr);
        $_6b0spykcjh8lz1ao.each(row.cells(), function (cell) {
          if (cell.isNew()) {
            newCells.push(cell.element());
          }
          setIfNot(cell.element(), 'colspan', cell.colspan(), 1);
          setIfNot(cell.element(), 'rowspan', cell.rowspan(), 1);
          $_6qqu1alnjh8lz1hg.append(tr, cell.element());
        });
        return tr;
      });
      $_d7tq5mlpjh8lz1hl.append(section, rows);
    };
    var removeSection = function (sectionName) {
      $_fiygddlhjh8lz1g7.child(table, sectionName).bind($_f2hny0lojh8lz1hi.remove);
    };
    var renderOrRemoveSection = function (gridSection, sectionName) {
      if (gridSection.length > 0) {
        renderSection(gridSection, sectionName);
      } else {
        removeSection(sectionName);
      }
    };
    var headSection = [];
    var bodySection = [];
    var footSection = [];
    $_6b0spykcjh8lz1ao.each(grid, function (row) {
      switch (row.section()) {
      case 'thead':
        headSection.push(row);
        break;
      case 'tbody':
        bodySection.push(row);
        break;
      case 'tfoot':
        footSection.push(row);
        break;
      }
    });
    renderOrRemoveSection(headSection, 'thead');
    renderOrRemoveSection(bodySection, 'tbody');
    renderOrRemoveSection(footSection, 'tfoot');
    return {
      newRows: $_bgyjg9kejh8lz1ax.constant(newRows),
      newCells: $_bgyjg9kejh8lz1ax.constant(newCells)
    };
  };
  var copy$2 = function (grid) {
    var rows = $_6b0spykcjh8lz1ao.map(grid, function (row) {
      var tr = $_zeqq4lrjh8lz1id.shallow(row.element());
      $_6b0spykcjh8lz1ao.each(row.cells(), function (cell) {
        var clonedCell = $_zeqq4lrjh8lz1id.deep(cell.element());
        setIfNot(clonedCell, 'colspan', cell.colspan(), 1);
        setIfNot(clonedCell, 'rowspan', cell.rowspan(), 1);
        $_6qqu1alnjh8lz1hg.append(tr, clonedCell);
      });
      return tr;
    });
    return rows;
  };
  var $_2lx51jn6jh8lz1sw = {
    render: render,
    copy: copy$2
  };

  var repeat = function (repititions, f) {
    var r = [];
    for (var i = 0; i < repititions; i++) {
      r.push(f(i));
    }
    return r;
  };
  var range$1 = function (start, end) {
    var r = [];
    for (var i = start; i < end; i++) {
      r.push(i);
    }
    return r;
  };
  var unique = function (xs, comparator) {
    var result = [];
    $_6b0spykcjh8lz1ao.each(xs, function (x, i) {
      if (i < xs.length - 1 && !comparator(x, xs[i + 1])) {
        result.push(x);
      } else if (i === xs.length - 1) {
        result.push(x);
      }
    });
    return result;
  };
  var deduce = function (xs, index) {
    if (index < 0 || index >= xs.length - 1)
      return Option.none();
    var current = xs[index].fold(function () {
      var rest = $_6b0spykcjh8lz1ao.reverse(xs.slice(0, index));
      return $_clgylhn2jh8lz1sg.findMap(rest, function (a, i) {
        return a.map(function (aa) {
          return {
            value: aa,
            delta: i + 1
          };
        });
      });
    }, function (c) {
      return Option.some({
        value: c,
        delta: 0
      });
    });
    var next = xs[index + 1].fold(function () {
      var rest = xs.slice(index + 1);
      return $_clgylhn2jh8lz1sg.findMap(rest, function (a, i) {
        return a.map(function (aa) {
          return {
            value: aa,
            delta: i + 1
          };
        });
      });
    }, function (n) {
      return Option.some({
        value: n,
        delta: 1
      });
    });
    return current.bind(function (c) {
      return next.map(function (n) {
        var extras = n.delta + c.delta;
        return Math.abs(n.value - c.value) / extras;
      });
    });
  };
  var $_3fj5mdn9jh8lz1uf = {
    repeat: repeat,
    range: range$1,
    unique: unique,
    deduce: deduce
  };

  var columns = function (warehouse) {
    var grid = warehouse.grid();
    var cols = $_3fj5mdn9jh8lz1uf.range(0, grid.columns());
    var rows = $_3fj5mdn9jh8lz1uf.range(0, grid.rows());
    return $_6b0spykcjh8lz1ao.map(cols, function (col) {
      var getBlock = function () {
        return $_6b0spykcjh8lz1ao.bind(rows, function (r) {
          return $_fxwupplkjh8lz1go.getAt(warehouse, r, col).filter(function (detail) {
            return detail.column() === col;
          }).fold($_bgyjg9kejh8lz1ax.constant([]), function (detail) {
            return [detail];
          });
        });
      };
      var isSingle = function (detail) {
        return detail.colspan() === 1;
      };
      var getFallback = function () {
        return $_fxwupplkjh8lz1go.getAt(warehouse, 0, col);
      };
      return decide(getBlock, isSingle, getFallback);
    });
  };
  var decide = function (getBlock, isSingle, getFallback) {
    var inBlock = getBlock();
    var singleInBlock = $_6b0spykcjh8lz1ao.find(inBlock, isSingle);
    var detailOption = singleInBlock.orThunk(function () {
      return Option.from(inBlock[0]).orThunk(getFallback);
    });
    return detailOption.map(function (detail) {
      return detail.element();
    });
  };
  var rows$1 = function (warehouse) {
    var grid = warehouse.grid();
    var rows = $_3fj5mdn9jh8lz1uf.range(0, grid.rows());
    var cols = $_3fj5mdn9jh8lz1uf.range(0, grid.columns());
    return $_6b0spykcjh8lz1ao.map(rows, function (row) {
      var getBlock = function () {
        return $_6b0spykcjh8lz1ao.bind(cols, function (c) {
          return $_fxwupplkjh8lz1go.getAt(warehouse, row, c).filter(function (detail) {
            return detail.row() === row;
          }).fold($_bgyjg9kejh8lz1ax.constant([]), function (detail) {
            return [detail];
          });
        });
      };
      var isSingle = function (detail) {
        return detail.rowspan() === 1;
      };
      var getFallback = function () {
        return $_fxwupplkjh8lz1go.getAt(warehouse, row, 0);
      };
      return decide(getBlock, isSingle, getFallback);
    });
  };
  var $_fdxhann8jh8lz1u7 = {
    columns: columns,
    rows: rows$1
  };

  var col = function (column, x, y, w, h) {
    var blocker = $_6vo9a4krjh8lz1do.fromTag('div');
    $_3ory84lljh8lz1gx.setAll(blocker, {
      position: 'absolute',
      left: x - w / 2 + 'px',
      top: y + 'px',
      height: h + 'px',
      width: w + 'px'
    });
    $_1mp8lglcjh8lz1fq.setAll(blocker, {
      'data-column': column,
      'role': 'presentation'
    });
    return blocker;
  };
  var row$1 = function (row, x, y, w, h) {
    var blocker = $_6vo9a4krjh8lz1do.fromTag('div');
    $_3ory84lljh8lz1gx.setAll(blocker, {
      position: 'absolute',
      left: x + 'px',
      top: y - h / 2 + 'px',
      height: h + 'px',
      width: w + 'px'
    });
    $_1mp8lglcjh8lz1fq.setAll(blocker, {
      'data-row': row,
      'role': 'presentation'
    });
    return blocker;
  };
  var $_eplkaenajh8lz1un = {
    col: col,
    row: row$1
  };

  var css = function (namespace) {
    var dashNamespace = namespace.replace(/\./g, '-');
    var resolve = function (str) {
      return dashNamespace + '-' + str;
    };
    return { resolve: resolve };
  };
  var $_2i90e7ncjh8lz1ux = { css: css };

  var styles = $_2i90e7ncjh8lz1ux.css('ephox-snooker');
  var $_ezk1iinbjh8lz1uu = { resolve: styles.resolve };

  function Toggler (turnOff, turnOn, initial) {
    var active = initial || false;
    var on = function () {
      turnOn();
      active = true;
    };
    var off = function () {
      turnOff();
      active = false;
    };
    var toggle = function () {
      var f = active ? off : on;
      f();
    };
    var isOn = function () {
      return active;
    };
    return {
      on: on,
      off: off,
      toggle: toggle,
      isOn: isOn
    };
  }

  var read = function (element, attr) {
    var value = $_1mp8lglcjh8lz1fq.get(element, attr);
    return value === undefined || value === '' ? [] : value.split(' ');
  };
  var add = function (element, attr, id) {
    var old = read(element, attr);
    var nu = old.concat([id]);
    $_1mp8lglcjh8lz1fq.set(element, attr, nu.join(' '));
  };
  var remove$3 = function (element, attr, id) {
    var nu = $_6b0spykcjh8lz1ao.filter(read(element, attr), function (v) {
      return v !== id;
    });
    if (nu.length > 0)
      $_1mp8lglcjh8lz1fq.set(element, attr, nu.join(' '));
    else
      $_1mp8lglcjh8lz1fq.remove(element, attr);
  };
  var $_92tat7ngjh8lz1v8 = {
    read: read,
    add: add,
    remove: remove$3
  };

  var supports = function (element) {
    return element.dom().classList !== undefined;
  };
  var get$6 = function (element) {
    return $_92tat7ngjh8lz1v8.read(element, 'class');
  };
  var add$1 = function (element, clazz) {
    return $_92tat7ngjh8lz1v8.add(element, 'class', clazz);
  };
  var remove$4 = function (element, clazz) {
    return $_92tat7ngjh8lz1v8.remove(element, 'class', clazz);
  };
  var toggle = function (element, clazz) {
    if ($_6b0spykcjh8lz1ao.contains(get$6(element), clazz)) {
      remove$4(element, clazz);
    } else {
      add$1(element, clazz);
    }
  };
  var $_7oeslpnfjh8lz1v2 = {
    get: get$6,
    add: add$1,
    remove: remove$4,
    toggle: toggle,
    supports: supports
  };

  var add$2 = function (element, clazz) {
    if ($_7oeslpnfjh8lz1v2.supports(element))
      element.dom().classList.add(clazz);
    else
      $_7oeslpnfjh8lz1v2.add(element, clazz);
  };
  var cleanClass = function (element) {
    var classList = $_7oeslpnfjh8lz1v2.supports(element) ? element.dom().classList : $_7oeslpnfjh8lz1v2.get(element);
    if (classList.length === 0) {
      $_1mp8lglcjh8lz1fq.remove(element, 'class');
    }
  };
  var remove$5 = function (element, clazz) {
    if ($_7oeslpnfjh8lz1v2.supports(element)) {
      var classList = element.dom().classList;
      classList.remove(clazz);
    } else
      $_7oeslpnfjh8lz1v2.remove(element, clazz);
    cleanClass(element);
  };
  var toggle$1 = function (element, clazz) {
    return $_7oeslpnfjh8lz1v2.supports(element) ? element.dom().classList.toggle(clazz) : $_7oeslpnfjh8lz1v2.toggle(element, clazz);
  };
  var toggler = function (element, clazz) {
    var hasClasslist = $_7oeslpnfjh8lz1v2.supports(element);
    var classList = element.dom().classList;
    var off = function () {
      if (hasClasslist)
        classList.remove(clazz);
      else
        $_7oeslpnfjh8lz1v2.remove(element, clazz);
    };
    var on = function () {
      if (hasClasslist)
        classList.add(clazz);
      else
        $_7oeslpnfjh8lz1v2.add(element, clazz);
    };
    return Toggler(off, on, has$1(element, clazz));
  };
  var has$1 = function (element, clazz) {
    return $_7oeslpnfjh8lz1v2.supports(element) && element.dom().classList.contains(clazz);
  };
  var $_evf7iendjh8lz1uz = {
    add: add$2,
    remove: remove$5,
    toggle: toggle$1,
    toggler: toggler,
    has: has$1
  };

  var resizeBar = $_ezk1iinbjh8lz1uu.resolve('resizer-bar');
  var resizeRowBar = $_ezk1iinbjh8lz1uu.resolve('resizer-rows');
  var resizeColBar = $_ezk1iinbjh8lz1uu.resolve('resizer-cols');
  var BAR_THICKNESS = 7;
  var clear = function (wire) {
    var previous = $_coxlualejh8lz1fz.descendants(wire.parent(), '.' + resizeBar);
    $_6b0spykcjh8lz1ao.each(previous, $_f2hny0lojh8lz1hi.remove);
  };
  var drawBar = function (wire, positions, create) {
    var origin = wire.origin();
    $_6b0spykcjh8lz1ao.each(positions, function (cpOption, i) {
      cpOption.each(function (cp) {
        var bar = create(origin, cp);
        $_evf7iendjh8lz1uz.add(bar, resizeBar);
        $_6qqu1alnjh8lz1hg.append(wire.parent(), bar);
      });
    });
  };
  var refreshCol = function (wire, colPositions, position, tableHeight) {
    drawBar(wire, colPositions, function (origin, cp) {
      var colBar = $_eplkaenajh8lz1un.col(cp.col(), cp.x() - origin.left(), position.top() - origin.top(), BAR_THICKNESS, tableHeight);
      $_evf7iendjh8lz1uz.add(colBar, resizeColBar);
      return colBar;
    });
  };
  var refreshRow = function (wire, rowPositions, position, tableWidth) {
    drawBar(wire, rowPositions, function (origin, cp) {
      var rowBar = $_eplkaenajh8lz1un.row(cp.row(), position.left() - origin.left(), cp.y() - origin.top(), tableWidth, BAR_THICKNESS);
      $_evf7iendjh8lz1uz.add(rowBar, resizeRowBar);
      return rowBar;
    });
  };
  var refreshGrid = function (wire, table, rows, cols, hdirection, vdirection) {
    var position = $_6xc5idmpjh8lz1ph.absolute(table);
    var rowPositions = rows.length > 0 ? hdirection.positions(rows, table) : [];
    refreshRow(wire, rowPositions, position, $_fu3j58mljh8lz1oz.getOuter(table));
    var colPositions = cols.length > 0 ? vdirection.positions(cols, table) : [];
    refreshCol(wire, colPositions, position, $_dc45zsmjjh8lz1or.getOuter(table));
  };
  var refresh = function (wire, table, hdirection, vdirection) {
    clear(wire);
    var list = $_ff1h20kmjh8lz1c3.fromTable(table);
    var warehouse = $_fxwupplkjh8lz1go.generate(list);
    var rows = $_fdxhann8jh8lz1u7.rows(warehouse);
    var cols = $_fdxhann8jh8lz1u7.columns(warehouse);
    refreshGrid(wire, table, rows, cols, hdirection, vdirection);
  };
  var each$2 = function (wire, f) {
    var bars = $_coxlualejh8lz1fz.descendants(wire.parent(), '.' + resizeBar);
    $_6b0spykcjh8lz1ao.each(bars, f);
  };
  var hide = function (wire) {
    each$2(wire, function (bar) {
      $_3ory84lljh8lz1gx.set(bar, 'display', 'none');
    });
  };
  var show = function (wire) {
    each$2(wire, function (bar) {
      $_3ory84lljh8lz1gx.set(bar, 'display', 'block');
    });
  };
  var isRowBar = function (element) {
    return $_evf7iendjh8lz1uz.has(element, resizeRowBar);
  };
  var isColBar = function (element) {
    return $_evf7iendjh8lz1uz.has(element, resizeColBar);
  };
  var $_b9z1gin7jh8lz1tj = {
    refresh: refresh,
    hide: hide,
    show: show,
    destroy: clear,
    isRowBar: isRowBar,
    isColBar: isColBar
  };

  var fromWarehouse = function (warehouse, generators) {
    return $_7a3bzon3jh8lz1si.toGrid(warehouse, generators, false);
  };
  var deriveRows = function (rendered, generators) {
    var findRow = function (details) {
      var rowOfCells = $_clgylhn2jh8lz1sg.findMap(details, function (detail) {
        return $_4hc7u2ktjh8lz1dv.parent(detail.element()).map(function (row) {
          var isNew = $_4hc7u2ktjh8lz1dv.parent(row).isNone();
          return $_g424vknjh8lz1cd.elementnew(row, isNew);
        });
      });
      return rowOfCells.getOrThunk(function () {
        return $_g424vknjh8lz1cd.elementnew(generators.row(), true);
      });
    };
    return $_6b0spykcjh8lz1ao.map(rendered, function (details) {
      var row = findRow(details.details());
      return $_g424vknjh8lz1cd.rowdatanew(row.element(), details.details(), details.section(), row.isNew());
    });
  };
  var toDetailList = function (grid, generators) {
    var rendered = $_7a3bzon3jh8lz1si.toDetails(grid, $_2eywnlkvjh8lz1e8.eq);
    return deriveRows(rendered, generators);
  };
  var findInWarehouse = function (warehouse, element) {
    var all = $_6b0spykcjh8lz1ao.flatten($_6b0spykcjh8lz1ao.map(warehouse.all(), function (r) {
      return r.cells();
    }));
    return $_6b0spykcjh8lz1ao.find(all, function (e) {
      return $_2eywnlkvjh8lz1e8.eq(element, e.element());
    });
  };
  var run = function (operation, extract, adjustment, postAction, genWrappers) {
    return function (wire, table, target, generators, direction) {
      var input = $_ff1h20kmjh8lz1c3.fromTable(table);
      var warehouse = $_fxwupplkjh8lz1go.generate(input);
      var output = extract(warehouse, target).map(function (info) {
        var model = fromWarehouse(warehouse, generators);
        var result = operation(model, info, $_2eywnlkvjh8lz1e8.eq, genWrappers(generators));
        var grid = toDetailList(result.grid(), generators);
        return {
          grid: $_bgyjg9kejh8lz1ax.constant(grid),
          cursor: result.cursor
        };
      });
      return output.fold(function () {
        return Option.none();
      }, function (out) {
        var newElements = $_2lx51jn6jh8lz1sw.render(table, out.grid());
        adjustment(table, out.grid(), direction);
        postAction(table);
        $_b9z1gin7jh8lz1tj.refresh(wire, table, $_sdnutmojh8lz1p3.height, direction);
        return Option.some({
          cursor: out.cursor,
          newRows: newElements.newRows,
          newCells: newElements.newCells
        });
      });
    };
  };
  var onCell = function (warehouse, target) {
    return $_ee8pmfkojh8lz1ch.cell(target.element()).bind(function (cell) {
      return findInWarehouse(warehouse, cell);
    });
  };
  var onPaste = function (warehouse, target) {
    return $_ee8pmfkojh8lz1ch.cell(target.element()).bind(function (cell) {
      return findInWarehouse(warehouse, cell).map(function (details) {
        return $_b4x7eon1jh8lz1se.merge(details, {
          generators: target.generators,
          clipboard: target.clipboard
        });
      });
    });
  };
  var onPasteRows = function (warehouse, target) {
    var details = $_6b0spykcjh8lz1ao.map(target.selection(), function (cell) {
      return $_ee8pmfkojh8lz1ch.cell(cell).bind(function (lc) {
        return findInWarehouse(warehouse, lc);
      });
    });
    var cells = $_clgylhn2jh8lz1sg.cat(details);
    return cells.length > 0 ? Option.some($_b4x7eon1jh8lz1se.merge({ cells: cells }, {
      generators: target.generators,
      clipboard: target.clipboard
    })) : Option.none();
  };
  var onMergable = function (warehouse, target) {
    return target.mergable();
  };
  var onUnmergable = function (warehouse, target) {
    return target.unmergable();
  };
  var onCells = function (warehouse, target) {
    var details = $_6b0spykcjh8lz1ao.map(target.selection(), function (cell) {
      return $_ee8pmfkojh8lz1ch.cell(cell).bind(function (lc) {
        return findInWarehouse(warehouse, lc);
      });
    });
    var cells = $_clgylhn2jh8lz1sg.cat(details);
    return cells.length > 0 ? Option.some(cells) : Option.none();
  };
  var $_1na6n8n0jh8lz1rt = {
    run: run,
    toDetailList: toDetailList,
    onCell: onCell,
    onCells: onCells,
    onPaste: onPaste,
    onPasteRows: onPasteRows,
    onMergable: onMergable,
    onUnmergable: onUnmergable
  };

  var value$1 = function (o) {
    var is = function (v) {
      return o === v;
    };
    var or = function (opt) {
      return value$1(o);
    };
    var orThunk = function (f) {
      return value$1(o);
    };
    var map = function (f) {
      return value$1(f(o));
    };
    var each = function (f) {
      f(o);
    };
    var bind = function (f) {
      return f(o);
    };
    var fold = function (_, onValue) {
      return onValue(o);
    };
    var exists = function (f) {
      return f(o);
    };
    var forall = function (f) {
      return f(o);
    };
    var toOption = function () {
      return Option.some(o);
    };
    return {
      is: is,
      isValue: $_bgyjg9kejh8lz1ax.always,
      isError: $_bgyjg9kejh8lz1ax.never,
      getOr: $_bgyjg9kejh8lz1ax.constant(o),
      getOrThunk: $_bgyjg9kejh8lz1ax.constant(o),
      getOrDie: $_bgyjg9kejh8lz1ax.constant(o),
      or: or,
      orThunk: orThunk,
      fold: fold,
      map: map,
      each: each,
      bind: bind,
      exists: exists,
      forall: forall,
      toOption: toOption
    };
  };
  var error = function (message) {
    var getOrThunk = function (f) {
      return f();
    };
    var getOrDie = function () {
      return $_bgyjg9kejh8lz1ax.die(String(message))();
    };
    var or = function (opt) {
      return opt;
    };
    var orThunk = function (f) {
      return f();
    };
    var map = function (f) {
      return error(message);
    };
    var bind = function (f) {
      return error(message);
    };
    var fold = function (onError, _) {
      return onError(message);
    };
    return {
      is: $_bgyjg9kejh8lz1ax.never,
      isValue: $_bgyjg9kejh8lz1ax.never,
      isError: $_bgyjg9kejh8lz1ax.always,
      getOr: $_bgyjg9kejh8lz1ax.identity,
      getOrThunk: getOrThunk,
      getOrDie: getOrDie,
      or: or,
      orThunk: orThunk,
      fold: fold,
      map: map,
      each: $_bgyjg9kejh8lz1ax.noop,
      bind: bind,
      exists: $_bgyjg9kejh8lz1ax.never,
      forall: $_bgyjg9kejh8lz1ax.always,
      toOption: Option.none
    };
  };
  var Result = {
    value: value$1,
    error: error
  };

  var measure = function (startAddress, gridA, gridB) {
    if (startAddress.row() >= gridA.length || startAddress.column() > $_cndk32n5jh8lz1ss.cellLength(gridA[0]))
      return Result.error('invalid start address out of table bounds, row: ' + startAddress.row() + ', column: ' + startAddress.column());
    var rowRemainder = gridA.slice(startAddress.row());
    var colRemainder = rowRemainder[0].cells().slice(startAddress.column());
    var colRequired = $_cndk32n5jh8lz1ss.cellLength(gridB[0]);
    var rowRequired = gridB.length;
    return Result.value({
      rowDelta: $_bgyjg9kejh8lz1ax.constant(rowRemainder.length - rowRequired),
      colDelta: $_bgyjg9kejh8lz1ax.constant(colRemainder.length - colRequired)
    });
  };
  var measureWidth = function (gridA, gridB) {
    var colLengthA = $_cndk32n5jh8lz1ss.cellLength(gridA[0]);
    var colLengthB = $_cndk32n5jh8lz1ss.cellLength(gridB[0]);
    return {
      rowDelta: $_bgyjg9kejh8lz1ax.constant(0),
      colDelta: $_bgyjg9kejh8lz1ax.constant(colLengthA - colLengthB)
    };
  };
  var fill = function (cells, generator) {
    return $_6b0spykcjh8lz1ao.map(cells, function () {
      return $_g424vknjh8lz1cd.elementnew(generator.cell(), true);
    });
  };
  var rowFill = function (grid, amount, generator) {
    return grid.concat($_3fj5mdn9jh8lz1uf.repeat(amount, function (_row) {
      return $_cndk32n5jh8lz1ss.setCells(grid[grid.length - 1], fill(grid[grid.length - 1].cells(), generator));
    }));
  };
  var colFill = function (grid, amount, generator) {
    return $_6b0spykcjh8lz1ao.map(grid, function (row) {
      return $_cndk32n5jh8lz1ss.setCells(row, row.cells().concat(fill($_3fj5mdn9jh8lz1uf.range(0, amount), generator)));
    });
  };
  var tailor = function (gridA, delta, generator) {
    var fillCols = delta.colDelta() < 0 ? colFill : $_bgyjg9kejh8lz1ax.identity;
    var fillRows = delta.rowDelta() < 0 ? rowFill : $_bgyjg9kejh8lz1ax.identity;
    var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta()), generator);
    var tailoredGrid = fillRows(modifiedCols, Math.abs(delta.rowDelta()), generator);
    return tailoredGrid;
  };
  var $_d3iwlknijh8lz1vi = {
    measure: measure,
    measureWidth: measureWidth,
    tailor: tailor
  };

  var merge$2 = function (grid, bounds, comparator, substitution) {
    if (grid.length === 0)
      return grid;
    for (var i = bounds.startRow(); i <= bounds.finishRow(); i++) {
      for (var j = bounds.startCol(); j <= bounds.finishCol(); j++) {
        $_cndk32n5jh8lz1ss.mutateCell(grid[i], j, $_g424vknjh8lz1cd.elementnew(substitution(), false));
      }
    }
    return grid;
  };
  var unmerge = function (grid, target, comparator, substitution) {
    var first = true;
    for (var i = 0; i < grid.length; i++) {
      for (var j = 0; j < $_cndk32n5jh8lz1ss.cellLength(grid[0]); j++) {
        var current = $_cndk32n5jh8lz1ss.getCellElement(grid[i], j);
        var isToReplace = comparator(current, target);
        if (isToReplace === true && first === false) {
          $_cndk32n5jh8lz1ss.mutateCell(grid[i], j, $_g424vknjh8lz1cd.elementnew(substitution(), true));
        } else if (isToReplace === true) {
          first = false;
        }
      }
    }
    return grid;
  };
  var uniqueCells = function (row, comparator) {
    return $_6b0spykcjh8lz1ao.foldl(row, function (rest, cell) {
      return $_6b0spykcjh8lz1ao.exists(rest, function (currentCell) {
        return comparator(currentCell.element(), cell.element());
      }) ? rest : rest.concat([cell]);
    }, []);
  };
  var splitRows = function (grid, index, comparator, substitution) {
    if (index > 0 && index < grid.length) {
      var rowPrevCells = grid[index - 1].cells();
      var cells = uniqueCells(rowPrevCells, comparator);
      $_6b0spykcjh8lz1ao.each(cells, function (cell) {
        var replacement = Option.none();
        for (var i = index; i < grid.length; i++) {
          for (var j = 0; j < $_cndk32n5jh8lz1ss.cellLength(grid[0]); j++) {
            var current = grid[i].cells()[j];
            var isToReplace = comparator(current.element(), cell.element());
            if (isToReplace) {
              if (replacement.isNone()) {
                replacement = Option.some(substitution());
              }
              replacement.each(function (sub) {
                $_cndk32n5jh8lz1ss.mutateCell(grid[i], j, $_g424vknjh8lz1cd.elementnew(sub, true));
              });
            }
          }
        }
      });
    }
    return grid;
  };
  var $_6f3hexnkjh8lz1w0 = {
    merge: merge$2,
    unmerge: unmerge,
    splitRows: splitRows
  };

  var isSpanning = function (grid, row, col, comparator) {
    var candidate = $_cndk32n5jh8lz1ss.getCell(grid[row], col);
    var matching = $_bgyjg9kejh8lz1ax.curry(comparator, candidate.element());
    var currentRow = grid[row];
    return grid.length > 1 && $_cndk32n5jh8lz1ss.cellLength(currentRow) > 1 && (col > 0 && matching($_cndk32n5jh8lz1ss.getCellElement(currentRow, col - 1)) || col < currentRow.length - 1 && matching($_cndk32n5jh8lz1ss.getCellElement(currentRow, col + 1)) || row > 0 && matching($_cndk32n5jh8lz1ss.getCellElement(grid[row - 1], col)) || row < grid.length - 1 && matching($_cndk32n5jh8lz1ss.getCellElement(grid[row + 1], col)));
  };
  var mergeTables = function (startAddress, gridA, gridB, generator, comparator) {
    var startRow = startAddress.row();
    var startCol = startAddress.column();
    var mergeHeight = gridB.length;
    var mergeWidth = $_cndk32n5jh8lz1ss.cellLength(gridB[0]);
    var endRow = startRow + mergeHeight;
    var endCol = startCol + mergeWidth;
    for (var r = startRow; r < endRow; r++) {
      for (var c = startCol; c < endCol; c++) {
        if (isSpanning(gridA, r, c, comparator)) {
          $_6f3hexnkjh8lz1w0.unmerge(gridA, $_cndk32n5jh8lz1ss.getCellElement(gridA[r], c), comparator, generator.cell);
        }
        var newCell = $_cndk32n5jh8lz1ss.getCellElement(gridB[r - startRow], c - startCol);
        var replacement = generator.replace(newCell);
        $_cndk32n5jh8lz1ss.mutateCell(gridA[r], c, $_g424vknjh8lz1cd.elementnew(replacement, true));
      }
    }
    return gridA;
  };
  var merge$3 = function (startAddress, gridA, gridB, generator, comparator) {
    var result = $_d3iwlknijh8lz1vi.measure(startAddress, gridA, gridB);
    return result.map(function (delta) {
      var fittedGrid = $_d3iwlknijh8lz1vi.tailor(gridA, delta, generator);
      return mergeTables(startAddress, fittedGrid, gridB, generator, comparator);
    });
  };
  var insert = function (index, gridA, gridB, generator, comparator) {
    $_6f3hexnkjh8lz1w0.splitRows(gridA, index, comparator, generator.cell);
    var delta = $_d3iwlknijh8lz1vi.measureWidth(gridB, gridA);
    var fittedNewGrid = $_d3iwlknijh8lz1vi.tailor(gridB, delta, generator);
    var secondDelta = $_d3iwlknijh8lz1vi.measureWidth(gridA, fittedNewGrid);
    var fittedOldGrid = $_d3iwlknijh8lz1vi.tailor(gridA, secondDelta, generator);
    return fittedOldGrid.slice(0, index).concat(fittedNewGrid).concat(fittedOldGrid.slice(index, fittedOldGrid.length));
  };
  var $_bq9moknhjh8lz1vd = {
    merge: merge$3,
    insert: insert
  };

  var insertRowAt = function (grid, index, example, comparator, substitution) {
    var before = grid.slice(0, index);
    var after = grid.slice(index);
    var between = $_cndk32n5jh8lz1ss.mapCells(grid[example], function (ex, c) {
      var withinSpan = index > 0 && index < grid.length && comparator($_cndk32n5jh8lz1ss.getCellElement(grid[index - 1], c), $_cndk32n5jh8lz1ss.getCellElement(grid[index], c));
      var ret = withinSpan ? $_cndk32n5jh8lz1ss.getCell(grid[index], c) : $_g424vknjh8lz1cd.elementnew(substitution(ex.element(), comparator), true);
      return ret;
    });
    return before.concat([between]).concat(after);
  };
  var insertColumnAt = function (grid, index, example, comparator, substitution) {
    return $_6b0spykcjh8lz1ao.map(grid, function (row) {
      var withinSpan = index > 0 && index < $_cndk32n5jh8lz1ss.cellLength(row) && comparator($_cndk32n5jh8lz1ss.getCellElement(row, index - 1), $_cndk32n5jh8lz1ss.getCellElement(row, index));
      var sub = withinSpan ? $_cndk32n5jh8lz1ss.getCell(row, index) : $_g424vknjh8lz1cd.elementnew(substitution($_cndk32n5jh8lz1ss.getCellElement(row, example), comparator), true);
      return $_cndk32n5jh8lz1ss.addCell(row, index, sub);
    });
  };
  var splitCellIntoColumns = function (grid, exampleRow, exampleCol, comparator, substitution) {
    var index = exampleCol + 1;
    return $_6b0spykcjh8lz1ao.map(grid, function (row, i) {
      var isTargetCell = i === exampleRow;
      var sub = isTargetCell ? $_g424vknjh8lz1cd.elementnew(substitution($_cndk32n5jh8lz1ss.getCellElement(row, exampleCol), comparator), true) : $_cndk32n5jh8lz1ss.getCell(row, exampleCol);
      return $_cndk32n5jh8lz1ss.addCell(row, index, sub);
    });
  };
  var splitCellIntoRows = function (grid, exampleRow, exampleCol, comparator, substitution) {
    var index = exampleRow + 1;
    var before = grid.slice(0, index);
    var after = grid.slice(index);
    var between = $_cndk32n5jh8lz1ss.mapCells(grid[exampleRow], function (ex, i) {
      var isTargetCell = i === exampleCol;
      return isTargetCell ? $_g424vknjh8lz1cd.elementnew(substitution(ex.element(), comparator), true) : ex;
    });
    return before.concat([between]).concat(after);
  };
  var deleteColumnsAt = function (grid, start, finish) {
    var rows = $_6b0spykcjh8lz1ao.map(grid, function (row) {
      var cells = row.cells().slice(0, start).concat(row.cells().slice(finish + 1));
      return $_g424vknjh8lz1cd.rowcells(cells, row.section());
    });
    return $_6b0spykcjh8lz1ao.filter(rows, function (row) {
      return row.cells().length > 0;
    });
  };
  var deleteRowsAt = function (grid, start, finish) {
    return grid.slice(0, start).concat(grid.slice(finish + 1));
  };
  var $_gaga3fnljh8lz1w7 = {
    insertRowAt: insertRowAt,
    insertColumnAt: insertColumnAt,
    splitCellIntoColumns: splitCellIntoColumns,
    splitCellIntoRows: splitCellIntoRows,
    deleteRowsAt: deleteRowsAt,
    deleteColumnsAt: deleteColumnsAt
  };

  var replaceIn = function (grid, targets, comparator, substitution) {
    var isTarget = function (cell) {
      return $_6b0spykcjh8lz1ao.exists(targets, function (target) {
        return comparator(cell.element(), target.element());
      });
    };
    return $_6b0spykcjh8lz1ao.map(grid, function (row) {
      return $_cndk32n5jh8lz1ss.mapCells(row, function (cell) {
        return isTarget(cell) ? $_g424vknjh8lz1cd.elementnew(substitution(cell.element(), comparator), true) : cell;
      });
    });
  };
  var notStartRow = function (grid, rowIndex, colIndex, comparator) {
    return $_cndk32n5jh8lz1ss.getCellElement(grid[rowIndex], colIndex) !== undefined && (rowIndex > 0 && comparator($_cndk32n5jh8lz1ss.getCellElement(grid[rowIndex - 1], colIndex), $_cndk32n5jh8lz1ss.getCellElement(grid[rowIndex], colIndex)));
  };
  var notStartColumn = function (row, index, comparator) {
    return index > 0 && comparator($_cndk32n5jh8lz1ss.getCellElement(row, index - 1), $_cndk32n5jh8lz1ss.getCellElement(row, index));
  };
  var replaceColumn = function (grid, index, comparator, substitution) {
    var targets = $_6b0spykcjh8lz1ao.bind(grid, function (row, i) {
      var alreadyAdded = notStartRow(grid, i, index, comparator) || notStartColumn(row, index, comparator);
      return alreadyAdded ? [] : [$_cndk32n5jh8lz1ss.getCell(row, index)];
    });
    return replaceIn(grid, targets, comparator, substitution);
  };
  var replaceRow = function (grid, index, comparator, substitution) {
    var targetRow = grid[index];
    var targets = $_6b0spykcjh8lz1ao.bind(targetRow.cells(), function (item, i) {
      var alreadyAdded = notStartRow(grid, index, i, comparator) || notStartColumn(targetRow, i, comparator);
      return alreadyAdded ? [] : [item];
    });
    return replaceIn(grid, targets, comparator, substitution);
  };
  var $_di6efunmjh8lz1wc = {
    replaceColumn: replaceColumn,
    replaceRow: replaceRow
  };

  var none$1 = function () {
    return folder(function (n, o, l, m, r) {
      return n();
    });
  };
  var only = function (index) {
    return folder(function (n, o, l, m, r) {
      return o(index);
    });
  };
  var left = function (index, next) {
    return folder(function (n, o, l, m, r) {
      return l(index, next);
    });
  };
  var middle = function (prev, index, next) {
    return folder(function (n, o, l, m, r) {
      return m(prev, index, next);
    });
  };
  var right = function (prev, index) {
    return folder(function (n, o, l, m, r) {
      return r(prev, index);
    });
  };
  var folder = function (fold) {
    return { fold: fold };
  };
  var $_6yfc1snpjh8lz1wv = {
    none: none$1,
    only: only,
    left: left,
    middle: middle,
    right: right
  };

  var neighbours$1 = function (input, index) {
    if (input.length === 0)
      return $_6yfc1snpjh8lz1wv.none();
    if (input.length === 1)
      return $_6yfc1snpjh8lz1wv.only(0);
    if (index === 0)
      return $_6yfc1snpjh8lz1wv.left(0, 1);
    if (index === input.length - 1)
      return $_6yfc1snpjh8lz1wv.right(index - 1, index);
    if (index > 0 && index < input.length - 1)
      return $_6yfc1snpjh8lz1wv.middle(index - 1, index, index + 1);
    return $_6yfc1snpjh8lz1wv.none();
  };
  var determine = function (input, column, step, tableSize) {
    var result = input.slice(0);
    var context = neighbours$1(input, column);
    var zero = function (array) {
      return $_6b0spykcjh8lz1ao.map(array, $_bgyjg9kejh8lz1ax.constant(0));
    };
    var onNone = $_bgyjg9kejh8lz1ax.constant(zero(result));
    var onOnly = function (index) {
      return tableSize.singleColumnWidth(result[index], step);
    };
    var onChange = function (index, next) {
      if (step >= 0) {
        var newNext = Math.max(tableSize.minCellWidth(), result[next] - step);
        return zero(result.slice(0, index)).concat([
          step,
          newNext - result[next]
        ]).concat(zero(result.slice(next + 1)));
      } else {
        var newThis = Math.max(tableSize.minCellWidth(), result[index] + step);
        var diffx = result[index] - newThis;
        return zero(result.slice(0, index)).concat([
          newThis - result[index],
          diffx
        ]).concat(zero(result.slice(next + 1)));
      }
    };
    var onLeft = onChange;
    var onMiddle = function (prev, index, next) {
      return onChange(index, next);
    };
    var onRight = function (prev, index) {
      if (step >= 0) {
        return zero(result.slice(0, index)).concat([step]);
      } else {
        var size = Math.max(tableSize.minCellWidth(), result[index] + step);
        return zero(result.slice(0, index)).concat([size - result[index]]);
      }
    };
    return context.fold(onNone, onOnly, onLeft, onMiddle, onRight);
  };
  var $_8l7lnenojh8lz1wp = { determine: determine };

  var getSpan$1 = function (cell, type) {
    return $_1mp8lglcjh8lz1fq.has(cell, type) && parseInt($_1mp8lglcjh8lz1fq.get(cell, type), 10) > 1;
  };
  var hasColspan = function (cell) {
    return getSpan$1(cell, 'colspan');
  };
  var hasRowspan = function (cell) {
    return getSpan$1(cell, 'rowspan');
  };
  var getInt = function (element, property) {
    return parseInt($_3ory84lljh8lz1gx.get(element, property), 10);
  };
  var $_agh84xnrjh8lz1x6 = {
    hasColspan: hasColspan,
    hasRowspan: hasRowspan,
    minWidth: $_bgyjg9kejh8lz1ax.constant(10),
    minHeight: $_bgyjg9kejh8lz1ax.constant(10),
    getInt: getInt
  };

  var getRaw$1 = function (cell, property, getter) {
    return $_3ory84lljh8lz1gx.getRaw(cell, property).fold(function () {
      return getter(cell) + 'px';
    }, function (raw) {
      return raw;
    });
  };
  var getRawW = function (cell) {
    return getRaw$1(cell, 'width', $_i2xtsmhjh8lz1nv.getPixelWidth);
  };
  var getRawH = function (cell) {
    return getRaw$1(cell, 'height', $_i2xtsmhjh8lz1nv.getHeight);
  };
  var getWidthFrom = function (warehouse, direction, getWidth, fallback, tableSize) {
    var columns = $_fdxhann8jh8lz1u7.columns(warehouse);
    var backups = $_6b0spykcjh8lz1ao.map(columns, function (cellOption) {
      return cellOption.map(direction.edge);
    });
    return $_6b0spykcjh8lz1ao.map(columns, function (cellOption, c) {
      var columnCell = cellOption.filter($_bgyjg9kejh8lz1ax.not($_agh84xnrjh8lz1x6.hasColspan));
      return columnCell.fold(function () {
        var deduced = $_3fj5mdn9jh8lz1uf.deduce(backups, c);
        return fallback(deduced);
      }, function (cell) {
        return getWidth(cell, tableSize);
      });
    });
  };
  var getDeduced = function (deduced) {
    return deduced.map(function (d) {
      return d + 'px';
    }).getOr('');
  };
  var getRawWidths = function (warehouse, direction) {
    return getWidthFrom(warehouse, direction, getRawW, getDeduced);
  };
  var getPercentageWidths = function (warehouse, direction, tableSize) {
    return getWidthFrom(warehouse, direction, $_i2xtsmhjh8lz1nv.getPercentageWidth, function (deduced) {
      return deduced.fold(function () {
        return tableSize.minCellWidth();
      }, function (cellWidth) {
        return cellWidth / tableSize.pixelWidth() * 100;
      });
    }, tableSize);
  };
  var getPixelWidths = function (warehouse, direction, tableSize) {
    return getWidthFrom(warehouse, direction, $_i2xtsmhjh8lz1nv.getPixelWidth, function (deduced) {
      return deduced.getOrThunk(tableSize.minCellWidth);
    }, tableSize);
  };
  var getHeightFrom = function (warehouse, direction, getHeight, fallback) {
    var rows = $_fdxhann8jh8lz1u7.rows(warehouse);
    var backups = $_6b0spykcjh8lz1ao.map(rows, function (cellOption) {
      return cellOption.map(direction.edge);
    });
    return $_6b0spykcjh8lz1ao.map(rows, function (cellOption, c) {
      var rowCell = cellOption.filter($_bgyjg9kejh8lz1ax.not($_agh84xnrjh8lz1x6.hasRowspan));
      return rowCell.fold(function () {
        var deduced = $_3fj5mdn9jh8lz1uf.deduce(backups, c);
        return fallback(deduced);
      }, function (cell) {
        return getHeight(cell);
      });
    });
  };
  var getPixelHeights = function (warehouse, direction) {
    return getHeightFrom(warehouse, direction, $_i2xtsmhjh8lz1nv.getHeight, function (deduced) {
      return deduced.getOrThunk($_agh84xnrjh8lz1x6.minHeight);
    });
  };
  var getRawHeights = function (warehouse, direction) {
    return getHeightFrom(warehouse, direction, getRawH, getDeduced);
  };
  var $_8h6liinqjh8lz1wx = {
    getRawWidths: getRawWidths,
    getPixelWidths: getPixelWidths,
    getPercentageWidths: getPercentageWidths,
    getPixelHeights: getPixelHeights,
    getRawHeights: getRawHeights
  };

  var total = function (start, end, measures) {
    var r = 0;
    for (var i = start; i < end; i++) {
      r += measures[i] !== undefined ? measures[i] : 0;
    }
    return r;
  };
  var recalculateWidth = function (warehouse, widths) {
    var all = $_fxwupplkjh8lz1go.justCells(warehouse);
    return $_6b0spykcjh8lz1ao.map(all, function (cell) {
      var width = total(cell.column(), cell.column() + cell.colspan(), widths);
      return {
        element: cell.element,
        width: $_bgyjg9kejh8lz1ax.constant(width),
        colspan: cell.colspan
      };
    });
  };
  var recalculateHeight = function (warehouse, heights) {
    var all = $_fxwupplkjh8lz1go.justCells(warehouse);
    return $_6b0spykcjh8lz1ao.map(all, function (cell) {
      var height = total(cell.row(), cell.row() + cell.rowspan(), heights);
      return {
        element: cell.element,
        height: $_bgyjg9kejh8lz1ax.constant(height),
        rowspan: cell.rowspan
      };
    });
  };
  var matchRowHeight = function (warehouse, heights) {
    return $_6b0spykcjh8lz1ao.map(warehouse.all(), function (row, i) {
      return {
        element: row.element,
        height: $_bgyjg9kejh8lz1ax.constant(heights[i])
      };
    });
  };
  var $_df6hx0nsjh8lz1xd = {
    recalculateWidth: recalculateWidth,
    recalculateHeight: recalculateHeight,
    matchRowHeight: matchRowHeight
  };

  var percentageSize = function (width, element) {
    var floatWidth = parseFloat(width);
    var pixelWidth = $_fu3j58mljh8lz1oz.get(element);
    var getCellDelta = function (delta) {
      return delta / pixelWidth * 100;
    };
    var singleColumnWidth = function (width, _delta) {
      return [100 - width];
    };
    var minCellWidth = function () {
      return $_agh84xnrjh8lz1x6.minWidth() / pixelWidth * 100;
    };
    var setTableWidth = function (table, _newWidths, delta) {
      var total = floatWidth + delta;
      $_i2xtsmhjh8lz1nv.setPercentageWidth(table, total);
    };
    return {
      width: $_bgyjg9kejh8lz1ax.constant(floatWidth),
      pixelWidth: $_bgyjg9kejh8lz1ax.constant(pixelWidth),
      getWidths: $_8h6liinqjh8lz1wx.getPercentageWidths,
      getCellDelta: getCellDelta,
      singleColumnWidth: singleColumnWidth,
      minCellWidth: minCellWidth,
      setElementWidth: $_i2xtsmhjh8lz1nv.setPercentageWidth,
      setTableWidth: setTableWidth
    };
  };
  var pixelSize = function (width) {
    var intWidth = parseInt(width, 10);
    var getCellDelta = $_bgyjg9kejh8lz1ax.identity;
    var singleColumnWidth = function (width, delta) {
      var newNext = Math.max($_agh84xnrjh8lz1x6.minWidth(), width + delta);
      return [newNext - width];
    };
    var setTableWidth = function (table, newWidths, _delta) {
      var total = $_6b0spykcjh8lz1ao.foldr(newWidths, function (b, a) {
        return b + a;
      }, 0);
      $_i2xtsmhjh8lz1nv.setPixelWidth(table, total);
    };
    return {
      width: $_bgyjg9kejh8lz1ax.constant(intWidth),
      pixelWidth: $_bgyjg9kejh8lz1ax.constant(intWidth),
      getWidths: $_8h6liinqjh8lz1wx.getPixelWidths,
      getCellDelta: getCellDelta,
      singleColumnWidth: singleColumnWidth,
      minCellWidth: $_agh84xnrjh8lz1x6.minWidth,
      setElementWidth: $_i2xtsmhjh8lz1nv.setPixelWidth,
      setTableWidth: setTableWidth
    };
  };
  var chooseSize = function (element, width) {
    if ($_i2xtsmhjh8lz1nv.percentageBasedSizeRegex().test(width)) {
      var percentMatch = $_i2xtsmhjh8lz1nv.percentageBasedSizeRegex().exec(width);
      return percentageSize(percentMatch[1], element);
    } else if ($_i2xtsmhjh8lz1nv.pixelBasedSizeRegex().test(width)) {
      var pixelMatch = $_i2xtsmhjh8lz1nv.pixelBasedSizeRegex().exec(width);
      return pixelSize(pixelMatch[1]);
    } else {
      var fallbackWidth = $_fu3j58mljh8lz1oz.get(element);
      return pixelSize(fallbackWidth);
    }
  };
  var getTableSize = function (element) {
    var width = $_i2xtsmhjh8lz1nv.getRawWidth(element);
    return width.fold(function () {
      var fallbackWidth = $_fu3j58mljh8lz1oz.get(element);
      return pixelSize(fallbackWidth);
    }, function (width) {
      return chooseSize(element, width);
    });
  };
  var $_b9pgttntjh8lz1xk = { getTableSize: getTableSize };

  var getWarehouse$1 = function (list) {
    return $_fxwupplkjh8lz1go.generate(list);
  };
  var sumUp = function (newSize) {
    return $_6b0spykcjh8lz1ao.foldr(newSize, function (b, a) {
      return b + a;
    }, 0);
  };
  var getTableWarehouse = function (table) {
    var list = $_ff1h20kmjh8lz1c3.fromTable(table);
    return getWarehouse$1(list);
  };
  var adjustWidth = function (table, delta, index, direction) {
    var tableSize = $_b9pgttntjh8lz1xk.getTableSize(table);
    var step = tableSize.getCellDelta(delta);
    var warehouse = getTableWarehouse(table);
    var widths = tableSize.getWidths(warehouse, direction, tableSize);
    var deltas = $_8l7lnenojh8lz1wp.determine(widths, index, step, tableSize);
    var newWidths = $_6b0spykcjh8lz1ao.map(deltas, function (dx, i) {
      return dx + widths[i];
    });
    var newSizes = $_df6hx0nsjh8lz1xd.recalculateWidth(warehouse, newWidths);
    $_6b0spykcjh8lz1ao.each(newSizes, function (cell) {
      tableSize.setElementWidth(cell.element(), cell.width());
    });
    if (index === warehouse.grid().columns() - 1) {
      tableSize.setTableWidth(table, newWidths, step);
    }
  };
  var adjustHeight = function (table, delta, index, direction) {
    var warehouse = getTableWarehouse(table);
    var heights = $_8h6liinqjh8lz1wx.getPixelHeights(warehouse, direction);
    var newHeights = $_6b0spykcjh8lz1ao.map(heights, function (dy, i) {
      return index === i ? Math.max(delta + dy, $_agh84xnrjh8lz1x6.minHeight()) : dy;
    });
    var newCellSizes = $_df6hx0nsjh8lz1xd.recalculateHeight(warehouse, newHeights);
    var newRowSizes = $_df6hx0nsjh8lz1xd.matchRowHeight(warehouse, newHeights);
    $_6b0spykcjh8lz1ao.each(newRowSizes, function (row) {
      $_i2xtsmhjh8lz1nv.setHeight(row.element(), row.height());
    });
    $_6b0spykcjh8lz1ao.each(newCellSizes, function (cell) {
      $_i2xtsmhjh8lz1nv.setHeight(cell.element(), cell.height());
    });
    var total = sumUp(newHeights);
    $_i2xtsmhjh8lz1nv.setHeight(table, total);
  };
  var adjustWidthTo = function (table, list, direction) {
    var tableSize = $_b9pgttntjh8lz1xk.getTableSize(table);
    var warehouse = getWarehouse$1(list);
    var widths = tableSize.getWidths(warehouse, direction, tableSize);
    var newSizes = $_df6hx0nsjh8lz1xd.recalculateWidth(warehouse, widths);
    $_6b0spykcjh8lz1ao.each(newSizes, function (cell) {
      tableSize.setElementWidth(cell.element(), cell.width());
    });
    var total = $_6b0spykcjh8lz1ao.foldr(widths, function (b, a) {
      return a + b;
    }, 0);
    if (newSizes.length > 0) {
      tableSize.setElementWidth(table, total);
    }
  };
  var $_7x5dznnjh8lz1wh = {
    adjustWidth: adjustWidth,
    adjustHeight: adjustHeight,
    adjustWidthTo: adjustWidthTo
  };

  var prune = function (table) {
    var cells = $_ee8pmfkojh8lz1ch.cells(table);
    if (cells.length === 0)
      $_f2hny0lojh8lz1hi.remove(table);
  };
  var outcome = $_d2ojjnkijh8lz1bv.immutable('grid', 'cursor');
  var elementFromGrid = function (grid, row, column) {
    return findIn(grid, row, column).orThunk(function () {
      return findIn(grid, 0, 0);
    });
  };
  var findIn = function (grid, row, column) {
    return Option.from(grid[row]).bind(function (r) {
      return Option.from(r.cells()[column]).bind(function (c) {
        return Option.from(c.element());
      });
    });
  };
  var bundle = function (grid, row, column) {
    return outcome(grid, findIn(grid, row, column));
  };
  var uniqueRows = function (details) {
    return $_6b0spykcjh8lz1ao.foldl(details, function (rest, detail) {
      return $_6b0spykcjh8lz1ao.exists(rest, function (currentDetail) {
        return currentDetail.row() === detail.row();
      }) ? rest : rest.concat([detail]);
    }, []).sort(function (detailA, detailB) {
      return detailA.row() - detailB.row();
    });
  };
  var uniqueColumns = function (details) {
    return $_6b0spykcjh8lz1ao.foldl(details, function (rest, detail) {
      return $_6b0spykcjh8lz1ao.exists(rest, function (currentDetail) {
        return currentDetail.column() === detail.column();
      }) ? rest : rest.concat([detail]);
    }, []).sort(function (detailA, detailB) {
      return detailA.column() - detailB.column();
    });
  };
  var insertRowBefore = function (grid, detail, comparator, genWrappers) {
    var example = detail.row();
    var targetIndex = detail.row();
    var newGrid = $_gaga3fnljh8lz1w7.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
    return bundle(newGrid, targetIndex, detail.column());
  };
  var insertRowsBefore = function (grid, details, comparator, genWrappers) {
    var example = details[0].row();
    var targetIndex = details[0].row();
    var rows = uniqueRows(details);
    var newGrid = $_6b0spykcjh8lz1ao.foldl(rows, function (newGrid, _row) {
      return $_gaga3fnljh8lz1w7.insertRowAt(newGrid, targetIndex, example, comparator, genWrappers.getOrInit);
    }, grid);
    return bundle(newGrid, targetIndex, details[0].column());
  };
  var insertRowAfter = function (grid, detail, comparator, genWrappers) {
    var example = detail.row();
    var targetIndex = detail.row() + detail.rowspan();
    var newGrid = $_gaga3fnljh8lz1w7.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
    return bundle(newGrid, targetIndex, detail.column());
  };
  var insertRowsAfter = function (grid, details, comparator, genWrappers) {
    var rows = uniqueRows(details);
    var example = rows[rows.length - 1].row();
    var targetIndex = rows[rows.length - 1].row() + rows[rows.length - 1].rowspan();
    var newGrid = $_6b0spykcjh8lz1ao.foldl(rows, function (newGrid, _row) {
      return $_gaga3fnljh8lz1w7.insertRowAt(newGrid, targetIndex, example, comparator, genWrappers.getOrInit);
    }, grid);
    return bundle(newGrid, targetIndex, details[0].column());
  };
  var insertColumnBefore = function (grid, detail, comparator, genWrappers) {
    var example = detail.column();
    var targetIndex = detail.column();
    var newGrid = $_gaga3fnljh8lz1w7.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
    return bundle(newGrid, detail.row(), targetIndex);
  };
  var insertColumnsBefore = function (grid, details, comparator, genWrappers) {
    var columns = uniqueColumns(details);
    var example = columns[0].column();
    var targetIndex = columns[0].column();
    var newGrid = $_6b0spykcjh8lz1ao.foldl(columns, function (newGrid, _row) {
      return $_gaga3fnljh8lz1w7.insertColumnAt(newGrid, targetIndex, example, comparator, genWrappers.getOrInit);
    }, grid);
    return bundle(newGrid, details[0].row(), targetIndex);
  };
  var insertColumnAfter = function (grid, detail, comparator, genWrappers) {
    var example = detail.column();
    var targetIndex = detail.column() + detail.colspan();
    var newGrid = $_gaga3fnljh8lz1w7.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
    return bundle(newGrid, detail.row(), targetIndex);
  };
  var insertColumnsAfter = function (grid, details, comparator, genWrappers) {
    var example = details[details.length - 1].column();
    var targetIndex = details[details.length - 1].column() + details[details.length - 1].colspan();
    var columns = uniqueColumns(details);
    var newGrid = $_6b0spykcjh8lz1ao.foldl(columns, function (newGrid, _row) {
      return $_gaga3fnljh8lz1w7.insertColumnAt(newGrid, targetIndex, example, comparator, genWrappers.getOrInit);
    }, grid);
    return bundle(newGrid, details[0].row(), targetIndex);
  };
  var makeRowHeader = function (grid, detail, comparator, genWrappers) {
    var newGrid = $_di6efunmjh8lz1wc.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
    return bundle(newGrid, detail.row(), detail.column());
  };
  var makeColumnHeader = function (grid, detail, comparator, genWrappers) {
    var newGrid = $_di6efunmjh8lz1wc.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
    return bundle(newGrid, detail.row(), detail.column());
  };
  var unmakeRowHeader = function (grid, detail, comparator, genWrappers) {
    var newGrid = $_di6efunmjh8lz1wc.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
    return bundle(newGrid, detail.row(), detail.column());
  };
  var unmakeColumnHeader = function (grid, detail, comparator, genWrappers) {
    var newGrid = $_di6efunmjh8lz1wc.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
    return bundle(newGrid, detail.row(), detail.column());
  };
  var splitCellIntoColumns$1 = function (grid, detail, comparator, genWrappers) {
    var newGrid = $_gaga3fnljh8lz1w7.splitCellIntoColumns(grid, detail.row(), detail.column(), comparator, genWrappers.getOrInit);
    return bundle(newGrid, detail.row(), detail.column());
  };
  var splitCellIntoRows$1 = function (grid, detail, comparator, genWrappers) {
    var newGrid = $_gaga3fnljh8lz1w7.splitCellIntoRows(grid, detail.row(), detail.column(), comparator, genWrappers.getOrInit);
    return bundle(newGrid, detail.row(), detail.column());
  };
  var eraseColumns = function (grid, details, comparator, _genWrappers) {
    var columns = uniqueColumns(details);
    var newGrid = $_gaga3fnljh8lz1w7.deleteColumnsAt(grid, columns[0].column(), columns[columns.length - 1].column());
    var cursor = elementFromGrid(newGrid, details[0].row(), details[0].column());
    return outcome(newGrid, cursor);
  };
  var eraseRows = function (grid, details, comparator, _genWrappers) {
    var rows = uniqueRows(details);
    var newGrid = $_gaga3fnljh8lz1w7.deleteRowsAt(grid, rows[0].row(), rows[rows.length - 1].row());
    var cursor = elementFromGrid(newGrid, details[0].row(), details[0].column());
    return outcome(newGrid, cursor);
  };
  var mergeCells = function (grid, mergable, comparator, _genWrappers) {
    var cells = mergable.cells();
    $_9305lemxjh8lz1qy.merge(cells);
    var newGrid = $_6f3hexnkjh8lz1w0.merge(grid, mergable.bounds(), comparator, $_bgyjg9kejh8lz1ax.constant(cells[0]));
    return outcome(newGrid, Option.from(cells[0]));
  };
  var unmergeCells = function (grid, unmergable, comparator, genWrappers) {
    var newGrid = $_6b0spykcjh8lz1ao.foldr(unmergable, function (b, cell) {
      return $_6f3hexnkjh8lz1w0.unmerge(b, cell, comparator, genWrappers.combine(cell));
    }, grid);
    return outcome(newGrid, Option.from(unmergable[0]));
  };
  var pasteCells = function (grid, pasteDetails, comparator, genWrappers) {
    var gridify = function (table, generators) {
      var list = $_ff1h20kmjh8lz1c3.fromTable(table);
      var wh = $_fxwupplkjh8lz1go.generate(list);
      return $_7a3bzon3jh8lz1si.toGrid(wh, generators, true);
    };
    var gridB = gridify(pasteDetails.clipboard(), pasteDetails.generators());
    var startAddress = $_g424vknjh8lz1cd.address(pasteDetails.row(), pasteDetails.column());
    var mergedGrid = $_bq9moknhjh8lz1vd.merge(startAddress, grid, gridB, pasteDetails.generators(), comparator);
    return mergedGrid.fold(function () {
      return outcome(grid, Option.some(pasteDetails.element()));
    }, function (nuGrid) {
      var cursor = elementFromGrid(nuGrid, pasteDetails.row(), pasteDetails.column());
      return outcome(nuGrid, cursor);
    });
  };
  var gridifyRows = function (rows, generators, example) {
    var pasteDetails = $_ff1h20kmjh8lz1c3.fromPastedRows(rows, example);
    var wh = $_fxwupplkjh8lz1go.generate(pasteDetails);
    return $_7a3bzon3jh8lz1si.toGrid(wh, generators, true);
  };
  var pasteRowsBefore = function (grid, pasteDetails, comparator, genWrappers) {
    var example = grid[pasteDetails.cells[0].row()];
    var index = pasteDetails.cells[0].row();
    var gridB = gridifyRows(pasteDetails.clipboard(), pasteDetails.generators(), example);
    var mergedGrid = $_bq9moknhjh8lz1vd.insert(index, grid, gridB, pasteDetails.generators(), comparator);
    var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row(), pasteDetails.cells[0].column());
    return outcome(mergedGrid, cursor);
  };
  var pasteRowsAfter = function (grid, pasteDetails, comparator, genWrappers) {
    var example = grid[pasteDetails.cells[0].row()];
    var index = pasteDetails.cells[pasteDetails.cells.length - 1].row() + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan();
    var gridB = gridifyRows(pasteDetails.clipboard(), pasteDetails.generators(), example);
    var mergedGrid = $_bq9moknhjh8lz1vd.insert(index, grid, gridB, pasteDetails.generators(), comparator);
    var cursor = elementFromGrid(mergedGrid, pasteDetails.cells[0].row(), pasteDetails.cells[0].column());
    return outcome(mergedGrid, cursor);
  };
  var resize = $_7x5dznnjh8lz1wh.adjustWidthTo;
  var $_68i0x8mtjh8lz1pt = {
    insertRowBefore: $_1na6n8n0jh8lz1rt.run(insertRowBefore, $_1na6n8n0jh8lz1rt.onCell, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    insertRowsBefore: $_1na6n8n0jh8lz1rt.run(insertRowsBefore, $_1na6n8n0jh8lz1rt.onCells, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    insertRowAfter: $_1na6n8n0jh8lz1rt.run(insertRowAfter, $_1na6n8n0jh8lz1rt.onCell, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    insertRowsAfter: $_1na6n8n0jh8lz1rt.run(insertRowsAfter, $_1na6n8n0jh8lz1rt.onCells, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    insertColumnBefore: $_1na6n8n0jh8lz1rt.run(insertColumnBefore, $_1na6n8n0jh8lz1rt.onCell, resize, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    insertColumnsBefore: $_1na6n8n0jh8lz1rt.run(insertColumnsBefore, $_1na6n8n0jh8lz1rt.onCells, resize, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    insertColumnAfter: $_1na6n8n0jh8lz1rt.run(insertColumnAfter, $_1na6n8n0jh8lz1rt.onCell, resize, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    insertColumnsAfter: $_1na6n8n0jh8lz1rt.run(insertColumnsAfter, $_1na6n8n0jh8lz1rt.onCells, resize, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    splitCellIntoColumns: $_1na6n8n0jh8lz1rt.run(splitCellIntoColumns$1, $_1na6n8n0jh8lz1rt.onCell, resize, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    splitCellIntoRows: $_1na6n8n0jh8lz1rt.run(splitCellIntoRows$1, $_1na6n8n0jh8lz1rt.onCell, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    eraseColumns: $_1na6n8n0jh8lz1rt.run(eraseColumns, $_1na6n8n0jh8lz1rt.onCells, resize, prune, $_46iqoomujh8lz1qf.modification),
    eraseRows: $_1na6n8n0jh8lz1rt.run(eraseRows, $_1na6n8n0jh8lz1rt.onCells, $_bgyjg9kejh8lz1ax.noop, prune, $_46iqoomujh8lz1qf.modification),
    makeColumnHeader: $_1na6n8n0jh8lz1rt.run(makeColumnHeader, $_1na6n8n0jh8lz1rt.onCell, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.transform('row', 'th')),
    unmakeColumnHeader: $_1na6n8n0jh8lz1rt.run(unmakeColumnHeader, $_1na6n8n0jh8lz1rt.onCell, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.transform(null, 'td')),
    makeRowHeader: $_1na6n8n0jh8lz1rt.run(makeRowHeader, $_1na6n8n0jh8lz1rt.onCell, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.transform('col', 'th')),
    unmakeRowHeader: $_1na6n8n0jh8lz1rt.run(unmakeRowHeader, $_1na6n8n0jh8lz1rt.onCell, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.transform(null, 'td')),
    mergeCells: $_1na6n8n0jh8lz1rt.run(mergeCells, $_1na6n8n0jh8lz1rt.onMergable, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.merging),
    unmergeCells: $_1na6n8n0jh8lz1rt.run(unmergeCells, $_1na6n8n0jh8lz1rt.onUnmergable, resize, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.merging),
    pasteCells: $_1na6n8n0jh8lz1rt.run(pasteCells, $_1na6n8n0jh8lz1rt.onPaste, resize, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    pasteRowsBefore: $_1na6n8n0jh8lz1rt.run(pasteRowsBefore, $_1na6n8n0jh8lz1rt.onPasteRows, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification),
    pasteRowsAfter: $_1na6n8n0jh8lz1rt.run(pasteRowsAfter, $_1na6n8n0jh8lz1rt.onPasteRows, $_bgyjg9kejh8lz1ax.noop, $_bgyjg9kejh8lz1ax.noop, $_46iqoomujh8lz1qf.modification)
  };

  var getBody$1 = function (editor) {
    return $_6vo9a4krjh8lz1do.fromDom(editor.getBody());
  };
  var getPixelWidth$1 = function (elm) {
    return elm.getBoundingClientRect().width;
  };
  var getPixelHeight = function (elm) {
    return elm.getBoundingClientRect().height;
  };
  var getIsRoot = function (editor) {
    return function (element) {
      return $_2eywnlkvjh8lz1e8.eq(element, getBody$1(editor));
    };
  };
  var removePxSuffix = function (size) {
    return size ? size.replace(/px$/, '') : '';
  };
  var addSizeSuffix = function (size) {
    if (/^[0-9]+$/.test(size)) {
      size += 'px';
    }
    return size;
  };
  var removeDataStyle = function (table) {
    var dataStyleCells = $_coxlualejh8lz1fz.descendants(table, 'td[data-mce-style],th[data-mce-style]');
    $_1mp8lglcjh8lz1fq.remove(table, 'data-mce-style');
    $_6b0spykcjh8lz1ao.each(dataStyleCells, function (cell) {
      $_1mp8lglcjh8lz1fq.remove(cell, 'data-mce-style');
    });
  };

  var onDirection = function (isLtr, isRtl) {
    return function (element) {
      return getDirection(element) === 'rtl' ? isRtl : isLtr;
    };
  };
  var getDirection = function (element) {
    return $_3ory84lljh8lz1gx.get(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  };
  var $_5eddzznwjh8lz1yc = {
    onDirection: onDirection,
    getDirection: getDirection
  };

  var ltr$1 = { isRtl: $_bgyjg9kejh8lz1ax.constant(false) };
  var rtl$1 = { isRtl: $_bgyjg9kejh8lz1ax.constant(true) };
  var directionAt = function (element) {
    var dir = $_5eddzznwjh8lz1yc.getDirection(element);
    return dir === 'rtl' ? rtl$1 : ltr$1;
  };
  var $_fe2yjsnvjh8lz1y8 = { directionAt: directionAt };

  var defaultTableToolbar = [
    'tableprops',
    'tabledelete',
    '|',
    'tableinsertrowbefore',
    'tableinsertrowafter',
    'tabledeleterow',
    '|',
    'tableinsertcolbefore',
    'tableinsertcolafter',
    'tabledeletecol'
  ];
  var defaultStyles = {
    'border-collapse': 'collapse',
    'width': '100%'
  };
  var defaultAttributes = { border: '1' };
  var getDefaultAttributes = function (editor) {
    return editor.getParam('table_default_attributes', defaultAttributes, 'object');
  };
  var getDefaultStyles = function (editor) {
    return editor.getParam('table_default_styles', defaultStyles, 'object');
  };
  var hasTableResizeBars = function (editor) {
    return editor.getParam('table_resize_bars', true, 'boolean');
  };
  var hasTabNavigation = function (editor) {
    return editor.getParam('table_tab_navigation', true, 'boolean');
  };
  var hasAdvancedCellTab = function (editor) {
    return editor.getParam('table_cell_advtab', true, 'boolean');
  };
  var hasAdvancedRowTab = function (editor) {
    return editor.getParam('table_row_advtab', true, 'boolean');
  };
  var hasAdvancedTableTab = function (editor) {
    return editor.getParam('table_advtab', true, 'boolean');
  };
  var hasAppearanceOptions = function (editor) {
    return editor.getParam('table_appearance_options', true, 'boolean');
  };
  var hasTableGrid = function (editor) {
    return editor.getParam('table_grid', true, 'boolean');
  };
  var shouldStyleWithCss = function (editor) {
    return editor.getParam('table_style_by_css', false, 'boolean');
  };
  var getCellClassList = function (editor) {
    return editor.getParam('table_cell_class_list', [], 'array');
  };
  var getRowClassList = function (editor) {
    return editor.getParam('table_row_class_list', [], 'array');
  };
  var getTableClassList = function (editor) {
    return editor.getParam('table_class_list', [], 'array');
  };
  var getColorPickerCallback = function (editor) {
    return editor.getParam('color_picker_callback');
  };
  var isPixelsForced = function (editor) {
    return editor.getParam('table_responsive_width') === false;
  };
  var getCloneElements = function (editor) {
    var cloneElements = editor.getParam('table_clone_elements');
    if ($_d1kyz8kfjh8lz1az.isString(cloneElements)) {
      return Option.some(cloneElements.split(/[ ,]/));
    } else if (Array.isArray(cloneElements)) {
      return Option.some(cloneElements);
    } else {
      return Option.none();
    }
  };
  var hasObjectResizing = function (editor) {
    var objectResizing = editor.getParam('object_resizing', true);
    return objectResizing === 'table' || objectResizing;
  };
  var getToolbar = function (editor) {
    var toolbar = editor.getParam('table_toolbar', defaultTableToolbar);
    if (toolbar === '' || toolbar === false) {
      return [];
    } else if ($_d1kyz8kfjh8lz1az.isString(toolbar)) {
      return toolbar.split(/[ ,]/);
    } else if ($_d1kyz8kfjh8lz1az.isArray(toolbar)) {
      return toolbar;
    } else {
      return [];
    }
  };

  var fireNewRow = function (editor, row) {
    return editor.fire('newrow', { node: row });
  };
  var fireNewCell = function (editor, cell) {
    return editor.fire('newcell', { node: cell });
  };
  var fireObjectResizeStart = function (editor, target, width, height) {
    editor.fire('ObjectResizeStart', {
      target: target,
      width: width,
      height: height
    });
  };
  var fireObjectResized = function (editor, target, width, height) {
    editor.fire('ObjectResized', {
      target: target,
      width: width,
      height: height
    });
  };

  var TableActions = function (editor, lazyWire) {
    var isTableBody = function (editor) {
      return $_a3izpgldjh8lz1fy.name(getBody$1(editor)) === 'table';
    };
    var lastRowGuard = function (table) {
      var size = $_fpjoz7msjh8lz1pq.getGridSize(table);
      return isTableBody(editor) === false || size.rows() > 1;
    };
    var lastColumnGuard = function (table) {
      var size = $_fpjoz7msjh8lz1pq.getGridSize(table);
      return isTableBody(editor) === false || size.columns() > 1;
    };
    var cloneFormats = getCloneElements(editor);
    var execute = function (operation, guard, mutate, lazyWire) {
      return function (table, target) {
        removeDataStyle(table);
        var wire = lazyWire();
        var doc = $_6vo9a4krjh8lz1do.fromDom(editor.getDoc());
        var direction = TableDirection($_fe2yjsnvjh8lz1y8.directionAt);
        var generators = $_3fxw02lqjh8lz1hp.cellOperations(mutate, doc, cloneFormats);
        return guard(table) ? operation(wire, table, target, generators, direction).bind(function (result) {
          $_6b0spykcjh8lz1ao.each(result.newRows(), function (row) {
            fireNewRow(editor, row.dom());
          });
          $_6b0spykcjh8lz1ao.each(result.newCells(), function (cell) {
            fireNewCell(editor, cell.dom());
          });
          return result.cursor().map(function (cell) {
            var rng = editor.dom.createRng();
            rng.setStart(cell.dom(), 0);
            rng.setEnd(cell.dom(), 0);
            return rng;
          });
        }) : Option.none();
      };
    };
    var deleteRow = execute($_68i0x8mtjh8lz1pt.eraseRows, lastRowGuard, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var deleteColumn = execute($_68i0x8mtjh8lz1pt.eraseColumns, lastColumnGuard, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var insertRowsBefore = execute($_68i0x8mtjh8lz1pt.insertRowsBefore, $_bgyjg9kejh8lz1ax.always, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var insertRowsAfter = execute($_68i0x8mtjh8lz1pt.insertRowsAfter, $_bgyjg9kejh8lz1ax.always, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var insertColumnsBefore = execute($_68i0x8mtjh8lz1pt.insertColumnsBefore, $_bgyjg9kejh8lz1ax.always, $_36r49rmgjh8lz1nt.halve, lazyWire);
    var insertColumnsAfter = execute($_68i0x8mtjh8lz1pt.insertColumnsAfter, $_bgyjg9kejh8lz1ax.always, $_36r49rmgjh8lz1nt.halve, lazyWire);
    var mergeCells = execute($_68i0x8mtjh8lz1pt.mergeCells, $_bgyjg9kejh8lz1ax.always, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var unmergeCells = execute($_68i0x8mtjh8lz1pt.unmergeCells, $_bgyjg9kejh8lz1ax.always, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var pasteRowsBefore = execute($_68i0x8mtjh8lz1pt.pasteRowsBefore, $_bgyjg9kejh8lz1ax.always, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var pasteRowsAfter = execute($_68i0x8mtjh8lz1pt.pasteRowsAfter, $_bgyjg9kejh8lz1ax.always, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    var pasteCells = execute($_68i0x8mtjh8lz1pt.pasteCells, $_bgyjg9kejh8lz1ax.always, $_bgyjg9kejh8lz1ax.noop, lazyWire);
    return {
      deleteRow: deleteRow,
      deleteColumn: deleteColumn,
      insertRowsBefore: insertRowsBefore,
      insertRowsAfter: insertRowsAfter,
      insertColumnsBefore: insertColumnsBefore,
      insertColumnsAfter: insertColumnsAfter,
      mergeCells: mergeCells,
      unmergeCells: unmergeCells,
      pasteRowsBefore: pasteRowsBefore,
      pasteRowsAfter: pasteRowsAfter,
      pasteCells: pasteCells
    };
  };

  var copyRows = function (table, target, generators) {
    var list = $_ff1h20kmjh8lz1c3.fromTable(table);
    var house = $_fxwupplkjh8lz1go.generate(list);
    var details = $_1na6n8n0jh8lz1rt.onCells(house, target);
    return details.map(function (selectedCells) {
      var grid = $_7a3bzon3jh8lz1si.toGrid(house, generators, false);
      var slicedGrid = grid.slice(selectedCells[0].row(), selectedCells[selectedCells.length - 1].row() + selectedCells[selectedCells.length - 1].rowspan());
      var slicedDetails = $_1na6n8n0jh8lz1rt.toDetailList(slicedGrid, generators);
      return $_2lx51jn6jh8lz1sw.copy(slicedDetails);
    });
  };
  var $_1r3m04o0jh8lz1z4 = { copyRows: copyRows };

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var getTDTHOverallStyle = function (dom, elm, name) {
    var cells = dom.select('td,th', elm);
    var firstChildStyle;
    var checkChildren = function (firstChildStyle, elms) {
      for (var i = 0; i < elms.length; i++) {
        var currentStyle = dom.getStyle(elms[i], name);
        if (typeof firstChildStyle === 'undefined') {
          firstChildStyle = currentStyle;
        }
        if (firstChildStyle !== currentStyle) {
          return '';
        }
      }
      return firstChildStyle;
    };
    firstChildStyle = checkChildren(firstChildStyle, cells);
    return firstChildStyle;
  };
  var applyAlign = function (editor, elm, name) {
    if (name) {
      editor.formatter.apply('align' + name, {}, elm);
    }
  };
  var applyVAlign = function (editor, elm, name) {
    if (name) {
      editor.formatter.apply('valign' + name, {}, elm);
    }
  };
  var unApplyAlign = function (editor, elm) {
    global$2.each('left center right'.split(' '), function (name) {
      editor.formatter.remove('align' + name, {}, elm);
    });
  };
  var unApplyVAlign = function (editor, elm) {
    global$2.each('top middle bottom'.split(' '), function (name) {
      editor.formatter.remove('valign' + name, {}, elm);
    });
  };
  var $_fmiiqro3jh8lz1zk = {
    applyAlign: applyAlign,
    applyVAlign: applyVAlign,
    unApplyAlign: unApplyAlign,
    unApplyVAlign: unApplyVAlign,
    getTDTHOverallStyle: getTDTHOverallStyle
  };

  var buildListItems = function (inputList, itemCallback, startItems) {
    var appendItems = function (values, output) {
      output = output || [];
      global$2.each(values, function (item) {
        var menuItem = { text: item.text || item.title };
        if (item.menu) {
          menuItem.menu = appendItems(item.menu);
        } else {
          menuItem.value = item.value;
          if (itemCallback) {
            itemCallback(menuItem);
          }
        }
        output.push(menuItem);
      });
      return output;
    };
    return appendItems(inputList, startItems || []);
  };
  var updateStyleField = function (editor, evt) {
    var dom = editor.dom;
    var rootControl = evt.control.rootControl;
    var data = rootControl.toJSON();
    var css = dom.parseStyle(data.style);
    if (evt.control.name() === 'style') {
      rootControl.find('#borderStyle').value(css['border-style'] || '')[0].fire('select');
      rootControl.find('#borderColor').value(css['border-color'] || '')[0].fire('change');
      rootControl.find('#backgroundColor').value(css['background-color'] || '')[0].fire('change');
      rootControl.find('#width').value(css.width || '').fire('change');
      rootControl.find('#height').value(css.height || '').fire('change');
    } else {
      css['border-style'] = data.borderStyle;
      css['border-color'] = data.borderColor;
      css['background-color'] = data.backgroundColor;
      css.width = data.width ? addSizeSuffix(data.width) : '';
      css.height = data.height ? addSizeSuffix(data.height) : '';
    }
    rootControl.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css))));
  };
  var extractAdvancedStyles = function (dom, elm) {
    var css = dom.parseStyle(dom.getAttrib(elm, 'style'));
    var data = {};
    if (css['border-style']) {
      data.borderStyle = css['border-style'];
    }
    if (css['border-color']) {
      data.borderColor = css['border-color'];
    }
    if (css['background-color']) {
      data.backgroundColor = css['background-color'];
    }
    data.style = dom.serializeStyle(css);
    return data;
  };
  var createStyleForm = function (editor) {
    var createColorPickAction = function () {
      var colorPickerCallback = getColorPickerCallback(editor);
      if (colorPickerCallback) {
        return function (evt) {
          return colorPickerCallback.call(editor, function (value) {
            evt.control.value(value).fire('change');
          }, evt.control.value());
        };
      }
    };
    return {
      title: 'Advanced',
      type: 'form',
      defaults: { onchange: $_bgyjg9kejh8lz1ax.curry(updateStyleField, editor) },
      items: [
        {
          label: 'Style',
          name: 'style',
          type: 'textbox'
        },
        {
          type: 'form',
          padding: 0,
          formItemDefaults: {
            layout: 'grid',
            alignH: [
              'start',
              'right'
            ]
          },
          defaults: { size: 7 },
          items: [
            {
              label: 'Border style',
              type: 'listbox',
              name: 'borderStyle',
              width: 90,
              onselect: $_bgyjg9kejh8lz1ax.curry(updateStyleField, editor),
              values: [
                {
                  text: 'Select...',
                  value: ''
                },
                {
                  text: 'Solid',
                  value: 'solid'
                },
                {
                  text: 'Dotted',
                  value: 'dotted'
                },
                {
                  text: 'Dashed',
                  value: 'dashed'
                },
                {
                  text: 'Double',
                  value: 'double'
                },
                {
                  text: 'Groove',
                  value: 'groove'
                },
                {
                  text: 'Ridge',
                  value: 'ridge'
                },
                {
                  text: 'Inset',
                  value: 'inset'
                },
                {
                  text: 'Outset',
                  value: 'outset'
                },
                {
                  text: 'None',
                  value: 'none'
                },
                {
                  text: 'Hidden',
                  value: 'hidden'
                }
              ]
            },
            {
              label: 'Border color',
              type: 'colorbox',
              name: 'borderColor',
              onaction: createColorPickAction()
            },
            {
              label: 'Background color',
              type: 'colorbox',
              name: 'backgroundColor',
              onaction: createColorPickAction()
            }
          ]
        }
      ]
    };
  };
  var $_7mumlpo4jh8lz1zt = {
    createStyleForm: createStyleForm,
    buildListItems: buildListItems,
    updateStyleField: updateStyleField,
    extractAdvancedStyles: extractAdvancedStyles
  };

  var updateStyles = function (elm, cssText) {
    delete elm.dataset.mceStyle;
    elm.style.cssText += ';' + cssText;
  };
  var extractDataFromElement = function (editor, elm) {
    var dom = editor.dom;
    var data = {
      width: dom.getStyle(elm, 'width') || dom.getAttrib(elm, 'width'),
      height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
      scope: dom.getAttrib(elm, 'scope'),
      class: dom.getAttrib(elm, 'class'),
      type: elm.nodeName.toLowerCase(),
      style: '',
      align: '',
      valign: ''
    };
    global$2.each('left center right'.split(' '), function (name) {
      if (editor.formatter.matchNode(elm, 'align' + name)) {
        data.align = name;
      }
    });
    global$2.each('top middle bottom'.split(' '), function (name) {
      if (editor.formatter.matchNode(elm, 'valign' + name)) {
        data.valign = name;
      }
    });
    if (hasAdvancedCellTab(editor)) {
      global$2.extend(data, $_7mumlpo4jh8lz1zt.extractAdvancedStyles(dom, elm));
    }
    return data;
  };
  var onSubmitCellForm = function (editor, cells, evt) {
    var dom = editor.dom;
    var data;
    function setAttrib(elm, name, value) {
      if (value) {
        dom.setAttrib(elm, name, value);
      }
    }
    function setStyle(elm, name, value) {
      if (value) {
        dom.setStyle(elm, name, value);
      }
    }
    $_7mumlpo4jh8lz1zt.updateStyleField(editor, evt);
    data = evt.control.rootControl.toJSON();
    editor.undoManager.transact(function () {
      global$2.each(cells, function (cellElm) {
        setAttrib(cellElm, 'scope', data.scope);
        if (cells.length === 1) {
          setAttrib(cellElm, 'style', data.style);
        } else {
          updateStyles(cellElm, data.style);
        }
        setAttrib(cellElm, 'class', data.class);
        setStyle(cellElm, 'width', addSizeSuffix(data.width));
        setStyle(cellElm, 'height', addSizeSuffix(data.height));
        if (data.type && cellElm.nodeName.toLowerCase() !== data.type) {
          cellElm = dom.rename(cellElm, data.type);
        }
        if (cells.length === 1) {
          $_fmiiqro3jh8lz1zk.unApplyAlign(editor, cellElm);
          $_fmiiqro3jh8lz1zk.unApplyVAlign(editor, cellElm);
        }
        if (data.align) {
          $_fmiiqro3jh8lz1zk.applyAlign(editor, cellElm, data.align);
        }
        if (data.valign) {
          $_fmiiqro3jh8lz1zk.applyVAlign(editor, cellElm, data.valign);
        }
      });
      editor.focus();
    });
  };
  var open = function (editor) {
    var cellElm, data, classListCtrl, cells = [];
    cells = editor.dom.select('td[data-mce-selected],th[data-mce-selected]');
    cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
    if (!cells.length && cellElm) {
      cells.push(cellElm);
    }
    cellElm = cellElm || cells[0];
    if (!cellElm) {
      return;
    }
    if (cells.length > 1) {
      data = {
        width: '',
        height: '',
        scope: '',
        class: '',
        align: '',
        valign: '',
        style: '',
        type: cellElm.nodeName.toLowerCase()
      };
    } else {
      data = extractDataFromElement(editor, cellElm);
    }
    if (getCellClassList(editor).length > 0) {
      classListCtrl = {
        name: 'class',
        type: 'listbox',
        label: 'Class',
        values: $_7mumlpo4jh8lz1zt.buildListItems(getCellClassList(editor), function (item) {
          if (item.value) {
            item.textStyle = function () {
              return editor.formatter.getCssText({
                block: 'td',
                classes: [item.value]
              });
            };
          }
        })
      };
    }
    var generalCellForm = {
      type: 'form',
      layout: 'flex',
      direction: 'column',
      labelGapCalc: 'children',
      padding: 0,
      items: [
        {
          type: 'form',
          layout: 'grid',
          columns: 2,
          labelGapCalc: false,
          padding: 0,
          defaults: {
            type: 'textbox',
            maxWidth: 50
          },
          items: [
            {
              label: 'Width',
              name: 'width',
              onchange: $_bgyjg9kejh8lz1ax.curry($_7mumlpo4jh8lz1zt.updateStyleField, editor)
            },
            {
              label: 'Height',
              name: 'height',
              onchange: $_bgyjg9kejh8lz1ax.curry($_7mumlpo4jh8lz1zt.updateStyleField, editor)
            },
            {
              label: 'Cell type',
              name: 'type',
              type: 'listbox',
              text: 'None',
              minWidth: 90,
              maxWidth: null,
              values: [
                {
                  text: 'Cell',
                  value: 'td'
                },
                {
                  text: 'Header cell',
                  value: 'th'
                }
              ]
            },
            {
              label: 'Scope',
              name: 'scope',
              type: 'listbox',
              text: 'None',
              minWidth: 90,
              maxWidth: null,
              values: [
                {
                  text: 'None',
                  value: ''
                },
                {
                  text: 'Row',
                  value: 'row'
                },
                {
                  text: 'Column',
                  value: 'col'
                },
                {
                  text: 'Row group',
                  value: 'rowgroup'
                },
                {
                  text: 'Column group',
                  value: 'colgroup'
                }
              ]
            },
            {
              label: 'H Align',
              name: 'align',
              type: 'listbox',
              text: 'None',
              minWidth: 90,
              maxWidth: null,
              values: [
                {
                  text: 'None',
                  value: ''
                },
                {
                  text: 'Left',
                  value: 'left'
                },
                {
                  text: 'Center',
                  value: 'center'
                },
                {
                  text: 'Right',
                  value: 'right'
                }
              ]
            },
            {
              label: 'V Align',
              name: 'valign',
              type: 'listbox',
              text: 'None',
              minWidth: 90,
              maxWidth: null,
              values: [
                {
                  text: 'None',
                  value: ''
                },
                {
                  text: 'Top',
                  value: 'top'
                },
                {
                  text: 'Middle',
                  value: 'middle'
                },
                {
                  text: 'Bottom',
                  value: 'bottom'
                }
              ]
            }
          ]
        },
        classListCtrl
      ]
    };
    if (hasAdvancedCellTab(editor)) {
      editor.windowManager.open({
        title: 'Cell properties',
        bodyType: 'tabpanel',
        data: data,
        body: [
          {
            title: 'General',
            type: 'form',
            items: generalCellForm
          },
          $_7mumlpo4jh8lz1zt.createStyleForm(editor)
        ],
        onsubmit: $_bgyjg9kejh8lz1ax.curry(onSubmitCellForm, editor, cells)
      });
    } else {
      editor.windowManager.open({
        title: 'Cell properties',
        data: data,
        body: generalCellForm,
        onsubmit: $_bgyjg9kejh8lz1ax.curry(onSubmitCellForm, editor, cells)
      });
    }
  };
  var $_eo7s5go2jh8lz1ze = { open: open };

  var extractDataFromElement$1 = function (editor, elm) {
    var dom = editor.dom;
    var data = {
      height: dom.getStyle(elm, 'height') || dom.getAttrib(elm, 'height'),
      scope: dom.getAttrib(elm, 'scope'),
      class: dom.getAttrib(elm, 'class'),
      align: '',
      style: '',
      type: elm.parentNode.nodeName.toLowerCase()
    };
    global$2.each('left center right'.split(' '), function (name) {
      if (editor.formatter.matchNode(elm, 'align' + name)) {
        data.align = name;
      }
    });
    if (hasAdvancedRowTab(editor)) {
      global$2.extend(data, $_7mumlpo4jh8lz1zt.extractAdvancedStyles(dom, elm));
    }
    return data;
  };
  var switchRowType = function (dom, rowElm, toType) {
    var tableElm = dom.getParent(rowElm, 'table');
    var oldParentElm = rowElm.parentNode;
    var parentElm = dom.select(toType, tableElm)[0];
    if (!parentElm) {
      parentElm = dom.create(toType);
      if (tableElm.firstChild) {
        if (tableElm.firstChild.nodeName === 'CAPTION') {
          dom.insertAfter(parentElm, tableElm.firstChild);
        } else {
          tableElm.insertBefore(parentElm, tableElm.firstChild);
        }
      } else {
        tableElm.appendChild(parentElm);
      }
    }
    parentElm.appendChild(rowElm);
    if (!oldParentElm.hasChildNodes()) {
      dom.remove(oldParentElm);
    }
  };
  function onSubmitRowForm(editor, rows, oldData, evt) {
    var dom = editor.dom;
    function setAttrib(elm, name, value) {
      if (value) {
        dom.setAttrib(elm, name, value);
      }
    }
    function setStyle(elm, name, value) {
      if (value) {
        dom.setStyle(elm, name, value);
      }
    }
    $_7mumlpo4jh8lz1zt.updateStyleField(editor, evt);
    var data = evt.control.rootControl.toJSON();
    editor.undoManager.transact(function () {
      global$2.each(rows, function (rowElm) {
        setAttrib(rowElm, 'scope', data.scope);
        setAttrib(rowElm, 'style', data.style);
        setAttrib(rowElm, 'class', data.class);
        setStyle(rowElm, 'height', addSizeSuffix(data.height));
        if (data.type !== rowElm.parentNode.nodeName.toLowerCase()) {
          switchRowType(editor.dom, rowElm, data.type);
        }
        if (data.align !== oldData.align) {
          $_fmiiqro3jh8lz1zk.unApplyAlign(editor, rowElm);
          $_fmiiqro3jh8lz1zk.applyAlign(editor, rowElm, data.align);
        }
      });
      editor.focus();
    });
  }
  var open$1 = function (editor) {
    var dom = editor.dom;
    var tableElm, cellElm, rowElm, classListCtrl, data;
    var rows = [];
    var generalRowForm;
    tableElm = dom.getParent(editor.selection.getStart(), 'table');
    cellElm = dom.getParent(editor.selection.getStart(), 'td,th');
    global$2.each(tableElm.rows, function (row) {
      global$2.each(row.cells, function (cell) {
        if (dom.getAttrib(cell, 'data-mce-selected') || cell === cellElm) {
          rows.push(row);
          return false;
        }
      });
    });
    rowElm = rows[0];
    if (!rowElm) {
      return;
    }
    if (rows.length > 1) {
      data = {
        height: '',
        scope: '',
        style: '',
        class: '',
        align: '',
        type: rowElm.parentNode.nodeName.toLowerCase()
      };
    } else {
      data = extractDataFromElement$1(editor, rowElm);
    }
    if (getRowClassList(editor).length > 0) {
      classListCtrl = {
        name: 'class',
        type: 'listbox',
        label: 'Class',
        values: $_7mumlpo4jh8lz1zt.buildListItems(getRowClassList(editor), function (item) {
          if (item.value) {
            item.textStyle = function () {
              return editor.formatter.getCssText({
                block: 'tr',
                classes: [item.value]
              });
            };
          }
        })
      };
    }
    generalRowForm = {
      type: 'form',
      columns: 2,
      padding: 0,
      defaults: { type: 'textbox' },
      items: [
        {
          type: 'listbox',
          name: 'type',
          label: 'Row type',
          text: 'Header',
          maxWidth: null,
          values: [
            {
              text: 'Header',
              value: 'thead'
            },
            {
              text: 'Body',
              value: 'tbody'
            },
            {
              text: 'Footer',
              value: 'tfoot'
            }
          ]
        },
        {
          type: 'listbox',
          name: 'align',
          label: 'Alignment',
          text: 'None',
          maxWidth: null,
          values: [
            {
              text: 'None',
              value: ''
            },
            {
              text: 'Left',
              value: 'left'
            },
            {
              text: 'Center',
              value: 'center'
            },
            {
              text: 'Right',
              value: 'right'
            }
          ]
        },
        {
          label: 'Height',
          name: 'height'
        },
        classListCtrl
      ]
    };
    if (hasAdvancedRowTab(editor)) {
      editor.windowManager.open({
        title: 'Row properties',
        data: data,
        bodyType: 'tabpanel',
        body: [
          {
            title: 'General',
            type: 'form',
            items: generalRowForm
          },
          $_7mumlpo4jh8lz1zt.createStyleForm(editor)
        ],
        onsubmit: $_bgyjg9kejh8lz1ax.curry(onSubmitRowForm, editor, rows, data)
      });
    } else {
      editor.windowManager.open({
        title: 'Row properties',
        data: data,
        body: generalRowForm,
        onsubmit: $_bgyjg9kejh8lz1ax.curry(onSubmitRowForm, editor, rows, data)
      });
    }
  };
  var $_1dfi9ho5jh8lz1zz = { open: open$1 };

  var global$3 = tinymce.util.Tools.resolve('tinymce.Env');

  var DefaultRenderOptions = {
    styles: {
      'border-collapse': 'collapse',
      width: '100%'
    },
    attributes: { border: '1' },
    percentages: true
  };
  var makeTable = function () {
    return $_6vo9a4krjh8lz1do.fromTag('table');
  };
  var tableBody = function () {
    return $_6vo9a4krjh8lz1do.fromTag('tbody');
  };
  var tableRow = function () {
    return $_6vo9a4krjh8lz1do.fromTag('tr');
  };
  var tableHeaderCell = function () {
    return $_6vo9a4krjh8lz1do.fromTag('th');
  };
  var tableCell = function () {
    return $_6vo9a4krjh8lz1do.fromTag('td');
  };
  var render$1 = function (rows, columns, rowHeaders, columnHeaders, renderOpts) {
    if (renderOpts === void 0) {
      renderOpts = DefaultRenderOptions;
    }
    var table = makeTable();
    $_3ory84lljh8lz1gx.setAll(table, renderOpts.styles);
    $_1mp8lglcjh8lz1fq.setAll(table, renderOpts.attributes);
    var tbody = tableBody();
    $_6qqu1alnjh8lz1hg.append(table, tbody);
    var trs = [];
    for (var i = 0; i < rows; i++) {
      var tr = tableRow();
      for (var j = 0; j < columns; j++) {
        var td = i < rowHeaders || j < columnHeaders ? tableHeaderCell() : tableCell();
        if (j < columnHeaders) {
          $_1mp8lglcjh8lz1fq.set(td, 'scope', 'row');
        }
        if (i < rowHeaders) {
          $_1mp8lglcjh8lz1fq.set(td, 'scope', 'col');
        }
        $_6qqu1alnjh8lz1hg.append(td, $_6vo9a4krjh8lz1do.fromTag('br'));
        if (renderOpts.percentages) {
          $_3ory84lljh8lz1gx.set(td, 'width', 100 / columns + '%');
        }
        $_6qqu1alnjh8lz1hg.append(tr, td);
      }
      trs.push(tr);
    }
    $_d7tq5mlpjh8lz1hl.append(tbody, trs);
    return table;
  };

  var get$7 = function (element) {
    return element.dom().innerHTML;
  };
  var set$5 = function (element, content) {
    var owner = $_4hc7u2ktjh8lz1dv.owner(element);
    var docDom = owner.dom();
    var fragment = $_6vo9a4krjh8lz1do.fromDom(docDom.createDocumentFragment());
    var contentElements = $_200no5lwjh8lz1iy.fromHtml(content, docDom);
    $_d7tq5mlpjh8lz1hl.append(fragment, contentElements);
    $_f2hny0lojh8lz1hi.empty(element);
    $_6qqu1alnjh8lz1hg.append(element, fragment);
  };
  var getOuter$2 = function (element) {
    var container = $_6vo9a4krjh8lz1do.fromTag('div');
    var clone = $_6vo9a4krjh8lz1do.fromDom(element.dom().cloneNode(true));
    $_6qqu1alnjh8lz1hg.append(container, clone);
    return get$7(container);
  };
  var $_1dtmigobjh8lz215 = {
    get: get$7,
    set: set$5,
    getOuter: getOuter$2
  };

  var placeCaretInCell = function (editor, cell) {
    editor.selection.select(cell.dom(), true);
    editor.selection.collapse(true);
  };
  var selectFirstCellInTable = function (editor, tableElm) {
    $_fiygddlhjh8lz1g7.descendant(tableElm, 'td,th').each($_bgyjg9kejh8lz1ax.curry(placeCaretInCell, editor));
  };
  var fireEvents = function (editor, table) {
    $_6b0spykcjh8lz1ao.each($_coxlualejh8lz1fz.descendants(table, 'tr'), function (row) {
      fireNewRow(editor, row.dom());
      $_6b0spykcjh8lz1ao.each($_coxlualejh8lz1fz.descendants(row, 'th,td'), function (cell) {
        fireNewCell(editor, cell.dom());
      });
    });
  };
  var isPercentage = function (width) {
    return $_d1kyz8kfjh8lz1az.isString(width) && width.indexOf('%') !== -1;
  };
  var insert$1 = function (editor, columns, rows) {
    var defaultStyles = getDefaultStyles(editor);
    var options = {
      styles: defaultStyles,
      attributes: getDefaultAttributes(editor),
      percentages: isPercentage(defaultStyles.width) && !isPixelsForced(editor)
    };
    var table = render$1(rows, columns, 0, 0, options);
    $_1mp8lglcjh8lz1fq.set(table, 'data-mce-id', '__mce');
    var html = $_1dtmigobjh8lz215.getOuter(table);
    editor.insertContent(html);
    return $_fiygddlhjh8lz1g7.descendant(getBody$1(editor), 'table[data-mce-id="__mce"]').map(function (table) {
      if (isPixelsForced(editor)) {
        $_3ory84lljh8lz1gx.set(table, 'width', $_3ory84lljh8lz1gx.get(table, 'width'));
      }
      $_1mp8lglcjh8lz1fq.remove(table, 'data-mce-id');
      fireEvents(editor, table);
      selectFirstCellInTable(editor, table);
      return table.dom();
    }).getOr(null);
  };
  var $_7a3xgho8jh8lz20d = { insert: insert$1 };

  function styleTDTH(dom, elm, name, value) {
    if (elm.tagName === 'TD' || elm.tagName === 'TH') {
      dom.setStyle(elm, name, value);
    } else {
      if (elm.children) {
        for (var i = 0; i < elm.children.length; i++) {
          styleTDTH(dom, elm.children[i], name, value);
        }
      }
    }
  }
  var extractDataFromElement$2 = function (editor, tableElm) {
    var dom = editor.dom;
    var data = {
      width: dom.getStyle(tableElm, 'width') || dom.getAttrib(tableElm, 'width'),
      height: dom.getStyle(tableElm, 'height') || dom.getAttrib(tableElm, 'height'),
      cellspacing: dom.getStyle(tableElm, 'border-spacing') || dom.getAttrib(tableElm, 'cellspacing'),
      cellpadding: dom.getAttrib(tableElm, 'data-mce-cell-padding') || dom.getAttrib(tableElm, 'cellpadding') || $_fmiiqro3jh8lz1zk.getTDTHOverallStyle(editor.dom, tableElm, 'padding'),
      border: dom.getAttrib(tableElm, 'data-mce-border') || dom.getAttrib(tableElm, 'border') || $_fmiiqro3jh8lz1zk.getTDTHOverallStyle(editor.dom, tableElm, 'border'),
      borderColor: dom.getAttrib(tableElm, 'data-mce-border-color'),
      caption: !!dom.select('caption', tableElm)[0],
      class: dom.getAttrib(tableElm, 'class')
    };
    global$2.each('left center right'.split(' '), function (name) {
      if (editor.formatter.matchNode(tableElm, 'align' + name)) {
        data.align = name;
      }
    });
    if (hasAdvancedTableTab(editor)) {
      global$2.extend(data, $_7mumlpo4jh8lz1zt.extractAdvancedStyles(dom, tableElm));
    }
    return data;
  };
  var applyDataToElement = function (editor, tableElm, data) {
    var dom = editor.dom;
    var attrs = {};
    var styles = {};
    attrs.class = data.class;
    styles.height = addSizeSuffix(data.height);
    if (dom.getAttrib(tableElm, 'width') && !shouldStyleWithCss(editor)) {
      attrs.width = removePxSuffix(data.width);
    } else {
      styles.width = addSizeSuffix(data.width);
    }
    if (shouldStyleWithCss(editor)) {
      styles['border-width'] = addSizeSuffix(data.border);
      styles['border-spacing'] = addSizeSuffix(data.cellspacing);
      global$2.extend(attrs, {
        'data-mce-border-color': data.borderColor,
        'data-mce-cell-padding': data.cellpadding,
        'data-mce-border': data.border
      });
    } else {
      global$2.extend(attrs, {
        border: data.border,
        cellpadding: data.cellpadding,
        cellspacing: data.cellspacing
      });
    }
    if (shouldStyleWithCss(editor)) {
      if (tableElm.children) {
        for (var i = 0; i < tableElm.children.length; i++) {
          styleTDTH(dom, tableElm.children[i], {
            'border-width': addSizeSuffix(data.border),
            'border-color': data.borderColor,
            'padding': addSizeSuffix(data.cellpadding)
          });
        }
      }
    }
    if (data.style) {
      global$2.extend(styles, dom.parseStyle(data.style));
    } else {
      styles = global$2.extend({}, dom.parseStyle(dom.getAttrib(tableElm, 'style')), styles);
    }
    attrs.style = dom.serializeStyle(styles);
    dom.setAttribs(tableElm, attrs);
  };
  var onSubmitTableForm = function (editor, tableElm, evt) {
    var dom = editor.dom;
    var captionElm;
    var data;
    $_7mumlpo4jh8lz1zt.updateStyleField(editor, evt);
    data = evt.control.rootControl.toJSON();
    if (data.class === false) {
      delete data.class;
    }
    editor.undoManager.transact(function () {
      if (!tableElm) {
        tableElm = $_7a3xgho8jh8lz20d.insert(editor, data.cols || 1, data.rows || 1);
      }
      applyDataToElement(editor, tableElm, data);
      captionElm = dom.select('caption', tableElm)[0];
      if (captionElm && !data.caption) {
        dom.remove(captionElm);
      }
      if (!captionElm && data.caption) {
        captionElm = dom.create('caption');
        captionElm.innerHTML = !global$3.ie ? '<br data-mce-bogus="1"/>' : '\xA0';
        tableElm.insertBefore(captionElm, tableElm.firstChild);
      }
      $_fmiiqro3jh8lz1zk.unApplyAlign(editor, tableElm);
      if (data.align) {
        $_fmiiqro3jh8lz1zk.applyAlign(editor, tableElm, data.align);
      }
      editor.focus();
      editor.addVisual();
    });
  };
  var open$2 = function (editor, isProps) {
    var dom = editor.dom;
    var tableElm, colsCtrl, rowsCtrl, classListCtrl, data = {}, generalTableForm;
    if (isProps === true) {
      tableElm = dom.getParent(editor.selection.getStart(), 'table');
      if (tableElm) {
        data = extractDataFromElement$2(editor, tableElm);
      }
    } else {
      colsCtrl = {
        label: 'Cols',
        name: 'cols'
      };
      rowsCtrl = {
        label: 'Rows',
        name: 'rows'
      };
    }
    if (getTableClassList(editor).length > 0) {
      if (data.class) {
        data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
      }
      classListCtrl = {
        name: 'class',
        type: 'listbox',
        label: 'Class',
        values: $_7mumlpo4jh8lz1zt.buildListItems(getTableClassList(editor), function (item) {
          if (item.value) {
            item.textStyle = function () {
              return editor.formatter.getCssText({
                block: 'table',
                classes: [item.value]
              });
            };
          }
        })
      };
    }
    generalTableForm = {
      type: 'form',
      layout: 'flex',
      direction: 'column',
      labelGapCalc: 'children',
      padding: 0,
      items: [
        {
          type: 'form',
          labelGapCalc: false,
          padding: 0,
          layout: 'grid',
          columns: 2,
          defaults: {
            type: 'textbox',
            maxWidth: 50
          },
          items: hasAppearanceOptions(editor) ? [
            colsCtrl,
            rowsCtrl,
            {
              label: 'Width',
              name: 'width',
              onchange: $_bgyjg9kejh8lz1ax.curry($_7mumlpo4jh8lz1zt.updateStyleField, editor)
            },
            {
              label: 'Height',
              name: 'height',
              onchange: $_bgyjg9kejh8lz1ax.curry($_7mumlpo4jh8lz1zt.updateStyleField, editor)
            },
            {
              label: 'Cell spacing',
              name: 'cellspacing'
            },
            {
              label: 'Cell padding',
              name: 'cellpadding'
            },
            {
              label: 'Border',
              name: 'border'
            },
            {
              label: 'Caption',
              name: 'caption',
              type: 'checkbox'
            }
          ] : [
            colsCtrl,
            rowsCtrl,
            {
              label: 'Width',
              name: 'width',
              onchange: $_bgyjg9kejh8lz1ax.curry($_7mumlpo4jh8lz1zt.updateStyleField, editor)
            },
            {
              label: 'Height',
              name: 'height',
              onchange: $_bgyjg9kejh8lz1ax.curry($_7mumlpo4jh8lz1zt.updateStyleField, editor)
            }
          ]
        },
        {
          label: 'Alignment',
          name: 'align',
          type: 'listbox',
          text: 'None',
          values: [
            {
              text: 'None',
              value: ''
            },
            {
              text: 'Left',
              value: 'left'
            },
            {
              text: 'Center',
              value: 'center'
            },
            {
              text: 'Right',
              value: 'right'
            }
          ]
        },
        classListCtrl
      ]
    };
    if (hasAdvancedTableTab(editor)) {
      editor.windowManager.open({
        title: 'Table properties',
        data: data,
        bodyType: 'tabpanel',
        body: [
          {
            title: 'General',
            type: 'form',
            items: generalTableForm
          },
          $_7mumlpo4jh8lz1zt.createStyleForm(editor)
        ],
        onsubmit: $_bgyjg9kejh8lz1ax.curry(onSubmitTableForm, editor, tableElm)
      });
    } else {
      editor.windowManager.open({
        title: 'Table properties',
        data: data,
        body: generalTableForm,
        onsubmit: $_bgyjg9kejh8lz1ax.curry(onSubmitTableForm, editor, tableElm)
      });
    }
  };
  var $_4ld2ndo6jh8lz205 = { open: open$2 };

  var each$3 = global$2.each;
  var registerCommands = function (editor, actions, cellSelection, selections, clipboardRows) {
    var isRoot = getIsRoot(editor);
    var eraseTable = function () {
      var cell = $_6vo9a4krjh8lz1do.fromDom(editor.dom.getParent(editor.selection.getStart(), 'th,td'));
      var table = $_ee8pmfkojh8lz1ch.table(cell, isRoot);
      table.filter($_bgyjg9kejh8lz1ax.not(isRoot)).each(function (table) {
        var cursor = $_6vo9a4krjh8lz1do.fromText('');
        $_6qqu1alnjh8lz1hg.after(table, cursor);
        $_f2hny0lojh8lz1hi.remove(table);
        var rng = editor.dom.createRng();
        rng.setStart(cursor.dom(), 0);
        rng.setEnd(cursor.dom(), 0);
        editor.selection.setRng(rng);
      });
    };
    var getSelectionStartCell = function () {
      return $_6vo9a4krjh8lz1do.fromDom(editor.dom.getParent(editor.selection.getStart(), 'th,td'));
    };
    var getTableFromCell = function (cell) {
      return $_ee8pmfkojh8lz1ch.table(cell, isRoot);
    };
    var getSize = function (table) {
      return {
        width: getPixelWidth$1(table.dom()),
        height: getPixelWidth$1(table.dom())
      };
    };
    var resizeChange = function (editor, oldSize, table) {
      var newSize = getSize(table);
      if (oldSize.width !== newSize.width || oldSize.height !== newSize.height) {
        fireObjectResizeStart(editor, table.dom(), oldSize.width, oldSize.height);
        fireObjectResized(editor, table.dom(), newSize.width, newSize.height);
      }
    };
    var actOnSelection = function (execute) {
      var cell = getSelectionStartCell();
      var table = getTableFromCell(cell);
      table.each(function (table) {
        var targets = $_3xfj7olxjh8lz1j2.forMenu(selections, table, cell);
        var beforeSize = getSize(table);
        execute(table, targets).each(function (rng) {
          resizeChange(editor, beforeSize, table);
          editor.selection.setRng(rng);
          editor.focus();
          cellSelection.clear(table);
          removeDataStyle(table);
        });
      });
    };
    var copyRowSelection = function (execute) {
      var cell = getSelectionStartCell();
      var table = getTableFromCell(cell);
      return table.bind(function (table) {
        var doc = $_6vo9a4krjh8lz1do.fromDom(editor.getDoc());
        var targets = $_3xfj7olxjh8lz1j2.forMenu(selections, table, cell);
        var generators = $_3fxw02lqjh8lz1hp.cellOperations($_bgyjg9kejh8lz1ax.noop, doc, Option.none());
        return $_1r3m04o0jh8lz1z4.copyRows(table, targets, generators);
      });
    };
    var pasteOnSelection = function (execute) {
      clipboardRows.get().each(function (rows) {
        var clonedRows = $_6b0spykcjh8lz1ao.map(rows, function (row) {
          return $_zeqq4lrjh8lz1id.deep(row);
        });
        var cell = getSelectionStartCell();
        var table = getTableFromCell(cell);
        table.bind(function (table) {
          var doc = $_6vo9a4krjh8lz1do.fromDom(editor.getDoc());
          var generators = $_3fxw02lqjh8lz1hp.paste(doc);
          var targets = $_3xfj7olxjh8lz1j2.pasteRows(selections, table, cell, clonedRows, generators);
          execute(table, targets).each(function (rng) {
            editor.selection.setRng(rng);
            editor.focus();
            cellSelection.clear(table);
          });
        });
      });
    };
    each$3({
      mceTableSplitCells: function () {
        actOnSelection(actions.unmergeCells);
      },
      mceTableMergeCells: function () {
        actOnSelection(actions.mergeCells);
      },
      mceTableInsertRowBefore: function () {
        actOnSelection(actions.insertRowsBefore);
      },
      mceTableInsertRowAfter: function () {
        actOnSelection(actions.insertRowsAfter);
      },
      mceTableInsertColBefore: function () {
        actOnSelection(actions.insertColumnsBefore);
      },
      mceTableInsertColAfter: function () {
        actOnSelection(actions.insertColumnsAfter);
      },
      mceTableDeleteCol: function () {
        actOnSelection(actions.deleteColumn);
      },
      mceTableDeleteRow: function () {
        actOnSelection(actions.deleteRow);
      },
      mceTableCutRow: function (grid) {
        clipboardRows.set(copyRowSelection());
        actOnSelection(actions.deleteRow);
      },
      mceTableCopyRow: function (grid) {
        clipboardRows.set(copyRowSelection());
      },
      mceTablePasteRowBefore: function (grid) {
        pasteOnSelection(actions.pasteRowsBefore);
      },
      mceTablePasteRowAfter: function (grid) {
        pasteOnSelection(actions.pasteRowsAfter);
      },
      mceTableDelete: eraseTable
    }, function (func, name) {
      editor.addCommand(name, func);
    });
    each$3({
      mceInsertTable: $_bgyjg9kejh8lz1ax.curry($_4ld2ndo6jh8lz205.open, editor),
      mceTableProps: $_bgyjg9kejh8lz1ax.curry($_4ld2ndo6jh8lz205.open, editor, true),
      mceTableRowProps: $_bgyjg9kejh8lz1ax.curry($_1dfi9ho5jh8lz1zz.open, editor),
      mceTableCellProps: $_bgyjg9kejh8lz1ax.curry($_eo7s5go2jh8lz1ze.open, editor)
    }, function (func, name) {
      editor.addCommand(name, function (ui, val) {
        func(val);
      });
    });
  };
  var $_cmt2k3nzjh8lz1ym = { registerCommands: registerCommands };

  var only$1 = function (element) {
    var parent = Option.from(element.dom().documentElement).map($_6vo9a4krjh8lz1do.fromDom).getOr(element);
    return {
      parent: $_bgyjg9kejh8lz1ax.constant(parent),
      view: $_bgyjg9kejh8lz1ax.constant(element),
      origin: $_bgyjg9kejh8lz1ax.constant(r(0, 0))
    };
  };
  var detached = function (editable, chrome) {
    var origin = $_bgyjg9kejh8lz1ax.curry($_6xc5idmpjh8lz1ph.absolute, chrome);
    return {
      parent: $_bgyjg9kejh8lz1ax.constant(chrome),
      view: $_bgyjg9kejh8lz1ax.constant(editable),
      origin: origin
    };
  };
  var body$1 = function (editable, chrome) {
    return {
      parent: $_bgyjg9kejh8lz1ax.constant(chrome),
      view: $_bgyjg9kejh8lz1ax.constant(editable),
      origin: $_bgyjg9kejh8lz1ax.constant(r(0, 0))
    };
  };
  var $_bdbkjodjh8lz21o = {
    only: only$1,
    detached: detached,
    body: body$1
  };

  function Event (fields) {
    var struct = $_d2ojjnkijh8lz1bv.immutable.apply(null, fields);
    var handlers = [];
    var bind = function (handler) {
      if (handler === undefined) {
        throw 'Event bind error: undefined handler';
      }
      handlers.push(handler);
    };
    var unbind = function (handler) {
      handlers = $_6b0spykcjh8lz1ao.filter(handlers, function (h) {
        return h !== handler;
      });
    };
    var trigger = function () {
      var event = struct.apply(null, arguments);
      $_6b0spykcjh8lz1ao.each(handlers, function (handler) {
        handler(event);
      });
    };
    return {
      bind: bind,
      unbind: unbind,
      trigger: trigger
    };
  }

  var create = function (typeDefs) {
    var registry = $_8kti2hkhjh8lz1bt.map(typeDefs, function (event) {
      return {
        bind: event.bind,
        unbind: event.unbind
      };
    });
    var trigger = $_8kti2hkhjh8lz1bt.map(typeDefs, function (event) {
      return event.trigger;
    });
    return {
      registry: registry,
      trigger: trigger
    };
  };
  var $_cmo273ogjh8lz22b = { create: create };

  var mode = $_2qijvhmwjh8lz1qv.exactly([
    'compare',
    'extract',
    'mutate',
    'sink'
  ]);
  var sink = $_2qijvhmwjh8lz1qv.exactly([
    'element',
    'start',
    'stop',
    'destroy'
  ]);
  var api$3 = $_2qijvhmwjh8lz1qv.exactly([
    'forceDrop',
    'drop',
    'move',
    'delayDrop'
  ]);
  var $_ay0s6wokjh8lz23r = {
    mode: mode,
    sink: sink,
    api: api$3
  };

  var styles$1 = $_2i90e7ncjh8lz1ux.css('ephox-dragster');
  var $_d4gfq4omjh8lz247 = { resolve: styles$1.resolve };

  function Blocker (options) {
    var settings = $_b4x7eon1jh8lz1se.merge({ 'layerClass': $_d4gfq4omjh8lz247.resolve('blocker') }, options);
    var div = $_6vo9a4krjh8lz1do.fromTag('div');
    $_1mp8lglcjh8lz1fq.set(div, 'role', 'presentation');
    $_3ory84lljh8lz1gx.setAll(div, {
      position: 'fixed',
      left: '0px',
      top: '0px',
      width: '100%',
      height: '100%'
    });
    $_evf7iendjh8lz1uz.add(div, $_d4gfq4omjh8lz247.resolve('blocker'));
    $_evf7iendjh8lz1uz.add(div, settings.layerClass);
    var element = function () {
      return div;
    };
    var destroy = function () {
      $_f2hny0lojh8lz1hi.remove(div);
    };
    return {
      element: element,
      destroy: destroy
    };
  }

  var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
    return {
      'target': $_bgyjg9kejh8lz1ax.constant(target),
      'x': $_bgyjg9kejh8lz1ax.constant(x),
      'y': $_bgyjg9kejh8lz1ax.constant(y),
      'stop': stop,
      'prevent': prevent,
      'kill': kill,
      'raw': $_bgyjg9kejh8lz1ax.constant(raw)
    };
  };
  var handle = function (filter, handler) {
    return function (rawEvent) {
      if (!filter(rawEvent))
        return;
      var target = $_6vo9a4krjh8lz1do.fromDom(rawEvent.target);
      var stop = function () {
        rawEvent.stopPropagation();
      };
      var prevent = function () {
        rawEvent.preventDefault();
      };
      var kill = $_bgyjg9kejh8lz1ax.compose(prevent, stop);
      var evt = mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
      handler(evt);
    };
  };
  var binder = function (element, event, filter, handler, useCapture) {
    var wrapped = handle(filter, handler);
    element.dom().addEventListener(event, wrapped, useCapture);
    return { unbind: $_bgyjg9kejh8lz1ax.curry(unbind, element, event, wrapped, useCapture) };
  };
  var bind$1 = function (element, event, filter, handler) {
    return binder(element, event, filter, handler, false);
  };
  var capture = function (element, event, filter, handler) {
    return binder(element, event, filter, handler, true);
  };
  var unbind = function (element, event, handler, useCapture) {
    element.dom().removeEventListener(event, handler, useCapture);
  };
  var $_8y86u3oojh8lz24e = {
    bind: bind$1,
    capture: capture
  };

  var filter$1 = $_bgyjg9kejh8lz1ax.constant(true);
  var bind$2 = function (element, event, handler) {
    return $_8y86u3oojh8lz24e.bind(element, event, filter$1, handler);
  };
  var capture$1 = function (element, event, handler) {
    return $_8y86u3oojh8lz24e.capture(element, event, filter$1, handler);
  };
  var $_5cpulvonjh8lz24a = {
    bind: bind$2,
    capture: capture$1
  };

  var compare = function (old, nu) {
    return r(nu.left() - old.left(), nu.top() - old.top());
  };
  var extract$1 = function (event) {
    return Option.some(r(event.x(), event.y()));
  };
  var mutate$1 = function (mutation, info) {
    mutation.mutate(info.left(), info.top());
  };
  var sink$1 = function (dragApi, settings) {
    var blocker = Blocker(settings);
    var mdown = $_5cpulvonjh8lz24a.bind(blocker.element(), 'mousedown', dragApi.forceDrop);
    var mup = $_5cpulvonjh8lz24a.bind(blocker.element(), 'mouseup', dragApi.drop);
    var mmove = $_5cpulvonjh8lz24a.bind(blocker.element(), 'mousemove', dragApi.move);
    var mout = $_5cpulvonjh8lz24a.bind(blocker.element(), 'mouseout', dragApi.delayDrop);
    var destroy = function () {
      blocker.destroy();
      mup.unbind();
      mmove.unbind();
      mout.unbind();
      mdown.unbind();
    };
    var start = function (parent) {
      $_6qqu1alnjh8lz1hg.append(parent, blocker.element());
    };
    var stop = function () {
      $_f2hny0lojh8lz1hi.remove(blocker.element());
    };
    return $_ay0s6wokjh8lz23r.sink({
      element: blocker.element,
      start: start,
      stop: stop,
      destroy: destroy
    });
  };
  var MouseDrag = $_ay0s6wokjh8lz23r.mode({
    compare: compare,
    extract: extract$1,
    sink: sink$1,
    mutate: mutate$1
  });

  function InDrag () {
    var previous = Option.none();
    var reset = function () {
      previous = Option.none();
    };
    var update = function (mode, nu) {
      var result = previous.map(function (old) {
        return mode.compare(old, nu);
      });
      previous = Option.some(nu);
      return result;
    };
    var onEvent = function (event, mode) {
      var dataOption = mode.extract(event);
      dataOption.each(function (data) {
        var offset = update(mode, data);
        offset.each(function (d) {
          events.trigger.move(d);
        });
      });
    };
    var events = $_cmo273ogjh8lz22b.create({ move: Event(['info']) });
    return {
      onEvent: onEvent,
      reset: reset,
      events: events.registry
    };
  }

  function NoDrag (anchor) {
    var onEvent = function (event, mode) {
    };
    return {
      onEvent: onEvent,
      reset: $_bgyjg9kejh8lz1ax.noop
    };
  }

  function Movement () {
    var noDragState = NoDrag();
    var inDragState = InDrag();
    var dragState = noDragState;
    var on = function () {
      dragState.reset();
      dragState = inDragState;
    };
    var off = function () {
      dragState.reset();
      dragState = noDragState;
    };
    var onEvent = function (event, mode) {
      dragState.onEvent(event, mode);
    };
    var isOn = function () {
      return dragState === inDragState;
    };
    return {
      on: on,
      off: off,
      isOn: isOn,
      onEvent: onEvent,
      events: inDragState.events
    };
  }

  var adaptable = function (fn, rate) {
    var timer = null;
    var args = null;
    var cancel = function () {
      if (timer !== null) {
        clearTimeout(timer);
        timer = null;
        args = null;
      }
    };
    var throttle = function () {
      args = arguments;
      if (timer === null) {
        timer = setTimeout(function () {
          fn.apply(null, args);
          timer = null;
          args = null;
        }, rate);
      }
    };
    return {
      cancel: cancel,
      throttle: throttle
    };
  };
  var first$4 = function (fn, rate) {
    var timer = null;
    var cancel = function () {
      if (timer !== null) {
        clearTimeout(timer);
        timer = null;
      }
    };
    var throttle = function () {
      var args = arguments;
      if (timer === null) {
        timer = setTimeout(function () {
          fn.apply(null, args);
          timer = null;
          args = null;
        }, rate);
      }
    };
    return {
      cancel: cancel,
      throttle: throttle
    };
  };
  var last$3 = function (fn, rate) {
    var timer = null;
    var cancel = function () {
      if (timer !== null) {
        clearTimeout(timer);
        timer = null;
      }
    };
    var throttle = function () {
      var args = arguments;
      if (timer !== null)
        clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(null, args);
        timer = null;
        args = null;
      }, rate);
    };
    return {
      cancel: cancel,
      throttle: throttle
    };
  };
  var $_eu7wkootjh8lz251 = {
    adaptable: adaptable,
    first: first$4,
    last: last$3
  };

  var setup = function (mutation, mode, settings) {
    var active = false;
    var events = $_cmo273ogjh8lz22b.create({
      start: Event([]),
      stop: Event([])
    });
    var movement = Movement();
    var drop = function () {
      sink.stop();
      if (movement.isOn()) {
        movement.off();
        events.trigger.stop();
      }
    };
    var throttledDrop = $_eu7wkootjh8lz251.last(drop, 200);
    var go = function (parent) {
      sink.start(parent);
      movement.on();
      events.trigger.start();
    };
    var mousemove = function (event, ui) {
      throttledDrop.cancel();
      movement.onEvent(event, mode);
    };
    movement.events.move.bind(function (event) {
      mode.mutate(mutation, event.info());
    });
    var on = function () {
      active = true;
    };
    var off = function () {
      active = false;
    };
    var runIfActive = function (f) {
      return function () {
        var args = Array.prototype.slice.call(arguments, 0);
        if (active) {
          return f.apply(null, args);
        }
      };
    };
    var sink = mode.sink($_ay0s6wokjh8lz23r.api({
      forceDrop: drop,
      drop: runIfActive(drop),
      move: runIfActive(mousemove),
      delayDrop: runIfActive(throttledDrop.throttle)
    }), settings);
    var destroy = function () {
      sink.destroy();
    };
    return {
      element: sink.element,
      go: go,
      on: on,
      off: off,
      destroy: destroy,
      events: events.registry
    };
  };
  var $_feeb1aopjh8lz24i = { setup: setup };

  var transform$1 = function (mutation, options) {
    var settings = options !== undefined ? options : {};
    var mode = settings.mode !== undefined ? settings.mode : MouseDrag;
    return $_feeb1aopjh8lz24i.setup(mutation, mode, options);
  };
  var $_dm1jluoijh8lz23a = { transform: transform$1 };

  function Mutation () {
    var events = $_cmo273ogjh8lz22b.create({
      'drag': Event([
        'xDelta',
        'yDelta'
      ])
    });
    var mutate = function (x, y) {
      events.trigger.drag(x, y);
    };
    return {
      mutate: mutate,
      events: events.registry
    };
  }

  function BarMutation () {
    var events = $_cmo273ogjh8lz22b.create({
      drag: Event([
        'xDelta',
        'yDelta',
        'target'
      ])
    });
    var target = Option.none();
    var delegate = Mutation();
    delegate.events.drag.bind(function (event) {
      target.each(function (t) {
        events.trigger.drag(event.xDelta(), event.yDelta(), t);
      });
    });
    var assign = function (t) {
      target = Option.some(t);
    };
    var get = function () {
      return target;
    };
    return {
      assign: assign,
      get: get,
      mutate: delegate.mutate,
      events: events.registry
    };
  }

  var any = function (selector) {
    return $_fiygddlhjh8lz1g7.first(selector).isSome();
  };
  var ancestor$2 = function (scope, selector, isRoot) {
    return $_fiygddlhjh8lz1g7.ancestor(scope, selector, isRoot).isSome();
  };
  var sibling$2 = function (scope, selector) {
    return $_fiygddlhjh8lz1g7.sibling(scope, selector).isSome();
  };
  var child$3 = function (scope, selector) {
    return $_fiygddlhjh8lz1g7.child(scope, selector).isSome();
  };
  var descendant$2 = function (scope, selector) {
    return $_fiygddlhjh8lz1g7.descendant(scope, selector).isSome();
  };
  var closest$2 = function (scope, selector, isRoot) {
    return $_fiygddlhjh8lz1g7.closest(scope, selector, isRoot).isSome();
  };
  var $_6z48nsowjh8lz25j = {
    any: any,
    ancestor: ancestor$2,
    sibling: sibling$2,
    child: child$3,
    descendant: descendant$2,
    closest: closest$2
  };

  var resizeBarDragging = $_ezk1iinbjh8lz1uu.resolve('resizer-bar-dragging');
  function BarManager (wire, direction, hdirection) {
    var mutation = BarMutation();
    var resizing = $_dm1jluoijh8lz23a.transform(mutation, {});
    var hoverTable = Option.none();
    var getResizer = function (element, type) {
      return Option.from($_1mp8lglcjh8lz1fq.get(element, type));
    };
    mutation.events.drag.bind(function (event) {
      getResizer(event.target(), 'data-row').each(function (_dataRow) {
        var currentRow = $_agh84xnrjh8lz1x6.getInt(event.target(), 'top');
        $_3ory84lljh8lz1gx.set(event.target(), 'top', currentRow + event.yDelta() + 'px');
      });
      getResizer(event.target(), 'data-column').each(function (_dataCol) {
        var currentCol = $_agh84xnrjh8lz1x6.getInt(event.target(), 'left');
        $_3ory84lljh8lz1gx.set(event.target(), 'left', currentCol + event.xDelta() + 'px');
      });
    });
    var getDelta = function (target, direction) {
      var newX = $_agh84xnrjh8lz1x6.getInt(target, direction);
      var oldX = parseInt($_1mp8lglcjh8lz1fq.get(target, 'data-initial-' + direction), 10);
      return newX - oldX;
    };
    resizing.events.stop.bind(function () {
      mutation.get().each(function (target) {
        hoverTable.each(function (table) {
          getResizer(target, 'data-row').each(function (row) {
            var delta = getDelta(target, 'top');
            $_1mp8lglcjh8lz1fq.remove(target, 'data-initial-top');
            events.trigger.adjustHeight(table, delta, parseInt(row, 10));
          });
          getResizer(target, 'data-column').each(function (column) {
            var delta = getDelta(target, 'left');
            $_1mp8lglcjh8lz1fq.remove(target, 'data-initial-left');
            events.trigger.adjustWidth(table, delta, parseInt(column, 10));
          });
          $_b9z1gin7jh8lz1tj.refresh(wire, table, hdirection, direction);
        });
      });
    });
    var handler = function (target, direction) {
      events.trigger.startAdjust();
      mutation.assign(target);
      $_1mp8lglcjh8lz1fq.set(target, 'data-initial-' + direction, parseInt($_3ory84lljh8lz1gx.get(target, direction), 10));
      $_evf7iendjh8lz1uz.add(target, resizeBarDragging);
      $_3ory84lljh8lz1gx.set(target, 'opacity', '0.2');
      resizing.go(wire.parent());
    };
    var mousedown = $_5cpulvonjh8lz24a.bind(wire.parent(), 'mousedown', function (event) {
      if ($_b9z1gin7jh8lz1tj.isRowBar(event.target()))
        handler(event.target(), 'top');
      if ($_b9z1gin7jh8lz1tj.isColBar(event.target()))
        handler(event.target(), 'left');
    });
    var isRoot = function (e) {
      return $_2eywnlkvjh8lz1e8.eq(e, wire.view());
    };
    var mouseover = $_5cpulvonjh8lz24a.bind(wire.view(), 'mouseover', function (event) {
      if ($_a3izpgldjh8lz1fy.name(event.target()) === 'table' || $_6z48nsowjh8lz25j.closest(event.target(), 'table', isRoot)) {
        hoverTable = $_a3izpgldjh8lz1fy.name(event.target()) === 'table' ? Option.some(event.target()) : $_fiygddlhjh8lz1g7.ancestor(event.target(), 'table', isRoot);
        hoverTable.each(function (ht) {
          $_b9z1gin7jh8lz1tj.refresh(wire, ht, hdirection, direction);
        });
      } else if ($_brbde9lgjh8lz1g4.inBody(event.target())) {
        $_b9z1gin7jh8lz1tj.destroy(wire);
      }
    });
    var destroy = function () {
      mousedown.unbind();
      mouseover.unbind();
      resizing.destroy();
      $_b9z1gin7jh8lz1tj.destroy(wire);
    };
    var refresh = function (tbl) {
      $_b9z1gin7jh8lz1tj.refresh(wire, tbl, hdirection, direction);
    };
    var events = $_cmo273ogjh8lz22b.create({
      adjustHeight: Event([
        'table',
        'delta',
        'row'
      ]),
      adjustWidth: Event([
        'table',
        'delta',
        'column'
      ]),
      startAdjust: Event([])
    });
    return {
      destroy: destroy,
      refresh: refresh,
      on: resizing.on,
      off: resizing.off,
      hideBars: $_bgyjg9kejh8lz1ax.curry($_b9z1gin7jh8lz1tj.hide, wire),
      showBars: $_bgyjg9kejh8lz1ax.curry($_b9z1gin7jh8lz1tj.show, wire),
      events: events.registry
    };
  }

  function TableResize (wire, vdirection) {
    var hdirection = $_sdnutmojh8lz1p3.height;
    var manager = BarManager(wire, vdirection, hdirection);
    var events = $_cmo273ogjh8lz22b.create({
      beforeResize: Event(['table']),
      afterResize: Event(['table']),
      startDrag: Event([])
    });
    manager.events.adjustHeight.bind(function (event) {
      events.trigger.beforeResize(event.table());
      var delta = hdirection.delta(event.delta(), event.table());
      $_7x5dznnjh8lz1wh.adjustHeight(event.table(), delta, event.row(), hdirection);
      events.trigger.afterResize(event.table());
    });
    manager.events.startAdjust.bind(function (event) {
      events.trigger.startDrag();
    });
    manager.events.adjustWidth.bind(function (event) {
      events.trigger.beforeResize(event.table());
      var delta = vdirection.delta(event.delta(), event.table());
      $_7x5dznnjh8lz1wh.adjustWidth(event.table(), delta, event.column(), vdirection);
      events.trigger.afterResize(event.table());
    });
    return {
      on: manager.on,
      off: manager.off,
      hideBars: manager.hideBars,
      showBars: manager.showBars,
      destroy: manager.destroy,
      events: events.registry
    };
  }

  var createContainer = function () {
    var container = $_6vo9a4krjh8lz1do.fromTag('div');
    $_3ory84lljh8lz1gx.setAll(container, {
      position: 'static',
      height: '0',
      width: '0',
      padding: '0',
      margin: '0',
      border: '0'
    });
    $_6qqu1alnjh8lz1hg.append($_brbde9lgjh8lz1g4.body(), container);
    return container;
  };
  var get$8 = function (editor, container) {
    return editor.inline ? $_bdbkjodjh8lz21o.body(getBody$1(editor), createContainer()) : $_bdbkjodjh8lz21o.only($_6vo9a4krjh8lz1do.fromDom(editor.getDoc()));
  };
  var remove$6 = function (editor, wire) {
    if (editor.inline) {
      $_f2hny0lojh8lz1hi.remove(wire.parent());
    }
  };
  var $_848v6boxjh8lz25l = {
    get: get$8,
    remove: remove$6
  };

  var ResizeHandler = function (editor) {
    var selectionRng = Option.none();
    var resize = Option.none();
    var wire = Option.none();
    var percentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
    var startW, startRawW;
    var isTable = function (elm) {
      return elm.nodeName === 'TABLE';
    };
    var getRawWidth = function (elm) {
      return editor.dom.getStyle(elm, 'width') || editor.dom.getAttrib(elm, 'width');
    };
    var lazyResize = function () {
      return resize;
    };
    var lazyWire = function () {
      return wire.getOr($_bdbkjodjh8lz21o.only($_6vo9a4krjh8lz1do.fromDom(editor.getBody())));
    };
    var destroy = function () {
      resize.each(function (sz) {
        sz.destroy();
      });
      wire.each(function (w) {
        $_848v6boxjh8lz25l.remove(editor, w);
      });
    };
    editor.on('init', function () {
      var direction = TableDirection($_fe2yjsnvjh8lz1y8.directionAt);
      var rawWire = $_848v6boxjh8lz25l.get(editor);
      wire = Option.some(rawWire);
      if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
        var sz = TableResize(rawWire, direction);
        sz.on();
        sz.events.startDrag.bind(function (event) {
          selectionRng = Option.some(editor.selection.getRng());
        });
        sz.events.beforeResize.bind(function (event) {
          var rawTable = event.table().dom();
          fireObjectResizeStart(editor, rawTable, getPixelWidth$1(rawTable), getPixelHeight(rawTable));
        });
        sz.events.afterResize.bind(function (event) {
          var table = event.table();
          var rawTable = table.dom();
          removeDataStyle(table);
          selectionRng.each(function (rng) {
            editor.selection.setRng(rng);
            editor.focus();
          });
          fireObjectResized(editor, rawTable, getPixelWidth$1(rawTable), getPixelHeight(rawTable));
          editor.undoManager.add();
        });
        resize = Option.some(sz);
      }
    });
    editor.on('ObjectResizeStart', function (e) {
      var targetElm = e.target;
      if (isTable(targetElm)) {
        startW = e.width;
        startRawW = getRawWidth(targetElm);
      }
    });
    editor.on('ObjectResized', function (e) {
      var targetElm = e.target;
      if (isTable(targetElm)) {
        var table = targetElm;
        if (percentageBasedSizeRegex.test(startRawW)) {
          var percentW = parseFloat(percentageBasedSizeRegex.exec(startRawW)[1]);
          var targetPercentW = e.width * percentW / startW;
          editor.dom.setStyle(table, 'width', targetPercentW + '%');
        } else {
          var newCellSizes_1 = [];
          global$2.each(table.rows, function (row) {
            global$2.each(row.cells, function (cell) {
              var width = editor.dom.getStyle(cell, 'width', true);
              newCellSizes_1.push({
                cell: cell,
                width: width
              });
            });
          });
          global$2.each(newCellSizes_1, function (newCellSize) {
            editor.dom.setStyle(newCellSize.cell, 'width', newCellSize.width);
            editor.dom.setAttrib(newCellSize.cell, 'width', null);
          });
        }
      }
    });
    return {
      lazyResize: lazyResize,
      lazyWire: lazyWire,
      destroy: destroy
    };
  };

  var none$2 = function (current) {
    return folder$1(function (n, f, m, l) {
      return n(current);
    });
  };
  var first$5 = function (current) {
    return folder$1(function (n, f, m, l) {
      return f(current);
    });
  };
  var middle$1 = function (current, target) {
    return folder$1(function (n, f, m, l) {
      return m(current, target);
    });
  };
  var last$4 = function (current) {
    return folder$1(function (n, f, m, l) {
      return l(current);
    });
  };
  var folder$1 = function (fold) {
    return { fold: fold };
  };
  var $_1x3ywmp0jh8lz26n = {
    none: none$2,
    first: first$5,
    middle: middle$1,
    last: last$4
  };

  var detect$4 = function (current, isRoot) {
    return $_ee8pmfkojh8lz1ch.table(current, isRoot).bind(function (table) {
      var all = $_ee8pmfkojh8lz1ch.cells(table);
      var index = $_6b0spykcjh8lz1ao.findIndex(all, function (x) {
        return $_2eywnlkvjh8lz1e8.eq(current, x);
      });
      return index.map(function (ind) {
        return {
          index: $_bgyjg9kejh8lz1ax.constant(ind),
          all: $_bgyjg9kejh8lz1ax.constant(all)
        };
      });
    });
  };
  var next = function (current, isRoot) {
    var detection = detect$4(current, isRoot);
    return detection.fold(function () {
      return $_1x3ywmp0jh8lz26n.none(current);
    }, function (info) {
      return info.index() + 1 < info.all().length ? $_1x3ywmp0jh8lz26n.middle(current, info.all()[info.index() + 1]) : $_1x3ywmp0jh8lz26n.last(current);
    });
  };
  var prev = function (current, isRoot) {
    var detection = detect$4(current, isRoot);
    return detection.fold(function () {
      return $_1x3ywmp0jh8lz26n.none();
    }, function (info) {
      return info.index() - 1 >= 0 ? $_1x3ywmp0jh8lz26n.middle(current, info.all()[info.index() - 1]) : $_1x3ywmp0jh8lz26n.first(current);
    });
  };
  var $_4luh0iozjh8lz26g = {
    next: next,
    prev: prev
  };

  var adt = $_659si2mejh8lz1n9.generate([
    { 'before': ['element'] },
    {
      'on': [
        'element',
        'offset'
      ]
    },
    { after: ['element'] }
  ]);
  var cata$1 = function (subject, onBefore, onOn, onAfter) {
    return subject.fold(onBefore, onOn, onAfter);
  };
  var getStart = function (situ) {
    return situ.fold($_bgyjg9kejh8lz1ax.identity, $_bgyjg9kejh8lz1ax.identity, $_bgyjg9kejh8lz1ax.identity);
  };
  var $_eviq86p2jh8lz26w = {
    before: adt.before,
    on: adt.on,
    after: adt.after,
    cata: cata$1,
    getStart: getStart
  };

  var type$2 = $_659si2mejh8lz1n9.generate([
    { domRange: ['rng'] },
    {
      relative: [
        'startSitu',
        'finishSitu'
      ]
    },
    {
      exact: [
        'start',
        'soffset',
        'finish',
        'foffset'
      ]
    }
  ]);
  var range$2 = $_d2ojjnkijh8lz1bv.immutable('start', 'soffset', 'finish', 'foffset');
  var exactFromRange = function (simRange) {
    return type$2.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  };
  var getStart$1 = function (selection) {
    return selection.match({
      domRange: function (rng) {
        return $_6vo9a4krjh8lz1do.fromDom(rng.startContainer);
      },
      relative: function (startSitu, finishSitu) {
        return $_eviq86p2jh8lz26w.getStart(startSitu);
      },
      exact: function (start, soffset, finish, foffset) {
        return start;
      }
    });
  };
  var getWin = function (selection) {
    var start = getStart$1(selection);
    return $_4hc7u2ktjh8lz1dv.defaultView(start);
  };
  var $_8ehldap1jh8lz26p = {
    domRange: type$2.domRange,
    relative: type$2.relative,
    exact: type$2.exact,
    exactFromRange: exactFromRange,
    range: range$2,
    getWin: getWin
  };

  var makeRange = function (start, soffset, finish, foffset) {
    var doc = $_4hc7u2ktjh8lz1dv.owner(start);
    var rng = doc.dom().createRange();
    rng.setStart(start.dom(), soffset);
    rng.setEnd(finish.dom(), foffset);
    return rng;
  };
  var commonAncestorContainer = function (start, soffset, finish, foffset) {
    var r = makeRange(start, soffset, finish, foffset);
    return $_6vo9a4krjh8lz1do.fromDom(r.commonAncestorContainer);
  };
  var after$2 = function (start, soffset, finish, foffset) {
    var r = makeRange(start, soffset, finish, foffset);
    var same = $_2eywnlkvjh8lz1e8.eq(start, finish) && soffset === foffset;
    return r.collapsed && !same;
  };
  var $_2h2fhyp4jh8lz27b = {
    after: after$2,
    commonAncestorContainer: commonAncestorContainer
  };

  var fromElements = function (elements, scope) {
    var doc = scope || document;
    var fragment = doc.createDocumentFragment();
    $_6b0spykcjh8lz1ao.each(elements, function (element) {
      fragment.appendChild(element.dom());
    });
    return $_6vo9a4krjh8lz1do.fromDom(fragment);
  };
  var $_7hriclp5jh8lz27d = { fromElements: fromElements };

  var selectNodeContents = function (win, element) {
    var rng = win.document.createRange();
    selectNodeContentsUsing(rng, element);
    return rng;
  };
  var selectNodeContentsUsing = function (rng, element) {
    rng.selectNodeContents(element.dom());
  };
  var isWithin$1 = function (outerRange, innerRange) {
    return innerRange.compareBoundaryPoints(outerRange.END_TO_START, outerRange) < 1 && innerRange.compareBoundaryPoints(outerRange.START_TO_END, outerRange) > -1;
  };
  var create$1 = function (win) {
    return win.document.createRange();
  };
  var setStart = function (rng, situ) {
    situ.fold(function (e) {
      rng.setStartBefore(e.dom());
    }, function (e, o) {
      rng.setStart(e.dom(), o);
    }, function (e) {
      rng.setStartAfter(e.dom());
    });
  };
  var setFinish = function (rng, situ) {
    situ.fold(function (e) {
      rng.setEndBefore(e.dom());
    }, function (e, o) {
      rng.setEnd(e.dom(), o);
    }, function (e) {
      rng.setEndAfter(e.dom());
    });
  };
  var replaceWith = function (rng, fragment) {
    deleteContents(rng);
    rng.insertNode(fragment.dom());
  };
  var relativeToNative = function (win, startSitu, finishSitu) {
    var range = win.document.createRange();
    setStart(range, startSitu);
    setFinish(range, finishSitu);
    return range;
  };
  var exactToNative = function (win, start, soffset, finish, foffset) {
    var rng = win.document.createRange();
    rng.setStart(start.dom(), soffset);
    rng.setEnd(finish.dom(), foffset);
    return rng;
  };
  var deleteContents = function (rng) {
    rng.deleteContents();
  };
  var cloneFragment = function (rng) {
    var fragment = rng.cloneContents();
    return $_6vo9a4krjh8lz1do.fromDom(fragment);
  };
  var toRect = function (rect) {
    return {
      left: $_bgyjg9kejh8lz1ax.constant(rect.left),
      top: $_bgyjg9kejh8lz1ax.constant(rect.top),
      right: $_bgyjg9kejh8lz1ax.constant(rect.right),
      bottom: $_bgyjg9kejh8lz1ax.constant(rect.bottom),
      width: $_bgyjg9kejh8lz1ax.constant(rect.width),
      height: $_bgyjg9kejh8lz1ax.constant(rect.height)
    };
  };
  var getFirstRect = function (rng) {
    var rects = rng.getClientRects();
    var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
    return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  };
  var getBounds$1 = function (rng) {
    var rect = rng.getBoundingClientRect();
    return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  };
  var toString = function (rng) {
    return rng.toString();
  };
  var $_4fhpzqp6jh8lz27h = {
    create: create$1,
    replaceWith: replaceWith,
    selectNodeContents: selectNodeContents,
    selectNodeContentsUsing: selectNodeContentsUsing,
    relativeToNative: relativeToNative,
    exactToNative: exactToNative,
    deleteContents: deleteContents,
    cloneFragment: cloneFragment,
    getFirstRect: getFirstRect,
    getBounds: getBounds$1,
    isWithin: isWithin$1,
    toString: toString
  };

  var adt$1 = $_659si2mejh8lz1n9.generate([
    {
      ltr: [
        'start',
        'soffset',
        'finish',
        'foffset'
      ]
    },
    {
      rtl: [
        'start',
        'soffset',
        'finish',
        'foffset'
      ]
    }
  ]);
  var fromRange = function (win, type, range) {
    return type($_6vo9a4krjh8lz1do.fromDom(range.startContainer), range.startOffset, $_6vo9a4krjh8lz1do.fromDom(range.endContainer), range.endOffset);
  };
  var getRanges = function (win, selection) {
    return selection.match({
      domRange: function (rng) {
        return {
          ltr: $_bgyjg9kejh8lz1ax.constant(rng),
          rtl: Option.none
        };
      },
      relative: function (startSitu, finishSitu) {
        return {
          ltr: $_aela9fl1jh8lz1es.cached(function () {
            return $_4fhpzqp6jh8lz27h.relativeToNative(win, startSitu, finishSitu);
          }),
          rtl: $_aela9fl1jh8lz1es.cached(function () {
            return Option.some($_4fhpzqp6jh8lz27h.relativeToNative(win, finishSitu, startSitu));
          })
        };
      },
      exact: function (start, soffset, finish, foffset) {
        return {
          ltr: $_aela9fl1jh8lz1es.cached(function () {
            return $_4fhpzqp6jh8lz27h.exactToNative(win, start, soffset, finish, foffset);
          }),
          rtl: $_aela9fl1jh8lz1es.cached(function () {
            return Option.some($_4fhpzqp6jh8lz27h.exactToNative(win, finish, foffset, start, soffset));
          })
        };
      }
    });
  };
  var doDiagnose = function (win, ranges) {
    var rng = ranges.ltr();
    if (rng.collapsed) {
      var reversed = ranges.rtl().filter(function (rev) {
        return rev.collapsed === false;
      });
      return reversed.map(function (rev) {
        return adt$1.rtl($_6vo9a4krjh8lz1do.fromDom(rev.endContainer), rev.endOffset, $_6vo9a4krjh8lz1do.fromDom(rev.startContainer), rev.startOffset);
      }).getOrThunk(function () {
        return fromRange(win, adt$1.ltr, rng);
      });
    } else {
      return fromRange(win, adt$1.ltr, rng);
    }
  };
  var diagnose = function (win, selection) {
    var ranges = getRanges(win, selection);
    return doDiagnose(win, ranges);
  };
  var asLtrRange = function (win, selection) {
    var diagnosis = diagnose(win, selection);
    return diagnosis.match({
      ltr: function (start, soffset, finish, foffset) {
        var rng = win.document.createRange();
        rng.setStart(start.dom(), soffset);
        rng.setEnd(finish.dom(), foffset);
        return rng;
      },
      rtl: function (start, soffset, finish, foffset) {
        var rng = win.document.createRange();
        rng.setStart(finish.dom(), foffset);
        rng.setEnd(start.dom(), soffset);
        return rng;
      }
    });
  };
  var $_dcfxf3p7jh8lz27p = {
    ltr: adt$1.ltr,
    rtl: adt$1.rtl,
    diagnose: diagnose,
    asLtrRange: asLtrRange
  };

  var searchForPoint = function (rectForOffset, x, y, maxX, length) {
    if (length === 0)
      return 0;
    else if (x === maxX)
      return length - 1;
    var xDelta = maxX;
    for (var i = 1; i < length; i++) {
      var rect = rectForOffset(i);
      var curDeltaX = Math.abs(x - rect.left);
      if (y > rect.bottom) {
      } else if (y < rect.top || curDeltaX > xDelta) {
        return i - 1;
      } else {
        xDelta = curDeltaX;
      }
    }
    return 0;
  };
  var inRect = function (rect, x, y) {
    return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  };
  var $_audrxxpajh8lz28a = {
    inRect: inRect,
    searchForPoint: searchForPoint
  };

  var locateOffset = function (doc, textnode, x, y, rect) {
    var rangeForOffset = function (offset) {
      var r = doc.dom().createRange();
      r.setStart(textnode.dom(), offset);
      r.collapse(true);
      return r;
    };
    var rectForOffset = function (offset) {
      var r = rangeForOffset(offset);
      return r.getBoundingClientRect();
    };
    var length = $_bri5anlujh8lz1in.get(textnode).length;
    var offset = $_audrxxpajh8lz28a.searchForPoint(rectForOffset, x, y, rect.right, length);
    return rangeForOffset(offset);
  };
  var locate = function (doc, node, x, y) {
    var r = doc.dom().createRange();
    r.selectNode(node.dom());
    var rects = r.getClientRects();
    var foundRect = $_clgylhn2jh8lz1sg.findMap(rects, function (rect) {
      return $_audrxxpajh8lz28a.inRect(rect, x, y) ? Option.some(rect) : Option.none();
    });
    return foundRect.map(function (rect) {
      return locateOffset(doc, node, x, y, rect);
    });
  };
  var $_g2tw93pbjh8lz28c = { locate: locate };

  var searchInChildren = function (doc, node, x, y) {
    var r = doc.dom().createRange();
    var nodes = $_4hc7u2ktjh8lz1dv.children(node);
    return $_clgylhn2jh8lz1sg.findMap(nodes, function (n) {
      r.selectNode(n.dom());
      return $_audrxxpajh8lz28a.inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Option.none();
    });
  };
  var locateNode = function (doc, node, x, y) {
    var locator = $_a3izpgldjh8lz1fy.isText(node) ? $_g2tw93pbjh8lz28c.locate : searchInChildren;
    return locator(doc, node, x, y);
  };
  var locate$1 = function (doc, node, x, y) {
    var r = doc.dom().createRange();
    r.selectNode(node.dom());
    var rect = r.getBoundingClientRect();
    var boundedX = Math.max(rect.left, Math.min(rect.right, x));
    var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
    return locateNode(doc, node, boundedX, boundedY);
  };
  var $_31ujrcp9jh8lz285 = { locate: locate$1 };

  var COLLAPSE_TO_LEFT = true;
  var COLLAPSE_TO_RIGHT = false;
  var getCollapseDirection = function (rect, x) {
    return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  };
  var createCollapsedNode = function (doc, target, collapseDirection) {
    var r = doc.dom().createRange();
    r.selectNode(target.dom());
    r.collapse(collapseDirection);
    return r;
  };
  var locateInElement = function (doc, node, x) {
    var cursorRange = doc.dom().createRange();
    cursorRange.selectNode(node.dom());
    var rect = cursorRange.getBoundingClientRect();
    var collapseDirection = getCollapseDirection(rect, x);
    var f = collapseDirection === COLLAPSE_TO_LEFT ? $_fpdn73lsjh8lz1ig.first : $_fpdn73lsjh8lz1ig.last;
    return f(node).map(function (target) {
      return createCollapsedNode(doc, target, collapseDirection);
    });
  };
  var locateInEmpty = function (doc, node, x) {
    var rect = node.dom().getBoundingClientRect();
    var collapseDirection = getCollapseDirection(rect, x);
    return Option.some(createCollapsedNode(doc, node, collapseDirection));
  };
  var search = function (doc, node, x) {
    var f = $_4hc7u2ktjh8lz1dv.children(node).length === 0 ? locateInEmpty : locateInElement;
    return f(doc, node, x);
  };
  var $_d2lo8npcjh8lz28i = { search: search };

  var caretPositionFromPoint = function (doc, x, y) {
    return Option.from(doc.dom().caretPositionFromPoint(x, y)).bind(function (pos) {
      if (pos.offsetNode === null)
        return Option.none();
      var r = doc.dom().createRange();
      r.setStart(pos.offsetNode, pos.offset);
      r.collapse();
      return Option.some(r);
    });
  };
  var caretRangeFromPoint = function (doc, x, y) {
    return Option.from(doc.dom().caretRangeFromPoint(x, y));
  };
  var searchTextNodes = function (doc, node, x, y) {
    var r = doc.dom().createRange();
    r.selectNode(node.dom());
    var rect = r.getBoundingClientRect();
    var boundedX = Math.max(rect.left, Math.min(rect.right, x));
    var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
    return $_31ujrcp9jh8lz285.locate(doc, node, boundedX, boundedY);
  };
  var searchFromPoint = function (doc, x, y) {
    return $_6vo9a4krjh8lz1do.fromPoint(doc, x, y).bind(function (elem) {
      var fallback = function () {
        return $_d2lo8npcjh8lz28i.search(doc, elem, x);
      };
      return $_4hc7u2ktjh8lz1dv.children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
    });
  };
  var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
  var fromPoint$1 = function (win, x, y) {
    var doc = $_6vo9a4krjh8lz1do.fromDom(win.document);
    return availableSearch(doc, x, y).map(function (rng) {
      return $_8ehldap1jh8lz26p.range($_6vo9a4krjh8lz1do.fromDom(rng.startContainer), rng.startOffset, $_6vo9a4krjh8lz1do.fromDom(rng.endContainer), rng.endOffset);
    });
  };
  var $_27o8otp8jh8lz27z = { fromPoint: fromPoint$1 };

  var withinContainer = function (win, ancestor, outerRange, selector) {
    var innerRange = $_4fhpzqp6jh8lz27h.create(win);
    var self = $_62so4qkqjh8lz1di.is(ancestor, selector) ? [ancestor] : [];
    var elements = self.concat($_coxlualejh8lz1fz.descendants(ancestor, selector));
    return $_6b0spykcjh8lz1ao.filter(elements, function (elem) {
      $_4fhpzqp6jh8lz27h.selectNodeContentsUsing(innerRange, elem);
      return $_4fhpzqp6jh8lz27h.isWithin(outerRange, innerRange);
    });
  };
  var find$3 = function (win, selection, selector) {
    var outerRange = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    var ancestor = $_6vo9a4krjh8lz1do.fromDom(outerRange.commonAncestorContainer);
    return $_a3izpgldjh8lz1fy.isElement(ancestor) ? withinContainer(win, ancestor, outerRange, selector) : [];
  };
  var $_fia266pdjh8lz28m = { find: find$3 };

  var beforeSpecial = function (element, offset) {
    var name = $_a3izpgldjh8lz1fy.name(element);
    if ('input' === name)
      return $_eviq86p2jh8lz26w.after(element);
    else if (!$_6b0spykcjh8lz1ao.contains([
        'br',
        'img'
      ], name))
      return $_eviq86p2jh8lz26w.on(element, offset);
    else
      return offset === 0 ? $_eviq86p2jh8lz26w.before(element) : $_eviq86p2jh8lz26w.after(element);
  };
  var preprocessRelative = function (startSitu, finishSitu) {
    var start = startSitu.fold($_eviq86p2jh8lz26w.before, beforeSpecial, $_eviq86p2jh8lz26w.after);
    var finish = finishSitu.fold($_eviq86p2jh8lz26w.before, beforeSpecial, $_eviq86p2jh8lz26w.after);
    return $_8ehldap1jh8lz26p.relative(start, finish);
  };
  var preprocessExact = function (start, soffset, finish, foffset) {
    var startSitu = beforeSpecial(start, soffset);
    var finishSitu = beforeSpecial(finish, foffset);
    return $_8ehldap1jh8lz26p.relative(startSitu, finishSitu);
  };
  var preprocess = function (selection) {
    return selection.match({
      domRange: function (rng) {
        var start = $_6vo9a4krjh8lz1do.fromDom(rng.startContainer);
        var finish = $_6vo9a4krjh8lz1do.fromDom(rng.endContainer);
        return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
      },
      relative: preprocessRelative,
      exact: preprocessExact
    });
  };
  var $_dvaskhpejh8lz28q = {
    beforeSpecial: beforeSpecial,
    preprocess: preprocess,
    preprocessRelative: preprocessRelative,
    preprocessExact: preprocessExact
  };

  var doSetNativeRange = function (win, rng) {
    Option.from(win.getSelection()).each(function (selection) {
      selection.removeAllRanges();
      selection.addRange(rng);
    });
  };
  var doSetRange = function (win, start, soffset, finish, foffset) {
    var rng = $_4fhpzqp6jh8lz27h.exactToNative(win, start, soffset, finish, foffset);
    doSetNativeRange(win, rng);
  };
  var findWithin = function (win, selection, selector) {
    return $_fia266pdjh8lz28m.find(win, selection, selector);
  };
  var setRangeFromRelative = function (win, relative) {
    return $_dcfxf3p7jh8lz27p.diagnose(win, relative).match({
      ltr: function (start, soffset, finish, foffset) {
        doSetRange(win, start, soffset, finish, foffset);
      },
      rtl: function (start, soffset, finish, foffset) {
        var selection = win.getSelection();
        if (selection.setBaseAndExtent) {
          selection.setBaseAndExtent(start.dom(), soffset, finish.dom(), foffset);
        } else if (selection.extend) {
          selection.collapse(start.dom(), soffset);
          selection.extend(finish.dom(), foffset);
        } else {
          doSetRange(win, finish, foffset, start, soffset);
        }
      }
    });
  };
  var setExact = function (win, start, soffset, finish, foffset) {
    var relative = $_dvaskhpejh8lz28q.preprocessExact(start, soffset, finish, foffset);
    setRangeFromRelative(win, relative);
  };
  var setRelative = function (win, startSitu, finishSitu) {
    var relative = $_dvaskhpejh8lz28q.preprocessRelative(startSitu, finishSitu);
    setRangeFromRelative(win, relative);
  };
  var toNative = function (selection) {
    var win = $_8ehldap1jh8lz26p.getWin(selection).dom();
    var getDomRange = function (start, soffset, finish, foffset) {
      return $_4fhpzqp6jh8lz27h.exactToNative(win, start, soffset, finish, foffset);
    };
    var filtered = $_dvaskhpejh8lz28q.preprocess(selection);
    return $_dcfxf3p7jh8lz27p.diagnose(win, filtered).match({
      ltr: getDomRange,
      rtl: getDomRange
    });
  };
  var readRange = function (selection) {
    if (selection.rangeCount > 0) {
      var firstRng = selection.getRangeAt(0);
      var lastRng = selection.getRangeAt(selection.rangeCount - 1);
      return Option.some($_8ehldap1jh8lz26p.range($_6vo9a4krjh8lz1do.fromDom(firstRng.startContainer), firstRng.startOffset, $_6vo9a4krjh8lz1do.fromDom(lastRng.endContainer), lastRng.endOffset));
    } else {
      return Option.none();
    }
  };
  var doGetExact = function (selection) {
    var anchorNode = $_6vo9a4krjh8lz1do.fromDom(selection.anchorNode);
    var focusNode = $_6vo9a4krjh8lz1do.fromDom(selection.focusNode);
    return $_2h2fhyp4jh8lz27b.after(anchorNode, selection.anchorOffset, focusNode, selection.focusOffset) ? Option.some($_8ehldap1jh8lz26p.range($_6vo9a4krjh8lz1do.fromDom(selection.anchorNode), selection.anchorOffset, $_6vo9a4krjh8lz1do.fromDom(selection.focusNode), selection.focusOffset)) : readRange(selection);
  };
  var setToElement = function (win, element) {
    var rng = $_4fhpzqp6jh8lz27h.selectNodeContents(win, element);
    doSetNativeRange(win, rng);
  };
  var forElement = function (win, element) {
    var rng = $_4fhpzqp6jh8lz27h.selectNodeContents(win, element);
    return $_8ehldap1jh8lz26p.range($_6vo9a4krjh8lz1do.fromDom(rng.startContainer), rng.startOffset, $_6vo9a4krjh8lz1do.fromDom(rng.endContainer), rng.endOffset);
  };
  var getExact = function (win) {
    return Option.from(win.getSelection()).filter(function (sel) {
      return sel.rangeCount > 0;
    }).bind(doGetExact);
  };
  var get$9 = function (win) {
    return getExact(win).map(function (range) {
      return $_8ehldap1jh8lz26p.exact(range.start(), range.soffset(), range.finish(), range.foffset());
    });
  };
  var getFirstRect$1 = function (win, selection) {
    var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    return $_4fhpzqp6jh8lz27h.getFirstRect(rng);
  };
  var getBounds$2 = function (win, selection) {
    var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    return $_4fhpzqp6jh8lz27h.getBounds(rng);
  };
  var getAtPoint = function (win, x, y) {
    return $_27o8otp8jh8lz27z.fromPoint(win, x, y);
  };
  var getAsString = function (win, selection) {
    var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    return $_4fhpzqp6jh8lz27h.toString(rng);
  };
  var clear$1 = function (win) {
    var selection = win.getSelection();
    selection.removeAllRanges();
  };
  var clone$2 = function (win, selection) {
    var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    return $_4fhpzqp6jh8lz27h.cloneFragment(rng);
  };
  var replace$1 = function (win, selection, elements) {
    var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    var fragment = $_7hriclp5jh8lz27d.fromElements(elements, win.document);
    $_4fhpzqp6jh8lz27h.replaceWith(rng, fragment);
  };
  var deleteAt = function (win, selection) {
    var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    $_4fhpzqp6jh8lz27h.deleteContents(rng);
  };
  var isCollapsed = function (start, soffset, finish, foffset) {
    return $_2eywnlkvjh8lz1e8.eq(start, finish) && soffset === foffset;
  };
  var $_3efg7cp3jh8lz272 = {
    setExact: setExact,
    getExact: getExact,
    get: get$9,
    setRelative: setRelative,
    toNative: toNative,
    setToElement: setToElement,
    clear: clear$1,
    clone: clone$2,
    replace: replace$1,
    deleteAt: deleteAt,
    forElement: forElement,
    getFirstRect: getFirstRect$1,
    getBounds: getBounds$2,
    getAtPoint: getAtPoint,
    findWithin: findWithin,
    getAsString: getAsString,
    isCollapsed: isCollapsed
  };

  var global$4 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var forward = function (editor, isRoot, cell, lazyWire) {
    return go(editor, isRoot, $_4luh0iozjh8lz26g.next(cell), lazyWire);
  };
  var backward = function (editor, isRoot, cell, lazyWire) {
    return go(editor, isRoot, $_4luh0iozjh8lz26g.prev(cell), lazyWire);
  };
  var getCellFirstCursorPosition = function (editor, cell) {
    var selection = $_8ehldap1jh8lz26p.exact(cell, 0, cell, 0);
    return $_3efg7cp3jh8lz272.toNative(selection);
  };
  var getNewRowCursorPosition = function (editor, table) {
    var rows = $_coxlualejh8lz1fz.descendants(table, 'tr');
    return $_6b0spykcjh8lz1ao.last(rows).bind(function (last) {
      return $_fiygddlhjh8lz1g7.descendant(last, 'td,th').map(function (first) {
        return getCellFirstCursorPosition(editor, first);
      });
    });
  };
  var go = function (editor, isRoot, cell, actions, lazyWire) {
    return cell.fold(Option.none, Option.none, function (current, next) {
      return $_fpdn73lsjh8lz1ig.first(next).map(function (cell) {
        return getCellFirstCursorPosition(editor, cell);
      });
    }, function (current) {
      return $_ee8pmfkojh8lz1ch.table(current, isRoot).bind(function (table) {
        var targets = $_3xfj7olxjh8lz1j2.noMenu(current);
        editor.undoManager.transact(function () {
          actions.insertRowsAfter(table, targets);
        });
        return getNewRowCursorPosition(editor, table);
      });
    });
  };
  var rootElements = [
    'table',
    'li',
    'dl'
  ];
  var handle$1 = function (event, editor, actions, lazyWire) {
    if (event.keyCode === global$4.TAB) {
      var body_1 = getBody$1(editor);
      var isRoot_1 = function (element) {
        var name = $_a3izpgldjh8lz1fy.name(element);
        return $_2eywnlkvjh8lz1e8.eq(element, body_1) || $_6b0spykcjh8lz1ao.contains(rootElements, name);
      };
      var rng = editor.selection.getRng();
      if (rng.collapsed) {
        var start = $_6vo9a4krjh8lz1do.fromDom(rng.startContainer);
        $_ee8pmfkojh8lz1ch.cell(start, isRoot_1).each(function (cell) {
          event.preventDefault();
          var navigation = event.shiftKey ? backward : forward;
          var rng = navigation(editor, isRoot_1, cell, actions, lazyWire);
          rng.each(function (range) {
            editor.selection.setRng(range);
          });
        });
      }
    }
  };
  var $_4jcvbhoyjh8lz25x = { handle: handle$1 };

  var response = $_d2ojjnkijh8lz1bv.immutable('selection', 'kill');
  var $_8xnxafpijh8lz29y = { response: response };

  var isKey = function (key) {
    return function (keycode) {
      return keycode === key;
    };
  };
  var isUp = isKey(38);
  var isDown = isKey(40);
  var isNavigation = function (keycode) {
    return keycode >= 37 && keycode <= 40;
  };
  var $_5bctktpjjh8lz2a1 = {
    ltr: {
      isBackward: isKey(37),
      isForward: isKey(39)
    },
    rtl: {
      isBackward: isKey(39),
      isForward: isKey(37)
    },
    isUp: isUp,
    isDown: isDown,
    isNavigation: isNavigation
  };

  var convertToRange = function (win, selection) {
    var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, selection);
    return {
      start: $_bgyjg9kejh8lz1ax.constant($_6vo9a4krjh8lz1do.fromDom(rng.startContainer)),
      soffset: $_bgyjg9kejh8lz1ax.constant(rng.startOffset),
      finish: $_bgyjg9kejh8lz1ax.constant($_6vo9a4krjh8lz1do.fromDom(rng.endContainer)),
      foffset: $_bgyjg9kejh8lz1ax.constant(rng.endOffset)
    };
  };
  var makeSitus = function (start, soffset, finish, foffset) {
    return {
      start: $_bgyjg9kejh8lz1ax.constant($_eviq86p2jh8lz26w.on(start, soffset)),
      finish: $_bgyjg9kejh8lz1ax.constant($_eviq86p2jh8lz26w.on(finish, foffset))
    };
  };
  var $_45u5rqpljh8lz2ah = {
    convertToRange: convertToRange,
    makeSitus: makeSitus
  };

  var isSafari = $_a6om0dl0jh8lz1ep.detect().browser.isSafari();
  var get$10 = function (_doc) {
    var doc = _doc !== undefined ? _doc.dom() : document;
    var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
    var y = doc.body.scrollTop || doc.documentElement.scrollTop;
    return r(x, y);
  };
  var to = function (x, y, _doc) {
    var doc = _doc !== undefined ? _doc.dom() : document;
    var win = doc.defaultView;
    win.scrollTo(x, y);
  };
  var by = function (x, y, _doc) {
    var doc = _doc !== undefined ? _doc.dom() : document;
    var win = doc.defaultView;
    win.scrollBy(x, y);
  };
  var setToElement$1 = function (win, element) {
    var pos = $_6xc5idmpjh8lz1ph.absolute(element);
    var doc = $_6vo9a4krjh8lz1do.fromDom(win.document);
    to(pos.left(), pos.top(), doc);
  };
  var preserve$1 = function (doc, f) {
    var before = get$10(doc);
    f();
    var after = get$10(doc);
    if (before.top() !== after.top() || before.left() !== after.left()) {
      to(before.left(), before.top(), doc);
    }
  };
  var capture$2 = function (doc) {
    var previous = Option.none();
    var save = function () {
      previous = Option.some(get$10(doc));
    };
    var restore = function () {
      previous.each(function (p) {
        to(p.left(), p.top(), doc);
      });
    };
    save();
    return {
      save: save,
      restore: restore
    };
  };
  var intoView = function (element, alignToTop) {
    if (isSafari && $_d1kyz8kfjh8lz1az.isFunction(element.dom().scrollIntoViewIfNeeded)) {
      element.dom().scrollIntoViewIfNeeded(false);
    } else {
      element.dom().scrollIntoView(alignToTop);
    }
  };
  var intoViewIfNeeded = function (element, container) {
    var containerBox = container.dom().getBoundingClientRect();
    var elementBox = element.dom().getBoundingClientRect();
    if (elementBox.top < containerBox.top) {
      intoView(element, true);
    } else if (elementBox.bottom > containerBox.bottom) {
      intoView(element, false);
    }
  };
  var scrollBarWidth = function () {
    var scrollDiv = $_6vo9a4krjh8lz1do.fromHtml('<div style="width: 100px; height: 100px; overflow: scroll; position: absolute; top: -9999px;"></div>');
    $_6qqu1alnjh8lz1hg.after($_brbde9lgjh8lz1g4.body(), scrollDiv);
    var w = scrollDiv.dom().offsetWidth - scrollDiv.dom().clientWidth;
    $_f2hny0lojh8lz1hi.remove(scrollDiv);
    return w;
  };
  var $_d8doq8pmjh8lz2ay = {
    get: get$10,
    to: to,
    by: by,
    preserve: preserve$1,
    capture: capture$2,
    intoView: intoView,
    intoViewIfNeeded: intoViewIfNeeded,
    setToElement: setToElement$1,
    scrollBarWidth: scrollBarWidth
  };

  function WindowBridge (win) {
    var elementFromPoint = function (x, y) {
      return $_6vo9a4krjh8lz1do.fromPoint($_6vo9a4krjh8lz1do.fromDom(win.document), x, y);
    };
    var getRect = function (element) {
      return element.dom().getBoundingClientRect();
    };
    var getRangedRect = function (start, soffset, finish, foffset) {
      var sel = $_8ehldap1jh8lz26p.exact(start, soffset, finish, foffset);
      return $_3efg7cp3jh8lz272.getFirstRect(win, sel).map(function (structRect) {
        return $_8kti2hkhjh8lz1bt.map(structRect, $_bgyjg9kejh8lz1ax.apply);
      });
    };
    var getSelection = function () {
      return $_3efg7cp3jh8lz272.get(win).map(function (exactAdt) {
        return $_45u5rqpljh8lz2ah.convertToRange(win, exactAdt);
      });
    };
    var fromSitus = function (situs) {
      var relative = $_8ehldap1jh8lz26p.relative(situs.start(), situs.finish());
      return $_45u5rqpljh8lz2ah.convertToRange(win, relative);
    };
    var situsFromPoint = function (x, y) {
      return $_3efg7cp3jh8lz272.getAtPoint(win, x, y).map(function (exact) {
        return {
          start: $_bgyjg9kejh8lz1ax.constant($_eviq86p2jh8lz26w.on(exact.start(), exact.soffset())),
          finish: $_bgyjg9kejh8lz1ax.constant($_eviq86p2jh8lz26w.on(exact.finish(), exact.foffset()))
        };
      });
    };
    var clearSelection = function () {
      $_3efg7cp3jh8lz272.clear(win);
    };
    var selectContents = function (element) {
      $_3efg7cp3jh8lz272.setToElement(win, element);
    };
    var setSelection = function (sel) {
      $_3efg7cp3jh8lz272.setExact(win, sel.start(), sel.soffset(), sel.finish(), sel.foffset());
    };
    var setRelativeSelection = function (start, finish) {
      $_3efg7cp3jh8lz272.setRelative(win, start, finish);
    };
    var getInnerHeight = function () {
      return win.innerHeight;
    };
    var getScrollY = function () {
      var pos = $_d8doq8pmjh8lz2ay.get($_6vo9a4krjh8lz1do.fromDom(win.document));
      return pos.top();
    };
    var scrollBy = function (x, y) {
      $_d8doq8pmjh8lz2ay.by(x, y, $_6vo9a4krjh8lz1do.fromDom(win.document));
    };
    return {
      elementFromPoint: elementFromPoint,
      getRect: getRect,
      getRangedRect: getRangedRect,
      getSelection: getSelection,
      fromSitus: fromSitus,
      situsFromPoint: situsFromPoint,
      clearSelection: clearSelection,
      setSelection: setSelection,
      setRelativeSelection: setRelativeSelection,
      selectContents: selectContents,
      getInnerHeight: getInnerHeight,
      getScrollY: getScrollY,
      scrollBy: scrollBy
    };
  }

  var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
    if (!($_2eywnlkvjh8lz1e8.eq(start, finish) && soffset === foffset)) {
      return $_fiygddlhjh8lz1g7.closest(start, 'td,th', isRoot).bind(function (s) {
        return $_fiygddlhjh8lz1g7.closest(finish, 'td,th', isRoot).bind(function (f) {
          return detect$5(container, isRoot, s, f, selectRange);
        });
      });
    } else {
      return Option.none();
    }
  };
  var detect$5 = function (container, isRoot, start, finish, selectRange) {
    if (!$_2eywnlkvjh8lz1e8.eq(start, finish)) {
      return $_5tpv0tm0jh8lz1jt.identify(start, finish, isRoot).bind(function (cellSel) {
        var boxes = cellSel.boxes().getOr([]);
        if (boxes.length > 0) {
          selectRange(container, boxes, cellSel.start(), cellSel.finish());
          return Option.some($_8xnxafpijh8lz29y.response(Option.some($_45u5rqpljh8lz2ah.makeSitus(start, 0, start, $_6759o9ltjh8lz1ij.getEnd(start))), true));
        } else {
          return Option.none();
        }
      });
    } else {
      return Option.none();
    }
  };
  var update = function (rows, columns, container, selected, annotations) {
    var updateSelection = function (newSels) {
      annotations.clear(container);
      annotations.selectRange(container, newSels.boxes(), newSels.start(), newSels.finish());
      return newSels.boxes();
    };
    return $_5tpv0tm0jh8lz1jt.shiftSelection(selected, rows, columns, annotations.firstSelectedSelector(), annotations.lastSelectedSelector()).map(updateSelection);
  };
  var $_2hlk4dpnjh8lz2b8 = {
    sync: sync,
    detect: detect$5,
    update: update
  };

  var nu$3 = $_d2ojjnkijh8lz1bv.immutableBag([
    'left',
    'top',
    'right',
    'bottom'
  ], []);
  var moveDown = function (caret, amount) {
    return nu$3({
      left: caret.left(),
      top: caret.top() + amount,
      right: caret.right(),
      bottom: caret.bottom() + amount
    });
  };
  var moveUp = function (caret, amount) {
    return nu$3({
      left: caret.left(),
      top: caret.top() - amount,
      right: caret.right(),
      bottom: caret.bottom() - amount
    });
  };
  var moveBottomTo = function (caret, bottom) {
    var height = caret.bottom() - caret.top();
    return nu$3({
      left: caret.left(),
      top: bottom - height,
      right: caret.right(),
      bottom: bottom
    });
  };
  var moveTopTo = function (caret, top) {
    var height = caret.bottom() - caret.top();
    return nu$3({
      left: caret.left(),
      top: top,
      right: caret.right(),
      bottom: top + height
    });
  };
  var translate = function (caret, xDelta, yDelta) {
    return nu$3({
      left: caret.left() + xDelta,
      top: caret.top() + yDelta,
      right: caret.right() + xDelta,
      bottom: caret.bottom() + yDelta
    });
  };
  var getTop$1 = function (caret) {
    return caret.top();
  };
  var getBottom = function (caret) {
    return caret.bottom();
  };
  var toString$1 = function (caret) {
    return '(' + caret.left() + ', ' + caret.top() + ') -> (' + caret.right() + ', ' + caret.bottom() + ')';
  };
  var $_8hoedhpqjh8lz2ck = {
    nu: nu$3,
    moveUp: moveUp,
    moveDown: moveDown,
    moveBottomTo: moveBottomTo,
    moveTopTo: moveTopTo,
    getTop: getTop$1,
    getBottom: getBottom,
    translate: translate,
    toString: toString$1
  };

  var getPartialBox = function (bridge, element, offset) {
    if (offset >= 0 && offset < $_6759o9ltjh8lz1ij.getEnd(element))
      return bridge.getRangedRect(element, offset, element, offset + 1);
    else if (offset > 0)
      return bridge.getRangedRect(element, offset - 1, element, offset);
    return Option.none();
  };
  var toCaret = function (rect) {
    return $_8hoedhpqjh8lz2ck.nu({
      left: rect.left,
      top: rect.top,
      right: rect.right,
      bottom: rect.bottom
    });
  };
  var getElemBox = function (bridge, element) {
    return Option.some(bridge.getRect(element));
  };
  var getBoxAt = function (bridge, element, offset) {
    if ($_a3izpgldjh8lz1fy.isElement(element))
      return getElemBox(bridge, element).map(toCaret);
    else if ($_a3izpgldjh8lz1fy.isText(element))
      return getPartialBox(bridge, element, offset).map(toCaret);
    else
      return Option.none();
  };
  var getEntireBox = function (bridge, element) {
    if ($_a3izpgldjh8lz1fy.isElement(element))
      return getElemBox(bridge, element).map(toCaret);
    else if ($_a3izpgldjh8lz1fy.isText(element))
      return bridge.getRangedRect(element, 0, element, $_6759o9ltjh8lz1ij.getEnd(element)).map(toCaret);
    else
      return Option.none();
  };
  var $_8dyzo9prjh8lz2ct = {
    getBoxAt: getBoxAt,
    getEntireBox: getEntireBox
  };

  var traverse = $_d2ojjnkijh8lz1bv.immutable('item', 'mode');
  var backtrack = function (universe, item, direction, _transition) {
    var transition = _transition !== undefined ? _transition : sidestep;
    return universe.property().parent(item).map(function (p) {
      return traverse(p, transition);
    });
  };
  var sidestep = function (universe, item, direction, _transition) {
    var transition = _transition !== undefined ? _transition : advance;
    return direction.sibling(universe, item).map(function (p) {
      return traverse(p, transition);
    });
  };
  var advance = function (universe, item, direction, _transition) {
    var transition = _transition !== undefined ? _transition : advance;
    var children = universe.property().children(item);
    var result = direction.first(children);
    return result.map(function (r) {
      return traverse(r, transition);
    });
  };
  var successors = [
    {
      current: backtrack,
      next: sidestep,
      fallback: Option.none()
    },
    {
      current: sidestep,
      next: advance,
      fallback: Option.some(backtrack)
    },
    {
      current: advance,
      next: advance,
      fallback: Option.some(sidestep)
    }
  ];
  var go$1 = function (universe, item, mode, direction, rules) {
    var rules = rules !== undefined ? rules : successors;
    var ruleOpt = $_6b0spykcjh8lz1ao.find(rules, function (succ) {
      return succ.current === mode;
    });
    return ruleOpt.bind(function (rule) {
      return rule.current(universe, item, direction, rule.next).orThunk(function () {
        return rule.fallback.bind(function (fb) {
          return go$1(universe, item, fb, direction);
        });
      });
    });
  };
  var $_5v9bytpwjh8lz2dx = {
    backtrack: backtrack,
    sidestep: sidestep,
    advance: advance,
    go: go$1
  };

  var left$1 = function () {
    var sibling = function (universe, item) {
      return universe.query().prevSibling(item);
    };
    var first = function (children) {
      return children.length > 0 ? Option.some(children[children.length - 1]) : Option.none();
    };
    return {
      sibling: sibling,
      first: first
    };
  };
  var right$1 = function () {
    var sibling = function (universe, item) {
      return universe.query().nextSibling(item);
    };
    var first = function (children) {
      return children.length > 0 ? Option.some(children[0]) : Option.none();
    };
    return {
      sibling: sibling,
      first: first
    };
  };
  var $_6gybyapxjh8lz2e5 = {
    left: left$1,
    right: right$1
  };

  var hone = function (universe, item, predicate, mode, direction, isRoot) {
    var next = $_5v9bytpwjh8lz2dx.go(universe, item, mode, direction);
    return next.bind(function (n) {
      if (isRoot(n.item()))
        return Option.none();
      else
        return predicate(n.item()) ? Option.some(n.item()) : hone(universe, n.item(), predicate, n.mode(), direction, isRoot);
    });
  };
  var left$2 = function (universe, item, predicate, isRoot) {
    return hone(universe, item, predicate, $_5v9bytpwjh8lz2dx.sidestep, $_6gybyapxjh8lz2e5.left(), isRoot);
  };
  var right$2 = function (universe, item, predicate, isRoot) {
    return hone(universe, item, predicate, $_5v9bytpwjh8lz2dx.sidestep, $_6gybyapxjh8lz2e5.right(), isRoot);
  };
  var $_fjuczcpvjh8lz2ds = {
    left: left$2,
    right: right$2
  };

  var isLeaf = function (universe, element) {
    return universe.property().children(element).length === 0;
  };
  var before$2 = function (universe, item, isRoot) {
    return seekLeft(universe, item, $_bgyjg9kejh8lz1ax.curry(isLeaf, universe), isRoot);
  };
  var after$3 = function (universe, item, isRoot) {
    return seekRight(universe, item, $_bgyjg9kejh8lz1ax.curry(isLeaf, universe), isRoot);
  };
  var seekLeft = function (universe, item, predicate, isRoot) {
    return $_fjuczcpvjh8lz2ds.left(universe, item, predicate, isRoot);
  };
  var seekRight = function (universe, item, predicate, isRoot) {
    return $_fjuczcpvjh8lz2ds.right(universe, item, predicate, isRoot);
  };
  var walkers = function () {
    return {
      left: $_6gybyapxjh8lz2e5.left,
      right: $_6gybyapxjh8lz2e5.right
    };
  };
  var walk = function (universe, item, mode, direction, _rules) {
    return $_5v9bytpwjh8lz2dx.go(universe, item, mode, direction, _rules);
  };
  var $_5k1owupujh8lz2do = {
    before: before$2,
    after: after$3,
    seekLeft: seekLeft,
    seekRight: seekRight,
    walkers: walkers,
    walk: walk,
    backtrack: $_5v9bytpwjh8lz2dx.backtrack,
    sidestep: $_5v9bytpwjh8lz2dx.sidestep,
    advance: $_5v9bytpwjh8lz2dx.advance
  };

  var universe$2 = DomUniverse();
  var gather = function (element, prune, transform) {
    return $_5k1owupujh8lz2do.gather(universe$2, element, prune, transform);
  };
  var before$3 = function (element, isRoot) {
    return $_5k1owupujh8lz2do.before(universe$2, element, isRoot);
  };
  var after$4 = function (element, isRoot) {
    return $_5k1owupujh8lz2do.after(universe$2, element, isRoot);
  };
  var seekLeft$1 = function (element, predicate, isRoot) {
    return $_5k1owupujh8lz2do.seekLeft(universe$2, element, predicate, isRoot);
  };
  var seekRight$1 = function (element, predicate, isRoot) {
    return $_5k1owupujh8lz2do.seekRight(universe$2, element, predicate, isRoot);
  };
  var walkers$1 = function () {
    return $_5k1owupujh8lz2do.walkers();
  };
  var walk$1 = function (item, mode, direction, _rules) {
    return $_5k1owupujh8lz2do.walk(universe$2, item, mode, direction, _rules);
  };
  var $_fayc8dptjh8lz2dk = {
    gather: gather,
    before: before$3,
    after: after$4,
    seekLeft: seekLeft$1,
    seekRight: seekRight$1,
    walkers: walkers$1,
    walk: walk$1
  };

  var JUMP_SIZE = 5;
  var NUM_RETRIES = 100;
  var adt$2 = $_659si2mejh8lz1n9.generate([
    { 'none': [] },
    { 'retry': ['caret'] }
  ]);
  var isOutside = function (caret, box) {
    return caret.left() < box.left() || Math.abs(box.right() - caret.left()) < 1 || caret.left() > box.right();
  };
  var inOutsideBlock = function (bridge, element, caret) {
    return $_aykj0glijh8lz1g9.closest(element, $_39l7z3myjh8lz1rk.isBlock).fold($_bgyjg9kejh8lz1ax.constant(false), function (cell) {
      return $_8dyzo9prjh8lz2ct.getEntireBox(bridge, cell).exists(function (box) {
        return isOutside(caret, box);
      });
    });
  };
  var adjustDown = function (bridge, element, guessBox, original, caret) {
    var lowerCaret = $_8hoedhpqjh8lz2ck.moveDown(caret, JUMP_SIZE);
    if (Math.abs(guessBox.bottom() - original.bottom()) < 1)
      return adt$2.retry(lowerCaret);
    else if (guessBox.top() > caret.bottom())
      return adt$2.retry(lowerCaret);
    else if (guessBox.top() === caret.bottom())
      return adt$2.retry($_8hoedhpqjh8lz2ck.moveDown(caret, 1));
    else
      return inOutsideBlock(bridge, element, caret) ? adt$2.retry($_8hoedhpqjh8lz2ck.translate(lowerCaret, JUMP_SIZE, 0)) : adt$2.none();
  };
  var adjustUp = function (bridge, element, guessBox, original, caret) {
    var higherCaret = $_8hoedhpqjh8lz2ck.moveUp(caret, JUMP_SIZE);
    if (Math.abs(guessBox.top() - original.top()) < 1)
      return adt$2.retry(higherCaret);
    else if (guessBox.bottom() < caret.top())
      return adt$2.retry(higherCaret);
    else if (guessBox.bottom() === caret.top())
      return adt$2.retry($_8hoedhpqjh8lz2ck.moveUp(caret, 1));
    else
      return inOutsideBlock(bridge, element, caret) ? adt$2.retry($_8hoedhpqjh8lz2ck.translate(higherCaret, JUMP_SIZE, 0)) : adt$2.none();
  };
  var upMovement = {
    point: $_8hoedhpqjh8lz2ck.getTop,
    adjuster: adjustUp,
    move: $_8hoedhpqjh8lz2ck.moveUp,
    gather: $_fayc8dptjh8lz2dk.before
  };
  var downMovement = {
    point: $_8hoedhpqjh8lz2ck.getBottom,
    adjuster: adjustDown,
    move: $_8hoedhpqjh8lz2ck.moveDown,
    gather: $_fayc8dptjh8lz2dk.after
  };
  var isAtTable = function (bridge, x, y) {
    return bridge.elementFromPoint(x, y).filter(function (elm) {
      return $_a3izpgldjh8lz1fy.name(elm) === 'table';
    }).isSome();
  };
  var adjustForTable = function (bridge, movement, original, caret, numRetries) {
    return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
  };
  var adjustTil = function (bridge, movement, original, caret, numRetries) {
    if (numRetries === 0)
      return Option.some(caret);
    if (isAtTable(bridge, caret.left(), movement.point(caret)))
      return adjustForTable(bridge, movement, original, caret, numRetries - 1);
    return bridge.situsFromPoint(caret.left(), movement.point(caret)).bind(function (guess) {
      return guess.start().fold(Option.none, function (element, offset) {
        return $_8dyzo9prjh8lz2ct.getEntireBox(bridge, element, offset).bind(function (guessBox) {
          return movement.adjuster(bridge, element, guessBox, original, caret).fold(Option.none, function (newCaret) {
            return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
          });
        }).orThunk(function () {
          return Option.some(caret);
        });
      }, Option.none);
    });
  };
  var ieTryDown = function (bridge, caret) {
    return bridge.situsFromPoint(caret.left(), caret.bottom() + JUMP_SIZE);
  };
  var ieTryUp = function (bridge, caret) {
    return bridge.situsFromPoint(caret.left(), caret.top() - JUMP_SIZE);
  };
  var checkScroll = function (movement, adjusted, bridge) {
    if (movement.point(adjusted) > bridge.getInnerHeight())
      return Option.some(movement.point(adjusted) - bridge.getInnerHeight());
    else if (movement.point(adjusted) < 0)
      return Option.some(-movement.point(adjusted));
    else
      return Option.none();
  };
  var retry = function (movement, bridge, caret) {
    var moved = movement.move(caret, JUMP_SIZE);
    var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
    return checkScroll(movement, adjusted, bridge).fold(function () {
      return bridge.situsFromPoint(adjusted.left(), movement.point(adjusted));
    }, function (delta) {
      bridge.scrollBy(0, delta);
      return bridge.situsFromPoint(adjusted.left(), movement.point(adjusted) - delta);
    });
  };
  var $_djarwopsjh8lz2d1 = {
    tryUp: $_bgyjg9kejh8lz1ax.curry(retry, upMovement),
    tryDown: $_bgyjg9kejh8lz1ax.curry(retry, downMovement),
    ieTryUp: ieTryUp,
    ieTryDown: ieTryDown,
    getJumpSize: $_bgyjg9kejh8lz1ax.constant(JUMP_SIZE)
  };

  var adt$3 = $_659si2mejh8lz1n9.generate([
    { 'none': ['message'] },
    { 'success': [] },
    { 'failedUp': ['cell'] },
    { 'failedDown': ['cell'] }
  ]);
  var isOverlapping = function (bridge, before, after) {
    var beforeBounds = bridge.getRect(before);
    var afterBounds = bridge.getRect(after);
    return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
  };
  var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
    return $_fiygddlhjh8lz1g7.closest(after, 'td,th', isRoot).bind(function (afterCell) {
      return $_fiygddlhjh8lz1g7.closest(before, 'td,th', isRoot).map(function (beforeCell) {
        if (!$_2eywnlkvjh8lz1e8.eq(afterCell, beforeCell)) {
          return $_5glne7m1jh8lz1kg.sharedOne(isRow, [
            afterCell,
            beforeCell
          ]).fold(function () {
            return isOverlapping(bridge, beforeCell, afterCell) ? adt$3.success() : failure(beforeCell);
          }, function (sharedRow) {
            return failure(beforeCell);
          });
        } else {
          return $_2eywnlkvjh8lz1e8.eq(after, afterCell) && $_6759o9ltjh8lz1ij.getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$3.none('in same cell');
        }
      });
    }).getOr(adt$3.none('default'));
  };
  var isRow = function (elem) {
    return $_fiygddlhjh8lz1g7.closest(elem, 'tr');
  };
  var cata$2 = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
    return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
  };
  var $_9gwioapyjh8lz2ea = {
    verify: verify,
    cata: cata$2,
    adt: adt$3
  };

  var point = $_d2ojjnkijh8lz1bv.immutable('element', 'offset');
  var delta = $_d2ojjnkijh8lz1bv.immutable('element', 'deltaOffset');
  var range$3 = $_d2ojjnkijh8lz1bv.immutable('element', 'start', 'finish');
  var points = $_d2ojjnkijh8lz1bv.immutable('begin', 'end');
  var text = $_d2ojjnkijh8lz1bv.immutable('element', 'text');
  var $_6wu737q0jh8lz2f9 = {
    point: point,
    delta: delta,
    range: range$3,
    points: points,
    text: text
  };

  var inAncestor = $_d2ojjnkijh8lz1bv.immutable('ancestor', 'descendants', 'element', 'index');
  var inParent = $_d2ojjnkijh8lz1bv.immutable('parent', 'children', 'element', 'index');
  var childOf = function (element, ancestor) {
    return $_aykj0glijh8lz1g9.closest(element, function (elem) {
      return $_4hc7u2ktjh8lz1dv.parent(elem).exists(function (parent) {
        return $_2eywnlkvjh8lz1e8.eq(parent, ancestor);
      });
    });
  };
  var indexInParent = function (element) {
    return $_4hc7u2ktjh8lz1dv.parent(element).bind(function (parent) {
      var children = $_4hc7u2ktjh8lz1dv.children(parent);
      return indexOf$1(children, element).map(function (index) {
        return inParent(parent, children, element, index);
      });
    });
  };
  var indexOf$1 = function (elements, element) {
    return $_6b0spykcjh8lz1ao.findIndex(elements, $_bgyjg9kejh8lz1ax.curry($_2eywnlkvjh8lz1e8.eq, element));
  };
  var selectorsInParent = function (element, selector) {
    return $_4hc7u2ktjh8lz1dv.parent(element).bind(function (parent) {
      var children = $_coxlualejh8lz1fz.children(parent, selector);
      return indexOf$1(children, element).map(function (index) {
        return inParent(parent, children, element, index);
      });
    });
  };
  var descendantsInAncestor = function (element, ancestorSelector, descendantSelector) {
    return $_fiygddlhjh8lz1g7.closest(element, ancestorSelector).bind(function (ancestor) {
      var descendants = $_coxlualejh8lz1fz.descendants(ancestor, descendantSelector);
      return indexOf$1(descendants, element).map(function (index) {
        return inAncestor(ancestor, descendants, element, index);
      });
    });
  };
  var $_1jwctkq1jh8lz2fd = {
    childOf: childOf,
    indexOf: indexOf$1,
    indexInParent: indexInParent,
    selectorsInParent: selectorsInParent,
    descendantsInAncestor: descendantsInAncestor
  };

  var isBr = function (elem) {
    return $_a3izpgldjh8lz1fy.name(elem) === 'br';
  };
  var gatherer = function (cand, gather, isRoot) {
    return gather(cand, isRoot).bind(function (target) {
      return $_a3izpgldjh8lz1fy.isText(target) && $_bri5anlujh8lz1in.get(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Option.some(target);
    });
  };
  var handleBr = function (isRoot, element, direction) {
    return direction.traverse(element).orThunk(function () {
      return gatherer(element, direction.gather, isRoot);
    }).map(direction.relative);
  };
  var findBr = function (element, offset) {
    return $_4hc7u2ktjh8lz1dv.child(element, offset).filter(isBr).orThunk(function () {
      return $_4hc7u2ktjh8lz1dv.child(element, offset - 1).filter(isBr);
    });
  };
  var handleParent = function (isRoot, element, offset, direction) {
    return findBr(element, offset).bind(function (br) {
      return direction.traverse(br).fold(function () {
        return gatherer(br, direction.gather, isRoot).map(direction.relative);
      }, function (adjacent) {
        return $_1jwctkq1jh8lz2fd.indexInParent(adjacent).map(function (info) {
          return $_eviq86p2jh8lz26w.on(info.parent(), info.index());
        });
      });
    });
  };
  var tryBr = function (isRoot, element, offset, direction) {
    var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
    return target.map(function (tgt) {
      return {
        start: $_bgyjg9kejh8lz1ax.constant(tgt),
        finish: $_bgyjg9kejh8lz1ax.constant(tgt)
      };
    });
  };
  var process = function (analysis) {
    return $_9gwioapyjh8lz2ea.cata(analysis, function (message) {
      return Option.none();
    }, function () {
      return Option.none();
    }, function (cell) {
      return Option.some($_6wu737q0jh8lz2f9.point(cell, 0));
    }, function (cell) {
      return Option.some($_6wu737q0jh8lz2f9.point(cell, $_6759o9ltjh8lz1ij.getEnd(cell)));
    });
  };
  var $_fdx5vppzjh8lz2eq = {
    tryBr: tryBr,
    process: process
  };

  var MAX_RETRIES = 20;
  var platform$1 = $_a6om0dl0jh8lz1ep.detect();
  var findSpot = function (bridge, isRoot, direction) {
    return bridge.getSelection().bind(function (sel) {
      return $_fdx5vppzjh8lz2eq.tryBr(isRoot, sel.finish(), sel.foffset(), direction).fold(function () {
        return Option.some($_6wu737q0jh8lz2f9.point(sel.finish(), sel.foffset()));
      }, function (brNeighbour) {
        var range = bridge.fromSitus(brNeighbour);
        var analysis = $_9gwioapyjh8lz2ea.verify(bridge, sel.finish(), sel.foffset(), range.finish(), range.foffset(), direction.failure, isRoot);
        return $_fdx5vppzjh8lz2eq.process(analysis);
      });
    });
  };
  var scan = function (bridge, isRoot, element, offset, direction, numRetries) {
    if (numRetries === 0)
      return Option.none();
    return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
      var range = bridge.fromSitus(situs);
      var analysis = $_9gwioapyjh8lz2ea.verify(bridge, element, offset, range.finish(), range.foffset(), direction.failure, isRoot);
      return $_9gwioapyjh8lz2ea.cata(analysis, function () {
        return Option.none();
      }, function () {
        return Option.some(situs);
      }, function (cell) {
        if ($_2eywnlkvjh8lz1e8.eq(element, cell) && offset === 0)
          return tryAgain(bridge, element, offset, $_8hoedhpqjh8lz2ck.moveUp, direction);
        else
          return scan(bridge, isRoot, cell, 0, direction, numRetries - 1);
      }, function (cell) {
        if ($_2eywnlkvjh8lz1e8.eq(element, cell) && offset === $_6759o9ltjh8lz1ij.getEnd(cell))
          return tryAgain(bridge, element, offset, $_8hoedhpqjh8lz2ck.moveDown, direction);
        else
          return scan(bridge, isRoot, cell, $_6759o9ltjh8lz1ij.getEnd(cell), direction, numRetries - 1);
      });
    });
  };
  var tryAgain = function (bridge, element, offset, move, direction) {
    return $_8dyzo9prjh8lz2ct.getBoxAt(bridge, element, offset).bind(function (box) {
      return tryAt(bridge, direction, move(box, $_djarwopsjh8lz2d1.getJumpSize()));
    });
  };
  var tryAt = function (bridge, direction, box) {
    if (platform$1.browser.isChrome() || platform$1.browser.isSafari() || platform$1.browser.isFirefox() || platform$1.browser.isEdge())
      return direction.otherRetry(bridge, box);
    else if (platform$1.browser.isIE())
      return direction.ieRetry(bridge, box);
    else
      return Option.none();
  };
  var tryCursor = function (bridge, isRoot, element, offset, direction) {
    return $_8dyzo9prjh8lz2ct.getBoxAt(bridge, element, offset).bind(function (box) {
      return tryAt(bridge, direction, box);
    });
  };
  var handle$2 = function (bridge, isRoot, direction) {
    return findSpot(bridge, isRoot, direction).bind(function (spot) {
      return scan(bridge, isRoot, spot.element(), spot.offset(), direction, MAX_RETRIES).map(bridge.fromSitus);
    });
  };
  var $_3ywvn5ppjh8lz2c7 = { handle: handle$2 };

  var any$1 = function (predicate) {
    return $_aykj0glijh8lz1g9.first(predicate).isSome();
  };
  var ancestor$3 = function (scope, predicate, isRoot) {
    return $_aykj0glijh8lz1g9.ancestor(scope, predicate, isRoot).isSome();
  };
  var closest$3 = function (scope, predicate, isRoot) {
    return $_aykj0glijh8lz1g9.closest(scope, predicate, isRoot).isSome();
  };
  var sibling$3 = function (scope, predicate) {
    return $_aykj0glijh8lz1g9.sibling(scope, predicate).isSome();
  };
  var child$4 = function (scope, predicate) {
    return $_aykj0glijh8lz1g9.child(scope, predicate).isSome();
  };
  var descendant$3 = function (scope, predicate) {
    return $_aykj0glijh8lz1g9.descendant(scope, predicate).isSome();
  };
  var $_2egcf2q2jh8lz2fq = {
    any: any$1,
    ancestor: ancestor$3,
    closest: closest$3,
    sibling: sibling$3,
    child: child$4,
    descendant: descendant$3
  };

  var detection = $_a6om0dl0jh8lz1ep.detect();
  var inSameTable = function (elem, table) {
    return $_2egcf2q2jh8lz2fq.ancestor(elem, function (e) {
      return $_4hc7u2ktjh8lz1dv.parent(e).exists(function (p) {
        return $_2eywnlkvjh8lz1e8.eq(p, table);
      });
    });
  };
  var simulate = function (bridge, isRoot, direction, initial, anchor) {
    return $_fiygddlhjh8lz1g7.closest(initial, 'td,th', isRoot).bind(function (start) {
      return $_fiygddlhjh8lz1g7.closest(start, 'table', isRoot).bind(function (table) {
        if (!inSameTable(anchor, table))
          return Option.none();
        return $_3ywvn5ppjh8lz2c7.handle(bridge, isRoot, direction).bind(function (range) {
          return $_fiygddlhjh8lz1g7.closest(range.finish(), 'td,th', isRoot).map(function (finish) {
            return {
              start: $_bgyjg9kejh8lz1ax.constant(start),
              finish: $_bgyjg9kejh8lz1ax.constant(finish),
              range: $_bgyjg9kejh8lz1ax.constant(range)
            };
          });
        });
      });
    });
  };
  var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
    if (detection.browser.isIE()) {
      return Option.none();
    } else {
      return precheck(initial, isRoot).orThunk(function () {
        return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
          var range = info.range();
          return $_8xnxafpijh8lz29y.response(Option.some($_45u5rqpljh8lz2ah.makeSitus(range.start(), range.soffset(), range.finish(), range.foffset())), true);
        });
      });
    }
  };
  var firstUpCheck = function (initial, isRoot) {
    return $_fiygddlhjh8lz1g7.closest(initial, 'tr', isRoot).bind(function (startRow) {
      return $_fiygddlhjh8lz1g7.closest(startRow, 'table', isRoot).bind(function (table) {
        var rows = $_coxlualejh8lz1fz.descendants(table, 'tr');
        if ($_2eywnlkvjh8lz1e8.eq(startRow, rows[0])) {
          return $_fayc8dptjh8lz2dk.seekLeft(table, function (element) {
            return $_fpdn73lsjh8lz1ig.last(element).isSome();
          }, isRoot).map(function (last) {
            var lastOffset = $_6759o9ltjh8lz1ij.getEnd(last);
            return $_8xnxafpijh8lz29y.response(Option.some($_45u5rqpljh8lz2ah.makeSitus(last, lastOffset, last, lastOffset)), true);
          });
        } else {
          return Option.none();
        }
      });
    });
  };
  var lastDownCheck = function (initial, isRoot) {
    return $_fiygddlhjh8lz1g7.closest(initial, 'tr', isRoot).bind(function (startRow) {
      return $_fiygddlhjh8lz1g7.closest(startRow, 'table', isRoot).bind(function (table) {
        var rows = $_coxlualejh8lz1fz.descendants(table, 'tr');
        if ($_2eywnlkvjh8lz1e8.eq(startRow, rows[rows.length - 1])) {
          return $_fayc8dptjh8lz2dk.seekRight(table, function (element) {
            return $_fpdn73lsjh8lz1ig.first(element).isSome();
          }, isRoot).map(function (first) {
            return $_8xnxafpijh8lz29y.response(Option.some($_45u5rqpljh8lz2ah.makeSitus(first, 0, first, 0)), true);
          });
        } else {
          return Option.none();
        }
      });
    });
  };
  var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
    return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
      return $_2hlk4dpnjh8lz2b8.detect(container, isRoot, info.start(), info.finish(), selectRange);
    });
  };
  var $_1iwm88pojh8lz2bj = {
    navigate: navigate,
    select: select,
    firstUpCheck: firstUpCheck,
    lastDownCheck: lastDownCheck
  };

  var findCell = function (target, isRoot) {
    return $_fiygddlhjh8lz1g7.closest(target, 'td,th', isRoot);
  };
  function MouseSelection (bridge, container, isRoot, annotations) {
    var cursor = Option.none();
    var clearState = function () {
      cursor = Option.none();
    };
    var mousedown = function (event) {
      annotations.clear(container);
      cursor = findCell(event.target(), isRoot);
    };
    var mouseover = function (event) {
      cursor.each(function (start) {
        annotations.clear(container);
        findCell(event.target(), isRoot).each(function (finish) {
          $_5tpv0tm0jh8lz1jt.identify(start, finish, isRoot).each(function (cellSel) {
            var boxes = cellSel.boxes().getOr([]);
            if (boxes.length > 1 || boxes.length === 1 && !$_2eywnlkvjh8lz1e8.eq(start, finish)) {
              annotations.selectRange(container, boxes, cellSel.start(), cellSel.finish());
              bridge.selectContents(finish);
            }
          });
        });
      });
    };
    var mouseup = function () {
      cursor.each(clearState);
    };
    return {
      mousedown: mousedown,
      mouseover: mouseover,
      mouseup: mouseup
    };
  }

  var $_24h2itq4jh8lz2fz = {
    down: {
      traverse: $_4hc7u2ktjh8lz1dv.nextSibling,
      gather: $_fayc8dptjh8lz2dk.after,
      relative: $_eviq86p2jh8lz26w.before,
      otherRetry: $_djarwopsjh8lz2d1.tryDown,
      ieRetry: $_djarwopsjh8lz2d1.ieTryDown,
      failure: $_9gwioapyjh8lz2ea.adt.failedDown
    },
    up: {
      traverse: $_4hc7u2ktjh8lz1dv.prevSibling,
      gather: $_fayc8dptjh8lz2dk.before,
      relative: $_eviq86p2jh8lz26w.before,
      otherRetry: $_djarwopsjh8lz2d1.tryUp,
      ieRetry: $_djarwopsjh8lz2d1.ieTryUp,
      failure: $_9gwioapyjh8lz2ea.adt.failedUp
    }
  };

  var rc = $_d2ojjnkijh8lz1bv.immutable('rows', 'cols');
  var mouse = function (win, container, isRoot, annotations) {
    var bridge = WindowBridge(win);
    var handlers = MouseSelection(bridge, container, isRoot, annotations);
    return {
      mousedown: handlers.mousedown,
      mouseover: handlers.mouseover,
      mouseup: handlers.mouseup
    };
  };
  var keyboard = function (win, container, isRoot, annotations) {
    var bridge = WindowBridge(win);
    var clearToNavigate = function () {
      annotations.clear(container);
      return Option.none();
    };
    var keydown = function (event, start, soffset, finish, foffset, direction) {
      var keycode = event.raw().which;
      var shiftKey = event.raw().shiftKey === true;
      var handler = $_5tpv0tm0jh8lz1jt.retrieve(container, annotations.selectedSelector()).fold(function () {
        if ($_5bctktpjjh8lz2a1.isDown(keycode) && shiftKey) {
          return $_bgyjg9kejh8lz1ax.curry($_1iwm88pojh8lz2bj.select, bridge, container, isRoot, $_24h2itq4jh8lz2fz.down, finish, start, annotations.selectRange);
        } else if ($_5bctktpjjh8lz2a1.isUp(keycode) && shiftKey) {
          return $_bgyjg9kejh8lz1ax.curry($_1iwm88pojh8lz2bj.select, bridge, container, isRoot, $_24h2itq4jh8lz2fz.up, finish, start, annotations.selectRange);
        } else if ($_5bctktpjjh8lz2a1.isDown(keycode)) {
          return $_bgyjg9kejh8lz1ax.curry($_1iwm88pojh8lz2bj.navigate, bridge, isRoot, $_24h2itq4jh8lz2fz.down, finish, start, $_1iwm88pojh8lz2bj.lastDownCheck);
        } else if ($_5bctktpjjh8lz2a1.isUp(keycode)) {
          return $_bgyjg9kejh8lz1ax.curry($_1iwm88pojh8lz2bj.navigate, bridge, isRoot, $_24h2itq4jh8lz2fz.up, finish, start, $_1iwm88pojh8lz2bj.firstUpCheck);
        } else {
          return Option.none;
        }
      }, function (selected) {
        var update = function (attempts) {
          return function () {
            var navigation = $_clgylhn2jh8lz1sg.findMap(attempts, function (delta) {
              return $_2hlk4dpnjh8lz2b8.update(delta.rows(), delta.cols(), container, selected, annotations);
            });
            return navigation.fold(function () {
              return $_5tpv0tm0jh8lz1jt.getEdges(container, annotations.firstSelectedSelector(), annotations.lastSelectedSelector()).map(function (edges) {
                var relative = $_5bctktpjjh8lz2a1.isDown(keycode) || direction.isForward(keycode) ? $_eviq86p2jh8lz26w.after : $_eviq86p2jh8lz26w.before;
                bridge.setRelativeSelection($_eviq86p2jh8lz26w.on(edges.first(), 0), relative(edges.table()));
                annotations.clear(container);
                return $_8xnxafpijh8lz29y.response(Option.none(), true);
              });
            }, function (_) {
              return Option.some($_8xnxafpijh8lz29y.response(Option.none(), true));
            });
          };
        };
        if ($_5bctktpjjh8lz2a1.isDown(keycode) && shiftKey)
          return update([rc(+1, 0)]);
        else if ($_5bctktpjjh8lz2a1.isUp(keycode) && shiftKey)
          return update([rc(-1, 0)]);
        else if (direction.isBackward(keycode) && shiftKey)
          return update([
            rc(0, -1),
            rc(-1, 0)
          ]);
        else if (direction.isForward(keycode) && shiftKey)
          return update([
            rc(0, +1),
            rc(+1, 0)
          ]);
        else if ($_5bctktpjjh8lz2a1.isNavigation(keycode) && shiftKey === false)
          return clearToNavigate;
        else
          return Option.none;
      });
      return handler();
    };
    var keyup = function (event, start, soffset, finish, foffset) {
      return $_5tpv0tm0jh8lz1jt.retrieve(container, annotations.selectedSelector()).fold(function () {
        var keycode = event.raw().which;
        var shiftKey = event.raw().shiftKey === true;
        if (shiftKey === false)
          return Option.none();
        if ($_5bctktpjjh8lz2a1.isNavigation(keycode))
          return $_2hlk4dpnjh8lz2b8.sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
        else
          return Option.none();
      }, Option.none);
    };
    return {
      keydown: keydown,
      keyup: keyup
    };
  };
  var $_5i27y1phjh8lz29m = {
    mouse: mouse,
    keyboard: keyboard
  };

  var add$3 = function (element, classes) {
    $_6b0spykcjh8lz1ao.each(classes, function (x) {
      $_evf7iendjh8lz1uz.add(element, x);
    });
  };
  var remove$7 = function (element, classes) {
    $_6b0spykcjh8lz1ao.each(classes, function (x) {
      $_evf7iendjh8lz1uz.remove(element, x);
    });
  };
  var toggle$2 = function (element, classes) {
    $_6b0spykcjh8lz1ao.each(classes, function (x) {
      $_evf7iendjh8lz1uz.toggle(element, x);
    });
  };
  var hasAll = function (element, classes) {
    return $_6b0spykcjh8lz1ao.forall(classes, function (clazz) {
      return $_evf7iendjh8lz1uz.has(element, clazz);
    });
  };
  var hasAny = function (element, classes) {
    return $_6b0spykcjh8lz1ao.exists(classes, function (clazz) {
      return $_evf7iendjh8lz1uz.has(element, clazz);
    });
  };
  var getNative = function (element) {
    var classList = element.dom().classList;
    var r = new Array(classList.length);
    for (var i = 0; i < classList.length; i++) {
      r[i] = classList.item(i);
    }
    return r;
  };
  var get$11 = function (element) {
    return $_7oeslpnfjh8lz1v2.supports(element) ? getNative(element) : $_7oeslpnfjh8lz1v2.get(element);
  };
  var $_g8lworq7jh8lz2gs = {
    add: add$3,
    remove: remove$7,
    toggle: toggle$2,
    hasAll: hasAll,
    hasAny: hasAny,
    get: get$11
  };

  var addClass = function (clazz) {
    return function (element) {
      $_evf7iendjh8lz1uz.add(element, clazz);
    };
  };
  var removeClass = function (clazz) {
    return function (element) {
      $_evf7iendjh8lz1uz.remove(element, clazz);
    };
  };
  var removeClasses = function (classes) {
    return function (element) {
      $_g8lworq7jh8lz2gs.remove(element, classes);
    };
  };
  var hasClass = function (clazz) {
    return function (element) {
      return $_evf7iendjh8lz1uz.has(element, clazz);
    };
  };
  var $_1e5pdaq6jh8lz2gr = {
    addClass: addClass,
    removeClass: removeClass,
    removeClasses: removeClasses,
    hasClass: hasClass
  };

  var byClass = function (ephemera) {
    var addSelectionClass = $_1e5pdaq6jh8lz2gr.addClass(ephemera.selected());
    var removeSelectionClasses = $_1e5pdaq6jh8lz2gr.removeClasses([
      ephemera.selected(),
      ephemera.lastSelected(),
      ephemera.firstSelected()
    ]);
    var clear = function (container) {
      var sels = $_coxlualejh8lz1fz.descendants(container, ephemera.selectedSelector());
      $_6b0spykcjh8lz1ao.each(sels, removeSelectionClasses);
    };
    var selectRange = function (container, cells, start, finish) {
      clear(container);
      $_6b0spykcjh8lz1ao.each(cells, addSelectionClass);
      $_evf7iendjh8lz1uz.add(start, ephemera.firstSelected());
      $_evf7iendjh8lz1uz.add(finish, ephemera.lastSelected());
    };
    return {
      clear: clear,
      selectRange: selectRange,
      selectedSelector: ephemera.selectedSelector,
      firstSelectedSelector: ephemera.firstSelectedSelector,
      lastSelectedSelector: ephemera.lastSelectedSelector
    };
  };
  var byAttr = function (ephemera) {
    var removeSelectionAttributes = function (element) {
      $_1mp8lglcjh8lz1fq.remove(element, ephemera.selected());
      $_1mp8lglcjh8lz1fq.remove(element, ephemera.firstSelected());
      $_1mp8lglcjh8lz1fq.remove(element, ephemera.lastSelected());
    };
    var addSelectionAttribute = function (element) {
      $_1mp8lglcjh8lz1fq.set(element, ephemera.selected(), '1');
    };
    var clear = function (container) {
      var sels = $_coxlualejh8lz1fz.descendants(container, ephemera.selectedSelector());
      $_6b0spykcjh8lz1ao.each(sels, removeSelectionAttributes);
    };
    var selectRange = function (container, cells, start, finish) {
      clear(container);
      $_6b0spykcjh8lz1ao.each(cells, addSelectionAttribute);
      $_1mp8lglcjh8lz1fq.set(start, ephemera.firstSelected(), '1');
      $_1mp8lglcjh8lz1fq.set(finish, ephemera.lastSelected(), '1');
    };
    return {
      clear: clear,
      selectRange: selectRange,
      selectedSelector: ephemera.selectedSelector,
      firstSelectedSelector: ephemera.firstSelectedSelector,
      lastSelectedSelector: ephemera.lastSelectedSelector
    };
  };
  var $_giqnj1q5jh8lz2g7 = {
    byClass: byClass,
    byAttr: byAttr
  };

  var hasInternalTarget = function (e) {
    return $_evf7iendjh8lz1uz.has($_6vo9a4krjh8lz1do.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
  };
  function CellSelection$1 (editor, lazyResize) {
    var handlerStruct = $_d2ojjnkijh8lz1bv.immutableBag([
      'mousedown',
      'mouseover',
      'mouseup',
      'keyup',
      'keydown'
    ], []);
    var handlers = Option.none();
    var annotations = $_giqnj1q5jh8lz2g7.byAttr($_2yroczmcjh8lz1n4);
    editor.on('init', function (e) {
      var win = editor.getWin();
      var body = getBody$1(editor);
      var isRoot = getIsRoot(editor);
      var syncSelection = function () {
        var sel = editor.selection;
        var start = $_6vo9a4krjh8lz1do.fromDom(sel.getStart());
        var end = $_6vo9a4krjh8lz1do.fromDom(sel.getEnd());
        var shared = $_5glne7m1jh8lz1kg.sharedOne($_ee8pmfkojh8lz1ch.table, [
          start,
          end
        ]);
        shared.fold(function () {
          annotations.clear(body);
        }, $_bgyjg9kejh8lz1ax.noop);
      };
      var mouseHandlers = $_5i27y1phjh8lz29m.mouse(win, body, isRoot, annotations);
      var keyHandlers = $_5i27y1phjh8lz29m.keyboard(win, body, isRoot, annotations);
      var hasShiftKey = function (event) {
        return event.raw().shiftKey === true;
      };
      var handleResponse = function (event, response) {
        if (!hasShiftKey(event)) {
          return;
        }
        if (response.kill()) {
          event.kill();
        }
        response.selection().each(function (ns) {
          var relative = $_8ehldap1jh8lz26p.relative(ns.start(), ns.finish());
          var rng = $_dcfxf3p7jh8lz27p.asLtrRange(win, relative);
          editor.selection.setRng(rng);
        });
      };
      var keyup = function (event) {
        var wrappedEvent = wrapEvent(event);
        if (wrappedEvent.raw().shiftKey && $_5bctktpjjh8lz2a1.isNavigation(wrappedEvent.raw().which)) {
          var rng = editor.selection.getRng();
          var start = $_6vo9a4krjh8lz1do.fromDom(rng.startContainer);
          var end = $_6vo9a4krjh8lz1do.fromDom(rng.endContainer);
          keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
            handleResponse(wrappedEvent, response);
          });
        }
      };
      var keydown = function (event) {
        var wrappedEvent = wrapEvent(event);
        lazyResize().each(function (resize) {
          resize.hideBars();
        });
        var rng = editor.selection.getRng();
        var startContainer = $_6vo9a4krjh8lz1do.fromDom(editor.selection.getStart());
        var start = $_6vo9a4krjh8lz1do.fromDom(rng.startContainer);
        var end = $_6vo9a4krjh8lz1do.fromDom(rng.endContainer);
        var direction = $_fe2yjsnvjh8lz1y8.directionAt(startContainer).isRtl() ? $_5bctktpjjh8lz2a1.rtl : $_5bctktpjjh8lz2a1.ltr;
        keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
          handleResponse(wrappedEvent, response);
        });
        lazyResize().each(function (resize) {
          resize.showBars();
        });
      };
      var isMouseEvent = function (event) {
        return event.hasOwnProperty('x') && event.hasOwnProperty('y');
      };
      var wrapEvent = function (event) {
        var target = $_6vo9a4krjh8lz1do.fromDom(event.target);
        var stop = function () {
          event.stopPropagation();
        };
        var prevent = function () {
          event.preventDefault();
        };
        var kill = $_bgyjg9kejh8lz1ax.compose(prevent, stop);
        return {
          target: $_bgyjg9kejh8lz1ax.constant(target),
          x: $_bgyjg9kejh8lz1ax.constant(isMouseEvent(event) ? event.x : null),
          y: $_bgyjg9kejh8lz1ax.constant(isMouseEvent(event) ? event.y : null),
          stop: stop,
          prevent: prevent,
          kill: kill,
          raw: $_bgyjg9kejh8lz1ax.constant(event)
        };
      };
      var isLeftMouse = function (raw) {
        return raw.button === 0;
      };
      var isLeftButtonPressed = function (raw) {
        if (raw.buttons === undefined) {
          return true;
        }
        return (raw.buttons & 1) !== 0;
      };
      var mouseDown = function (e) {
        if (isLeftMouse(e) && hasInternalTarget(e)) {
          mouseHandlers.mousedown(wrapEvent(e));
        }
      };
      var mouseOver = function (e) {
        if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
          mouseHandlers.mouseover(wrapEvent(e));
        }
      };
      var mouseUp = function (e) {
        if (isLeftMouse(e) && hasInternalTarget(e)) {
          mouseHandlers.mouseup(wrapEvent(e));
        }
      };
      editor.on('mousedown', mouseDown);
      editor.on('mouseover', mouseOver);
      editor.on('mouseup', mouseUp);
      editor.on('keyup', keyup);
      editor.on('keydown', keydown);
      editor.on('nodechange', syncSelection);
      handlers = Option.some(handlerStruct({
        mousedown: mouseDown,
        mouseover: mouseOver,
        mouseup: mouseUp,
        keyup: keyup,
        keydown: keydown
      }));
    });
    var destroy = function () {
      handlers.each(function (handlers) {
      });
    };
    return {
      clear: annotations.clear,
      destroy: destroy
    };
  }

  var Selections = function (editor) {
    var get = function () {
      var body = getBody$1(editor);
      return $_21toytlzjh8lz1jj.retrieve(body, $_2yroczmcjh8lz1n4.selectedSelector()).fold(function () {
        if (editor.selection.getStart() === undefined) {
          return $_crzziemdjh8lz1n7.none();
        } else {
          return $_crzziemdjh8lz1n7.single(editor.selection);
        }
      }, function (cells) {
        return $_crzziemdjh8lz1n7.multiple(cells);
      });
    };
    return { get: get };
  };

  var each$4 = global$2.each;
  var addButtons = function (editor) {
    var menuItems = [];
    each$4('inserttable tableprops deletetable | cell row column'.split(' '), function (name) {
      if (name === '|') {
        menuItems.push({ text: '-' });
      } else {
        menuItems.push(editor.menuItems[name]);
      }
    });
    editor.addButton('table', {
      type: 'menubutton',
      title: 'Table',
      menu: menuItems
    });
    function cmd(command) {
      return function () {
        editor.execCommand(command);
      };
    }
    editor.addButton('tableprops', {
      title: 'Table properties',
      onclick: cmd('mceTableProps'),
      icon: 'table'
    });
    editor.addButton('tabledelete', {
      title: 'Delete table',
      onclick: cmd('mceTableDelete')
    });
    editor.addButton('tablecellprops', {
      title: 'Cell properties',
      onclick: cmd('mceTableCellProps')
    });
    editor.addButton('tablemergecells', {
      title: 'Merge cells',
      onclick: cmd('mceTableMergeCells')
    });
    editor.addButton('tablesplitcells', {
      title: 'Split cell',
      onclick: cmd('mceTableSplitCells')
    });
    editor.addButton('tableinsertrowbefore', {
      title: 'Insert row before',
      onclick: cmd('mceTableInsertRowBefore')
    });
    editor.addButton('tableinsertrowafter', {
      title: 'Insert row after',
      onclick: cmd('mceTableInsertRowAfter')
    });
    editor.addButton('tabledeleterow', {
      title: 'Delete row',
      onclick: cmd('mceTableDeleteRow')
    });
    editor.addButton('tablerowprops', {
      title: 'Row properties',
      onclick: cmd('mceTableRowProps')
    });
    editor.addButton('tablecutrow', {
      title: 'Cut row',
      onclick: cmd('mceTableCutRow')
    });
    editor.addButton('tablecopyrow', {
      title: 'Copy row',
      onclick: cmd('mceTableCopyRow')
    });
    editor.addButton('tablepasterowbefore', {
      title: 'Paste row before',
      onclick: cmd('mceTablePasteRowBefore')
    });
    editor.addButton('tablepasterowafter', {
      title: 'Paste row after',
      onclick: cmd('mceTablePasteRowAfter')
    });
    editor.addButton('tableinsertcolbefore', {
      title: 'Insert column before',
      onclick: cmd('mceTableInsertColBefore')
    });
    editor.addButton('tableinsertcolafter', {
      title: 'Insert column after',
      onclick: cmd('mceTableInsertColAfter')
    });
    editor.addButton('tabledeletecol', {
      title: 'Delete column',
      onclick: cmd('mceTableDeleteCol')
    });
  };
  var addToolbars = function (editor) {
    var isTable = function (table) {
      var selectorMatched = editor.dom.is(table, 'table') && editor.getBody().contains(table);
      return selectorMatched;
    };
    var toolbar = getToolbar(editor);
    if (toolbar.length > 0) {
      editor.addContextToolbar(isTable, toolbar.join(' '));
    }
  };
  var $_7ezhclq9jh8lz2h1 = {
    addButtons: addButtons,
    addToolbars: addToolbars
  };

  var addMenuItems = function (editor, selections) {
    var targets = Option.none();
    var tableCtrls = [];
    var cellCtrls = [];
    var mergeCtrls = [];
    var unmergeCtrls = [];
    var noTargetDisable = function (ctrl) {
      ctrl.disabled(true);
    };
    var ctrlEnable = function (ctrl) {
      ctrl.disabled(false);
    };
    var pushTable = function () {
      var self = this;
      tableCtrls.push(self);
      targets.fold(function () {
        noTargetDisable(self);
      }, function (targets) {
        ctrlEnable(self);
      });
    };
    var pushCell = function () {
      var self = this;
      cellCtrls.push(self);
      targets.fold(function () {
        noTargetDisable(self);
      }, function (targets) {
        ctrlEnable(self);
      });
    };
    var pushMerge = function () {
      var self = this;
      mergeCtrls.push(self);
      targets.fold(function () {
        noTargetDisable(self);
      }, function (targets) {
        self.disabled(targets.mergable().isNone());
      });
    };
    var pushUnmerge = function () {
      var self = this;
      unmergeCtrls.push(self);
      targets.fold(function () {
        noTargetDisable(self);
      }, function (targets) {
        self.disabled(targets.unmergable().isNone());
      });
    };
    var setDisabledCtrls = function () {
      targets.fold(function () {
        $_6b0spykcjh8lz1ao.each(tableCtrls, noTargetDisable);
        $_6b0spykcjh8lz1ao.each(cellCtrls, noTargetDisable);
        $_6b0spykcjh8lz1ao.each(mergeCtrls, noTargetDisable);
        $_6b0spykcjh8lz1ao.each(unmergeCtrls, noTargetDisable);
      }, function (targets) {
        $_6b0spykcjh8lz1ao.each(tableCtrls, ctrlEnable);
        $_6b0spykcjh8lz1ao.each(cellCtrls, ctrlEnable);
        $_6b0spykcjh8lz1ao.each(mergeCtrls, function (mergeCtrl) {
          mergeCtrl.disabled(targets.mergable().isNone());
        });
        $_6b0spykcjh8lz1ao.each(unmergeCtrls, function (unmergeCtrl) {
          unmergeCtrl.disabled(targets.unmergable().isNone());
        });
      });
    };
    editor.on('init', function () {
      editor.on('nodechange', function (e) {
        var cellOpt = Option.from(editor.dom.getParent(editor.selection.getStart(), 'th,td'));
        targets = cellOpt.bind(function (cellDom) {
          var cell = $_6vo9a4krjh8lz1do.fromDom(cellDom);
          var table = $_ee8pmfkojh8lz1ch.table(cell);
          return table.map(function (table) {
            return $_3xfj7olxjh8lz1j2.forMenu(selections, table, cell);
          });
        });
        setDisabledCtrls();
      });
    });
    var generateTableGrid = function () {
      var html = '';
      html = '<table role="grid" class="mce-grid mce-grid-border" aria-readonly="true">';
      for (var y = 0; y < 10; y++) {
        html += '<tr>';
        for (var x = 0; x < 10; x++) {
          html += '<td role="gridcell" tabindex="-1"><a id="mcegrid' + (y * 10 + x) + '" href="#" ' + 'data-mce-x="' + x + '" data-mce-y="' + y + '"></a></td>';
        }
        html += '</tr>';
      }
      html += '</table>';
      html += '<div class="mce-text-center" role="presentation">1 x 1</div>';
      return html;
    };
    var selectGrid = function (editor, tx, ty, control) {
      var table = control.getEl().getElementsByTagName('table')[0];
      var x, y, focusCell, cell, active;
      var rtl = control.isRtl() || control.parent().rel === 'tl-tr';
      table.nextSibling.innerHTML = tx + 1 + ' x ' + (ty + 1);
      if (rtl) {
        tx = 9 - tx;
      }
      for (y = 0; y < 10; y++) {
        for (x = 0; x < 10; x++) {
          cell = table.rows[y].childNodes[x].firstChild;
          active = (rtl ? x >= tx : x <= tx) && y <= ty;
          editor.dom.toggleClass(cell, 'mce-active', active);
          if (active) {
            focusCell = cell;
          }
        }
      }
      return focusCell.parentNode;
    };
    var insertTable = hasTableGrid(editor) === false ? {
      text: 'Table',
      icon: 'table',
      context: 'table',
      onclick: cmd('mceInsertTable')
    } : {
      text: 'Table',
      icon: 'table',
      context: 'table',
      ariaHideMenu: true,
      onclick: function (e) {
        if (e.aria) {
          this.parent().hideAll();
          e.stopImmediatePropagation();
          editor.execCommand('mceInsertTable');
        }
      },
      onshow: function () {
        selectGrid(editor, 0, 0, this.menu.items()[0]);
      },
      onhide: function () {
        var elements = this.menu.items()[0].getEl().getElementsByTagName('a');
        editor.dom.removeClass(elements, 'mce-active');
        editor.dom.addClass(elements[0], 'mce-active');
      },
      menu: [{
          type: 'container',
          html: generateTableGrid(),
          onPostRender: function () {
            this.lastX = this.lastY = 0;
          },
          onmousemove: function (e) {
            var target = e.target;
            var x, y;
            if (target.tagName.toUpperCase() === 'A') {
              x = parseInt(target.getAttribute('data-mce-x'), 10);
              y = parseInt(target.getAttribute('data-mce-y'), 10);
              if (this.isRtl() || this.parent().rel === 'tl-tr') {
                x = 9 - x;
              }
              if (x !== this.lastX || y !== this.lastY) {
                selectGrid(editor, x, y, e.control);
                this.lastX = x;
                this.lastY = y;
              }
            }
          },
          onclick: function (e) {
            var self = this;
            if (e.target.tagName.toUpperCase() === 'A') {
              e.preventDefault();
              e.stopPropagation();
              self.parent().cancel();
              editor.undoManager.transact(function () {
                $_7a3xgho8jh8lz20d.insert(editor, self.lastX + 1, self.lastY + 1);
              });
              editor.addVisual();
            }
          }
        }]
    };
    function cmd(command) {
      return function () {
        editor.execCommand(command);
      };
    }
    var tableProperties = {
      text: 'Table properties',
      context: 'table',
      onPostRender: pushTable,
      onclick: cmd('mceTableProps')
    };
    var deleteTable = {
      text: 'Delete table',
      context: 'table',
      onPostRender: pushTable,
      cmd: 'mceTableDelete'
    };
    var row = {
      text: 'Row',
      context: 'table',
      menu: [
        {
          text: 'Insert row before',
          onclick: cmd('mceTableInsertRowBefore'),
          onPostRender: pushCell
        },
        {
          text: 'Insert row after',
          onclick: cmd('mceTableInsertRowAfter'),
          onPostRender: pushCell
        },
        {
          text: 'Delete row',
          onclick: cmd('mceTableDeleteRow'),
          onPostRender: pushCell
        },
        {
          text: 'Row properties',
          onclick: cmd('mceTableRowProps'),
          onPostRender: pushCell
        },
        { text: '-' },
        {
          text: 'Cut row',
          onclick: cmd('mceTableCutRow'),
          onPostRender: pushCell
        },
        {
          text: 'Copy row',
          onclick: cmd('mceTableCopyRow'),
          onPostRender: pushCell
        },
        {
          text: 'Paste row before',
          onclick: cmd('mceTablePasteRowBefore'),
          onPostRender: pushCell
        },
        {
          text: 'Paste row after',
          onclick: cmd('mceTablePasteRowAfter'),
          onPostRender: pushCell
        }
      ]
    };
    var column = {
      text: 'Column',
      context: 'table',
      menu: [
        {
          text: 'Insert column before',
          onclick: cmd('mceTableInsertColBefore'),
          onPostRender: pushCell
        },
        {
          text: 'Insert column after',
          onclick: cmd('mceTableInsertColAfter'),
          onPostRender: pushCell
        },
        {
          text: 'Delete column',
          onclick: cmd('mceTableDeleteCol'),
          onPostRender: pushCell
        }
      ]
    };
    var cell = {
      separator: 'before',
      text: 'Cell',
      context: 'table',
      menu: [
        {
          text: 'Cell properties',
          onclick: cmd('mceTableCellProps'),
          onPostRender: pushCell
        },
        {
          text: 'Merge cells',
          onclick: cmd('mceTableMergeCells'),
          onPostRender: pushMerge
        },
        {
          text: 'Split cell',
          onclick: cmd('mceTableSplitCells'),
          onPostRender: pushUnmerge
        }
      ]
    };
    editor.addMenuItem('inserttable', insertTable);
    editor.addMenuItem('tableprops', tableProperties);
    editor.addMenuItem('deletetable', deleteTable);
    editor.addMenuItem('row', row);
    editor.addMenuItem('column', column);
    editor.addMenuItem('cell', cell);
  };
  var $_g08j12qajh8lz2h4 = { addMenuItems: addMenuItems };

  var getClipboardRows = function (clipboardRows) {
    return clipboardRows.get().fold(function () {
      return;
    }, function (rows) {
      return $_6b0spykcjh8lz1ao.map(rows, function (row) {
        return row.dom();
      });
    });
  };
  var setClipboardRows = function (rows, clipboardRows) {
    var sugarRows = $_6b0spykcjh8lz1ao.map(rows, $_6vo9a4krjh8lz1do.fromDom);
    clipboardRows.set(Option.from(sugarRows));
  };
  var getApi = function (editor, clipboardRows) {
    return {
      insertTable: function (columns, rows) {
        return $_7a3xgho8jh8lz20d.insert(editor, columns, rows);
      },
      setClipboardRows: function (rows) {
        return setClipboardRows(rows, clipboardRows);
      },
      getClipboardRows: function () {
        return getClipboardRows(clipboardRows);
      }
    };
  };

  function Plugin(editor) {
    var resizeHandler = ResizeHandler(editor);
    var cellSelection = CellSelection$1(editor, resizeHandler.lazyResize);
    var actions = TableActions(editor, resizeHandler.lazyWire);
    var selections = Selections(editor);
    var clipboardRows = Cell(Option.none());
    $_cmt2k3nzjh8lz1ym.registerCommands(editor, actions, cellSelection, selections, clipboardRows);
    $_3x42x9kbjh8lz1a2.registerEvents(editor, selections, actions, cellSelection);
    $_g08j12qajh8lz2h4.addMenuItems(editor, selections);
    $_7ezhclq9jh8lz2h1.addButtons(editor);
    $_7ezhclq9jh8lz2h1.addToolbars(editor);
    editor.on('PreInit', function () {
      editor.serializer.addTempAttr($_2yroczmcjh8lz1n4.firstSelected());
      editor.serializer.addTempAttr($_2yroczmcjh8lz1n4.lastSelected());
    });
    if (hasTabNavigation(editor)) {
      editor.on('keydown', function (e) {
        $_4jcvbhoyjh8lz25x.handle(e, editor, actions, resizeHandler.lazyWire);
      });
    }
    editor.on('remove', function () {
      resizeHandler.destroy();
      cellSelection.destroy();
    });
    return getApi(editor, clipboardRows);
  }
  global.add('table', Plugin);
  function Plugin$1 () {
  }

  return Plugin$1;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-template", ["tinymce"], function() {
  return (function() {
(function () {
var template = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var noop = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
  };
  var noarg = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return f();
    };
  };
  var compose = function (fa, fb) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return fa(fb.apply(null, arguments));
    };
  };
  var constant = function (value) {
    return function () {
      return value;
    };
  };
  var identity = function (x) {
    return x;
  };
  var tripleEquals = function (a, b) {
    return a === b;
  };
  var curry = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = new Array(arguments.length - 1);
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      var newArgs = new Array(arguments.length);
      for (var j = 0; j < newArgs.length; j++)
        newArgs[j] = arguments[j];
      var all = args.concat(newArgs);
      return f.apply(null, all);
    };
  };
  var not = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return !f.apply(null, arguments);
    };
  };
  var die = function (msg) {
    return function () {
      throw new Error(msg);
    };
  };
  var apply = function (f) {
    return f();
  };
  var call = function (f) {
    f();
  };
  var never = constant(false);
  var always = constant(true);
  var $_4ldd4lqfjh8lz34o = {
    noop: noop,
    noarg: noarg,
    compose: compose,
    constant: constant,
    identity: identity,
    tripleEquals: tripleEquals,
    curry: curry,
    not: not,
    die: die,
    apply: apply,
    call: call,
    never: never,
    always: always
  };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.XHR');

  var global$3 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var getCreationDateClasses = function (editor) {
    return editor.getParam('template_cdate_classes', 'cdate');
  };
  var getModificationDateClasses = function (editor) {
    return editor.getParam('template_mdate_classes', 'mdate');
  };
  var getSelectedContentClasses = function (editor) {
    return editor.getParam('template_selected_content_classes', 'selcontent');
  };
  var getPreviewReplaceValues = function (editor) {
    return editor.getParam('template_preview_replace_values');
  };
  var getTemplateReplaceValues = function (editor) {
    return editor.getParam('template_replace_values');
  };
  var getTemplates = function (editorSettings) {
    return editorSettings.templates;
  };
  var getCdateFormat = function (editor) {
    return editor.getParam('template_cdate_format', editor.getLang('template.cdate_format'));
  };
  var getMdateFormat = function (editor) {
    return editor.getParam('template_mdate_format', editor.getLang('template.mdate_format'));
  };
  var getDialogWidth = function (editor) {
    return editor.getParam('template_popup_width', 600);
  };
  var getDialogHeight = function (editor) {
    return Math.min(global$3.DOM.getViewPort().h, editor.getParam('template_popup_height', 500));
  };
  var $_aakka8qjjh8lz34u = {
    getCreationDateClasses: getCreationDateClasses,
    getModificationDateClasses: getModificationDateClasses,
    getSelectedContentClasses: getSelectedContentClasses,
    getPreviewReplaceValues: getPreviewReplaceValues,
    getTemplateReplaceValues: getTemplateReplaceValues,
    getTemplates: getTemplates,
    getCdateFormat: getCdateFormat,
    getMdateFormat: getMdateFormat,
    getDialogWidth: getDialogWidth,
    getDialogHeight: getDialogHeight
  };

  var addZeros = function (value, len) {
    value = '' + value;
    if (value.length < len) {
      for (var i = 0; i < len - value.length; i++) {
        value = '0' + value;
      }
    }
    return value;
  };
  var getDateTime = function (editor, fmt, date) {
    var daysShort = 'Sun Mon Tue Wed Thu Fri Sat Sun'.split(' ');
    var daysLong = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' ');
    var monthsShort = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
    var monthsLong = 'January February March April May June July August September October November December'.split(' ');
    date = date || new Date();
    fmt = fmt.replace('%D', '%m/%d/%Y');
    fmt = fmt.replace('%r', '%I:%M:%S %p');
    fmt = fmt.replace('%Y', '' + date.getFullYear());
    fmt = fmt.replace('%y', '' + date.getYear());
    fmt = fmt.replace('%m', addZeros(date.getMonth() + 1, 2));
    fmt = fmt.replace('%d', addZeros(date.getDate(), 2));
    fmt = fmt.replace('%H', '' + addZeros(date.getHours(), 2));
    fmt = fmt.replace('%M', '' + addZeros(date.getMinutes(), 2));
    fmt = fmt.replace('%S', '' + addZeros(date.getSeconds(), 2));
    fmt = fmt.replace('%I', '' + ((date.getHours() + 11) % 12 + 1));
    fmt = fmt.replace('%p', '' + (date.getHours() < 12 ? 'AM' : 'PM'));
    fmt = fmt.replace('%B', '' + editor.translate(monthsLong[date.getMonth()]));
    fmt = fmt.replace('%b', '' + editor.translate(monthsShort[date.getMonth()]));
    fmt = fmt.replace('%A', '' + editor.translate(daysLong[date.getDay()]));
    fmt = fmt.replace('%a', '' + editor.translate(daysShort[date.getDay()]));
    fmt = fmt.replace('%%', '%');
    return fmt;
  };
  var $_c5oa7zqljh8lz34w = { getDateTime: getDateTime };

  var createTemplateList = function (editorSettings, callback) {
    return function () {
      var templateList = $_aakka8qjjh8lz34u.getTemplates(editorSettings);
      if (typeof templateList === 'function') {
        templateList(callback);
        return;
      }
      if (typeof templateList === 'string') {
        global$2.send({
          url: templateList,
          success: function (text) {
            callback(JSON.parse(text));
          }
        });
      } else {
        callback(templateList);
      }
    };
  };
  var replaceTemplateValues = function (editor, html, templateValues) {
    global$1.each(templateValues, function (v, k) {
      if (typeof v === 'function') {
        v = v(k);
      }
      html = html.replace(new RegExp('\\{\\$' + k + '\\}', 'g'), v);
    });
    return html;
  };
  var replaceVals = function (editor, e) {
    var dom = editor.dom, vl = $_aakka8qjjh8lz34u.getTemplateReplaceValues(editor);
    global$1.each(dom.select('*', e), function (e) {
      global$1.each(vl, function (v, k) {
        if (dom.hasClass(e, k)) {
          if (typeof vl[k] === 'function') {
            vl[k](e);
          }
        }
      });
    });
  };
  var hasClass = function (n, c) {
    return new RegExp('\\b' + c + '\\b', 'g').test(n.className);
  };
  var insertTemplate = function (editor, ui, html) {
    var el;
    var n;
    var dom = editor.dom;
    var sel = editor.selection.getContent();
    html = replaceTemplateValues(editor, html, $_aakka8qjjh8lz34u.getTemplateReplaceValues(editor));
    el = dom.create('div', null, html);
    n = dom.select('.mceTmpl', el);
    if (n && n.length > 0) {
      el = dom.create('div', null);
      el.appendChild(n[0].cloneNode(true));
    }
    global$1.each(dom.select('*', el), function (n) {
      if (hasClass(n, $_aakka8qjjh8lz34u.getCreationDateClasses(editor).replace(/\s+/g, '|'))) {
        n.innerHTML = $_c5oa7zqljh8lz34w.getDateTime(editor, $_aakka8qjjh8lz34u.getCdateFormat(editor));
      }
      if (hasClass(n, $_aakka8qjjh8lz34u.getModificationDateClasses(editor).replace(/\s+/g, '|'))) {
        n.innerHTML = $_c5oa7zqljh8lz34w.getDateTime(editor, $_aakka8qjjh8lz34u.getMdateFormat(editor));
      }
      if (hasClass(n, $_aakka8qjjh8lz34u.getSelectedContentClasses(editor).replace(/\s+/g, '|'))) {
        n.innerHTML = sel;
      }
    });
    replaceVals(editor, el);
    editor.execCommand('mceInsertContent', false, el.innerHTML);
    editor.addVisual();
  };
  var $_4rrmzqgjh8lz34q = {
    createTemplateList: createTemplateList,
    replaceTemplateValues: replaceTemplateValues,
    replaceVals: replaceVals,
    insertTemplate: insertTemplate
  };

  var register = function (editor) {
    editor.addCommand('mceInsertTemplate', $_4ldd4lqfjh8lz34o.curry($_4rrmzqgjh8lz34q.insertTemplate, editor));
  };
  var $_ffyhw9qejh8lz34k = { register: register };

  var setup = function (editor) {
    editor.on('PreProcess', function (o) {
      var dom = editor.dom, dateFormat = $_aakka8qjjh8lz34u.getMdateFormat(editor);
      global$1.each(dom.select('div', o.node), function (e) {
        if (dom.hasClass(e, 'mceTmpl')) {
          global$1.each(dom.select('*', e), function (e) {
            if (dom.hasClass(e, editor.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|'))) {
              e.innerHTML = $_c5oa7zqljh8lz34w.getDateTime(editor, dateFormat);
            }
          });
          $_4rrmzqgjh8lz34q.replaceVals(editor, e);
        }
      });
    });
  };
  var $_fi8njaqmjh8lz34y = { setup: setup };

  var insertIframeHtml = function (editor, win, html) {
    if (html.indexOf('<html>') === -1) {
      var contentCssLinks_1 = '';
      global$1.each(editor.contentCSS, function (url) {
        contentCssLinks_1 += '<link type="text/css" rel="stylesheet" href="' + editor.documentBaseURI.toAbsolute(url) + '">';
      });
      var bodyClass = editor.settings.body_class || '';
      if (bodyClass.indexOf('=') !== -1) {
        bodyClass = editor.getParam('body_class', '', 'hash');
        bodyClass = bodyClass[editor.id] || '';
      }
      html = '<!DOCTYPE html>' + '<html>' + '<head>' + contentCssLinks_1 + '</head>' + '<body class="' + bodyClass + '">' + html + '</body>' + '</html>';
    }
    html = $_4rrmzqgjh8lz34q.replaceTemplateValues(editor, html, $_aakka8qjjh8lz34u.getPreviewReplaceValues(editor));
    var doc = win.find('iframe')[0].getEl().contentWindow.document;
    doc.open();
    doc.write(html);
    doc.close();
  };
  var open = function (editor, templateList) {
    var win;
    var values = [];
    var templateHtml;
    if (!templateList || templateList.length === 0) {
      var message = editor.translate('No templates defined.');
      editor.notificationManager.open({
        text: message,
        type: 'info'
      });
      return;
    }
    global$1.each(templateList, function (template) {
      values.push({
        selected: !values.length,
        text: template.title,
        value: {
          url: template.url,
          content: template.content,
          description: template.description
        }
      });
    });
    var onSelectTemplate = function (e) {
      var value = e.control.value();
      if (value.url) {
        global$2.send({
          url: value.url,
          success: function (html) {
            templateHtml = html;
            insertIframeHtml(editor, win, templateHtml);
          }
        });
      } else {
        templateHtml = value.content;
        insertIframeHtml(editor, win, templateHtml);
      }
      win.find('#description')[0].text(e.control.value().description);
    };
    win = editor.windowManager.open({
      title: 'Insert template',
      layout: 'flex',
      direction: 'column',
      align: 'stretch',
      padding: 15,
      spacing: 10,
      items: [
        {
          type: 'form',
          flex: 0,
          padding: 0,
          items: [{
              type: 'container',
              label: 'Templates',
              items: {
                type: 'listbox',
                label: 'Templates',
                name: 'template',
                values: values,
                onselect: onSelectTemplate
              }
            }]
        },
        {
          type: 'label',
          name: 'description',
          label: 'Description',
          text: '\xA0'
        },
        {
          type: 'iframe',
          flex: 1,
          border: 1
        }
      ],
      onsubmit: function () {
        $_4rrmzqgjh8lz34q.insertTemplate(editor, false, templateHtml);
      },
      minWidth: $_aakka8qjjh8lz34u.getDialogWidth(editor),
      minHeight: $_aakka8qjjh8lz34u.getDialogHeight(editor)
    });
    win.find('listbox')[0].fire('select');
  };
  var $_7vfghaqojh8lz351 = { open: open };

  var showDialog = function (editor) {
    return function (templates) {
      $_7vfghaqojh8lz351.open(editor, templates);
    };
  };
  var register$1 = function (editor) {
    editor.addButton('template', {
      title: 'Insert template',
      onclick: $_4rrmzqgjh8lz34q.createTemplateList(editor.settings, showDialog(editor))
    });
    editor.addMenuItem('template', {
      text: 'Template',
      onclick: $_4rrmzqgjh8lz34q.createTemplateList(editor.settings, showDialog(editor)),
      icon: 'template',
      context: 'insert'
    });
  };
  var $_c0clk2qnjh8lz34z = { register: register$1 };

  global.add('template', function (editor) {
    $_c0clk2qnjh8lz34z.register(editor);
    $_ffyhw9qejh8lz34k.register(editor);
    $_fi8njaqmjh8lz34y.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-textcolor", ["tinymce"], function() {
  return (function() {
(function () {
var textcolor = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var getCurrentColor = function (editor, format) {
    var color;
    editor.dom.getParents(editor.selection.getStart(), function (elm) {
      var value;
      if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
        color = value;
      }
    });
    return color;
  };
  var mapColors = function (colorMap) {
    var i;
    var colors = [];
    for (i = 0; i < colorMap.length; i += 2) {
      colors.push({
        text: colorMap[i + 1],
        color: '#' + colorMap[i]
      });
    }
    return colors;
  };
  var applyFormat = function (editor, format, value) {
    editor.undoManager.transact(function () {
      editor.focus();
      editor.formatter.apply(format, { value: value });
      editor.nodeChanged();
    });
  };
  var removeFormat = function (editor, format) {
    editor.undoManager.transact(function () {
      editor.focus();
      editor.formatter.remove(format, { value: null }, null, true);
      editor.nodeChanged();
    });
  };
  var $_1d7gtwqsjh8lz35z = {
    getCurrentColor: getCurrentColor,
    mapColors: mapColors,
    applyFormat: applyFormat,
    removeFormat: removeFormat
  };

  var register = function (editor) {
    editor.addCommand('mceApplyTextcolor', function (format, value) {
      $_1d7gtwqsjh8lz35z.applyFormat(editor, format, value);
    });
    editor.addCommand('mceRemoveTextcolor', function (format) {
      $_1d7gtwqsjh8lz35z.removeFormat(editor, format);
    });
  };
  var $_9kt0cyqrjh8lz35y = { register: register };

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var defaultColorMap = [
    '000000',
    'Black',
    '993300',
    'Burnt orange',
    '333300',
    'Dark olive',
    '003300',
    'Dark green',
    '003366',
    'Dark azure',
    '000080',
    'Navy Blue',
    '333399',
    'Indigo',
    '333333',
    'Very dark gray',
    '800000',
    'Maroon',
    'FF6600',
    'Orange',
    '808000',
    'Olive',
    '008000',
    'Green',
    '008080',
    'Teal',
    '0000FF',
    'Blue',
    '666699',
    'Grayish blue',
    '808080',
    'Gray',
    'FF0000',
    'Red',
    'FF9900',
    'Amber',
    '99CC00',
    'Yellow green',
    '339966',
    'Sea green',
    '33CCCC',
    'Turquoise',
    '3366FF',
    'Royal blue',
    '800080',
    'Purple',
    '999999',
    'Medium gray',
    'FF00FF',
    'Magenta',
    'FFCC00',
    'Gold',
    'FFFF00',
    'Yellow',
    '00FF00',
    'Lime',
    '00FFFF',
    'Aqua',
    '00CCFF',
    'Sky blue',
    '993366',
    'Red violet',
    'FFFFFF',
    'White',
    'FF99CC',
    'Pink',
    'FFCC99',
    'Peach',
    'FFFF99',
    'Light yellow',
    'CCFFCC',
    'Pale green',
    'CCFFFF',
    'Pale cyan',
    '99CCFF',
    'Light sky blue',
    'CC99FF',
    'Plum'
  ];
  var getTextColorMap = function (editor) {
    return editor.getParam('textcolor_map', defaultColorMap);
  };
  var getForeColorMap = function (editor) {
    return editor.getParam('forecolor_map', getTextColorMap(editor));
  };
  var getBackColorMap = function (editor) {
    return editor.getParam('backcolor_map', getTextColorMap(editor));
  };
  var getTextColorRows = function (editor) {
    return editor.getParam('textcolor_rows', 5);
  };
  var getTextColorCols = function (editor) {
    return editor.getParam('textcolor_cols', 8);
  };
  var getForeColorRows = function (editor) {
    return editor.getParam('forecolor_rows', getTextColorRows(editor));
  };
  var getBackColorRows = function (editor) {
    return editor.getParam('backcolor_rows', getTextColorRows(editor));
  };
  var getForeColorCols = function (editor) {
    return editor.getParam('forecolor_cols', getTextColorCols(editor));
  };
  var getBackColorCols = function (editor) {
    return editor.getParam('backcolor_cols', getTextColorCols(editor));
  };
  var getColorPickerCallback = function (editor) {
    return editor.getParam('color_picker_callback', null);
  };
  var hasColorPicker = function (editor) {
    return typeof getColorPickerCallback(editor) === 'function';
  };
  var $_cupc58qwjh8lz366 = {
    getForeColorMap: getForeColorMap,
    getBackColorMap: getBackColorMap,
    getForeColorRows: getForeColorRows,
    getBackColorRows: getBackColorRows,
    getForeColorCols: getForeColorCols,
    getBackColorCols: getBackColorCols,
    getColorPickerCallback: getColorPickerCallback,
    hasColorPicker: hasColorPicker
  };

  var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');

  var getHtml = function (cols, rows, colorMap, hasColorPicker) {
    var colors, color, html, last, x, y, i, count = 0;
    var id = global$1.DOM.uniqueId('mcearia');
    var getColorCellHtml = function (color, title) {
      var isNoColor = color === 'transparent';
      return '<td class="mce-grid-cell' + (isNoColor ? ' mce-colorbtn-trans' : '') + '">' + '<div id="' + id + '-' + count++ + '"' + ' data-mce-color="' + (color ? color : '') + '"' + ' role="option"' + ' tabIndex="-1"' + ' style="' + (color ? 'background-color: ' + color : '') + '"' + ' title="' + global$3.translate(title) + '">' + (isNoColor ? '&#215;' : '') + '</div>' + '</td>';
    };
    colors = $_1d7gtwqsjh8lz35z.mapColors(colorMap);
    colors.push({
      text: global$3.translate('No color'),
      color: 'transparent'
    });
    html = '<table class="mce-grid mce-grid-border mce-colorbutton-grid" role="list" cellspacing="0"><tbody>';
    last = colors.length - 1;
    for (y = 0; y < rows; y++) {
      html += '<tr>';
      for (x = 0; x < cols; x++) {
        i = y * cols + x;
        if (i > last) {
          html += '<td></td>';
        } else {
          color = colors[i];
          html += getColorCellHtml(color.color, color.text);
        }
      }
      html += '</tr>';
    }
    if (hasColorPicker) {
      html += '<tr>' + '<td colspan="' + cols + '" class="mce-custom-color-btn">' + '<div id="' + id + '-c" class="mce-widget mce-btn mce-btn-small mce-btn-flat" ' + 'role="button" tabindex="-1" aria-labelledby="' + id + '-c" style="width: 100%">' + '<button type="button" role="presentation" tabindex="-1">' + global$3.translate('Custom...') + '</button>' + '</div>' + '</td>' + '</tr>';
      html += '<tr>';
      for (x = 0; x < cols; x++) {
        html += getColorCellHtml('', 'Custom color');
      }
      html += '</tr>';
    }
    html += '</tbody></table>';
    return html;
  };
  var $_yigkpqxjh8lz368 = { getHtml: getHtml };

  var setDivColor = function setDivColor(div, value) {
    div.style.background = value;
    div.setAttribute('data-mce-color', value);
  };
  var onButtonClick = function (editor) {
    return function (e) {
      var ctrl = e.control;
      if (ctrl._color) {
        editor.execCommand('mceApplyTextcolor', ctrl.settings.format, ctrl._color);
      } else {
        editor.execCommand('mceRemoveTextcolor', ctrl.settings.format);
      }
    };
  };
  var onPanelClick = function (editor, cols) {
    return function (e) {
      var buttonCtrl = this.parent();
      var value;
      var currentColor = $_1d7gtwqsjh8lz35z.getCurrentColor(editor, buttonCtrl.settings.format);
      var selectColor = function (value) {
        editor.execCommand('mceApplyTextcolor', buttonCtrl.settings.format, value);
        buttonCtrl.hidePanel();
        buttonCtrl.color(value);
      };
      var resetColor = function () {
        editor.execCommand('mceRemoveTextcolor', buttonCtrl.settings.format);
        buttonCtrl.hidePanel();
        buttonCtrl.resetColor();
      };
      if (global$1.DOM.getParent(e.target, '.mce-custom-color-btn')) {
        buttonCtrl.hidePanel();
        var colorPickerCallback = $_cupc58qwjh8lz366.getColorPickerCallback(editor);
        colorPickerCallback.call(editor, function (value) {
          var tableElm = buttonCtrl.panel.getEl().getElementsByTagName('table')[0];
          var customColorCells, div, i;
          customColorCells = global$2.map(tableElm.rows[tableElm.rows.length - 1].childNodes, function (elm) {
            return elm.firstChild;
          });
          for (i = 0; i < customColorCells.length; i++) {
            div = customColorCells[i];
            if (!div.getAttribute('data-mce-color')) {
              break;
            }
          }
          if (i === cols) {
            for (i = 0; i < cols - 1; i++) {
              setDivColor(customColorCells[i], customColorCells[i + 1].getAttribute('data-mce-color'));
            }
          }
          setDivColor(div, value);
          selectColor(value);
        }, currentColor);
      }
      value = e.target.getAttribute('data-mce-color');
      if (value) {
        if (this.lastId) {
          global$1.DOM.get(this.lastId).setAttribute('aria-selected', 'false');
        }
        e.target.setAttribute('aria-selected', true);
        this.lastId = e.target.id;
        if (value === 'transparent') {
          resetColor();
        } else {
          selectColor(value);
        }
      } else if (value !== null) {
        buttonCtrl.hidePanel();
      }
    };
  };
  var renderColorPicker = function (editor, foreColor) {
    return function () {
      var cols = foreColor ? $_cupc58qwjh8lz366.getForeColorCols(editor) : $_cupc58qwjh8lz366.getBackColorCols(editor);
      var rows = foreColor ? $_cupc58qwjh8lz366.getForeColorRows(editor) : $_cupc58qwjh8lz366.getBackColorRows(editor);
      var colorMap = foreColor ? $_cupc58qwjh8lz366.getForeColorMap(editor) : $_cupc58qwjh8lz366.getBackColorMap(editor);
      var hasColorPicker = $_cupc58qwjh8lz366.hasColorPicker(editor);
      return $_yigkpqxjh8lz368.getHtml(cols, rows, colorMap, hasColorPicker);
    };
  };
  var register$1 = function (editor) {
    editor.addButton('forecolor', {
      type: 'colorbutton',
      tooltip: 'Text color',
      format: 'forecolor',
      panel: {
        role: 'application',
        ariaRemember: true,
        html: renderColorPicker(editor, true),
        onclick: onPanelClick(editor, $_cupc58qwjh8lz366.getForeColorCols(editor))
      },
      onclick: onButtonClick(editor)
    });
    editor.addButton('backcolor', {
      type: 'colorbutton',
      tooltip: 'Background color',
      format: 'hilitecolor',
      panel: {
        role: 'application',
        ariaRemember: true,
        html: renderColorPicker(editor, false),
        onclick: onPanelClick(editor, $_cupc58qwjh8lz366.getBackColorCols(editor))
      },
      onclick: onButtonClick(editor)
    });
  };
  var $_dk5fhnqtjh8lz361 = { register: register$1 };

  global.add('textcolor', function (editor) {
    $_9kt0cyqrjh8lz35y.register(editor);
    $_dk5fhnqtjh8lz361.register(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-textpattern", ["tinymce"], function() {
  return (function() {
(function () {
var textpattern = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var get = function (patternsState) {
    var setPatterns = function (newPatterns) {
      patternsState.set(newPatterns);
    };
    var getPatterns = function () {
      return patternsState.get();
    };
    return {
      setPatterns: setPatterns,
      getPatterns: getPatterns
    };
  };
  var $_2txh6dr2jh8lz36u = { get: get };

  var defaultPatterns = [
    {
      start: '*',
      end: '*',
      format: 'italic'
    },
    {
      start: '**',
      end: '**',
      format: 'bold'
    },
    {
      start: '***',
      end: '***',
      format: [
        'bold',
        'italic'
      ]
    },
    {
      start: '#',
      format: 'h1'
    },
    {
      start: '##',
      format: 'h2'
    },
    {
      start: '###',
      format: 'h3'
    },
    {
      start: '####',
      format: 'h4'
    },
    {
      start: '#####',
      format: 'h5'
    },
    {
      start: '######',
      format: 'h6'
    },
    {
      start: '1. ',
      cmd: 'InsertOrderedList'
    },
    {
      start: '* ',
      cmd: 'InsertUnorderedList'
    },
    {
      start: '- ',
      cmd: 'InsertUnorderedList'
    }
  ];
  var getPatterns = function (editorSettings) {
    return editorSettings.textpattern_patterns !== undefined ? editorSettings.textpattern_patterns : defaultPatterns;
  };
  var $_2d3ibsr3jh8lz36v = { getPatterns: getPatterns };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');

  var global$4 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var sortPatterns = function (patterns) {
    return patterns.sort(function (a, b) {
      if (a.start.length > b.start.length) {
        return -1;
      }
      if (a.start.length < b.start.length) {
        return 1;
      }
      return 0;
    });
  };
  var findPattern = function (patterns, text) {
    for (var i = 0; i < patterns.length; i++) {
      if (text.indexOf(patterns[i].start) !== 0) {
        continue;
      }
      if (patterns[i].end && text.lastIndexOf(patterns[i].end) !== text.length - patterns[i].end.length) {
        continue;
      }
      return patterns[i];
    }
  };
  var isMatchingPattern = function (pattern, text, offset, delta) {
    var textEnd = text.substr(offset - pattern.end.length - delta, pattern.end.length);
    return textEnd === pattern.end;
  };
  var hasContent = function (offset, delta, pattern) {
    return offset - delta - pattern.end.length - pattern.start.length > 0;
  };
  var findEndPattern = function (patterns, text, offset, delta) {
    var pattern, i;
    var sortedPatterns = sortPatterns(patterns);
    for (i = 0; i < sortedPatterns.length; i++) {
      pattern = sortedPatterns[i];
      if (pattern.end !== undefined && isMatchingPattern(pattern, text, offset, delta) && hasContent(offset, delta, pattern)) {
        return pattern;
      }
    }
  };
  var $_el6qhwrbjh8lz37d = {
    findPattern: findPattern,
    findEndPattern: findEndPattern
  };

  var splitContainer = function (container, pattern, endOffset, startOffset, space) {
    container = startOffset > 0 ? container.splitText(startOffset) : container;
    container.splitText(endOffset - startOffset + pattern.end.length);
    container.deleteData(0, pattern.start.length);
    container.deleteData(container.data.length - pattern.end.length, pattern.end.length);
    return container;
  };
  var patternFromRng = function (patterns, rng, space) {
    if (rng.collapsed === false) {
      return;
    }
    var container = rng.startContainer;
    var text = container.data;
    var delta = space === true ? 1 : 0;
    if (container.nodeType !== 3) {
      return;
    }
    var endPattern = $_el6qhwrbjh8lz37d.findEndPattern(patterns, text, rng.startOffset, delta);
    if (endPattern === undefined) {
      return;
    }
    var endOffset = text.lastIndexOf(endPattern.end, rng.startOffset - delta);
    var startOffset = text.lastIndexOf(endPattern.start, endOffset - endPattern.end.length);
    endOffset = text.indexOf(endPattern.end, startOffset + endPattern.start.length);
    if (startOffset === -1) {
      return;
    }
    var patternRng = document.createRange();
    patternRng.setStart(container, startOffset);
    patternRng.setEnd(container, endOffset + endPattern.end.length);
    var startPattern = $_el6qhwrbjh8lz37d.findPattern(patterns, patternRng.toString());
    if (endPattern === undefined || startPattern !== endPattern || container.data.length <= endPattern.start.length + endPattern.end.length) {
      return;
    }
    return {
      pattern: endPattern,
      startOffset: startOffset,
      endOffset: endOffset
    };
  };
  var splitAndApply = function (editor, container, found, space) {
    var formatArray = global$4.isArray(found.pattern.format) ? found.pattern.format : [found.pattern.format];
    var validFormats = global$4.grep(formatArray, function (formatName) {
      var format = editor.formatter.get(formatName);
      return format && format[0].inline;
    });
    if (validFormats.length !== 0) {
      editor.undoManager.transact(function () {
        container = splitContainer(container, found.pattern, found.endOffset, found.startOffset, space);
        formatArray.forEach(function (format) {
          editor.formatter.apply(format, {}, container);
        });
      });
      return container;
    }
  };
  var doApplyInlineFormat = function (editor, patterns, space) {
    var rng = editor.selection.getRng(true);
    var foundPattern = patternFromRng(patterns, rng, space);
    if (foundPattern) {
      return splitAndApply(editor, rng.startContainer, foundPattern, space);
    }
  };
  var applyInlineFormatSpace = function (editor, patterns) {
    return doApplyInlineFormat(editor, patterns, true);
  };
  var applyInlineFormatEnter = function (editor, patterns) {
    return doApplyInlineFormat(editor, patterns, false);
  };
  var applyBlockFormat = function (editor, patterns) {
    var selection, dom, container, firstTextNode, node, format, textBlockElm, pattern, walker, rng, offset;
    selection = editor.selection;
    dom = editor.dom;
    if (!selection.isCollapsed()) {
      return;
    }
    textBlockElm = dom.getParent(selection.getStart(), 'p');
    if (textBlockElm) {
      walker = new global$3(textBlockElm, textBlockElm);
      while (node = walker.next()) {
        if (node.nodeType === 3) {
          firstTextNode = node;
          break;
        }
      }
      if (firstTextNode) {
        pattern = $_el6qhwrbjh8lz37d.findPattern(patterns, firstTextNode.data);
        if (!pattern) {
          return;
        }
        rng = selection.getRng(true);
        container = rng.startContainer;
        offset = rng.startOffset;
        if (firstTextNode === container) {
          offset = Math.max(0, offset - pattern.start.length);
        }
        if (global$4.trim(firstTextNode.data).length === pattern.start.length) {
          return;
        }
        if (pattern.format) {
          format = editor.formatter.get(pattern.format);
          if (format && format[0].block) {
            firstTextNode.deleteData(0, pattern.start.length);
            editor.formatter.apply(pattern.format, {}, firstTextNode);
            rng.setStart(container, offset);
            rng.collapse(true);
            selection.setRng(rng);
          }
        }
        if (pattern.cmd) {
          editor.undoManager.transact(function () {
            firstTextNode.deleteData(0, pattern.start.length);
            editor.execCommand(pattern.cmd);
          });
        }
      }
    }
  };
  var $_gffj5fr8jh8lz379 = {
    patternFromRng: patternFromRng,
    applyInlineFormatSpace: applyInlineFormatSpace,
    applyInlineFormatEnter: applyInlineFormatEnter,
    applyBlockFormat: applyBlockFormat
  };

  function handleEnter(editor, patterns) {
    var wrappedTextNode, rng;
    wrappedTextNode = $_gffj5fr8jh8lz379.applyInlineFormatEnter(editor, patterns);
    if (wrappedTextNode) {
      rng = editor.dom.createRng();
      rng.setStart(wrappedTextNode, wrappedTextNode.data.length);
      rng.setEnd(wrappedTextNode, wrappedTextNode.data.length);
      editor.selection.setRng(rng);
    }
    $_gffj5fr8jh8lz379.applyBlockFormat(editor, patterns);
  }
  function handleInlineKey(editor, patterns) {
    var wrappedTextNode, lastChar, lastCharNode, rng, dom;
    wrappedTextNode = $_gffj5fr8jh8lz379.applyInlineFormatSpace(editor, patterns);
    if (wrappedTextNode) {
      dom = editor.dom;
      lastChar = wrappedTextNode.data.slice(-1);
      if (/[\u00a0 ]/.test(lastChar)) {
        wrappedTextNode.deleteData(wrappedTextNode.data.length - 1, 1);
        lastCharNode = dom.doc.createTextNode(lastChar);
        dom.insertAfter(lastCharNode, wrappedTextNode.parentNode);
        rng = dom.createRng();
        rng.setStart(lastCharNode, 1);
        rng.setEnd(lastCharNode, 1);
        editor.selection.setRng(rng);
      }
    }
  }
  var checkKeyEvent = function (codes, event, predicate) {
    for (var i = 0; i < codes.length; i++) {
      if (predicate(codes[i], event)) {
        return true;
      }
    }
  };
  var checkKeyCode = function (codes, event) {
    return checkKeyEvent(codes, event, function (code, event) {
      return code === event.keyCode && global$2.modifierPressed(event) === false;
    });
  };
  var checkCharCode = function (chars, event) {
    return checkKeyEvent(chars, event, function (chr, event) {
      return chr.charCodeAt(0) === event.charCode;
    });
  };
  var $_6uf8aer7jh8lz36z = {
    handleEnter: handleEnter,
    handleInlineKey: handleInlineKey,
    checkCharCode: checkCharCode,
    checkKeyCode: checkKeyCode
  };

  var setup = function (editor, patternsState) {
    var charCodes = [
      ',',
      '.',
      ';',
      ':',
      '!',
      '?'
    ];
    var keyCodes = [32];
    editor.on('keydown', function (e) {
      if (e.keyCode === 13 && !global$2.modifierPressed(e)) {
        $_6uf8aer7jh8lz36z.handleEnter(editor, patternsState.get());
      }
    }, true);
    editor.on('keyup', function (e) {
      if ($_6uf8aer7jh8lz36z.checkKeyCode(keyCodes, e)) {
        $_6uf8aer7jh8lz36z.handleInlineKey(editor, patternsState.get());
      }
    });
    editor.on('keypress', function (e) {
      if ($_6uf8aer7jh8lz36z.checkCharCode(charCodes, e)) {
        global$1.setEditorTimeout(editor, function () {
          $_6uf8aer7jh8lz36z.handleInlineKey(editor, patternsState.get());
        });
      }
    });
  };
  var $_6vgmler4jh8lz36x = { setup: setup };

  global.add('textpattern', function (editor) {
    var patternsState = Cell($_2d3ibsr3jh8lz36v.getPatterns(editor.settings));
    $_6vgmler4jh8lz36x.setup(editor, patternsState);
    return $_2txh6dr2jh8lz36u.get(patternsState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-visualblocks", ["tinymce"], function() {
  return (function() {
(function () {
var visualblocks = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var fireVisualBlocks = function (editor, state) {
    editor.fire('VisualBlocks', { state: state });
  };
  var $_h9rpfrsjh8lz3ee = { fireVisualBlocks: fireVisualBlocks };

  var isEnabledByDefault = function (editor) {
    return editor.getParam('visualblocks_default_state', false);
  };
  var getContentCss = function (editor) {
    return editor.settings.visualblocks_content_css;
  };
  var $_t5nqwrtjh8lz3ef = {
    isEnabledByDefault: isEnabledByDefault,
    getContentCss: getContentCss
  };

  var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

  var cssId = global$1.DOM.uniqueId();
  var load = function (doc, url) {
    var linkElements = global$2.toArray(doc.getElementsByTagName('link'));
    var matchingLinkElms = global$2.grep(linkElements, function (head) {
      return head.id === cssId;
    });
    if (matchingLinkElms.length === 0) {
      var linkElm = global$1.DOM.create('link', {
        id: cssId,
        rel: 'stylesheet',
        href: url
      });
      doc.getElementsByTagName('head')[0].appendChild(linkElm);
    }
  };
  var $_g7sccqrujh8lz3eg = { load: load };

  var toggleVisualBlocks = function (editor, pluginUrl, enabledState) {
    var dom = editor.dom;
    var contentCss = $_t5nqwrtjh8lz3ef.getContentCss(editor);
    $_g7sccqrujh8lz3eg.load(editor.getDoc(), contentCss ? contentCss : pluginUrl + '/css/visualblocks.css');
    dom.toggleClass(editor.getBody(), 'mce-visualblocks');
    enabledState.set(!enabledState.get());
    $_h9rpfrsjh8lz3ee.fireVisualBlocks(editor, enabledState.get());
  };
  var $_7ddznfrrjh8lz3ed = { toggleVisualBlocks: toggleVisualBlocks };

  var register = function (editor, pluginUrl, enabledState) {
    editor.addCommand('mceVisualBlocks', function () {
      $_7ddznfrrjh8lz3ed.toggleVisualBlocks(editor, pluginUrl, enabledState);
    });
  };
  var $_82j3kqrqjh8lz3ec = { register: register };

  var setup = function (editor, pluginUrl, enabledState) {
    editor.on('PreviewFormats AfterPreviewFormats', function (e) {
      if (enabledState.get()) {
        editor.dom.toggleClass(editor.getBody(), 'mce-visualblocks', e.type === 'afterpreviewformats');
      }
    });
    editor.on('init', function () {
      if ($_t5nqwrtjh8lz3ef.isEnabledByDefault(editor)) {
        $_7ddznfrrjh8lz3ed.toggleVisualBlocks(editor, pluginUrl, enabledState);
      }
    });
    editor.on('remove', function () {
      editor.dom.removeClass(editor.getBody(), 'mce-visualblocks');
    });
  };
  var $_cs6iq5rxjh8lz3ei = { setup: setup };

  var toggleActiveState = function (editor, enabledState) {
    return function (e) {
      var ctrl = e.control;
      ctrl.active(enabledState.get());
      editor.on('VisualBlocks', function (e) {
        ctrl.active(e.state);
      });
    };
  };
  var register$1 = function (editor, enabledState) {
    editor.addButton('visualblocks', {
      active: false,
      title: 'Show blocks',
      cmd: 'mceVisualBlocks',
      onPostRender: toggleActiveState(editor, enabledState)
    });
    editor.addMenuItem('visualblocks', {
      text: 'Show blocks',
      cmd: 'mceVisualBlocks',
      onPostRender: toggleActiveState(editor, enabledState),
      selectable: true,
      context: 'view',
      prependToContext: true
    });
  };
  var $_9qaw0mryjh8lz3ej = { register: register$1 };

  global.add('visualblocks', function (editor, pluginUrl) {
    var enabledState = Cell(false);
    $_82j3kqrqjh8lz3ec.register(editor, pluginUrl, enabledState);
    $_9qaw0mryjh8lz3ej.register(editor, enabledState);
    $_cs6iq5rxjh8lz3ei.setup(editor, pluginUrl, enabledState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-visualchars", ["tinymce"], function() {
  return (function() {
(function () {
var visualchars = (function () {
  'use strict';

  var Cell = function (initial) {
    var value = initial;
    var get = function () {
      return value;
    };
    var set = function (v) {
      value = v;
    };
    var clone = function () {
      return Cell(get());
    };
    return {
      get: get,
      set: set,
      clone: clone
    };
  };

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var get = function (toggleState) {
    var isEnabled = function () {
      return toggleState.get();
    };
    return { isEnabled: isEnabled };
  };
  var $_bmmym6s2jh8lz3f4 = { get: get };

  var fireVisualChars = function (editor, state) {
    return editor.fire('VisualChars', { state: state });
  };
  var $_ca1g8as5jh8lz3f7 = { fireVisualChars: fireVisualChars };

  var charMap = {
    '\xA0': 'nbsp',
    '\xAD': 'shy'
  };
  var charMapToRegExp = function (charMap, global) {
    var key, regExp = '';
    for (key in charMap) {
      regExp += key;
    }
    return new RegExp('[' + regExp + ']', global ? 'g' : '');
  };
  var charMapToSelector = function (charMap) {
    var key, selector = '';
    for (key in charMap) {
      if (selector) {
        selector += ',';
      }
      selector += 'span.mce-' + charMap[key];
    }
    return selector;
  };
  var $_4quw9ds7jh8lz3fg = {
    charMap: charMap,
    regExp: charMapToRegExp(charMap),
    regExpGlobal: charMapToRegExp(charMap, true),
    selector: charMapToSelector(charMap),
    charMapToRegExp: charMapToRegExp,
    charMapToSelector: charMapToSelector
  };

  var noop = function () {
    var x = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      x[_i] = arguments[_i];
    }
  };
  var noarg = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return f();
    };
  };
  var compose = function (fa, fb) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return fa(fb.apply(null, arguments));
    };
  };
  var constant = function (value) {
    return function () {
      return value;
    };
  };
  var identity = function (x) {
    return x;
  };
  var tripleEquals = function (a, b) {
    return a === b;
  };
  var curry = function (f) {
    var x = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      x[_i - 1] = arguments[_i];
    }
    var args = new Array(arguments.length - 1);
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      var newArgs = new Array(arguments.length);
      for (var j = 0; j < newArgs.length; j++)
        newArgs[j] = arguments[j];
      var all = args.concat(newArgs);
      return f.apply(null, all);
    };
  };
  var not = function (f) {
    return function () {
      var x = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        x[_i] = arguments[_i];
      }
      return !f.apply(null, arguments);
    };
  };
  var die = function (msg) {
    return function () {
      throw new Error(msg);
    };
  };
  var apply = function (f) {
    return f();
  };
  var call = function (f) {
    f();
  };
  var never = constant(false);
  var always = constant(true);
  var $_7oq9iksbjh8lz3g0 = {
    noop: noop,
    noarg: noarg,
    compose: compose,
    constant: constant,
    identity: identity,
    tripleEquals: tripleEquals,
    curry: curry,
    not: not,
    die: die,
    apply: apply,
    call: call,
    never: never,
    always: always
  };

  var never$1 = $_7oq9iksbjh8lz3g0.never;
  var always$1 = $_7oq9iksbjh8lz3g0.always;
  var none = function () {
    return NONE;
  };
  var NONE = function () {
    var eq = function (o) {
      return o.isNone();
    };
    var call = function (thunk) {
      return thunk();
    };
    var id = function (n) {
      return n;
    };
    var noop = function () {
    };
    var me = {
      fold: function (n, s) {
        return n();
      },
      is: never$1,
      isSome: never$1,
      isNone: always$1,
      getOr: id,
      getOrThunk: call,
      getOrDie: function (msg) {
        throw new Error(msg || 'error: getOrDie called on none.');
      },
      or: id,
      orThunk: call,
      map: none,
      ap: none,
      each: noop,
      bind: none,
      flatten: none,
      exists: never$1,
      forall: always$1,
      filter: none,
      equals: eq,
      equals_: eq,
      toArray: function () {
        return [];
      },
      toString: $_7oq9iksbjh8lz3g0.constant('none()')
    };
    if (Object.freeze)
      Object.freeze(me);
    return me;
  }();
  var some = function (a) {
    var constant_a = function () {
      return a;
    };
    var self = function () {
      return me;
    };
    var map = function (f) {
      return some(f(a));
    };
    var bind = function (f) {
      return f(a);
    };
    var me = {
      fold: function (n, s) {
        return s(a);
      },
      is: function (v) {
        return a === v;
      },
      isSome: always$1,
      isNone: never$1,
      getOr: constant_a,
      getOrThunk: constant_a,
      getOrDie: constant_a,
      or: self,
      orThunk: self,
      map: map,
      ap: function (optfab) {
        return optfab.fold(none, function (fab) {
          return some(fab(a));
        });
      },
      each: function (f) {
        f(a);
      },
      bind: bind,
      flatten: constant_a,
      exists: bind,
      forall: bind,
      filter: function (f) {
        return f(a) ? me : NONE;
      },
      equals: function (o) {
        return o.is(a);
      },
      equals_: function (o, elementEq) {
        return o.fold(never$1, function (b) {
          return elementEq(a, b);
        });
      },
      toArray: function () {
        return [a];
      },
      toString: function () {
        return 'some(' + a + ')';
      }
    };
    return me;
  };
  var from = function (value) {
    return value === null || value === undefined ? NONE : some(value);
  };
  var Option = {
    some: some,
    none: none,
    from: from
  };

  var typeOf = function (x) {
    if (x === null)
      return 'null';
    var t = typeof x;
    if (t === 'object' && Array.prototype.isPrototypeOf(x))
      return 'array';
    if (t === 'object' && String.prototype.isPrototypeOf(x))
      return 'string';
    return t;
  };
  var isType = function (type) {
    return function (value) {
      return typeOf(value) === type;
    };
  };
  var $_fnb6mscjh8lz3g2 = {
    isString: isType('string'),
    isObject: isType('object'),
    isArray: isType('array'),
    isNull: isType('null'),
    isBoolean: isType('boolean'),
    isUndefined: isType('undefined'),
    isFunction: isType('function'),
    isNumber: isType('number')
  };

  var rawIndexOf = function () {
    var pIndexOf = Array.prototype.indexOf;
    var fastIndex = function (xs, x) {
      return pIndexOf.call(xs, x);
    };
    var slowIndex = function (xs, x) {
      return slowIndexOf(xs, x);
    };
    return pIndexOf === undefined ? slowIndex : fastIndex;
  }();
  var indexOf = function (xs, x) {
    var r = rawIndexOf(xs, x);
    return r === -1 ? Option.none() : Option.some(r);
  };
  var contains = function (xs, x) {
    return rawIndexOf(xs, x) > -1;
  };
  var exists = function (xs, pred) {
    return findIndex(xs, pred).isSome();
  };
  var range = function (num, f) {
    var r = [];
    for (var i = 0; i < num; i++) {
      r.push(f(i));
    }
    return r;
  };
  var chunk = function (array, size) {
    var r = [];
    for (var i = 0; i < array.length; i += size) {
      var s = array.slice(i, i + size);
      r.push(s);
    }
    return r;
  };
  var map = function (xs, f) {
    var len = xs.length;
    var r = new Array(len);
    for (var i = 0; i < len; i++) {
      var x = xs[i];
      r[i] = f(x, i, xs);
    }
    return r;
  };
  var each = function (xs, f) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var eachr = function (xs, f) {
    for (var i = xs.length - 1; i >= 0; i--) {
      var x = xs[i];
      f(x, i, xs);
    }
  };
  var partition = function (xs, pred) {
    var pass = [];
    var fail = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      var arr = pred(x, i, xs) ? pass : fail;
      arr.push(x);
    }
    return {
      pass: pass,
      fail: fail
    };
  };
  var filter = function (xs, pred) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        r.push(x);
      }
    }
    return r;
  };
  var groupBy = function (xs, f) {
    if (xs.length === 0) {
      return [];
    } else {
      var wasType = f(xs[0]);
      var r = [];
      var group = [];
      for (var i = 0, len = xs.length; i < len; i++) {
        var x = xs[i];
        var type = f(x);
        if (type !== wasType) {
          r.push(group);
          group = [];
        }
        wasType = type;
        group.push(x);
      }
      if (group.length !== 0) {
        r.push(group);
      }
      return r;
    }
  };
  var foldr = function (xs, f, acc) {
    eachr(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var foldl = function (xs, f, acc) {
    each(xs, function (x) {
      acc = f(acc, x);
    });
    return acc;
  };
  var find = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(x);
      }
    }
    return Option.none();
  };
  var findIndex = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      if (pred(x, i, xs)) {
        return Option.some(i);
      }
    }
    return Option.none();
  };
  var slowIndexOf = function (xs, x) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (xs[i] === x) {
        return i;
      }
    }
    return -1;
  };
  var push = Array.prototype.push;
  var flatten = function (xs) {
    var r = [];
    for (var i = 0, len = xs.length; i < len; ++i) {
      if (!Array.prototype.isPrototypeOf(xs[i]))
        throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
      push.apply(r, xs[i]);
    }
    return r;
  };
  var bind = function (xs, f) {
    var output = map(xs, f);
    return flatten(output);
  };
  var forall = function (xs, pred) {
    for (var i = 0, len = xs.length; i < len; ++i) {
      var x = xs[i];
      if (pred(x, i, xs) !== true) {
        return false;
      }
    }
    return true;
  };
  var equal = function (a1, a2) {
    return a1.length === a2.length && forall(a1, function (x, i) {
      return x === a2[i];
    });
  };
  var slice = Array.prototype.slice;
  var reverse = function (xs) {
    var r = slice.call(xs, 0);
    r.reverse();
    return r;
  };
  var difference = function (a1, a2) {
    return filter(a1, function (x) {
      return !contains(a2, x);
    });
  };
  var mapToObject = function (xs, f) {
    var r = {};
    for (var i = 0, len = xs.length; i < len; i++) {
      var x = xs[i];
      r[String(x)] = f(x, i);
    }
    return r;
  };
  var pure = function (x) {
    return [x];
  };
  var sort = function (xs, comparator) {
    var copy = slice.call(xs, 0);
    copy.sort(comparator);
    return copy;
  };
  var head = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  };
  var last = function (xs) {
    return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  };
  var from$1 = $_fnb6mscjh8lz3g2.isFunction(Array.from) ? Array.from : function (x) {
    return slice.call(x);
  };
  var $_9i8hjds9jh8lz3fq = {
    map: map,
    each: each,
    eachr: eachr,
    partition: partition,
    filter: filter,
    groupBy: groupBy,
    indexOf: indexOf,
    foldr: foldr,
    foldl: foldl,
    find: find,
    findIndex: findIndex,
    flatten: flatten,
    bind: bind,
    forall: forall,
    exists: exists,
    contains: contains,
    equal: equal,
    reverse: reverse,
    chunk: chunk,
    difference: difference,
    mapToObject: mapToObject,
    pure: pure,
    sort: sort,
    range: range,
    head: head,
    last: last,
    from: from$1
  };

  var fromHtml = function (html, scope) {
    var doc = scope || document;
    var div = doc.createElement('div');
    div.innerHTML = html;
    if (!div.hasChildNodes() || div.childNodes.length > 1) {
      console.error('HTML does not have a single root node', html);
      throw 'HTML must have a single root node';
    }
    return fromDom(div.childNodes[0]);
  };
  var fromTag = function (tag, scope) {
    var doc = scope || document;
    var node = doc.createElement(tag);
    return fromDom(node);
  };
  var fromText = function (text, scope) {
    var doc = scope || document;
    var node = doc.createTextNode(text);
    return fromDom(node);
  };
  var fromDom = function (node) {
    if (node === null || node === undefined)
      throw new Error('Node cannot be null or undefined');
    return { dom: $_7oq9iksbjh8lz3g0.constant(node) };
  };
  var fromPoint = function (doc, x, y) {
    return Option.from(doc.dom().elementFromPoint(x, y)).map(fromDom);
  };
  var $_ca7ezesdjh8lz3g4 = {
    fromHtml: fromHtml,
    fromTag: fromTag,
    fromText: fromText,
    fromDom: fromDom,
    fromPoint: fromPoint
  };

  var $_6wgyobsfjh8lz3gb = {
    ATTRIBUTE: 2,
    CDATA_SECTION: 4,
    COMMENT: 8,
    DOCUMENT: 9,
    DOCUMENT_TYPE: 10,
    DOCUMENT_FRAGMENT: 11,
    ELEMENT: 1,
    TEXT: 3,
    PROCESSING_INSTRUCTION: 7,
    ENTITY_REFERENCE: 5,
    ENTITY: 6,
    NOTATION: 12
  };

  var name = function (element) {
    var r = element.dom().nodeName;
    return r.toLowerCase();
  };
  var type = function (element) {
    return element.dom().nodeType;
  };
  var value = function (element) {
    return element.dom().nodeValue;
  };
  var isType$1 = function (t) {
    return function (element) {
      return type(element) === t;
    };
  };
  var isComment = function (element) {
    return type(element) === $_6wgyobsfjh8lz3gb.COMMENT || name(element) === '#comment';
  };
  var isElement = isType$1($_6wgyobsfjh8lz3gb.ELEMENT);
  var isText = isType$1($_6wgyobsfjh8lz3gb.TEXT);
  var isDocument = isType$1($_6wgyobsfjh8lz3gb.DOCUMENT);
  var $_aa8ah0sejh8lz3g9 = {
    name: name,
    type: type,
    value: value,
    isElement: isElement,
    isText: isText,
    isDocument: isDocument,
    isComment: isComment
  };

  var wrapCharWithSpan = function (value) {
    return '<span data-mce-bogus="1" class="mce-' + $_4quw9ds7jh8lz3fg.charMap[value] + '">' + value + '</span>';
  };
  var $_g64rhxsgjh8lz3gb = { wrapCharWithSpan: wrapCharWithSpan };

  var isMatch = function (n) {
    return $_aa8ah0sejh8lz3g9.isText(n) && $_aa8ah0sejh8lz3g9.value(n) !== undefined && $_4quw9ds7jh8lz3fg.regExp.test($_aa8ah0sejh8lz3g9.value(n));
  };
  var filterDescendants = function (scope, predicate) {
    var result = [];
    var dom = scope.dom();
    var children = $_9i8hjds9jh8lz3fq.map(dom.childNodes, $_ca7ezesdjh8lz3g4.fromDom);
    $_9i8hjds9jh8lz3fq.each(children, function (x) {
      if (predicate(x)) {
        result = result.concat([x]);
      }
      result = result.concat(filterDescendants(x, predicate));
    });
    return result;
  };
  var findParentElm = function (elm, rootElm) {
    while (elm.parentNode) {
      if (elm.parentNode === rootElm) {
        return elm;
      }
      elm = elm.parentNode;
    }
  };
  var replaceWithSpans = function (html) {
    return html.replace($_4quw9ds7jh8lz3fg.regExpGlobal, $_g64rhxsgjh8lz3gb.wrapCharWithSpan);
  };
  var $_5w2pzts8jh8lz3fi = {
    isMatch: isMatch,
    filterDescendants: filterDescendants,
    findParentElm: findParentElm,
    replaceWithSpans: replaceWithSpans
  };

  var show = function (editor, rootElm) {
    var node, div;
    var nodeList = $_5w2pzts8jh8lz3fi.filterDescendants($_ca7ezesdjh8lz3g4.fromDom(rootElm), $_5w2pzts8jh8lz3fi.isMatch);
    $_9i8hjds9jh8lz3fq.each(nodeList, function (n) {
      var withSpans = $_5w2pzts8jh8lz3fi.replaceWithSpans($_aa8ah0sejh8lz3g9.value(n));
      div = editor.dom.create('div', null, withSpans);
      while (node = div.lastChild) {
        editor.dom.insertAfter(node, n.dom());
      }
      editor.dom.remove(n.dom());
    });
  };
  var hide = function (editor, body) {
    var nodeList = editor.dom.select($_4quw9ds7jh8lz3fg.selector, body);
    $_9i8hjds9jh8lz3fq.each(nodeList, function (node) {
      editor.dom.remove(node, 1);
    });
  };
  var toggle = function (editor) {
    var body = editor.getBody();
    var bookmark = editor.selection.getBookmark();
    var parentNode = $_5w2pzts8jh8lz3fi.findParentElm(editor.selection.getNode(), body);
    parentNode = parentNode !== undefined ? parentNode : body;
    hide(editor, parentNode);
    show(editor, parentNode);
    editor.selection.moveToBookmark(bookmark);
  };
  var $_3w2dxys6jh8lz3f8 = {
    show: show,
    hide: hide,
    toggle: toggle
  };

  var toggleVisualChars = function (editor, toggleState) {
    var body = editor.getBody();
    var selection = editor.selection;
    var bookmark;
    toggleState.set(!toggleState.get());
    $_ca1g8as5jh8lz3f7.fireVisualChars(editor, toggleState.get());
    bookmark = selection.getBookmark();
    if (toggleState.get() === true) {
      $_3w2dxys6jh8lz3f8.show(editor, body);
    } else {
      $_3w2dxys6jh8lz3f8.hide(editor, body);
    }
    selection.moveToBookmark(bookmark);
  };
  var $_8znikjs4jh8lz3f6 = { toggleVisualChars: toggleVisualChars };

  var register = function (editor, toggleState) {
    editor.addCommand('mceVisualChars', function () {
      $_8znikjs4jh8lz3f6.toggleVisualChars(editor, toggleState);
    });
  };
  var $_fbutd9s3jh8lz3f5 = { register: register };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var setup = function (editor, toggleState) {
    var debouncedToggle = global$1.debounce(function () {
      $_3w2dxys6jh8lz3f8.toggle(editor);
    }, 300);
    if (editor.settings.forced_root_block !== false) {
      editor.on('keydown', function (e) {
        if (toggleState.get() === true) {
          e.keyCode === 13 ? $_3w2dxys6jh8lz3f8.toggle(editor) : debouncedToggle();
        }
      });
    }
  };
  var $_353u01shjh8lz3gd = { setup: setup };

  var toggleActiveState = function (editor) {
    return function (e) {
      var ctrl = e.control;
      editor.on('VisualChars', function (e) {
        ctrl.active(e.state);
      });
    };
  };
  var register$1 = function (editor) {
    editor.addButton('visualchars', {
      active: false,
      title: 'Show invisible characters',
      cmd: 'mceVisualChars',
      onPostRender: toggleActiveState(editor)
    });
    editor.addMenuItem('visualchars', {
      text: 'Show invisible characters',
      cmd: 'mceVisualChars',
      onPostRender: toggleActiveState(editor),
      selectable: true,
      context: 'view',
      prependToContext: true
    });
  };

  global.add('visualchars', function (editor) {
    var toggleState = Cell(false);
    $_fbutd9s3jh8lz3f5.register(editor, toggleState);
    register$1(editor);
    $_353u01shjh8lz3gd.setup(editor, toggleState);
    return $_bmmym6s2jh8lz3f4.get(toggleState);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-wordcount", ["tinymce"], function() {
  return (function() {
(function () {
var wordcount = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var regExps = {
    aletter: '[A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05F3\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u10a0-\u10c5\u10d0-\u10fa\u10fc\u1100-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1a00-\u1a16\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bc0-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u24B6-\u24E9\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2d00-\u2d25\u2d30-\u2d65\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005\u303b\u303c\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790\ua791\ua7a0-\ua7a9\ua7fa-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]',
    midnumlet: '[-\'\\.\u2018\u2019\u2024\uFE52\uFF07\uFF0E]',
    midletter: '[:\xB7\xB7\u05F4\u2027\uFE13\uFE55\uFF1A]',
    midnum: '[\xB1+*/,;;\u0589\u060C\u060D\u066C\u07F8\u2044\uFE10\uFE14\uFE50\uFE54\uFF0C\uFF1B]',
    numeric: '[0-9\u0660-\u0669\u066B\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819\u1946-\u194f\u19d0-\u19d9\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9\ua900-\ua909\ua9d0-\ua9d9\uaa50-\uaa59\uabf0-\uabf9]',
    cr: '\\r',
    lf: '\\n',
    newline: '[\x0B\f\x85\u2028\u2029]',
    extend: '[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f\u109a-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b6-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u192b\u1930-\u193b\u19b0-\u19c0\u19c8\u19c9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f\u1b00-\u1b04\u1b34-\u1b44\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1baa\u1be6-\u1bf3\u1c24-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\uA672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe3-\uabea\uabec\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]',
    format: '[\xAD\u0600-\u0603\u06DD\u070F\u17b4\u17b5\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFEFF\uFFF9-\uFFFB]',
    katakana: '[\u3031-\u3035\u309B\u309C\u30A0-\u30fa\u30fc-\u30ff\u31f0-\u31ff\u32D0-\u32FE\u3300-\u3357\uff66-\uff9d]',
    extendnumlet: '[=_\u203f\u2040\u2054\ufe33\ufe34\ufe4d-\ufe4f\uff3f\u2200-\u22FF<>]',
    punctuation: '[!-#%-*,-\\/:;?@\\[-\\]_{}\xA1\xAB\xB7\xBB\xBF;\xB7\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1361-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u3008\u3009\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30\u2E31\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uff3f\uFF5B\uFF5D\uFF5F-\uFF65]'
  };
  var characterIndices = {
    ALETTER: 0,
    MIDNUMLET: 1,
    MIDLETTER: 2,
    MIDNUM: 3,
    NUMERIC: 4,
    CR: 5,
    LF: 6,
    NEWLINE: 7,
    EXTEND: 8,
    FORMAT: 9,
    KATAKANA: 10,
    EXTENDNUMLET: 11,
    AT: 12,
    OTHER: 13
  };
  var SETS = [
    new RegExp(regExps.aletter),
    new RegExp(regExps.midnumlet),
    new RegExp(regExps.midletter),
    new RegExp(regExps.midnum),
    new RegExp(regExps.numeric),
    new RegExp(regExps.cr),
    new RegExp(regExps.lf),
    new RegExp(regExps.newline),
    new RegExp(regExps.extend),
    new RegExp(regExps.format),
    new RegExp(regExps.katakana),
    new RegExp(regExps.extendnumlet),
    new RegExp('@')
  ];
  var EMPTY_STRING = '';
  var PUNCTUATION = new RegExp('^' + regExps.punctuation + '$');
  var WHITESPACE = /^\s+$/;
  var $_7u8uzzspjh8lz3i4 = {
    characterIndices: characterIndices,
    SETS: SETS,
    EMPTY_STRING: EMPTY_STRING,
    PUNCTUATION: PUNCTUATION,
    WHITESPACE: WHITESPACE
  };

  var each = function (o, cb, s) {
    var n, l;
    if (!o) {
      return 0;
    }
    s = s || o;
    if (o.length !== undefined) {
      for (n = 0, l = o.length; n < l; n++) {
        if (cb.call(s, o[n], n, o) === false) {
          return 0;
        }
      }
    } else {
      for (n in o) {
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false) {
            return 0;
          }
        }
      }
    }
    return 1;
  };
  var map = function (array, callback) {
    var out = [];
    each(array, function (item, index) {
      out.push(callback(item, index, array));
    });
    return out;
  };
  var $_4dn8xisrjh8lz3i9 = {
    each: each,
    map: map
  };

  var SETS$1 = $_7u8uzzspjh8lz3i4.SETS;
  var OTHER = $_7u8uzzspjh8lz3i4.characterIndices.OTHER;
  var getType = function (char) {
    var j, set, type = OTHER;
    var setsLength = SETS$1.length;
    for (j = 0; j < setsLength; ++j) {
      set = SETS$1[j];
      if (set && set.test(char)) {
        type = j;
        break;
      }
    }
    return type;
  };
  var memoize = function (func) {
    var cache = {};
    return function (char) {
      if (cache[char]) {
        return cache[char];
      } else {
        var result = func(char);
        cache[char] = result;
        return result;
      }
    };
  };
  var classify = function (string) {
    var memoized = memoize(getType);
    return $_4dn8xisrjh8lz3i9.map(string.split(''), memoized);
  };
  var $_7jetzwsqjh8lz3i8 = { classify: classify };

  var ci = $_7u8uzzspjh8lz3i4.characterIndices;
  var isWordBoundary = function (map, index) {
    var prevType;
    var type = map[index];
    var nextType = map[index + 1];
    var nextNextType;
    if (index < 0 || index > map.length - 1 && index !== 0) {
      return false;
    }
    if (type === ci.ALETTER && nextType === ci.ALETTER) {
      return false;
    }
    nextNextType = map[index + 2];
    if (type === ci.ALETTER && (nextType === ci.MIDLETTER || nextType === ci.MIDNUMLET || nextType === ci.AT) && nextNextType === ci.ALETTER) {
      return false;
    }
    prevType = map[index - 1];
    if ((type === ci.MIDLETTER || type === ci.MIDNUMLET || nextType === ci.AT) && nextType === ci.ALETTER && prevType === ci.ALETTER) {
      return false;
    }
    if ((type === ci.NUMERIC || type === ci.ALETTER) && (nextType === ci.NUMERIC || nextType === ci.ALETTER)) {
      return false;
    }
    if ((type === ci.MIDNUM || type === ci.MIDNUMLET) && nextType === ci.NUMERIC && prevType === ci.NUMERIC) {
      return false;
    }
    if (type === ci.NUMERIC && (nextType === ci.MIDNUM || nextType === ci.MIDNUMLET) && nextNextType === ci.NUMERIC) {
      return false;
    }
    if (type === ci.EXTEND || type === ci.FORMAT || prevType === ci.EXTEND || prevType === ci.FORMAT || nextType === ci.EXTEND || nextType === ci.FORMAT) {
      return false;
    }
    if (type === ci.CR && nextType === ci.LF) {
      return false;
    }
    if (type === ci.NEWLINE || type === ci.CR || type === ci.LF) {
      return true;
    }
    if (nextType === ci.NEWLINE || nextType === ci.CR || nextType === ci.LF) {
      return true;
    }
    if (type === ci.KATAKANA && nextType === ci.KATAKANA) {
      return false;
    }
    if (nextType === ci.EXTENDNUMLET && (type === ci.ALETTER || type === ci.NUMERIC || type === ci.KATAKANA || type === ci.EXTENDNUMLET)) {
      return false;
    }
    if (type === ci.EXTENDNUMLET && (nextType === ci.ALETTER || nextType === ci.NUMERIC || nextType === ci.KATAKANA)) {
      return false;
    }
    if (type === ci.AT) {
      return false;
    }
    return true;
  };
  var $_b8cfs8ssjh8lz3ib = { isWordBoundary: isWordBoundary };

  var EMPTY_STRING$1 = $_7u8uzzspjh8lz3i4.EMPTY_STRING;
  var WHITESPACE$1 = $_7u8uzzspjh8lz3i4.WHITESPACE;
  var PUNCTUATION$1 = $_7u8uzzspjh8lz3i4.PUNCTUATION;
  var isProtocol = function (word) {
    return word === 'http' || word === 'https';
  };
  var findWordEnd = function (str, index) {
    var i;
    for (i = index; i < str.length; ++i) {
      var chr = str.charAt(i);
      if (WHITESPACE$1.test(chr)) {
        break;
      }
    }
    return i;
  };
  var extractUrl = function (word, str, index) {
    var endIndex = findWordEnd(str, index + 1);
    var peakedWord = str.substring(index + 1, endIndex);
    if (peakedWord.substr(0, 3) === '://') {
      return {
        word: word + peakedWord,
        index: endIndex
      };
    }
    return {
      word: word,
      index: index
    };
  };
  var doGetWords = function (str, options) {
    var i = 0;
    var map = $_7jetzwsqjh8lz3i8.classify(str);
    var len = map.length;
    var word = [];
    var words = [];
    var chr;
    var includePunctuation;
    var includeWhitespace;
    if (!options) {
      options = {};
    }
    if (options.ignoreCase) {
      str = str.toLowerCase();
    }
    includePunctuation = options.includePunctuation;
    includeWhitespace = options.includeWhitespace;
    for (; i < len; ++i) {
      chr = str.charAt(i);
      word.push(chr);
      if ($_b8cfs8ssjh8lz3ib.isWordBoundary(map, i)) {
        word = word.join(EMPTY_STRING$1);
        if (word && (includeWhitespace || !WHITESPACE$1.test(word)) && (includePunctuation || !PUNCTUATION$1.test(word))) {
          if (isProtocol(word)) {
            var obj = extractUrl(word, str, i);
            words.push(obj.word);
            i = obj.index;
          } else {
            words.push(word);
          }
        }
        word = [];
      }
    }
    return words;
  };
  var getWords = function (str, options) {
    return doGetWords(str.replace(/\ufeff/g, ''), options);
  };
  var $_70byijsojh8lz3i1 = { getWords: getWords };

  var getTextContent = function (editor) {
    return editor.removed ? '' : editor.getBody().innerText;
  };
  var getCount = function (editor) {
    return $_70byijsojh8lz3i1.getWords(getTextContent(editor)).length;
  };
  var $_e2zt0csnjh8lz3i0 = { getCount: getCount };

  var get = function (editor) {
    var getCount = function () {
      return $_e2zt0csnjh8lz3i0.getCount(editor);
    };
    return { getCount: getCount };
  };
  var $_c37nf7smjh8lz3hz = { get: get };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.Delay');

  var global$2 = tinymce.util.Tools.resolve('tinymce.util.I18n');

  var setup = function (editor) {
    var wordsToText = function (editor) {
      return global$2.translate([
        '{0} words',
        $_e2zt0csnjh8lz3i0.getCount(editor)
      ]);
    };
    var update = function () {
      editor.theme.panel.find('#wordcount').text(wordsToText(editor));
    };
    editor.on('init', function () {
      var statusbar = editor.theme.panel && editor.theme.panel.find('#statusbar')[0];
      var debouncedUpdate = global$1.debounce(update, 300);
      if (statusbar) {
        global$1.setEditorTimeout(editor, function () {
          statusbar.insert({
            type: 'label',
            name: 'wordcount',
            text: wordsToText(editor),
            classes: 'wordcount',
            disabled: editor.settings.readonly
          }, 0);
          editor.on('setcontent beforeaddundo undo redo keyup', debouncedUpdate);
        }, 0);
      }
    });
  };
  var $_30dxcostjh8lz3ie = { setup: setup };

  global.add('wordcount', function (editor) {
    $_30dxcostjh8lz3ie.setup(editor);
    return $_c37nf7smjh8lz3hz.get(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


  }).apply(root, arguments);
});
}(this));

(function(root) {
define("tinymce-compat3x", ["tinymce"], function() {
  return (function() {
/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/*global tinymce:true, console:true */
/*eslint no-console:0, new-cap:0 */

/**
 * This plugin adds missing events form the 4.x API back. Not every event is
 * properly supported but most things should work.
 *
 * Unsupported things:
 *  - No editor.onEvent
 *  - Can't cancel execCommands with beforeExecCommand
 */
(function (tinymce) {
  var reported;

  function noop() {
  }

  function log(apiCall) {
    if (!reported && window && window.console) {
      reported = true;
      console.log("Deprecated TinyMCE API call: " + apiCall);
    }
  }

  function Dispatcher(target, newEventName, argsMap, defaultScope) {
    target = target || this;
    var cbs = [];

    if (!newEventName) {
      this.add = this.addToTop = this.remove = this.dispatch = noop;
      return;
    }

    this.add = function (callback, scope, prepend) {
      log('<target>.on' + newEventName + ".add(..)");

      // Convert callback({arg1:x, arg2:x}) -> callback(arg1, arg2)
      function patchedEventCallback(e) {
        var callbackArgs = [];

        if (typeof argsMap == "string") {
          argsMap = argsMap.split(" ");
        }

        if (argsMap && typeof argsMap !== "function") {
          for (var i = 0; i < argsMap.length; i++) {
            callbackArgs.push(e[argsMap[i]]);
          }
        }

        if (typeof argsMap == "function") {
          callbackArgs = argsMap(newEventName, e, target);
          if (!callbackArgs) {
            return;
          }
        }

        if (!argsMap) {
          callbackArgs = [e];
        }

        callbackArgs.unshift(defaultScope || target);

        if (callback.apply(scope || defaultScope || target, callbackArgs) === false) {
          e.stopImmediatePropagation();
        }
      }

      target.on(newEventName, patchedEventCallback, prepend);

      var handlers = {
        original: callback,
        patched: patchedEventCallback
      };

      cbs.push(handlers);
      return patchedEventCallback;
    };

    this.addToTop = function (callback, scope) {
      this.add(callback, scope, true);
    };

    this.remove = function (callback) {
      cbs.forEach(function (item, i) {
        if (item.original === callback) {
          cbs.splice(i, 1);
          return target.off(newEventName, item.patched);
        }
      });

      return target.off(newEventName, callback);
    };

    this.dispatch = function () {
      target.fire(newEventName);
      return true;
    };
  }

  tinymce.util.Dispatcher = Dispatcher;
  tinymce.onBeforeUnload = new Dispatcher(tinymce, "BeforeUnload");
  tinymce.onAddEditor = new Dispatcher(tinymce, "AddEditor", "editor");
  tinymce.onRemoveEditor = new Dispatcher(tinymce, "RemoveEditor", "editor");

  tinymce.util.Cookie = {
    get: noop, getHash: noop, remove: noop, set: noop, setHash: noop
  };

  function patchEditor(editor) {

    function translate(str) {
      var prefix = editor.settings.language || "en";
      var prefixedStr = [prefix, str].join('.');
      var translatedStr = tinymce.i18n.translate(prefixedStr);

      return prefixedStr !== translatedStr ? translatedStr : tinymce.i18n.translate(str);
    }

    function patchEditorEvents(oldEventNames, argsMap) {
      tinymce.each(oldEventNames.split(" "), function (oldName) {
        editor["on" + oldName] = new Dispatcher(editor, oldName, argsMap);
      });
    }

    function convertUndoEventArgs(type, event, target) {
      return [
        event.level,
        target
      ];
    }

    function filterSelectionEvents(needsSelection) {
      return function (type, e) {
        if ((!e.selection && !needsSelection) || e.selection == needsSelection) {
          return [e];
        }
      };
    }

    if (editor.controlManager) {
      return;
    }

    function cmNoop() {
      var obj = {}, methods = 'add addMenu addSeparator collapse createMenu destroy displayColor expand focus ' +
        'getLength hasMenus hideMenu isActive isCollapsed isDisabled isRendered isSelected mark ' +
        'postRender remove removeAll renderHTML renderMenu renderNode renderTo select selectByIndex ' +
        'setActive setAriaProperty setColor setDisabled setSelected setState showMenu update';

      log('editor.controlManager.*');

      function _noop() {
        return cmNoop();
      }

      tinymce.each(methods.split(' '), function (method) {
        obj[method] = _noop;
      });

      return obj;
    }

    editor.controlManager = {
      buttons: {},

      setDisabled: function (name, state) {
        log("controlManager.setDisabled(..)");

        if (this.buttons[name]) {
          this.buttons[name].disabled(state);
        }
      },

      setActive: function (name, state) {
        log("controlManager.setActive(..)");

        if (this.buttons[name]) {
          this.buttons[name].active(state);
        }
      },

      onAdd: new Dispatcher(),
      onPostRender: new Dispatcher(),

      add: function (obj) {
        return obj;
      },
      createButton: cmNoop,
      createColorSplitButton: cmNoop,
      createControl: cmNoop,
      createDropMenu: cmNoop,
      createListBox: cmNoop,
      createMenuButton: cmNoop,
      createSeparator: cmNoop,
      createSplitButton: cmNoop,
      createToolbar: cmNoop,
      createToolbarGroup: cmNoop,
      destroy: noop,
      get: noop,
      setControlType: cmNoop
    };

    patchEditorEvents("PreInit BeforeRenderUI PostRender Load Init Remove Activate Deactivate", "editor");
    patchEditorEvents("Click MouseUp MouseDown DblClick KeyDown KeyUp KeyPress ContextMenu Paste Submit Reset");
    patchEditorEvents("BeforeExecCommand ExecCommand", "command ui value args"); // args.terminate not supported
    patchEditorEvents("PreProcess PostProcess LoadContent SaveContent Change");
    patchEditorEvents("BeforeSetContent BeforeGetContent SetContent GetContent", filterSelectionEvents(false));
    patchEditorEvents("SetProgressState", "state time");
    patchEditorEvents("VisualAid", "element hasVisual");
    patchEditorEvents("Undo Redo", convertUndoEventArgs);

    patchEditorEvents("NodeChange", function (type, e) {
      return [
        editor.controlManager,
        e.element,
        editor.selection.isCollapsed(),
        e
      ];
    });

    var originalAddButton = editor.addButton;
    editor.addButton = function (name, settings) {
      var originalOnPostRender;

      function patchedPostRender() {
        editor.controlManager.buttons[name] = this;

        if (originalOnPostRender) {
          return originalOnPostRender.apply(this, arguments);
        }
      }

      for (var key in settings) {
        if (key.toLowerCase() === "onpostrender") {
          originalOnPostRender = settings[key];
          settings.onPostRender = patchedPostRender;
        }
      }

      if (!originalOnPostRender) {
        settings.onPostRender = patchedPostRender;
      }

      if (settings.title) {
        settings.title = translate(settings.title);
      }

      return originalAddButton.call(this, name, settings);
    };

    editor.on('init', function () {
      var undoManager = editor.undoManager, selection = editor.selection;

      undoManager.onUndo = new Dispatcher(editor, "Undo", convertUndoEventArgs, null, undoManager);
      undoManager.onRedo = new Dispatcher(editor, "Redo", convertUndoEventArgs, null, undoManager);
      undoManager.onBeforeAdd = new Dispatcher(editor, "BeforeAddUndo", null, undoManager);
      undoManager.onAdd = new Dispatcher(editor, "AddUndo", null, undoManager);

      selection.onBeforeGetContent = new Dispatcher(editor, "BeforeGetContent", filterSelectionEvents(true), selection);
      selection.onGetContent = new Dispatcher(editor, "GetContent", filterSelectionEvents(true), selection);
      selection.onBeforeSetContent = new Dispatcher(editor, "BeforeSetContent", filterSelectionEvents(true), selection);
      selection.onSetContent = new Dispatcher(editor, "SetContent", filterSelectionEvents(true), selection);
    });

    editor.on('BeforeRenderUI', function () {
      var windowManager = editor.windowManager;

      windowManager.onOpen = new Dispatcher();
      windowManager.onClose = new Dispatcher();
      windowManager.createInstance = function (className, a, b, c, d, e) {
        log("windowManager.createInstance(..)");

        var constr = tinymce.resolve(className);
        return new constr(a, b, c, d, e);
      };
    });
  }

  tinymce.on('SetupEditor', function (e) {
    patchEditor(e.editor);
  });

  tinymce.PluginManager.add("compat3x", patchEditor);

  tinymce.addI18n = function (prefix, o) {
    var I18n = tinymce.util.I18n, each = tinymce.each;

    if (typeof prefix == "string" && prefix.indexOf('.') === -1) {
      I18n.add(prefix, o);
      return;
    }

    if (!tinymce.is(prefix, 'string')) {
      each(prefix, function (o, lc) {
        each(o, function (o, g) {
          each(o, function (o, k) {
            if (g === 'common') {
              I18n.data[lc + '.' + k] = o;
            } else {
              I18n.data[lc + '.' + g + '.' + k] = o;
            }
          });
        });
      });
    } else {
      each(o, function (o, k) {
        I18n.data[prefix + '.' + k] = o;
      });
    }
  };
})(tinymce);


  }).apply(root, arguments);
});
}(this));

/*
 * customizing original tiny pattern...
 *
 * - Download link implementation(/view vs download)
 * - Modal popup implementation
 * 
 * ToDo:
 * - extend from plone instead of copy/paste
 * - or, should be rewritten with react?
 */

define('mockup-patterns-tinymce',[
  'jquery',
  'underscore',
  'pat-base',
  'tinymce',
  'text!mockup-patterns-tinymce-url/templates/result.xml',
  'text!mockup-patterns-tinymce-url/templates/selection.xml',
  'mockup-utils',
  'mockup-patterns-tinymce-url/js/links',
  'mockup-i18n',
  'translate',
  'tinymce-modern-theme',
  'tinymce-advlist',
  'tinymce-anchor',
  'tinymce-autolink',
  'tinymce-autoresize',
  'tinymce-autosave',
  'tinymce-bbcode',
  'tinymce-charmap',
  'tinymce-code',
  'tinymce-colorpicker',
  'tinymce-contextmenu',
  'tinymce-directionality',
  'tinymce-emoticons',
  'tinymce-fullpage',
  'tinymce-fullscreen',
  'tinymce-hr',
  'tinymce-image',
  'tinymce-importcss',
  'tinymce-insertdatetime',
  'tinymce-legacyoutput',
  'tinymce-link',
  'tinymce-lists',
  'tinymce-media',
  'tinymce-nonbreaking',
  'tinymce-noneditable',
  'tinymce-pagebreak',
  'tinymce-paste',
  'tinymce-preview',
  'tinymce-print',
  'tinymce-save',
  'tinymce-searchreplace',
  'tinymce-spellchecker',
  'tinymce-tabfocus',
  'tinymce-table',
  'tinymce-template',
  'tinymce-textcolor',
  'tinymce-textpattern',
  'tinymce-visualblocks',
  'tinymce-visualchars',
  'tinymce-wordcount',
  'tinymce-compat3x'
], function($, _,
            Base, tinymce,
            ResultTemplate, SelectionTemplate,
            utils, LinkModal, I18n, _t) {
  'use strict';

  var blocks = ['p', 'div', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];

  var TinyMCE = Base.extend({
    name: 'tinymce',
    trigger: '.pat-tinymce',
    parser: 'mockup',
    defaults: {
      relatedItems: {
        // UID attribute is required here since we're working with related items
        attributes: ['UID', 'Title', 'portal_type', 'path','getURL', 'getIcon','is_folderish','review_state'],
        batchSize: 20,
        vocabularyUrl: null,
        width: 500,
        maximumSelectionSize: 1,
        placeholder: _t('Search for item on site...')
      },
      text: {
        insertBtn: _t('Insert'), // so this can be configurable for different languages
        cancelBtn: _t('Cancel'),
        insertHeading: _t('Insert link'),
        title: _t('Title'),
        internal: _t('Internal'),
        external: _t('External URL (can be relative within this site or absolute if it starts with http:// or https://)'),
        email: _t('Email Address'),
        anchor: _t('Anchor'),
        subject: _t('Email Subject (optional)'),
        image: _t('Image'),
        imageAlign: _t('Align'),
        scale: _t('Size'),
        alt: _t('Alternative Text'),
        externalImage: _t('External Image URL (can be relative within this site or absolute if it starts with http:// or https://)')
      },
      // URL generation options
      loadingBaseUrl: '../../../bower_components/tinymce-builded/js/tinymce/',
      prependToUrl: '',
      appendToUrl: '',
      linkAttribute: 'path', // attribute to get link value from data
      prependToScalePart: '/imagescale/', // some value here is required to be able to parse scales back
      appendToScalePart: '',
      appendToOriginalScalePart: '',
      defaultScale: 'large',
      scales: _t('Listing (16x16):listing,Icon (32x32):icon,Tile (64x64):tile,' +
              'Thumb (128x128):thumb,Mini (200x200):mini,Preview (400x400):preview,' +
              'Large (768x768):large'),
      targetList: [
        {text: _t('Open in this window / frame'), value: ''},
        {text: _t('Open in new window'), value: '_blank'},
        {text: _t('Open in parent window / frame'), value: '_parent'},
        {text: _t('Open in top frame (replaces all frames)'), value: '_top'}
      ],
      imageTypes: ['Image'],
      folderTypes: ['Folder', 'Plone Site'],
      tiny: {
        'content_css': '../../../bower_components/tinymce-builded/js/tinymce/skins/lightgray/content.min.css',
        theme: 'modern',
        plugins: ['advlist', 'autolink', 'lists', 'charmap', 'print', 'preview', 'anchor', 'searchreplace',
                  'visualblocks', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'contextmenu',
                  'paste', 'plonelink', 'ploneimage'],
        menubar: 'edit table format tools view insert',
        toolbar: 'undo redo | styleselect | bold italic | ' +
                 'alignleft aligncenter alignright alignjustify | ' +
                 'bullist numlist outdent indent | ' +
                 'unlink plonelink ploneimage',
        //'autoresize_max_height': 900,
        'height': 400,
        // stick here because it's easier to config without
        // additional settings
        linkTypes: ['internal', 'external', 'email', 'anchor']
      },
      inline: false
    },
    addLinkClicked: function() {
      var self = this;
      if (self.linkModal === null) {
        var $el = $('<div/>').insertAfter(self.$el);
        var linkTypes = self.options.tiny.linkTypes;
        if(!linkTypes){
          // in case someone screws up config
          linkTypes = ['internal', 'external', 'email', 'anchor'];
        }
        self.linkModal = new LinkModal($el,
          $.extend(true, {}, self.options, {
            tinypattern: self,
            linkTypes: linkTypes
          })
        );
        self.linkModal.show();
      } else {
        self.linkModal.reinitialize();
        self.linkModal.show();
      }
    },
    addImageClicked: function() {
      var self = this;
      if (self.imageModal === null) {
        var linkTypes = ['image', 'externalImage'];
        var options = $.extend(true, {}, self.options, {
          tinypattern: self,
          linkTypes: linkTypes,
          initialLinkType: 'image',
          text: {
            insertHeading: _t('Insert Image')
          },
          relatedItems: {
            baseCriteria: [{
              i: 'portal_type',
              o: 'plone.app.querystring.operation.list.contains',
              v: self.options.imageTypes.concat(self.options.folderTypes)
            }],
            selectableTypes: self.options.imageTypes,
            resultTemplate: ResultTemplate,
            selectionTemplate: SelectionTemplate
          }
        });
        var $el = $('<div/>').insertAfter(self.$el);
        self.imageModal = new LinkModal($el, options);
        self.imageModal.show();
      } else {
        self.imageModal.reinitialize();
        self.imageModal.show();
      }
    },
    generateUrl: function(data) {
      var self = this;
      var part = data[self.options.linkAttribute];
      return self.options.prependToUrl + part + self.options.appendToUrl;
    },
    generateImageUrl: function(data, scale_name) {
      var self = this;
      var url = self.generateUrl(data);
      if (scale_name !== ''){
        var part = scale_name;
        for(var i=0; i<self.options.scales.length; i=i+1){
          if(self.options.scales[i].name === scale_name){
            part = self.options.scales[i].part;
          }
        }
        url = (url + self.options.prependToScalePart + part +
               self.options.appendToScalePart);
      }else{
        url = url + self.options.appendToOriginalScalePart;
      }
      return url;
    },
    stripGeneratedUrl: function(url) {
      // to get original attribute back
      var self = this;
      url = url.split(self.options.prependToScalePart, 2)[0];
      if (self.options.prependToUrl) {
        var parts = url.split(self.options.prependToUrl, 2);
        if (parts.length === 2) {
          url = parts[1];
        }
      }
      if (self.options.appendToUrl) {
        url = url.split(self.options.appendToUrl)[0];
      }
      return url;
    },
    getScaleFromUrl: function(url) {
      var self = this;
      var split = url.split(self.options.prependToScalePart);
      if (split.length !== 2) {
        // not valid scale, screw it
        return null;
      }
      if (self.options.appendToScalePart) {
        url = split[1].split(self.options.appendToScalePart)[0];
      } else {
        url = split[1];
      }
      if (url.indexOf('/image_') !== -1) {
        url = url.split('/image_')[1];
      }
      return url;
    },
    initLanguage: function(call_back){
      // remove it all for now... calling too many requests...
      call_back();
    },
    init: function() {
      var self = this;
      self.linkModal = self.imageModal = self.pasteModal = null;
      // tiny needs an id in order to initialize. Creat it if not set.
      var id = utils.setId(self.$el);
      var tinyOptions = self.options.tiny;
      if (self.options.inline === true) {
        self.options.tiny.inline = true;
      }
      self.tinyId = self.options.inline ? id + '-editable' : id;  // when displaying TinyMCE inline, a separate div is created.
      tinyOptions.selector = '#' + self.tinyId;
      tinyOptions.addLinkClicked = function() {
        self.addLinkClicked.apply(self, []);
      };
      tinyOptions.addImageClicked = function(file) {
        self.addImageClicked.apply(self, [file] );
      };
      // XXX: disabled skin means it wont load css files which we already
      // include in widgets.min.css
      tinyOptions.skin = false;
      self.options.relatedItems.generateImageUrl = function(data, scale) {
        // this is so, in our result and selection template, we can
        // access getting actual urls from related items
        return self.generateImageUrl.apply(self, [data, scale]);
      };

      tinyOptions.init_instance_callback = function(editor) {
        if (self.tiny === undefined || self.tiny === null) {
          self.tiny = editor;
        }
      };

      var found = [];
      tinyOptions.importcss_selector_converter = function(selector){
        var split = selector.split('.');
        if(split.length !== 2){
          return;
        }
        var className = split[1];
        className = className.split('::')[0].split(':')[0];
        if(found.indexOf(className) !== -1 ||
            ['callout', 'portalMessage'].indexOf(className) !== -1) {// a few are blacklisted){
          // do not duplicate;
          return;
        }
        var title = className.replace(/-/g, ' ');
        title = title[0].toUpperCase() + title.substring(1);

        var style = {
            title: title,
            classes: className
        };
        if(blocks.indexOf(split[0]) !== -1){
          style.block = split[0];
        }
        found.push(className);
        return style;
      };

      self.initLanguage(function() {
        if(typeof(self.options.scales) === 'string'){
          self.options.scales = _.map(self.options.scales.split(','), function(scale){
            scale = scale.split(':');
            return {
              part: scale[1],
              name: scale[1],
              label: scale[0]
            };
          });
        }
        if(typeof(self.options.folderTypes) === 'string'){
          self.options.folderTypes = self.options.folderTypes.split(',');
        }
        if(typeof(self.options.imageTypes) === 'string'){
          self.options.imageTypes = self.options.imageTypes.split(',');
        }

        if (self.options.inline === true) {
          // create a div, which will be made content-editable by TinyMCE and
          // copy contents from textarea to it. Then hide textarea.
          self.$el.after('<div id="' + self.tinyId + '">' + self.$el.val() + '</div>');
          self.$el.hide();
        }

        if(tinyOptions.importcss_file_filter && tinyOptions.importcss_file_filter.indexOf(',') !== -1){
          // need a custom function to check now
          var files = tinyOptions.importcss_file_filter.split(',');

          tinyOptions.importcss_file_filter = function(value) {
            for(var i=0; i<files.length; i++){
              if(value.indexOf(files[i]) !== -1){
                return true;
              }
            }
            return false;
          };
        }

        tinymce.init(tinyOptions);
        self.tiny = tinymce.get(self.tinyId);

        /* tiny really should be doing this by default
         * but this fixes overlays not saving data */
        var $form = self.$el.parents('form');
        $form.on('submit', function() {
          if (self.options.inline === true) {
            // save back from contenteditable to textarea
            self.$el.val(self.tiny.getContent());
          } else {
            // normal case
            self.tiny.save();
          }
        });
      });
    },
    destroy: function() {
      if (this.tiny) {
        if (this.options.inline === true) {
          // destroy also inline editable
          this.$el.val(this.tiny.getContent());
          $('#' + this.tinyId).remove();
          this.$el.show();
        }
        this.tiny.destroy();
        this.tiny = undefined;
      }
    }
  });

  return TinyMCE;

});

/* TextareaMimetypeSelector pattern.
 *
 *
 * Options:
 *    textareaName(string): Value of name attribute of the textarea ('')
 *    widgets(object): MimeType/PatternConfig pairs ({'text/html': {pattern: 'tinymce', patternOptions: {}}})
 *
 *
 * Documentation:
 *   # General
 *
 *   This pattern displays a mimetype selection widget for textareas. It
 *   switches the widget according to the selected mimetype.
 *
 *   ## widgets option Structure
 *
 *   Complex Object/JSON structure with MimeType/PatternConfig pairs. The
 *   MimeType is a string like "text/html". The PatternConfig is a object with
 *   a "pattern" and an optional "patternOptions" attribute. The "pattern"
 *   attribute's value is a string with the patterns name and the
 *   "patternOptions" attribute is a object with whatever options the pattern
 *   needs. For example, to use the TinyMCE pattern for the HTML mimetype, use
 *   "text/html": {"pattern": "tinymce"}
 *
 *   # Mimetype selection on textarea including text/html mimetype with TinyMCE editor.
 *
 *   {{ example-1 }}
 *
 *   # Mimetype selection on textarea with inline TinyMCE editor.
 *
 *   {{ example-2 }}
 *
  * Example: example-1
 *    <textarea name="text">
 *      <h1>hello world</h1>
 *    </textarea>
 *    <select
 *        name="text.mimeType"
 *        class="pat-textareamimetypeselector"
 *        data-pat-textareamimetypeselector='{
 *          "textareaName": "text",
 *          "widgets": {
 *            "text/html": {
 *              "pattern": "tinymce",
 *              "patternOptions": {
 *                "tiny": {
 *                  "plugins": [],
 *                  "menubar": "edit format tools",
 *                  "toolbar": " "
 *                }
 *              }
 *            }
 *          }
 *        }'
 *      >
 *      <option value="text/html">text/html</option>
 *      <option value="text/plain" selected="selected">text/plain</option>
 *    </select>
 *
 * Example: example-2
 *    <textarea name="text2">
 *      <h1>hello world</h1>
 *    </textarea>
 *    <select
 *        name="text.mimeType"
 *        class="pat-textareamimetypeselector"
 *        data-pat-textareamimetypeselector='{
 *          "textareaName": "text2",
 *          "widgets": {
 *            "text/html": {
 *              "pattern": "tinymce",
 *              "patternOptions": {
 *                "inline": true,
 *                "tiny": {
 *                  "plugins": [],
 *                  "menubar": "edit format tools",
 *                  "toolbar": " "
 *                }
 *              }
 *            }
 *          }
 *        }'
 *      >
 *      <option value="text/html">text/html</option>
 *      <option value="text/plain" selected="selected">text/plain</option>
 *    </select>
 *
 */

define('mockup-patterns-textareamimetypeselector',[
  'jquery',
  'pat-base',
  'pat-registry',
  'mockup-patterns-tinymce'
], function ($, Base, registry) {
  'use strict';

  var TextareaMimetypeSelector = Base.extend({
    name: 'textareamimetypeselector',
    trigger: '.pat-textareamimetypeselector',
    parser: 'mockup',
    textarea: undefined,
    currentWidget: undefined,
    defaults: {
      textareaName: '',
      widgets: {'text/html': {pattern: 'tinymce', patternOptions: {}}}
    },
    init: function () {
      var self = this,
          $el = self.$el,
          current;
      self.textarea = $('[name="' + self.options.textareaName + '"]');
      $el.change(function (e) {
        self.initTextarea(e.target.value);
      });
      self.initTextarea($el.val());

    },
    initTextarea: function (mimetype) {
      var self = this,
          patternConfig = self.options.widgets[mimetype],
          pattern;
      // First, destroy current
      if (self.currentWidget) {
        // The pattern must implement the destroy method.
        self.currentWidget.destroy();
      }
      // Then, setup new
      if (patternConfig) {
          pattern = new registry.patterns[patternConfig.pattern](
            self.textarea,
            patternConfig.patternOptions || {}
          );
          self.currentWidget = pattern;
      }
    }

  });

  return TextareaMimetypeSelector;
});

/* global define */

define('castle-url/patterns/castledynamicform',[
  'jquery',
  'pat-base',
  'mockup-utils'
], function($, Base, utils) {
  'use strict';

  var FormPattern = Base.extend({
    name: 'castledynamicform',
    trigger: '.pat-castledynamicform',
    parser: 'mockup',
    defaults: {
    },
    init: function() {
      var self = this;
      var $form = self.$el.parents('form');
      if($form.size() === 0){
        return;
      }
      self.$form = $form;
      self.bind();
      self.manipulate();
    },
    manipulate: function(){
      // show/hide stuff
      var self = this;
      var $useQuery = self.getUseQuery();
      if($useQuery.size() === 1){
        if($('input', self.getUseQuery())[0].checked){
          self.getQuery().show();
          self.getLimit().show();
          self.getContent().hide();
        }else{
          self.getQuery().hide();
          self.getLimit().hide();
          self.getContent().show();
        }
      }
      var $useDesc = self.getUseDescription();
      if($useDesc.size() === 1){
        if($('input', self.getUseDescription())[0].checked){
          self.getCustomText().hide();
        }else{
          self.getCustomText().show();
        }
      }
      var $navType = self.getNavType();
      if($navType.size() === 1){
        var val = $navType.val();
        if(val === 'query'){
          self.getQuery().show();
          self.getContent().hide();
        }else if(val === 'content'){
          self.getQuery().hide();
          self.getContent().show();
        }else{
          self.getQuery().hide();
          self.getContent().hide();
        }
      }
    },
    bind: function(){
      var self = this;
      $('input', self.getUseQuery()).change(function(){
        self.manipulate();
      });
      $('input', self.getUseDescription()).change(function(){
        self.manipulate();
      });
      self.getNavType().change(function(){
        self.manipulate();
      });
    },
    getLimit: function(){
      return $('div[id$="-limit"]', this.$form);
    },
    getUseQuery: function(){
      return $('div[id$="-use_query"]', this.$form);
    },
    getUseDescription: function(){
      return $('div[id$="-use_description"]', this.$form);
    },
    getQuery: function(){
      return $('div[id$="-query"]', this.$form);
    },
    getContent: function(){
      return $('div[id$="-content"],div[id$="-images"]', this.$form);
    },
    getCustomText: function(){
      return $('div[id$="-custom_text"]', this.$form);
    },
    getNavType: function(){
      return $('#castle-cms-navigation-nav_type', this.$form);
    }
  });
  return FormPattern;

});

/* global define */

define('castle-url/patterns/edittile',[
  'jquery',
  'pat-base',
  'mockup-patterns-modal',
  'mockup-utils'
], function($, Base, Modal, utils) {
  'use strict';

  var EditTile = Base.extend({
    name: 'edittile',
    trigger: '.pat-edittile',
    parser: 'mockup',
    defaults: {
      url: null,
      editUrl: null,
      label: 'Tile'
    },
    init: function() {
      var self = this;
      var $editBtn = $('<a href="' + self.options.editUrl + '" class="edit-tile">' + self.options.label + '</a>');

      $editBtn.click(function(e){
        utils.loading.show();
        e.preventDefault();
        $.ajax({
          type: "GET",
          url: self.options.editUrl,
          success: function(value, xhr) {
            utils.loading.hide();
            var modal = new Modal(self.$el, {
              html: value,
              loadLinksWithinModal: true,
              buttons: '.formControls > input[type="submit"], .actionButtons > input[type="submit"]'
            });
            modal.$el.off('after-render');
            modal.on('after-render', function() {
              $('input[name*="cancel"]', modal.$modal).off('click').on('click', function() {
                // Close overlay
                modal.hide();
              });
            });
            modal.show();
            modal.$el.off('formActionSuccess');
            modal.on('formActionSuccess', function (event, response, state, xhr) {
              window.location.reload();
            });
          }
        });
      });
      self.$el.append($editBtn);
    }
  });
  return EditTile;

});

/* global define, mOxie */

define('castle-url/patterns/focalpointselect',[
  'jquery',
  'pat-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'castle-url/components/image-focal-point-selector',
  'mockup-utils',
  'castle-url/libs/moxie/bin/js/moxie'
], function($, Base, _, R, FocalPointSelector, utils) {
  'use strict';

  var D = R.DOM;

  var FocalPointSelectorComponent = R.createClass({

    getInitialState: function(){
      return {
        loading: false,
        override_focal_point: this.props.focal_point,
        image_focal_point: this.props.focal_point,
        image: null,
        previewImage: null,
        previewWidth: '',
        previewHeight: '',
        originalFocalwUrl: '',
        originalFocal: true
      };
    },

    getDefaultProps: function(){
      return {
        focal_point: [0, 0],
        reference: null
      };
    },

    loadImage: function(asset){
      var that = this;
      that.setState({
        loading: true
      });
      that.state.image = new mOxie.Image();
      utils.loading.show();
      that.state.image.onload = function() {
        // make a new image object for the downsize
        that.props.width = that.state.image.width;
        that.props.height = that.state.image.height;
        if(that.state.override_focal_point[0] > that.state.image.width ||
           that.state.override_focal_point[0] === 0){
          that.state.override_focal_point[0] = that.state.image.width / 2;
        }
        if(that.state.override_focal_point[1] > that.state.image.height ||
           that.state.override_focal_point[1] === 0){
          that.state.override_focal_point[1] = that.state.image.height / 2;
        }
        that.props.exists = true;

        var blob = that.state.image.getAsBlob();
        var resizedImg = new mOxie.Image();
        resizedImg.onload = function(){
          resizedImg.onresize = function(){
            utils.loading.hide();
            that.setState({
              previewUrl: resizedImg.getAsDataURL('image/png'),
              previewWidth: resizedImg.width,
              previewHeight: resizedImg.height,
              loading: false,
              previewImage: resizedImg
            });
          };
          resizedImg.downsize({width: 300});
        };
        resizedImg.load(blob);
      };
      that.state.image.onerror = function(){
        utils.loading.hide();
        that.props.exists = false;
        that.setState({
          loading: false
        });
      };
      that.state.image.load(asset);
    },

    render: function(){
      var that = this;
      if(that.state.loading){
        return D.div({}, 'Loading image...');
      }
      if(!that.props.exists){
        return D.div({}, 'No image selected');
      }

      var focalPointSelectorOps = {
        readOnly: that.state.originalFocal,
        url: that.state.previewUrl,
        width: that.state.previewWidth,
        fullWidth: that.props.width,
        height: that.state.previewHeight,
        fullHeight: that.props.height,
        focalPoint: (that.state.originalFocal)?this.state.image_focal_point:that.state.override_focal_point,
        onFocalSet: function(focal_point){
          if(!that.state.originalFocal){
            that.state.override_focal_point = focal_point;
            that.setState({
              dirty: true
            });
            that.props.onSelected(focal_point);
          }
        }
      }

      return D.div({ className: 'imagewidget-image-container'}, [
        R.createElement(FocalPointSelector, focalPointSelectorOps)
      ]);
    },
  });

  var FocalPointSelectPattern = Base.extend({
    name: 'focalpointselect',
    trigger: '.pat-focalpointselect',
    parser: 'mockup',
    defaults: {
    },
    init: function() {
      var self = this;
      self.$el.attr('type', 'hidden');
      var $form = self.$el.closest('form');

      var $relatedItems = $('.pat-relateditems', $form);
      var $displayType = $('[id*="-display_type"].field', $form);
      var $parent = self.$el.parent();

      var focal_point_val = self.$el.val();
      var focal_point;
      if(focal_point_val){
        focal_point = JSON.parse(focal_point_val);
      }else{
        focal_point = [0,0];
      }

      var $checkboxContainer = $('<div class="checkbox"><label><input type="checkbox"> Override focal point for selected image</label></div>');
      var $checkbox = $('input', $checkboxContainer);
      $parent.append($checkboxContainer);

      var el = document.createElement('div');
      $parent.append(el);

      self.component = R.render(R.createElement(FocalPointSelectorComponent, {
        onSelected: function(fp){
          self.$el.val(JSON.stringify(fp));
        },
        focal_point: focal_point
      }), el);

      var portalUrl = $('body').attr('data-portal-url');
      function getImageData(e){
        if(e.target.value){
          var that = self;
          that.component.loadImage(portalUrl + '/resolveuid/' + e.target.value + '/@@images/image?_=' + utils.generateId());
          $.ajax({
            url: portalUrl + '/resolveuid/' + e.target.value + '/@@imageinfo',
            dataType: 'JSON',
            type: 'GET',
          }).done(function(data){
            that.component.setState({image_focal_point: data.focal_point});
          })
        }else{
          self.component.setState({
            exists: false
          });
        }
      }

      function getMediaData() {
        try {
          var imageUID = $relatedItems[0].value;
          var videoUID = $relatedItems[1].value;
        } catch (err) {}
        
        var that = self;
        if (!imageUID && !videoUID) {
          self.component.setState({
            exists: false
          });
          $parent.hide();
          return;
        }

        $parent.show();
        that.component.loadImage(portalUrl + "/resolveuid/" + (imageUID ? imageUID : videoUID) + "/@@images/image?_=" + utils.generateId());

        if (imageUID) {
          $.ajax({
            url: portalUrl + "/resolveuid/" + imageUID + "/@@imageinfo",
            dataType: "JSON",
            type: "GET"
          }).done(function(data) {
            that.component.setState({ image_focal_point: data.focal_point });
          });
        }
      } 

      $relatedItems.on('change', getMediaData);
            
      var uid = $relatedItems.val()
      if(!uid) {
        try{
          uid = $relatedItems[1].value;
        } catch (err) {
        }
      } 
      
      if(uid){
        getMediaData();
      }

      if(focal_point_val){
        $checkbox[0].checked = true;
        self.component.setState({
          originalFocal: false
        });
      }else{
        self.component.setState({
          originalFocal: true
        });
      }

      $checkbox.on('change', function(e){
        if(e.target.checked){
          self.component.setState({
            originalFocal: false
          });
        }else{
          self.component.setState({
            originalFocal: true
          });
          self.$el.attr('value', '');
        }
      });

      // if there is a display type, we are not even showing this field if natural is selected
      if($displayType.size() > 0){
        var val = $('select', $displayType).val();
        if(!val || val === 'natural' || val === 'fullwidth'){
          $parent.hide();
        }
        $('select', $displayType).on('change', function(e){
          var val = e.target.value;
          if(!val || val === 'natural' || val === 'fullwidth'){
            $parent.hide();
          }else{
            $parent.show();
          }
        });
      }
    }
  });

  return FocalPointSelectPattern;

});

/* global mOxie */

define('castle-url/patterns/imagewidget',[
  'jquery',
  'pat-base',
  'castle-url/libs/react/react.min',
  'castle-url/components/image-focal-point-selector',
  'castle-url/components/image-editor',
  'castle-url/components/utils',
  'mockup-utils',
  'mockup-patterns-relateditems',
  'castle-url/libs/moxie/bin/js/moxie'
], function($, Base, R, FocalPointSelector, ImageEditor, cutils, utils, RelatedItems) {
  "use strict";

  var D = R.DOM;

  var ImageWidgetComponent = R.createClass({

    getInitialState: function(){
      return {
        dragging: false,
        dirty: false,
        remove: false,
        imageDirty: false,
        loading: true,
        showEditor: false,
        focal_point: this.props.focal_point,
        image: null,
        previewImage: null,
        previewWidth: '',
        previewHeight: '',
        previewUrl: '',
        selectReference: this.props.reference !== null
      };
    },

    getDefaultProps: function(){
      return {
        focal_point: [0, 0],
        reference: null
      };
    },

    loadImage: function(asset){
      var that = this;
      that.state.image = new mOxie.Image();
      utils.loading.show();
      that.state.image.onload = function() {
        // make a new image object for the downsize
        that.props.width = that.state.image.width;
        that.props.height = that.state.image.height;
        if(!that.props.focal_point){
          that.props.focal_point = [0, 0];
        }
        if(that.props.focal_point[0] > that.state.image.width ||
           that.props.focal_point[0] === 0){
          that.props.focal_point[0] = that.state.image.width / 2;
        }
        if(that.props.focal_point[1] > that.state.image.height ||
           that.props.focal_point[1] === 0){
          that.props.focal_point[1] = that.state.image.height / 2;
        }
        that.props.exists = true;

        var blob = that.state.image.getAsBlob();
        var resizedImg = new mOxie.Image();
        resizedImg.onload = function(){
          resizedImg.onresize = function(){
            utils.loading.hide();
            that.setState({
              previewUrl: resizedImg.getAsDataURL('image/png'),
              previewWidth: resizedImg.width,
              previewHeight: resizedImg.height,
              loading: false,
              previewImage: resizedImg
            });
          };
          resizedImg.downsize({width: 300});
        };
        resizedImg.load(blob);
      };
      that.state.image.onerror = function(){
        utils.loading.hide();
        that.props.exists = false;
        that.setState({
          loading: false
        });
      };
      that.state.image.load(asset);
    },

    componentDidMount: function(){
      var that = this;
      if(that.props.exists){
        that.loadImage(that.props.download_url);
      }else{
        that.setState({
          loading: false
        });
      }

      var accept = [
        {title: "Images", extensions: "jpg,gif,png"}
      ];

      var portalUrl = $('body').attr('data-portal-url');
      mOxie.Env.swf_url = portalUrl + '/++plone++castle/libs/moxie/bin/flash/Moxie.min.swf';
      mOxie.Env.xap_url = portalUrl + '/++plone++castle/libs/moxie/bin/silverlight/Moxie.min.xap';

      var fileInput = new mOxie.FileInput({
        browse_button: that.refs.upload_btn.getDOMNode(),
        runtime_order: 'html5,flash,html4',
        multiple: false,
        accept: accept
      });

      var handlFileAdded = function(image){
        that.props.filename = image.name;
        that.setState({
          dirty: true,
          imageDirty: true,
          loading: true,
          remove: false
        }, function(){
          if(image.type === 'image/gif'){
            // need to convert it first
            that.loadGif(image);
          }else{
            that.loadImage(image);
          }
        });
      };

      fileInput.onchange = function(e) {
        handlFileAdded(e.target.files[0]);
      };

      fileInput.init(); // initialize

      var dropEl = that.refs.droparea.getDOMNode();
      var fileDrop = new mOxie.FileDrop({
        drop_zone: dropEl,
        accept: accept
      });

      fileDrop.ondrop = function() {
        var dz = this;
        handlFileAdded(dz.files[0]);
        dropEl.style.background = '';
      };
      fileDrop.ondragenter = function(){
        that.setState({
          dragging: true
        });
      };
      fileDrop.ondragleave = function(){
        that.setState({
          dragging: false
        });
      };

      fileDrop.init();

      /* setup related items */
      var selection = [];
      if(this.props.reference){
        selection = [this.props.reference];
      }
      var $re = $(that.refs.relateditem.getDOMNode());
      try {
        var options = JSON.parse($('.pat-relateditems').attr('data-pat-relateditems'));
      } catch (e) {
        var options = {};
      }
      var pattern = new RelatedItems($re, cutils.extend(options, {
        vocabularyUrl: $('body').attr('data-portal-url') + '/@@getVocabulary?name=plone.app.vocabularies.Catalog',
        maximumSelectionSize: 1,
        multiple: false,
        allowAdd: false,
        noItemsSelectedText: 'No image selected',
        initial_selection: selection,
        selectableTypes: ['Image'],
        baseCriteria: [{
          i: 'portal_type',
          o: 'plone.app.querystring.operation.selection.any',
          v: ['Image', 'Folder']
        }]
      }));
      $re.on('change', function(){
        if(pattern.component.state.selected.length > 0){
          that.props.reference = pattern.component.state.selected[0];
        }else{
          that.props.reference = null;
        }
      });
    },

    loadGif: function(image){
      var that = this;
      utils.loading.show();
      var xhr = new mOxie.XMLHttpRequest();
      var fd = new mOxie.FormData();
      xhr.open('post', $('body').attr('data-base-url') + '/@@convert-to-png');
      fd.append('data', image.slice());
      xhr.onload = function() {
        if (xhr.response) {
          that.loadImage('data:image/png;base64,' + xhr.response);
        }else{
          alert('error converting image');
        }
        utils.loading.hide();
      };
      xhr.bind('error runtimeerror', function() {
        utils.loading.hide();
        alert('error converting image');
      });

      xhr.send(fd, {
        runtime_order: 'html5,flash,html4',
        required_caps: {
          send_multipart: true
        }
      });
    },

    renderImage: function(){
      var that = this;
      if(that.state.loading){
        return D.div({}, 'Loading image...');
      }
      if(!that.props.exists){
        return D.div({}, 'No image');
      }
      return D.div({ className: 'imagewidget-image-container'}, [
        R.createElement(FocalPointSelector, {
          url: that.state.previewUrl,
          width: that.state.previewWidth,
          fullWidth: that.props.width,
          height: that.state.previewHeight,
          fullHeight: that.props.height,
          focalPoint: that.props.focal_point,
          onFocalSet: function(focal_point){
            that.props.focal_point = focal_point;
            that.setState({
              dirty: true
            });
          }
        }),
        D.p({ className: 'discreet'}, 'Filename: ' + that.props.filename)
      ]);
    },

    renderUploader: function(){
      var that = this;
      var style = {};
      if(that.state.loading || that.state.showEditor){
        style = { display: 'none'};
      }
      return D.div({ ref: 'droparea', className: 'droparea', style: style }, [
        'Drop here to replace image or ',
        D.button({ ref: 'upload_btn', className: 'btn btn-default castle-btn-select-files' }, 'Select an image'),
      ]);
    },

    render: function(){
      var that = this;
      var left = [];
      var buttons = [];
      var right = [
        that.renderUploader()
      ];

      if(that.state.dirty){
        buttons.push(D.button({ className: 'plone-btn plone-btn-default',
                                onClick: function(e){
                                  e.preventDefault();
                                  that.props.focal_point = that.props.original_focal_point;
                                  that.setState({
                                    dirty: false,
                                    imageDirty: false,
                                    loading: true,
                                    remove: false
                                  }, function(){
                                    that.loadImage(that.props.download_url);
                                  });
                                }}, 'Cancel changes'));
      }

      if(that.props.exists && !that.state.remove){
        left.push(that.renderImage());
        if(!that.props.required){
          buttons.push(D.button({ className: 'plone-btn plone-btn-default',
                                  onClick: function(e){
                                    e.preventDefault();
                                    that.setState({
                                      remove: true,
                                      dirty: true
                                    });
                                  }}, 'Remove image'));
        }

        if(!that.state.loading && !that.state.remove){
          if(that.state.showEditor){
            right.push(R.createElement(ImageEditor, {
              key: 'image-editor',
              file: that.state.image,
              onSave: function(blob){
                that.setState({
                  showEditor: false,
                  loading: true,
                  dirty: true,
                  imageDirty: true
                }, function(){
                  that.loadImage(blob);
                });
              },
              onCancel: function(){
                that.setState({
                  showEditor: false
                });
              }}));
          }else{
            buttons.push(D.button({
              className: "plone-btn plone-btn-default castle-btn-edit",
              onClick: function(e){
                e.preventDefault();
                that.setState({
                  showEditor: true
                });
              }}, 'Edit Image'));
          }
        }
      }

      var leftClass = 'col-md-5';
      var rightClass = 'col-md-7';
      if(left.length === 0){
        leftClass = '';
        rightClass = 'col-md-12';
      }

      return D.div({ className: 'castle-imagewidget-container'}, [
        D.div({ style: that.state.selectReference && { display: 'none'} || {}}, [
          D.div({ className: 'row'}, [
            D.div({ className: leftClass }, left),
            D.div({ className: rightClass}, [
              right
            ])
          ]),
          D.div({ className: 'btn-container'}, buttons)
        ]),
        D.div({ style: !that.state.selectReference && { display: 'none'} || {}}, [
          D.input({ ref: 'relateditem', type: 'hidden' })
        ]),
        D.div({ className: 'form-group'},
          D.label({}, [
            D.input({ type: 'checkbox', checked: that.state.selectReference, onClick: function(){
              that.setState({
                selectReference: !that.state.selectReference
              });
            }}),
            'Or, select image from site to use as the lead image'
          ])
        )
      ]);
    }
  });

  var ImageWidget = Base.extend({
    name: 'imagewidget',
    trigger: '.pat-imagewidget',
    parser: 'mockup',
    defaults: {
    },
    init: function() {
      var that = this;
      that.$action = that.$el.siblings('.imagewidget-action');
      var options = cutils.extend(that.options, {
        original_focal_point: that.options.focal_point
      });
      that.component = R.render(R.createElement(ImageWidgetComponent, options), that.$el[0]);

      that.$el.closest('form').on('submit', function(){
        if(that.component.state.selectReference){
          if(that.component.props.reference){
            that.$action.val('');
            that.addReference();
          } else {
            that.$action.val('nochange');
          }
        } else if(that.component.state.remove){
          that.$action.val('remove');
        }else if(!that.component.state.dirty){
          that.$action.val('nochange');
        }else{
          // add image data
          if(that.component.state.imageDirty){
            that.$action.val('');
            var data = document.createElement('input');
            data.type = 'hidden';
            data.name = that.options.name;
            data.value = that.component.state.image.getAsDataURL(that.component.state.image.type, 100);
            $(data).insertAfter(that.$el);

            var filename = document.createElement('input');
            filename.type = 'hidden';
            filename.name = that.options.name + '.filename';
            filename.value = that.component.props.filename;
            $(filename).insertAfter(that.$el);
          } else {
            that.$action.val('nochange');
          }

          // then add focal point data
          var focalX = document.createElement('input');
          focalX.type = 'hidden';
          focalX.name = that.options.name + '.focalX';
          focalX.value = that.component.props.focal_point[0];
          $(focalX).insertAfter(that.$el);

          var focalY = document.createElement('input');
          focalY.type = 'hidden';
          focalY.name = that.options.name + '.focalY';
          focalY.value = that.component.props.focal_point[1];
          $(focalY).insertAfter(that.$el);
        }
      });
    },
    addReference: function(){
      var that = this;
      var reference = document.createElement('input');
      reference.type = 'hidden';
      reference.name = that.options.name;
      if(that.component.state.selectReference){
        reference.value = 'reference:' + that.component.props.reference;
      } else {
        reference.value = '';
        that.$action.val('nochange');
      }
      $(reference).insertAfter(that.$el);
    }
  });

  return ImageWidget;

});

/*!
  * $script.js JS loader & dependency manager
  * https://github.com/ded/script.js
  * (c) Dustin Diaz 2014 | License MIT
  */
(function(e,t){typeof module!="undefined"&&module.exports?module.exports=t():typeof define=="function"&&define.amd?define('castle-url/libs/script',t):this[e]=t()})("$script",function(){function p(e,t){for(var n=0,i=e.length;n<i;++n)if(!t(e[n]))return r;return 1}function d(e,t){p(e,function(e){return t(e),1})}function v(e,t,n){function g(e){return e.call?e():u[e]}function y(){if(!--h){u[o]=1,s&&s();for(var e in f)p(e.split("|"),g)&&!d(f[e],g)&&(f[e]=[])}}e=e[i]?e:[e];var r=t&&t.call,s=r?t:n,o=r?e.join(""):t,h=e.length;return setTimeout(function(){d(e,function t(e,n){if(e===null)return y();!n&&!/^https?:\/\//.test(e)&&c&&(e=e.indexOf(".js")===-1?c+e+".js":c+e);if(l[e])return o&&(a[o]=1),l[e]==2?y():setTimeout(function(){t(e,!0)},0);l[e]=1,o&&(a[o]=1),m(e,y)})},0),v}function m(n,r){var i=e.createElement("script"),u;i.onload=i.onerror=i[o]=function(){if(i[s]&&!/^c|loade/.test(i[s])||u)return;i.onload=i[o]=null,u=1,l[n]=2,r()},i.async=1,i.src=h?n+(n.indexOf("?")===-1?"?":"&")+h:n,t.insertBefore(i,t.lastChild)}var e=document,t=e.getElementsByTagName("head")[0],n="string",r=!1,i="push",s="readyState",o="onreadystatechange",u={},a={},f={},l={},c,h;return v.get=m,v.order=function(e,t,n){(function r(i){i=e.shift(),e.length?v(i,r):v(i,t,n)})()},v.path=function(e){c=e},v.urlArgs=function(e){h=e},v.ready=function(e,t,n){e=e[i]?e:[e];var r=[];return!d(e,function(e){u[e]||r[i](e)})&&p(e,function(e){return u[e]})?t():!function(e){f[e]=f[e]||[],f[e][i](t),n&&n(r)}(e.join("|")),v},v.done=function(e){v([null],e)},v})
;
/* global define, alert */

define('castle-url/patterns/mapselect',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'pat-registry',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-url/components/utils',
  'mockup-patterns-tinymce',
  'pat-mockup-parser',
  'castle-url/libs/script'
], function($, Base, _, registry, R, utils, Modal, component_utils, TinyMCE, Parser, $script) {
  'use strict';

  var D = R.DOM;
  var apiKey = '';

  var generateColorDropdown = function(selected) {
    var colorList = { Red: '#e6194b', Green: '#3cb44b', Yellow: '#ffe119', Blue: '#0082c8', Orange: '#f58231', Purple: '#911eb4', Cyan: '#46f0f0', Magenta: '#f032e6', Lime: '#d2f53c', Pink: '#fabebe', Teal: '#008080', Lavender: '#e6beff', Brown: '#aa6e28', Beige: '#fffac8', Maroon: '#800000', Mint: '#aaffc3', Olive: '#808000', Coral: '#ffd8b1', Navy: '#000080', Grey: '#808080', White: '#FFFFFF', Black: '#000000'};
    var color_keys = Object.keys(colorList);
    return [
      D.label({}, 'Color'),
      D.select({
        ref: 'color',
        defaultValue: selected,
        className: 'input-group'},[
          color_keys.map(function(name) {
            var color = colorList[name];
            return D.option({
              value: color }, name);
          })
        ])
    ];
  };

  var getLat = function(data){
    return (data.geometry.location.lat && data.geometry.location.lat()) || data.geometry.location.G;
  };
  var getLng = function(data){
    return (data.geometry.location.lng && data.geometry.location.lng()) || data.geometry.location.K;
  };
  var formatEntry = function(address, lat, lng){
    if(!lat || !lng){
      return 'No point selected';
    }
    return address + '(' + lat.toFixed(6) + ',' + lng.toFixed(6) + ')';
  };

  var MapSearchComponent = R.createClass({
    getInitialState: function(){
      return {
        results: [],
        searchTerm: '',
        searched: false,
        selected: -1
      };
    },
    searchClicked: function(e){
      if(e){
        e.preventDefault();
      }
      var that = this;
      utils.loading.show();
      var geocoder = new window.google.maps.Geocoder();
      geocoder.geocode({ 'address': that.state.searchTerm }, function (results) {
        utils.loading.hide();
        that.setState({
          results: results,
          searched: true,
          selected: -1
        });
      });
    },
    searchInput: function(e){
      this.setState({
        searchTerm: e.target.value
      });
    },
    selectItem: function(idx, e){
      e.preventDefault();
      this.setState({
        selected: idx
      });
    },
    searchInputKeyPress: function(e){
      /* purpose here is to be able to use the enter key
         to go to next page in form */
      if((e.charCode || e.keyCode) === 13){
        this.searchClicked();
      }
    },
    render: function(){
      var that = this;
      var results = '';
      if(that.state.searched){
        if(that.state.results.length > 0){
          results = D.div({}, [
            D.p({ className: 'discreet'}, 'Select item from results'),
            D.ul({ className: 'castle-map-search-results'}, that.state.results.map(function(item, idx){
              var className = '';
              if(idx === that.state.selected){
                className = 'selected glyphicon glyphicon-ok';
              }
              var formatted = formatEntry(item.formatted_address, getLat(item), getLng(item));
              return D.li({className: className}, [
                D.a({ href: '#', onClick: that.selectItem.bind(that, idx)}, formatted)
              ]);
            }))
          ]);
        }else if(apiKey == ''){
          results = D.div({}, [
            D.span({}, 'Google Maps Api Key not configured. To set an api key go to Site Setup -> CastleCMS -> APIs tab. If you need an api key go '),
            D.a({href: 'https://developers.google.com/maps/documentation/javascript/get-api-key'}, 'here'),
            D.span({}, ' and follow the instructions.')
          ]);
        } else{
          results = 'No results';
        }
      }
      return D.div({ className: 'map-search-container'}, [
        D.div({ className: 'form-group'}, [
          D.label({}, 'Search Location'),
          D.div({ className: 'input-group'}, [
            D.input({type: "text", placeholder: 'Location', className: 'form-control',
                     value: that.state.searchTerm, onChange: that.searchInput,
                     onKeyDown: that.searchInputKeyPress}),
            D.span({ className: "input-group-btn"},
              D.button({ className: "plone-btn plone-btn-primary", type: "button",
                         onClick: that.searchClicked }, 'Search')
            )
          ])
        ]),
        results
      ]);
    }
  });

  var MapperAddMarkerComponent = component_utils.Class([Modal], {
    getInitialState: function(){
      return {
        customIcon: false
      };
    },
    addButtonClicked: function(e){
      e.preventDefault();
      var search = this.refs.search;
      var icon = this.getIcon();
      if(search.state.selected !== -1){
        var data = search.state.results[search.state.selected];
        var marker = {
          formatted: data.formatted_address,
          lat: getLat(data),
          lng: getLng(data),
          popup: this.props.tiny.tiny.getContent()
        };
        if( icon ) {
          marker.icon = icon;
        }
        this.props.parent.add(marker);
        this.hide();
      }else{
        alert('You have not selected a location');
      }
    },
    componentDidMount: function(){
      Modal.componentDidMount.apply(this);
      var $el = $(this.refs.tiny.getDOMNode());
      var options = $.extend({}, true, Parser.getOptions($el, 'tinymce'), {
        tiny: {
          height: 100
        }
      });
      this.props.tiny = new TinyMCE($el, options);
    },
    getIcon: function() {
      if( this.state.customIcon ) {
        return {
          'color': this.refs.color.getDOMNode().value,
          'iconText': this.refs.iconText.getDOMNode().value
        };
      }else{
        return false;
      }
    },
    renderContent: function(){
      var that = this;
      return D.div({ className: 'castle-markers-container'}, [
        R.createElement(MapSearchComponent, {parent: that, ref: 'search'}),
        D.div({ className: 'form-group'}, [
          D.label({}, 'Custom Icon'),
          D.input({
            type: 'checkbox',
            onClick: function(){
              that.setState({
                customIcon: !that.state.customIcon
              });
            }
          })
        ]),
        this.renderCustomIconForm(),
        D.div({ className: 'form-group'}, [
          D.label({}, 'Text'),
          D.textarea({ ref: 'tiny' })
        ])
      ]);
    },
    renderCustomIconForm: function() {
      if( this.state.customIcon) {
        return D.div({ className: 'form-group'}, [
          generateColorDropdown(false),
          D.label({}, 'Label'),
          D.input({ref: 'iconText',  'className': 'input-group'})
        ]);
      }else{
        return [];
      }
    },
    renderFooter: function(){
      var buttons = [D.button({
        type: 'button', className: 'btn btn-default small',
        onClick: this.addButtonClicked }, 'Add')];
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'add-marker-modal',
        title: 'Add Marker'
      });
    }
  });

  var MapperEditMarkerComponent = component_utils.Class([Modal], {
    getInitialState: function(){
      var icon = false;
      if( this.props.icon != false ) {
        icon = true;
      }
      return {
        customIcon: icon
      };
    },
    saveButtonClicked: function(e){
      e.preventDefault();
      this.hide();
      var popup = this.props.tiny.tiny.getContent();
      var icon = false;
      if( this.refs.color !== undefined ) {
        icon = {
          color: this.refs.color.getDOMNode().value,
          iconText: this.refs.iconText.getDOMNode().value
        };
      }

      this.props.callback(popup, icon);
    },
    componentDidMount: function(){
      Modal.componentDidMount.apply(this);
      var $el = $(this.refs.tiny.getDOMNode());
      var options = $.extend({}, true, Parser.getOptions($el, 'tinymce'), {
        tiny: {
          height: 100
        }
      });
      this.props.tiny = new TinyMCE($el, options);
    },
    renderCustomIconForm: function() {
      if( this.state.customIcon ) {
        return D.div({ className: 'form-group'}, [
          generateColorDropdown(this.props.icon.color),
          D.label({}, 'Label'),
          D.input({
            ref: 'iconText',
            className: 'input-group',
            defaultValue: this.props.icon.iconText
          })
        ]);
      }else{
        return [];
      }
    },
    renderContent: function(){
      var that = this;
      return D.div({ className: 'castle-edit-marker-container-container'}, [
        D.div({ className: 'form-group'}, [
          D.div({ className: 'form-group'}, [
            D.label({}, 'Custom Icon'),
            D.input({
              type: 'checkbox',
              checked: this.state.customIcon,
              onClick: function(){
                that.setState({
                  customIcon: !that.state.customIcon
                });
              }
            })
          ]),
          this.renderCustomIconForm(),
          D.label({}, 'Text'),
          D.textarea({ ref: 'tiny', value: this.props.data })
        ])
      ]);
    },
    renderFooter: function(){
      var buttons = [D.button({
        type: 'button', className: 'btn btn-default small',
        onClick: this.saveButtonClicked }, 'Save')];
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'edit-marker-modal',
        title: 'Edit Marker'
      });
    }
  });

  var MarkersComponent = R.createClass({
    addMarkerClicked: function(e){
      e.preventDefault();
      component_utils.createModalComponent(
        MapperAddMarkerComponent, 'castle-add-marker-modal', {
          parent: this
        });
    },
    add: function(data){
      this.props.value.push(data);
      this.forceUpdate();
      this.props.el.value = JSON.stringify(this.props.value);
    },
    removeClicked: function(idx, e){
      e.preventDefault();
      this.props.value.splice(idx, 1);
      this.forceUpdate();
      this.props.el.value = JSON.stringify(this.props.value);
    },
    editClicked: function(idx, e){
      e.preventDefault();
      var that = this;
      var marker = this.props.value[idx];
      component_utils.createModalComponent(
        MapperEditMarkerComponent, 'castle-add-marker-modal', {
          parent: this,
          data: marker.popup,
          icon: marker.icon || false,
          callback: function(popup, icon){
            marker.popup = popup;
            if( icon !== false ) {
              marker.icon = icon;
            }else{
              delete marker.icon;
            }
            that.forceUpdate();
            that.props.el.value = JSON.stringify(that.props.value);
          }
        });
    },
    render: function(){
      var that = this;
      var noMarkers = '';
      if(that.props.value.length === 0){
        noMarkers = D.p({ className: 'discreet'}, 'Currently no custom markers set');
      }
      return D.div({className: 'markers-container'}, [
        noMarkers,
        D.ul({}, that.props.value.map(function(marker, idx){
          return D.li({}, [
            D.span({ className: 'marker-label' }, marker.formatted),
            D.a({ href: '#', className: 'plone-btn plone-btn-default plone-btn-xs',
                  onClick: that.editClicked.bind(that, idx)}, 'Edit'),
            D.a({ href: '#', className: 'plone-btn plone-btn-warning plone-btn-xs',
                  onClick: that.removeClicked.bind(that, idx)},
              D.span({ className: 'glyphicon glyphicon-trash'}, 'Remove')),
          ]);
        })),
        D.a({href:'#', className:'plone-btn plone-btn-default plone-btn-sm',
             onClick: that.addMarkerClicked }, 'Add Marker')
      ]);
    }
  });

  var MapperSetPointComponent = component_utils.Class([Modal], {
    getInitialState: function(){
      return {
      };
    },
    addButtonClicked: function(e){
      e.preventDefault();
      var search = this.refs.search;
      if(search.state.selected !== -1){
        var data = search.state.results[search.state.selected];
        var state = null;
        var city = null;
        for (var i=0;i<data['address_components'].length;i++){
          var component = data['address_components'][i];
          if (component['types'].indexOf('administrative_area_level_1') >= 0){
            state = component['short_name'];
          } else if (component['types'].indexOf('locality') >= 0) {
            city = component['long_name'];
          }
        }
        this.props.parent.set({
          formatted: data.formatted_address,
          lat: (data.geometry.location.lat && data.geometry.location.lat()) || data.geometry.location.G,
          lng: (data.geometry.location.lng && data.geometry.location.lng()) || data.geometry.location.K,
          city: city,
          state: state
        });
        this.hide();
      }else{
        alert('You have not selected a location');
      }
    },
    renderContent: function(){
      var that = this;
      return D.div({ className: 'castle-markers-container'}, [
        R.createElement(MapSearchComponent, {parent: that, ref: 'search'})
      ]);
    },
    renderFooter: function(){
      var buttons = [D.button({
        type: 'button', className: 'btn btn-default small',
        onClick: this.addButtonClicked }, 'Set')];
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'set-center-point-modal',
        title: 'Set Center Point'
      });
    }
  });

  var CenterPointComponent = R.createClass({
    setPointClicked: function(e){
      e.preventDefault();
      component_utils.createModalComponent(
        MapperSetPointComponent, 'castle-add-center-modal', {
          parent: this
        });
    },
    set: function(data){
      this.props.value = data;
      this.props.el.value = JSON.stringify(data);
      this.forceUpdate();
    },
    render: function(){
      var that = this;
      var value = '';
      if(that.props.value){
        value = D.p({ className: 'discreet'},
          formatEntry(that.props.value.formatted, that.props.value.lat, that.props.value.lng));
      }
      return D.div({className: 'markers-container'}, [
        value,
        D.a({href:'#', className:'btn btn-default',
             onClick: that.setPointClicked }, 'Set point')
      ]);
    }
  });

  var PointsComponent = R.createClass({
    addPointClicked: function(e){
      e.preventDefault();
      component_utils.createModalComponent(
        MapperSetPointComponent, 'castle-add-center-modal', {
          parent: this
        });
    },
    set: function(data){
      if(!this.props.value){
        this.props.value = [];
      }
      this.props.value.push(data);
      this.props.el.value = JSON.stringify(this.props.value);
      this.forceUpdate();
    },
    removePoint: function(idx, e){
      e.preventDefault();
      this.props.value.splice(idx, 1);
      this.props.el.value = JSON.stringify(this.props.value);
      this.forceUpdate();
    },
    render: function(){
      var that = this;
      var value = that.props.value || [];
      var entries = [];

      value.forEach(function(item, idx){
        entries.push(D.li({ className: 'discreet', style: { display: 'block'}, key: 'map-entry-' + idx}, [
          formatEntry(item.formatted, item.lat, item.lng),
          ' - (',
          D.a({ href: '#', onClick: that.removePoint.bind(that, idx)}, 'Remove'),
          ')'
        ]));
      });
      return D.div({className: 'markers-container'}, [
        D.ul({}, entries),
        D.br({}, ''),
        D.a({href:'#', className:'btn btn-default',
             onClick: that.addPointClicked }, 'Add location')
      ]);
    }
  });


  var MapSelect = Base.extend({
    name: 'mapselect',
    trigger: '.pat-mapselect',
    parser: 'mockup',
    defaults: {
      type: 'markers'
    },
    init: function() {
      var self = this;
      if(window.google && window.google.maps){
        self.initialize();
      }else{
        var mapApiUrl = 'https://maps.google.com/maps/api/js?v=3&sensor=false';
        apiKey = $('body').attr('data-google-maps-api-key');
        if(apiKey){
          mapApiUrl += '&key=' + apiKey;
        }
        $script(mapApiUrl, function(){
          self.initialize();
        });
      }
    },
    initialize: function(){
      var self = this;
      self.val = $.parseJSON(self.$el.val());
      self.$el.hide();
      var el = document.createElement('div');
      self.$el.parent().append(el);
      if(self.options.type === 'markers'){
        R.render(R.createElement(MarkersComponent, {
          el: self.$el[0],
          value: self.val || []
        }), el);
      }else if(self.options.type === 'point'){
        R.render(R.createElement(CenterPointComponent, {
          el: self.$el[0],
          value: self.val || {}
        }), el);
      }else if(self.options.type === 'points'){
        var val = self.val;
        if(val && val.lat && val.lng){
          // try to convert
          val = [val];
        }
        if(!val){
          val = [];
        }
        R.render(R.createElement(PointsComponent, {
          el: self.$el[0],
          value: val
        }), el);
      }
    }
  });

  return MapSelect;
});

/* global define */

define('castle-url/patterns/previewselect',[
  'jquery',
  'pat-base',
  'underscore'
], function($, Base, _) {
  'use strict';

  var _selectTemplate = '<div class="row previewselect-container">' +
  '<div class="col-md-6 input"></div>' +
  '<div class="col-md-6 preview"></div>' +
'</div>';

  var PreviewSelectPattern = Base.extend({
    name: 'previewselect',
    trigger: '.pat-previewselect',
    defaults: {
      previews: {}
    },
    parser: 'mockup',
    init: function() {
      var self = this;
      var $dom = $(_selectTemplate);
      var $parent = self.$el.parent();
      $parent.append($dom);
      $('.input', $dom).append(self.$el);

      var _change = function(){
        var val = self.$el.val();
        $('.preview', $dom).empty();
        if(self.options.previews[val]){
          $('.preview', $dom).append(
            '<div><h4>Preview</h4><img src="' +
              $('body').attr('data-portal-url') + '/' + self.options.previews[val] +
            '" /></div>');
        }
      };
      _change();
      self.$el.on('change', _change);
    }
  });

  return PreviewSelectPattern;

});

define('mockup-ui-url/views/toolbar',[
  'mockup-ui-url/views/container'
], function(ContainerView) {
  'use strict';

  var Toolbar = ContainerView.extend({
    tagName: 'div',
    className: 'navbar',
    idPrefix: 'toolbar-'
  });

  return Toolbar;
});

define('mockup-ui-url/views/buttongroup',[
  'underscore',
  'mockup-ui-url/views/container'
], function(_, ContainerView) {
  'use strict';

  var ButtonGroup = ContainerView.extend({
    tagName: 'div',
    className: 'btn-group',
    idPrefix: 'btngroup-',
    disable: function() {
      _.each(this.items, function(button) {
        button.trigger('disable');
      });
    },
    enable: function() {
      _.each(this.items, function(button) {
        button.trigger('enable');
      });
    }
  });

  return ButtonGroup;
});

/* Tooltip pattern.
 *
 * Options:
 *    enterEvent(string): Event used to trigger tooltip. ('mouseenter')
 *    exitEvent(string): Event used to dismiss tooltip. ('mouseleave')
 *
 * Documentation:
 *    # Directions
 *
 *    You can use this inside Plone or on any static page. Please check below
 *    for additional directions for non-Plone sites as there are some lines
 *    of code you need to add to the header of your webpage.
 *
 *    # Adding tooltip using Plone
 *
 *    - Make sure your viewing the page you want to add the tool tip too.
 *    - Log in
 *    - Create some text that you want to be the link that will reveal the
 *      tooltip.
 *    - Select the view html button
 *    - Find your text, and surround it with an HTML tag. Any normal tag works fine.
 *    - It should look like:
 *      <span class="pat-tooltip" data-toggle="tooltip" title="Tooltip text">My link text</span>
 *    - Choose Save
 *
 *    # Example
 *
 *    {{ example-1 }}
 *
 * Example: example-1
 *      <a href="#" data-toggle="tooltip" class="pat-tooltip"
 *            title="Setting the data-toggle and title makes this show up">
 *            Hover over this line to see a tooltip
 *      </a>
 *
 */

define('mockup-patterns-tooltip',[
  'jquery',
  'pat-base'
], function($, Base, undefined) {
  'use strict';

  //This is pulled almost directly from the Bootstrap Tooltip
  //extension. We rename it just to differentiate from the pattern.
  var bootstrapTooltip = function (element, options) {
    this.type       =
    this.options    =
    this.enabled    =
    this.timeout    =
    this.hoverState =
    this.$element   = null

    this.init('tooltip', element, options)
  }

  bootstrapTooltip.VERSION  = '3.2.0'

  bootstrapTooltip.DEFAULTS = {
    animation: true,
    placement: 'top',
    selector: false,
    template: '<div class="tooltip mockup-tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
    trigger: 'hover focus',
    title: '',
    delay: 0,
    html: true,  // TODO: fix bug, where this setting overwrites whatever is set in options
    container: false,
    viewport: {
      selector: 'body',
      padding: 0
    }
  }

  bootstrapTooltip.prototype.init = function (type, element, options) {
    this.enabled   = true
    this.type      = type
    this.$element  = $(element)
    this.options   = this.getOptions(options)
    this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)

    var triggers = this.options.trigger.split(' ')

    for (var i = triggers.length; i--;) {
      var trigger = triggers[i]

      if (trigger == 'click') {
        this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
      } else if (trigger != 'manual') {
        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin'
        var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'

        this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
        this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
      }
    }

    this.options.selector ?
      (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
      this.fixTitle()
  }

  bootstrapTooltip.prototype.getDefaults = function () {
    return bootstrapTooltip.DEFAULTS
  }

  bootstrapTooltip.prototype.getOptions = function (options) {
    options = $.extend({}, this.getDefaults(), this.$element.data(), options)

    if (options.delay && typeof options.delay == 'number') {
      options.delay = {
        show: options.delay,
        hide: options.delay
      }
    }

    return options
  }

  bootstrapTooltip.prototype.getDelegateOptions = function () {
    var options  = {}
    var defaults = this.getDefaults()

    this._options && $.each(this._options, function (key, value) {
      if (defaults[key] != value) options[key] = value
    })

    return options
  }

  bootstrapTooltip.prototype.enter = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    clearTimeout(self.timeout)

    self.hoverState = 'in'

    if (!self.options.delay || !self.options.delay.show) return self.show()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'in') self.show()
    }, self.options.delay.show)
  }

  bootstrapTooltip.prototype.leave = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    clearTimeout(self.timeout)

    self.hoverState = 'out'

    if (!self.options.delay || !self.options.delay.hide) return self.hide()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'out') self.hide()
    }, self.options.delay.hide)
  }

  bootstrapTooltip.prototype.show = function () {
    var e = $.Event('show.bs.' + this.type)

    if (this.hasContent() && this.enabled) {
      this.$element.trigger(e)

      var inDom = $.contains(document.documentElement, this.$element[0])
      if (e.isDefaultPrevented() || !inDom) return
      var that = this

      var $tip = this.tip()

      var tipId = this.getUID(this.type)

      this.setContent()
      $tip.attr('id', tipId)
      this.$element.attr('aria-describedby', tipId)

      if (this.options.animation) $tip.addClass('fade')

      var placement = typeof this.options.placement == 'function' ?
        this.options.placement.call(this, $tip[0], this.$element[0]) :
        this.options.placement

      var autoToken = /\s?auto?\s?/i
      var autoPlace = autoToken.test(placement)
      if (autoPlace) placement = placement.replace(autoToken, '') || 'top'

      $tip
        .detach()
        .css({ top: 0, left: 0, display: 'block' })
        .addClass(placement)
        .data('bs.' + this.type, this)

      this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)

      var pos          = this.getPosition()
      var actualWidth  = $tip[0].offsetWidth
      var actualHeight = $tip[0].offsetHeight

      if (autoPlace) {
        var orgPlacement = placement
        var $parent      = this.$element.parent()
        var parentDim    = this.getPosition($parent)

        placement = placement == 'bottom' && pos.top   + pos.height       + actualHeight - parentDim.scroll > parentDim.height ? 'top'    :
                    placement == 'top'    && pos.top   - parentDim.scroll - actualHeight < 0                                   ? 'bottom' :
                    placement == 'right'  && pos.right + actualWidth      > parentDim.width                                    ? 'left'   :
                    placement == 'left'   && pos.left  - actualWidth      < parentDim.left                                     ? 'right'  :
                    placement

        $tip
          .removeClass(orgPlacement)
          .addClass(placement)
      }

      var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

      this.applyPlacement(calculatedOffset, placement)

      var complete = function () {
        that.$element.trigger('shown.bs.' + that.type)
        that.hoverState = null
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        $tip
          .one('bsTransitionEnd', complete)
          .emulateTransitionEnd(150) :
        complete()
    }
  }

  bootstrapTooltip.prototype.applyPlacement = function (offset, placement) {
    var $tip   = this.tip()
    var width  = $tip[0].offsetWidth
    var height = $tip[0].offsetHeight

    // manually read margins because getBoundingClientRect includes difference
    var marginTop = parseInt($tip.css('margin-top'), 10)
    var marginLeft = parseInt($tip.css('margin-left'), 10)

    // we must check for NaN for ie 8/9
    if (isNaN(marginTop))  marginTop  = 0
    if (isNaN(marginLeft)) marginLeft = 0

    offset.top  = offset.top  + marginTop
    offset.left = offset.left + marginLeft

    // $.fn.offset doesn't round pixel values
    // so we use setOffset directly with our own function B-0
    $.offset.setOffset($tip[0], $.extend({
      using: function (props) {
        $tip.css({
          top: Math.round(props.top),
          left: Math.round(props.left)
        })
      }
    }, offset), 0)

    $tip.addClass('in')

    // check to see if placing tip in new offset caused the tip to resize itself
    var actualWidth  = $tip[0].offsetWidth
    var actualHeight = $tip[0].offsetHeight

    if (placement == 'top' && actualHeight != height) {
      offset.top = offset.top + height - actualHeight
    }

    var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)

    if (delta.left) offset.left += delta.left
    else offset.top += delta.top

    var arrowDelta          = delta.left ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
    var arrowPosition       = delta.left ? 'left'        : 'top'
    var arrowOffsetPosition = delta.left ? 'offsetWidth' : 'offsetHeight'

    $tip.offset(offset)
    this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition)
  }

  bootstrapTooltip.prototype.replaceArrow = function (delta, dimension, position) {
    this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
  }

  bootstrapTooltip.prototype.setContent = function () {
    var $tip  = this.tip()
    var title = this.getTitle()

    $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
    $tip.removeClass('fade in top bottom left right')
  }

  bootstrapTooltip.prototype.hide = function () {
    var that = this
    var $tip = this.tip()
    var e    = $.Event('hide.bs.' + this.type)

    this.$element.removeAttr('aria-describedby')

    function complete() {
      if (that.hoverState != 'in') $tip.detach()
      that.$element.trigger('hidden.bs.' + that.type)
    }

    this.$element.trigger(e)

    if (e.isDefaultPrevented()) return

    $tip.removeClass('in')

    $.support.transition && this.$tip.hasClass('fade') ?
      $tip
        .one('bsTransitionEnd', complete)
        .emulateTransitionEnd(150) :
      complete()

    this.hoverState = null

    return this
  }

  bootstrapTooltip.prototype.fixTitle = function () {
    var $e = this.$element
    if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
      $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
    }
  }

  bootstrapTooltip.prototype.hasContent = function () {
    return this.getTitle()
  }

  bootstrapTooltip.prototype.getPosition = function ($element) {
    $element   = $element || this.$element
    var el     = $element[0]
    var isBody = el.tagName == 'BODY'
    return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : null, {
      scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop(),
      width:  isBody ? $(window).width()  : $element.outerWidth(),
      height: isBody ? $(window).height() : $element.outerHeight()
    }, isBody ? { top: 0, left: 0 } : $element.offset())
  }

  bootstrapTooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2  } :
           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2  } :
           placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width   }

  }

  bootstrapTooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
    var delta = { top: 0, left: 0 }
    if (!this.$viewport) return delta

    var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
    var viewportDimensions = this.getPosition(this.$viewport)

    if (/right|left/.test(placement)) {
      var topEdgeOffset    = pos.top - viewportPadding - viewportDimensions.scroll
      var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
      if (topEdgeOffset < viewportDimensions.top) { // top overflow
        delta.top = viewportDimensions.top - topEdgeOffset
      } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
        delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
      }
    } else {
      var leftEdgeOffset  = pos.left - viewportPadding
      var rightEdgeOffset = pos.left + viewportPadding + actualWidth
      if (leftEdgeOffset < viewportDimensions.left) { // left overflow
        delta.left = viewportDimensions.left - leftEdgeOffset
      } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
        delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
      }
    }

    return delta
  }

  bootstrapTooltip.prototype.getTitle = function () {
    var title
    var $e = this.$element
    var o  = this.options

    title = $e.attr('data-original-title')
      || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

    return title
  }

  bootstrapTooltip.prototype.getUID = function (prefix) {
    do prefix += ~~(Math.random() * 1000000)
    while (document.getElementById(prefix))
    return prefix
  }

  bootstrapTooltip.prototype.tip = function () {
    return (this.$tip = this.$tip || $(this.options.template))
  }

  bootstrapTooltip.prototype.arrow = function () {
    return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
  }

  bootstrapTooltip.prototype.validate = function () {
    if (!this.$element[0].parentNode) {
      this.hide()
      this.$element = null
      this.options  = null
    }
  }

  bootstrapTooltip.prototype.enable = function () {
    this.enabled = true
  }

  bootstrapTooltip.prototype.disable = function () {
    this.enabled = false
  }

  bootstrapTooltip.prototype.toggleEnabled = function () {
    this.enabled = !this.enabled
  }

  bootstrapTooltip.prototype.toggle = function (e) {
    var self = this
    if (e) {
      self = $(e.currentTarget).data('bs.' + this.type)
      if (!self) {
        self = new this.constructor(e.currentTarget, this.getDelegateOptions())
        $(e.currentTarget).data('bs.' + this.type, self)
      }
    }

    self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
  }

  bootstrapTooltip.prototype.destroy = function () {
    clearTimeout(this.timeout)
    this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
  }

  var Tooltip = Base.extend({
    name: 'tooltip',
    trigger: '.pat-tooltip',
    parser: 'mockup',
    defaults: {
      html: false,
      placement: 'top'
    },
    init: function() {
        if (this.options.html === 'true') {
          // TODO: fix the parser!
          this.options.html = true;
        } else {
          this.options.html = false;
        }
        this.data = new bootstrapTooltip(this.$el[0], this.options);
      },
  });

  return Tooltip;

});

define('mockup-ui-url/views/button',[
  'underscore',
  'mockup-ui-url/views/base',
  'mockup-patterns-tooltip'
], function(_, BaseView, Tooltip) {
  'use strict';

  var ButtonView = BaseView.extend({
    tagName: 'a',
    className: 'btn',
    eventPrefix: 'button',
    context: 'default',
    idPrefix: 'btn-',
    attributes: {
      'href': '#'
    },
    extraClasses: [],
    tooltip: null,
    template: '<% if (icon) { %><span class="glyphicon glyphicon-<%= icon %>"></span><% } %> <%= title %>',
    events: {
      'click': 'handleClick'
    },
    initialize: function(options) {
      if (!options.id) {
        var title = options.title || '';
        options.id = title !== '' ? title.toLowerCase().replace(' ', '-') : this.cid;
      }
      BaseView.prototype.initialize.apply(this, [options]);

      this.on('disable', function() {
        this.disable();
      }, this);

      this.on('enable', function() {
        this.enable();
      }, this);

      this.on('render', function() {
        this.$el.attr('title', this.options.title || '');
        this.$el.attr('aria-label', this.options.title || this.options.tooltip || '');
        if (this.context !== null) {
          this.$el.addClass('btn-' + this.context);
        }
        _.each(this.extraClasses, function(klass){
          this.$el.addClass(klass);
        });

        if (this.tooltip !== null) {

          this.$el.attr('title', this.tooltip);
          var tooltipPattern = new Tooltip(this.$el);
          // XXX since tooltip triggers hidden
          // suppress so it plays nice with modals, backdrops, etc
          this.$el.on('hidden', function(e) {
            if (e.type === 'hidden') {
              e.stopPropagation();
            }
          });
        }
      }, this);
    },
    handleClick: function(e) {
      e.preventDefault();
      if (!this.$el.is('.disabled')) {
        this.uiEventTrigger('click', this, e);
      }
    },
    serializedModel: function() {
      return _.extend({'icon': '', 'title': ''}, this.options);
    },
    disable: function() {
      this.options.disabled = true;
      this.$el.addClass('disabled');
    },
    enable: function() {
      this.options.disabled = false;
      this.$el.removeClass('disabled');
    }
  });

  return ButtonView;
});

define('castle-url/patterns/structure//js/navigation',[
  'backbone',
  'mockup-utils',
], function(Backbone, utils) {
  'use strict';

  // use a more primative class than Backbone.Model?
  var Navigation = Backbone.Model.extend({
    initialize: function(options) {
      this.options = options;
      this.app = options.app;
      this.model = options.model;
    },
    folderClicked: function(e) {
      e.preventDefault();
      // handler for folder, go down path and show in contents window.
      var self = this;
      self.app.setCurrentPath(self.model.attributes.path);
      // also switch to fix page in batch
      self.app.collection.goTo(self.app.collection.information.firstPage);
    },
  });

  return Navigation;
});

define('castle-url/patterns/structure//js/models/result',['backbone'], function(Backbone) {
  'use strict';

  var Result = Backbone.Model.extend({
    defaults: function() {
      return {
        'is_folderish': false,
        'review_state': '',
        'getURL': ''
      };
    },
    uid: function() {
      return this.attributes.UID;
    }
  });

  return Result;
});

define('castle-url/patterns/structure//js/actions',[
  'jquery',
  'underscore',
  'backbone',
  'castle-url/patterns/structure//js/models/result',
  'mockup-utils',
  'translate',
], function($, _, Backbone, Result, utils, _t) {
  'use strict';

  // use a more primative class than Backbone.Model?
  var Actions = Backbone.Model.extend({
    initialize: function(options) {
      this.options = options;
      this.app = options.app;
      this.model = options.model;
      this.selectedCollection = this.app.selectedCollection;
    },
    selectAll: function(e) {
      // This implementation is very specific to the default collection
      // with the reliance on its queryParser and queryHelper.  Custom
      // collection (Backbone.Paginator.requestPager implementation)
      // will have to come up with their own action for this.
      e.preventDefault();
      var self = this;
      var page = 1;
      var count = 0;
      var getPage = function() {
        self.app.loading.show();
        $.ajax({
          url: self.app.collection.url,
          type: 'GET',
          dataType: 'json',
          data: {
            query: self.app.collection.queryParser({
              searchPath: self.model.attributes.path
            }),
            batch: JSON.stringify({
              page: page,
              size: 100
            }),
            attributes: JSON.stringify(
              self.app.collection.queryHelper.options.attributes)
          }
        }).done(function(data) {
          var items = self.app.collection.parse(data, count);
          count += items.length;
          _.each(items, function(item) {
            self.app.selectedCollection.add(new Result(item));
          });
          page += 1;
          if (data.total > count) {
            getPage();
          } else {
            self.app.loading.hide();
            self.app.tableView.render();
          }
        });
      };
      getPage();
    },

    doAction: function(buttonName, successMsg, failMsg) {
      var self = this;
      $.ajax({
        url: self.app.buttons.get(buttonName).options.url,
        data: {
          selection: JSON.stringify([self.model.attributes.UID]),
          folder: self.model.attributes.path,
          _authenticator: utils.getAuthenticator()
        },
        dataType: 'json',
        type: 'POST'
      }).done(function(data) {
        var msg;
        if (data.status === 'success') {
          msg = _t(successMsg + ' "' + self.model.attributes.Title + '"');
          self.app.collection.pager();
          self.app.updateButtons();
        } else {
          msg = _t('Error ' + failMsg + ' "' + self.model.attributes.Title + '"');
        }
        self.app.setStatus({text: msg, type: data.status || 'warning'});
      });
    },

    cutClicked: function(e) {
      var self = this;
      e.preventDefault();
      self.doAction('cut', _t('Cut'), _t('cutting'));
    },
    copyClicked: function(e) {
      var self = this;
      e.preventDefault();
      self.doAction('copy', _t('Copied'), _t('copying'));
    },
    pasteClicked: function(e) {
      var self = this;
      e.preventDefault();
      self.doAction('paste', _t('Pasted into'), _t('Error pasting into'));
    },
    moveTopClicked: function(e) {
      e.preventDefault();
      this.app.moveItem(this.model.attributes.id, 'top');
    },
    moveBottomClicked: function(e) {
      e.preventDefault();
      this.app.moveItem(this.model.attributes.id, 'bottom');
    },
    setDefaultPageClicked: function(e) {
      e.preventDefault();
      var self = this;
      $.ajax({
        url: self.app.getAjaxUrl(self.app.setDefaultPageUrl),
        type: 'POST',
        data: {
          '_authenticator': $('[name="_authenticator"]').val(),
          'id': this.model.attributes.id
        },
        success: function(data) {
          self.app.ajaxSuccessResponse.apply(self.app, [data]);
        },
        error: function(data) {
          self.app.ajaxErrorResponse.apply(self.app, [data]);
        }
      });
    },
  });

  return Actions;
});

define('castle-url/patterns/structure//js/actionmenu',['underscore'], function(_) {
  'use strict';

  var menuOptions = {
    'openItem': {
      'url':      '#',
      'title':    'Open',
      'category': 'button',
      'iconCSS':  'glyphicon glyphicon-eye-open',
      'css': '',
      'modal':    false
    },
    'editItem': {
      'url':      '#',
      'title':    'Edit',
      'category': 'button',
      'iconCSS':  'glyphicon glyphicon-pencil',
      'css': '',
      'modal':    false
    },
    'cutItem': {
      'library':  'castle-url/patterns/structure//js/actions',
      'method':   'cutClicked',
      'url':      '#',
      'title':    'Cut',
      'category': 'dropdown',
      'iconCSS':  'glyphicon glyphicon-scissors',
      'css': '',
      'modal':    false
    },
    'copyItem': {
      'library':  'castle-url/patterns/structure//js/actions',
      'method':   'copyClicked',
      'url':      '#',
      'title':    'Copy',
      'category': 'dropdown',
      'iconCSS':  'glyphicon glyphicon-duplicate',
      'css': '',
      'modal':    false
    },
    'pasteItem': {
      'library':  'castle-url/patterns/structure//js/actions',
      'method':   'pasteClicked',
      'url':      '#',
      'title':    'Paste',
      'category': 'dropdown',
      'iconCSS':  'glyphicon glyphicon-open-file',
      'css': '',
      'modal':    false
    },
    'move-top': {
      'library':  'castle-url/patterns/structure//js/actions',
      'method':   'moveTopClicked',
      'url':      '#',
      'title':    'Move to top of folder',
      'category': 'dropdown',
      'iconCSS':  'glyphicon glyphicon-step-backward rright',
      'css': '',
      'modal':    false
    },
    'move-bottom': {
      'library':  'castle-url/patterns/structure//js/actions',
      'method':   'moveBottomClicked',
      'url':      '#',
      'title':    'Move to bottom of folder',
      'category': 'dropdown',
      'iconCSS':  'glyphicon glyphicon-step-backward rleft',
      'css': '',
      'modal':    false
    },
    'set-default-page': {
      'library':  'castle-url/patterns/structure//js/actions',
      'method':   'setDefaultPageClicked',
      'url':      '#',
      'title':    'Set as default page',
      'category': 'dropdown',
      'iconCSS':  'glyphicon glyphicon-ok-circle',
      'css': '',
      'modal':    false
    },
    'selectAll': {
      'library':  'castle-url/patterns/structure//js/actions',
      'method':   'selectAll',
      'url':      '#',
      'title':    'Select all contained items',
      'category': 'dropdown',
      'iconCSS':  'glyphicon glyphicon-check',
      'css': '',
      'modal':    false
    }
  };

  var ActionMenu = function(menu) {
    // If an explicit menu was specified as an option to AppView, this
    // constructor will not override that.
    if (menu.menuOptions !== null) {
      return menu.menuOptions;
    }

    var model = menu.model.attributes;
    var app = menu.app;

    var result = _.clone(menuOptions);
    if ( !(app.pasteAllowed && model.is_folderish)) {
      delete result.pasteItem;
    }
    if (app.inQueryMode() || menu.options.canMove === false) {
      delete result['move-top'];
      delete result['move-bottom'];
    }
    if (model.is_folderish || !app.setDefaultPageUrl) {
      delete result['set-default-page'];
    }

    if (!model.is_folderish) {
      delete result.selectAll;
    }

    var typeToViewAction = app.options.typeToViewAction;
    var viewAction = typeToViewAction && typeToViewAction[model.portal_type] || '';
    result.openItem.url = model.getURL + viewAction;
    result.editItem.url = model.getURL + '/@@edit';

    return result;
  };

  return ActionMenu;
});


define('text!castle-url/patterns/structure//templates/actionmenu.xml',[],function () { return '<% _.each(menuOptions.button, function(menuOption){ %>\n<a class="action <%- menuOption.name %> <%- menuOption.idx %> pat-tooltip <%- menuOption.css %>"\n    href="<%- menuOption.url %>"\n    title="<%- _t(menuOption.title) %>">\n  <% if (menuOption.iconCSS) { %>\n  <span class="<%- menuOption.iconCSS %>"></span>\n  <% } else { %>\n  <%- _t(menuOption.title) %> \n  <% } %>\n</a>&nbsp;\n<% }); %>\n\n\n<% if (menuOptions.dropdown) { %>\n<a class="dropdown-toggle"\n    data-toggle="dropdown"\n    href="#"\n    aria-haspopup="true"\n    aria-expanded="true"\n    id="<%- id %>"\n    title="Actions">\n  <span class="glyphicon glyphicon-cog"></span><span class="caret"></span>\n</a>\n<ul class="dropdown-menu pull-right" aria-labelledby="<%- id %>">\n  <% if (header) { %>\n    <li class="dropdown-header"><%- header %></li>\n    <li class="divider"></li>\n  <% } %>\n\n  <% _.each(menuOptions.dropdown, function(menuOption){ %>\n  <li>\n    <a class="action <%- menuOption.name %> <%- menuOption.idx %> <%- menuOption.css %>"\n        href="<%- menuOption.url %>">\n      <% if (menuOption.iconCSS) { %>\n      <span class="<%- menuOption.iconCSS %>"></span>\n      <% } %>\n      <%- _t(menuOption.title) %>\n    </a>\n  </li>\n  <% }); %>\n</ul>\n<% } %>\n';});

define('castle-url/patterns/structure//js/views/actionmenu',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/base',
  'mockup-utils',
  'castle-url/patterns/structure//js/models/result',
  'castle-url/patterns/structure//js/actions',
  'castle-url/patterns/structure//js/actionmenu',
  'text!castle-url/patterns/structure//templates/actionmenu.xml',
  'pat-registry',
  'translate',
  'mockup-patterns-tooltip',
  'bootstrap-dropdown'
], function($, _, BaseView, utils, Result, Actions, ActionMenu, ActionMenuTemplate, registry, _t) {
  'use strict';

  var ActionMenuView = BaseView.extend({
    className: 'btn-group actionmenu',
    template: _.template(ActionMenuTemplate),

    // Static menu options
    menuOptions: null,
    // Dynamic menu options
    menuGenerator: 'castle-url/patterns/structure//js/actionmenu',

    eventConstructor: function(definition) {
      var self = this;
      var libName = definition.library,
          method = definition.method;

      if (!((typeof libName === 'string') && (typeof method === 'string'))) {
        return false;
      }

      var doEvent = function(e) {
        var libCls = require(libName);
        var lib = new libCls(self);
        return lib[method] && lib[method](e);
      };
      return doEvent;
    },

    events: function() {
      /* Backbone.view.events
       * Specify a set of DOM events, which will bound to methods on the view.
       */
      var self = this;
      var result = {};
      var menuOptionsCategorized = {};
      _.each(self.menuOptions, function(menuOption, key) {
          // set a unique identifier to uniquely bind the events.
          var idx = utils.generateId();
          menuOption.idx = idx;
          menuOption.name = key;  // we want to add the action's key as class name to the output.

          var category = menuOption.category || 'dropdown';
          if (menuOptionsCategorized[category] === undefined) {
              menuOptionsCategorized[category] = [];
          }
          menuOptionsCategorized[category].push(menuOption);
          menuOption.css = menuOption.css || '';
          if (menuOption.modal === true) {
            // add standard pat-plone-modal.
            // If you want another modal implementation, don't use modal=true but set the css option on action items.
            menuOption.css += ' pat-plone-modal';
          }

          // Create event handler and add it to the results object.
          var e = self.eventConstructor(menuOption);
          if (e) {
            result['click a.' + idx] = e;
          }
      });

      // Abusing the loop above to also initialize menuOptionsCategorized
      self.menuOptionsCategorized = menuOptionsCategorized;
      return result;
    },

    initialize: function(options) {
      var self = this;
      BaseView.prototype.initialize.apply(self, [options]);
      self.options = options;
      self.selectedCollection = self.app.selectedCollection;

      // Then acquire the constructor method if specified, and
      var menuGenerator = self.options.menuGenerator || self.menuGenerator;
      if (menuGenerator) {
        var menuGen = require(menuGenerator);
        // override those options here.  All definition done here so
        // that self.events() will return the right things.
        var menuOptions = menuGen(self);
        if (typeof menuOptions === 'object') {
          // Only assign this if we got the right basic type.
          self.menuOptions = menuOptions;
          // Should warn otherwise.
        }
      }
    },
    render: function() {
      var self = this;
      self.$el.empty();

      var data = this.model.toJSON();
      data.header = self.options.header || null;
      data.menuOptions = self.menuOptionsCategorized;
      self.$el.html(self.template($.extend({
        _t: _t,
        id: utils.generateId()
      }, data)));

      if (data.menuOptions.dropdown) {
        self.$dropdown = self.$('.dropdown-toggle');
        self.$dropdown.dropdown();
      }

      if (self.options.className) {
        self.$el.addClass(self.options.className);
      }

      registry.scan(this.$el);

      return this;
    }
  });

  return ActionMenuView;
});


define('text!castle-url/patterns/structure//templates/tablerow.xml',[],function () { return '<td class="selection"><input type="checkbox" <% if(selected){ %> checked="checked" <% } %>/></td>\n\n<td class="title">\n  <div class="pull-left">\n    <a href="<%- viewURL %>"\n        class="manage state-<%- review_state %> contenttype-<%- contenttype %>"\n        title="<%- portal_type %>">\n      <% if(Title){ %>\n        <%- Title %>\n      <% } else { %>\n        <em><%- id %></em>\n      <% } %>\n    </a>\n    <% if(expired){ %>\n      <span class="plone-item-expired"><%- _t(\'Expired\') %></span>\n    <% } %>\n  </div>\n  <% if(attributes["getIcon"] ){ %>\n  <img class="image-<%- iconSize %> pull-right" src="<%- getURL %>/@@images/image/<%- iconSize %>">\n  <% } %>\n</td>\n\n<% _.each(activeColumns, function(column) { %>\n  <% if(_.has(availableColumns, column)) { %>\n    <td class="<%- column %>"><%- attributes[column] %></td>\n  <% } %>\n<% }); %>\n\n<td class="actionmenu-container"></td>\n';});

!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define('moment',b):a.moment=b()}(this,function(){"use strict";function a(){return Md.apply(null,arguments)}function b(a){Md=a}function c(a){return"[object Array]"===Object.prototype.toString.call(a)}function d(a){return a instanceof Date||"[object Date]"===Object.prototype.toString.call(a)}function e(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function f(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function g(a,b){for(var c in b)f(b,c)&&(a[c]=b[c]);return f(b,"toString")&&(a.toString=b.toString),f(b,"valueOf")&&(a.valueOf=b.valueOf),a}function h(a,b,c,d){return Ca(a,b,c,d,!0).utc()}function i(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function j(a){return null==a._pf&&(a._pf=i()),a._pf}function k(a){if(null==a._isValid){var b=j(a);a._isValid=!(isNaN(a._d.getTime())||!(b.overflow<0)||b.empty||b.invalidMonth||b.invalidWeekday||b.nullInput||b.invalidFormat||b.userInvalidated),a._strict&&(a._isValid=a._isValid&&0===b.charsLeftOver&&0===b.unusedTokens.length&&void 0===b.bigHour)}return a._isValid}function l(a){var b=h(NaN);return null!=a?g(j(b),a):j(b).userInvalidated=!0,b}function m(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=j(b)),"undefined"!=typeof b._locale&&(a._locale=b._locale),Od.length>0)for(c in Od)d=Od[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function n(b){m(this,b),this._d=new Date(null!=b._d?b._d.getTime():NaN),Pd===!1&&(Pd=!0,a.updateOffset(this),Pd=!1)}function o(a){return a instanceof n||null!=a&&null!=a._isAMomentObject}function p(a){return 0>a?Math.ceil(a):Math.floor(a)}function q(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=p(b)),c}function r(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&q(a[d])!==q(b[d]))&&g++;return g+f}function s(){}function t(a){return a?a.toLowerCase().replace("_","-"):a}function u(a){for(var b,c,d,e,f=0;f<a.length;){for(e=t(a[f]).split("-"),b=e.length,c=t(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=v(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&r(e,c,!0)>=b-1)break;b--}f++}return null}function v(a){var b=null;if(!Qd[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Nd._abbr,require("./locale/"+a),w(b)}catch(c){}return Qd[a]}function w(a,b){var c;return a&&(c="undefined"==typeof b?y(a):x(a,b),c&&(Nd=c)),Nd._abbr}function x(a,b){return null!==b?(b.abbr=a,Qd[a]=Qd[a]||new s,Qd[a].set(b),w(a),Qd[a]):(delete Qd[a],null)}function y(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Nd;if(!c(a)){if(b=v(a))return b;a=[a]}return u(a)}function z(a,b){var c=a.toLowerCase();Rd[c]=Rd[c+"s"]=Rd[b]=a}function A(a){return"string"==typeof a?Rd[a]||Rd[a.toLowerCase()]:void 0}function B(a){var b,c,d={};for(c in a)f(a,c)&&(b=A(c),b&&(d[b]=a[c]));return d}function C(b,c){return function(d){return null!=d?(E(this,b,d),a.updateOffset(this,c),this):D(this,b)}}function D(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function E(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function F(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=A(a),"function"==typeof this[a])return this[a](b);return this}function G(a,b,c){var d=""+Math.abs(a),e=b-d.length,f=a>=0;return(f?c?"+":"":"-")+Math.pow(10,Math.max(0,e)).toString().substr(1)+d}function H(a,b,c,d){var e=d;"string"==typeof d&&(e=function(){return this[d]()}),a&&(Vd[a]=e),b&&(Vd[b[0]]=function(){return G(e.apply(this,arguments),b[1],b[2])}),c&&(Vd[c]=function(){return this.localeData().ordinal(e.apply(this,arguments),a)})}function I(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function J(a){var b,c,d=a.match(Sd);for(b=0,c=d.length;c>b;b++)Vd[d[b]]?d[b]=Vd[d[b]]:d[b]=I(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function K(a,b){return a.isValid()?(b=L(b,a.localeData()),Ud[b]=Ud[b]||J(b),Ud[b](a)):a.localeData().invalidDate()}function L(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Td.lastIndex=0;d>=0&&Td.test(a);)a=a.replace(Td,c),Td.lastIndex=0,d-=1;return a}function M(a){return"function"==typeof a&&"[object Function]"===Object.prototype.toString.call(a)}function N(a,b,c){ie[a]=M(b)?b:function(a){return a&&c?c:b}}function O(a,b){return f(ie,a)?ie[a](b._strict,b._locale):new RegExp(P(a))}function P(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function Q(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=q(a)}),c=0;c<a.length;c++)je[a[c]]=d}function R(a,b){Q(a,function(a,c,d,e){d._w=d._w||{},b(a,d._w,d,e)})}function S(a,b,c){null!=b&&f(je,a)&&je[a](b,c._a,c,a)}function T(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function U(a){return this._months[a.month()]}function V(a){return this._monthsShort[a.month()]}function W(a,b,c){var d,e,f;for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=h([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function X(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),T(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function Y(b){return null!=b?(X(this,b),a.updateOffset(this,!0),this):D(this,"Month")}function Z(){return T(this.year(),this.month())}function $(a){var b,c=a._a;return c&&-2===j(a).overflow&&(b=c[le]<0||c[le]>11?le:c[me]<1||c[me]>T(c[ke],c[le])?me:c[ne]<0||c[ne]>24||24===c[ne]&&(0!==c[oe]||0!==c[pe]||0!==c[qe])?ne:c[oe]<0||c[oe]>59?oe:c[pe]<0||c[pe]>59?pe:c[qe]<0||c[qe]>999?qe:-1,j(a)._overflowDayOfYear&&(ke>b||b>me)&&(b=me),j(a).overflow=b),a}function _(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function aa(a,b){var c=!0;return g(function(){return c&&(_(a+"\n"+(new Error).stack),c=!1),b.apply(this,arguments)},b)}function ba(a,b){te[a]||(_(b),te[a]=!0)}function ca(a){var b,c,d=a._i,e=ue.exec(d);if(e){for(j(a).iso=!0,b=0,c=ve.length;c>b;b++)if(ve[b][1].exec(d)){a._f=ve[b][0];break}for(b=0,c=we.length;c>b;b++)if(we[b][1].exec(d)){a._f+=(e[6]||" ")+we[b][0];break}d.match(fe)&&(a._f+="Z"),va(a)}else a._isValid=!1}function da(b){var c=xe.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(ca(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ea(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function fa(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function ga(a){return ha(a)?366:365}function ha(a){return a%4===0&&a%100!==0||a%400===0}function ia(){return ha(this.year())}function ja(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=Da(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ka(a){return ja(a,this._week.dow,this._week.doy).week}function la(){return this._week.dow}function ma(){return this._week.doy}function na(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function oa(a){var b=ja(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function pa(a,b,c,d,e){var f,g=6+e-d,h=fa(a,0,1+g),i=h.getUTCDay();return e>i&&(i+=7),c=null!=c?1*c:e,f=1+g+7*(b-1)-i+c,{year:f>0?a:a-1,dayOfYear:f>0?f:ga(a-1)+f}}function qa(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function ra(a,b,c){return null!=a?a:null!=b?b:c}function sa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function ta(a){var b,c,d,e,f=[];if(!a._d){for(d=sa(a),a._w&&null==a._a[me]&&null==a._a[le]&&ua(a),a._dayOfYear&&(e=ra(a._a[ke],d[ke]),a._dayOfYear>ga(e)&&(j(a)._overflowDayOfYear=!0),c=fa(e,0,a._dayOfYear),a._a[le]=c.getUTCMonth(),a._a[me]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[ne]&&0===a._a[oe]&&0===a._a[pe]&&0===a._a[qe]&&(a._nextDay=!0,a._a[ne]=0),a._d=(a._useUTC?fa:ea).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[ne]=24)}}function ua(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=ra(b.GG,a._a[ke],ja(Da(),1,4).year),d=ra(b.W,1),e=ra(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=ra(b.gg,a._a[ke],ja(Da(),f,g).year),d=ra(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=pa(c,d,e,g,f),a._a[ke]=h.year,a._dayOfYear=h.dayOfYear}function va(b){if(b._f===a.ISO_8601)return void ca(b);b._a=[],j(b).empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,k=0;for(e=L(b._f,b._locale).match(Sd)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(O(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&j(b).unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),k+=d.length),Vd[f]?(d?j(b).empty=!1:j(b).unusedTokens.push(f),S(f,d,b)):b._strict&&!d&&j(b).unusedTokens.push(f);j(b).charsLeftOver=i-k,h.length>0&&j(b).unusedInput.push(h),j(b).bigHour===!0&&b._a[ne]<=12&&b._a[ne]>0&&(j(b).bigHour=void 0),b._a[ne]=wa(b._locale,b._a[ne],b._meridiem),ta(b),$(b)}function wa(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function xa(a){var b,c,d,e,f;if(0===a._f.length)return j(a).invalidFormat=!0,void(a._d=new Date(NaN));for(e=0;e<a._f.length;e++)f=0,b=m({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._f=a._f[e],va(b),k(b)&&(f+=j(b).charsLeftOver,f+=10*j(b).unusedTokens.length,j(b).score=f,(null==d||d>f)&&(d=f,c=b));g(a,c||b)}function ya(a){if(!a._d){var b=B(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],ta(a)}}function za(a){var b=new n($(Aa(a)));return b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b}function Aa(a){var b=a._i,e=a._f;return a._locale=a._locale||y(a._l),null===b||void 0===e&&""===b?l({nullInput:!0}):("string"==typeof b&&(a._i=b=a._locale.preparse(b)),o(b)?new n($(b)):(c(e)?xa(a):e?va(a):d(b)?a._d=b:Ba(a),a))}function Ba(b){var f=b._i;void 0===f?b._d=new Date:d(f)?b._d=new Date(+f):"string"==typeof f?da(b):c(f)?(b._a=e(f.slice(0),function(a){return parseInt(a,10)}),ta(b)):"object"==typeof f?ya(b):"number"==typeof f?b._d=new Date(f):a.createFromInputFallback(b)}function Ca(a,b,c,d,e){var f={};return"boolean"==typeof c&&(d=c,c=void 0),f._isAMomentObject=!0,f._useUTC=f._isUTC=e,f._l=c,f._i=a,f._f=b,f._strict=d,za(f)}function Da(a,b,c,d){return Ca(a,b,c,d,!1)}function Ea(a,b){var d,e;if(1===b.length&&c(b[0])&&(b=b[0]),!b.length)return Da();for(d=b[0],e=1;e<b.length;++e)(!b[e].isValid()||b[e][a](d))&&(d=b[e]);return d}function Fa(){var a=[].slice.call(arguments,0);return Ea("isBefore",a)}function Ga(){var a=[].slice.call(arguments,0);return Ea("isAfter",a)}function Ha(a){var b=B(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=y(),this._bubble()}function Ia(a){return a instanceof Ha}function Ja(a,b){H(a,0,0,function(){var a=this.utcOffset(),c="+";return 0>a&&(a=-a,c="-"),c+G(~~(a/60),2)+b+G(~~a%60,2)})}function Ka(a){var b=(a||"").match(fe)||[],c=b[b.length-1]||[],d=(c+"").match(Ce)||["-",0,0],e=+(60*d[1])+q(d[2]);return"+"===d[0]?e:-e}function La(b,c){var e,f;return c._isUTC?(e=c.clone(),f=(o(b)||d(b)?+b:+Da(b))-+e,e._d.setTime(+e._d+f),a.updateOffset(e,!1),e):Da(b).local()}function Ma(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Na(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ka(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ma(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?bb(this,Ya(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ma(this)}function Oa(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function Pa(a){return this.utcOffset(0,a)}function Qa(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ma(this),"m")),this}function Ra(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ka(this._i)),this}function Sa(a){return a=a?Da(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Ta(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Ua(){if("undefined"!=typeof this._isDSTShifted)return this._isDSTShifted;var a={};if(m(a,this),a=Aa(a),a._a){var b=a._isUTC?h(a._a):Da(a._a);this._isDSTShifted=this.isValid()&&r(a._a,b.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted}function Va(){return!this._isUTC}function Wa(){return this._isUTC}function Xa(){return this._isUTC&&0===this._offset}function Ya(a,b){var c,d,e,g=a,h=null;return Ia(a)?g={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(g={},b?g[b]=a:g.milliseconds=a):(h=De.exec(a))?(c="-"===h[1]?-1:1,g={y:0,d:q(h[me])*c,h:q(h[ne])*c,m:q(h[oe])*c,s:q(h[pe])*c,ms:q(h[qe])*c}):(h=Ee.exec(a))?(c="-"===h[1]?-1:1,g={y:Za(h[2],c),M:Za(h[3],c),d:Za(h[4],c),h:Za(h[5],c),m:Za(h[6],c),s:Za(h[7],c),w:Za(h[8],c)}):null==g?g={}:"object"==typeof g&&("from"in g||"to"in g)&&(e=_a(Da(g.from),Da(g.to)),g={},g.ms=e.milliseconds,g.M=e.months),d=new Ha(g),Ia(a)&&f(a,"_locale")&&(d._locale=a._locale),d}function Za(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function $a(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function _a(a,b){var c;return b=La(b,a),a.isBefore(b)?c=$a(a,b):(c=$a(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function ab(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(ba(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Ya(c,d),bb(this,e,a),this}}function bb(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&E(b,"Date",D(b,"Date")+g*d),h&&X(b,D(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function cb(a,b){var c=a||Da(),d=La(c,this).startOf("day"),e=this.diff(d,"days",!0),f=-6>e?"sameElse":-1>e?"lastWeek":0>e?"lastDay":1>e?"sameDay":2>e?"nextDay":7>e?"nextWeek":"sameElse";return this.format(b&&b[f]||this.localeData().calendar(f,this,Da(c)))}function db(){return new n(this)}function eb(a,b){var c;return b=A("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Da(a),+this>+a):(c=o(a)?+a:+Da(a),c<+this.clone().startOf(b))}function fb(a,b){var c;return b=A("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Da(a),+a>+this):(c=o(a)?+a:+Da(a),+this.clone().endOf(b)<c)}function gb(a,b,c){return this.isAfter(a,c)&&this.isBefore(b,c)}function hb(a,b){var c;return b=A(b||"millisecond"),"millisecond"===b?(a=o(a)?a:Da(a),+this===+a):(c=+Da(a),+this.clone().startOf(b)<=c&&c<=+this.clone().endOf(b))}function ib(a,b,c){var d,e,f=La(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=A(b),"year"===b||"month"===b||"quarter"===b?(e=jb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:p(e)}function jb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function kb(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function lb(){var a=this.clone().utc();return 0<a.year()&&a.year()<=9999?"function"==typeof Date.prototype.toISOString?this.toDate().toISOString():K(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):K(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function mb(b){var c=K(this,b||a.defaultFormat);return this.localeData().postformat(c)}function nb(a,b){return this.isValid()?Ya({to:this,from:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function ob(a){return this.from(Da(),a)}function pb(a,b){return this.isValid()?Ya({from:this,to:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function qb(a){return this.to(Da(),a)}function rb(a){var b;return void 0===a?this._locale._abbr:(b=y(a),null!=b&&(this._locale=b),this)}function sb(){return this._locale}function tb(a){switch(a=A(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a&&this.weekday(0),"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this}function ub(a){return a=A(a),void 0===a||"millisecond"===a?this:this.startOf(a).add(1,"isoWeek"===a?"week":a).subtract(1,"ms")}function vb(){return+this._d-6e4*(this._offset||0)}function wb(){return Math.floor(+this/1e3)}function xb(){return this._offset?new Date(+this):this._d}function yb(){var a=this;return[a.year(),a.month(),a.date(),a.hour(),a.minute(),a.second(),a.millisecond()]}function zb(){var a=this;return{years:a.year(),months:a.month(),date:a.date(),hours:a.hours(),minutes:a.minutes(),seconds:a.seconds(),milliseconds:a.milliseconds()}}function Ab(){return k(this)}function Bb(){return g({},j(this))}function Cb(){return j(this).overflow}function Db(a,b){H(0,[a,a.length],0,b)}function Eb(a,b,c){return ja(Da([a,11,31+b-c]),b,c).week}function Fb(a){var b=ja(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return null==a?b:this.add(a-b,"y")}function Gb(a){var b=ja(this,1,4).year;return null==a?b:this.add(a-b,"y")}function Hb(){return Eb(this.year(),1,4)}function Ib(){var a=this.localeData()._week;return Eb(this.year(),a.dow,a.doy)}function Jb(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)}function Kb(a,b){return"string"!=typeof a?a:isNaN(a)?(a=b.weekdaysParse(a),"number"==typeof a?a:null):parseInt(a,10)}function Lb(a){return this._weekdays[a.day()]}function Mb(a){return this._weekdaysShort[a.day()]}function Nb(a){return this._weekdaysMin[a.day()]}function Ob(a){var b,c,d;for(this._weekdaysParse=this._weekdaysParse||[],b=0;7>b;b++)if(this._weekdaysParse[b]||(c=Da([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Pb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Kb(a,this.localeData()),this.add(a-b,"d")):b}function Qb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Rb(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Sb(a,b){H(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Tb(a,b){return b._meridiemParse}function Ub(a){return"p"===(a+"").toLowerCase().charAt(0)}function Vb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Wb(a,b){b[qe]=q(1e3*("0."+a))}function Xb(){return this._isUTC?"UTC":""}function Yb(){return this._isUTC?"Coordinated Universal Time":""}function Zb(a){return Da(1e3*a)}function $b(){return Da.apply(null,arguments).parseZone()}function _b(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function ac(a){var b=this._longDateFormat[a],c=this._longDateFormat[a.toUpperCase()];return b||!c?b:(this._longDateFormat[a]=c.replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a])}function bc(){return this._invalidDate}function cc(a){return this._ordinal.replace("%d",a)}function dc(a){return a}function ec(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function fc(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function gc(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function hc(a,b,c,d){var e=y(),f=h().set(d,b);return e[c](f,a)}function ic(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return hc(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=hc(a,f,c,e);return g}function jc(a,b){return ic(a,b,"months",12,"month")}function kc(a,b){return ic(a,b,"monthsShort",12,"month")}function lc(a,b){return ic(a,b,"weekdays",7,"day")}function mc(a,b){return ic(a,b,"weekdaysShort",7,"day")}function nc(a,b){return ic(a,b,"weekdaysMin",7,"day")}function oc(){var a=this._data;return this._milliseconds=_e(this._milliseconds),this._days=_e(this._days),this._months=_e(this._months),a.milliseconds=_e(a.milliseconds),a.seconds=_e(a.seconds),a.minutes=_e(a.minutes),a.hours=_e(a.hours),a.months=_e(a.months),a.years=_e(a.years),this}function pc(a,b,c,d){var e=Ya(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function qc(a,b){return pc(this,a,b,1)}function rc(a,b){return pc(this,a,b,-1)}function sc(a){return 0>a?Math.floor(a):Math.ceil(a)}function tc(){var a,b,c,d,e,f=this._milliseconds,g=this._days,h=this._months,i=this._data;return f>=0&&g>=0&&h>=0||0>=f&&0>=g&&0>=h||(f+=864e5*sc(vc(h)+g),g=0,h=0),i.milliseconds=f%1e3,a=p(f/1e3),i.seconds=a%60,b=p(a/60),i.minutes=b%60,c=p(b/60),i.hours=c%24,g+=p(c/24),e=p(uc(g)),h+=e,g-=sc(vc(e)),d=p(h/12),h%=12,i.days=g,i.months=h,i.years=d,this}function uc(a){return 4800*a/146097}function vc(a){return 146097*a/4800}function wc(a){var b,c,d=this._milliseconds;if(a=A(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+uc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(vc(this._months)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 1440*b+d/6e4;case"second":return 86400*b+d/1e3;case"millisecond":return Math.floor(864e5*b)+d;default:throw new Error("Unknown unit "+a)}}function xc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*q(this._months/12)}function yc(a){return function(){return this.as(a)}}function zc(a){return a=A(a),this[a+"s"]()}function Ac(a){return function(){return this._data[a]}}function Bc(){return p(this.days()/7)}function Cc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function Dc(a,b,c){var d=Ya(a).abs(),e=qf(d.as("s")),f=qf(d.as("m")),g=qf(d.as("h")),h=qf(d.as("d")),i=qf(d.as("M")),j=qf(d.as("y")),k=e<rf.s&&["s",e]||1===f&&["m"]||f<rf.m&&["mm",f]||1===g&&["h"]||g<rf.h&&["hh",g]||1===h&&["d"]||h<rf.d&&["dd",h]||1===i&&["M"]||i<rf.M&&["MM",i]||1===j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,Cc.apply(null,k)}function Ec(a,b){return void 0===rf[a]?!1:void 0===b?rf[a]:(rf[a]=b,!0)}function Fc(a){var b=this.localeData(),c=Dc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function Gc(){var a,b,c,d=sf(this._milliseconds)/1e3,e=sf(this._days),f=sf(this._months);a=p(d/60),b=p(a/60),d%=60,a%=60,c=p(f/12),f%=12;var g=c,h=f,i=e,j=b,k=a,l=d,m=this.asSeconds();return m?(0>m?"-":"")+"P"+(g?g+"Y":"")+(h?h+"M":"")+(i?i+"D":"")+(j||k||l?"T":"")+(j?j+"H":"")+(k?k+"M":"")+(l?l+"S":""):"P0D"}
//! moment.js locale configuration
//! locale : belarusian (be)
//! author : Dmitry Demidov : https://github.com/demidov91
//! author: Praleska: http://praleska.pro/
//! Author : Menelion Elensúle : https://github.com/Oire
function Hc(a,b){var c=a.split("_");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function Ic(a,b,c){var d={mm:b?"хвіліна_хвіліны_хвілін":"хвіліну_хвіліны_хвілін",hh:b?"гадзіна_гадзіны_гадзін":"гадзіну_гадзіны_гадзін",dd:"дзень_дні_дзён",MM:"месяц_месяцы_месяцаў",yy:"год_гады_гадоў"};return"m"===c?b?"хвіліна":"хвіліну":"h"===c?b?"гадзіна":"гадзіну":a+" "+Hc(d[c],+a)}function Jc(a,b){var c={nominative:"студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань".split("_"),accusative:"студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function Kc(a,b){var c={nominative:"нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота".split("_"),accusative:"нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу".split("_")},d=/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/.test(b)?"accusative":"nominative";return c[d][a.day()]}
//! moment.js locale configuration
//! locale : breton (br)
//! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou
function Lc(a,b,c){var d={mm:"munutenn",MM:"miz",dd:"devezh"};return a+" "+Oc(d[c],a)}function Mc(a){switch(Nc(a)){case 1:case 3:case 4:case 5:case 9:return a+" bloaz";default:return a+" vloaz"}}function Nc(a){return a>9?Nc(a%10):a}function Oc(a,b){return 2===b?Pc(a):a}function Pc(a){var b={m:"v",b:"v",d:"z"};return void 0===b[a.charAt(0)]?a:b[a.charAt(0)]+a.substring(1)}
//! moment.js locale configuration
//! locale : bosnian (bs)
//! author : Nedim Cholich : https://github.com/frontyard
//! based on (hr) translation by Bojan Marković
function Qc(a,b,c){var d=a+" ";switch(c){case"m":return b?"jedna minuta":"jedne minute";case"mm":return d+=1===a?"minuta":2===a||3===a||4===a?"minute":"minuta";case"h":return b?"jedan sat":"jednog sata";case"hh":return d+=1===a?"sat":2===a||3===a||4===a?"sata":"sati";case"dd":return d+=1===a?"dan":"dana";case"MM":return d+=1===a?"mjesec":2===a||3===a||4===a?"mjeseca":"mjeseci";case"yy":return d+=1===a?"godina":2===a||3===a||4===a?"godine":"godina"}}function Rc(a){return a>1&&5>a&&1!==~~(a/10)}function Sc(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"pár sekund":"pár sekundami";case"m":return b?"minuta":d?"minutu":"minutou";case"mm":return b||d?e+(Rc(a)?"minuty":"minut"):e+"minutami";break;case"h":return b?"hodina":d?"hodinu":"hodinou";case"hh":return b||d?e+(Rc(a)?"hodiny":"hodin"):e+"hodinami";break;case"d":return b||d?"den":"dnem";case"dd":return b||d?e+(Rc(a)?"dny":"dní"):e+"dny";break;case"M":return b||d?"měsíc":"měsícem";case"MM":return b||d?e+(Rc(a)?"měsíce":"měsíců"):e+"měsíci";break;case"y":return b||d?"rok":"rokem";case"yy":return b||d?e+(Rc(a)?"roky":"let"):e+"lety"}}
//! moment.js locale configuration
//! locale : austrian german (de-at)
//! author : lluchs : https://github.com/lluchs
//! author: Menelion Elensúle: https://github.com/Oire
//! author : Martin Groller : https://github.com/MadMG
function Tc(a,b,c,d){var e={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[a+" Tage",a+" Tagen"],M:["ein Monat","einem Monat"],MM:[a+" Monate",a+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[a+" Jahre",a+" Jahren"]};return b?e[c][0]:e[c][1]}
//! moment.js locale configuration
//! locale : german (de)
//! author : lluchs : https://github.com/lluchs
//! author: Menelion Elensúle: https://github.com/Oire
function Uc(a,b,c,d){var e={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[a+" Tage",a+" Tagen"],M:["ein Monat","einem Monat"],MM:[a+" Monate",a+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[a+" Jahre",a+" Jahren"]};return b?e[c][0]:e[c][1]}
//! moment.js locale configuration
//! locale : estonian (et)
//! author : Henry Kehlmann : https://github.com/madhenry
//! improvements : Illimar Tambek : https://github.com/ragulka
function Vc(a,b,c,d){var e={s:["mõne sekundi","mõni sekund","paar sekundit"],m:["ühe minuti","üks minut"],mm:[a+" minuti",a+" minutit"],h:["ühe tunni","tund aega","üks tund"],hh:[a+" tunni",a+" tundi"],d:["ühe päeva","üks päev"],M:["kuu aja","kuu aega","üks kuu"],MM:[a+" kuu",a+" kuud"],y:["ühe aasta","aasta","üks aasta"],yy:[a+" aasta",a+" aastat"]};return b?e[c][2]?e[c][2]:e[c][1]:d?e[c][0]:e[c][1]}function Wc(a,b,c,d){var e="";switch(c){case"s":return d?"muutaman sekunnin":"muutama sekunti";case"m":return d?"minuutin":"minuutti";case"mm":e=d?"minuutin":"minuuttia";break;case"h":return d?"tunnin":"tunti";case"hh":e=d?"tunnin":"tuntia";break;case"d":return d?"päivän":"päivä";case"dd":e=d?"päivän":"päivää";break;case"M":return d?"kuukauden":"kuukausi";case"MM":e=d?"kuukauden":"kuukautta";break;case"y":return d?"vuoden":"vuosi";case"yy":e=d?"vuoden":"vuotta"}return e=Xc(a,d)+" "+e}function Xc(a,b){return 10>a?b?Pf[a]:Of[a]:a}
//! moment.js locale configuration
//! locale : hrvatski (hr)
//! author : Bojan Marković : https://github.com/bmarkovic
function Yc(a,b,c){var d=a+" ";switch(c){case"m":return b?"jedna minuta":"jedne minute";case"mm":return d+=1===a?"minuta":2===a||3===a||4===a?"minute":"minuta";case"h":return b?"jedan sat":"jednog sata";case"hh":return d+=1===a?"sat":2===a||3===a||4===a?"sata":"sati";case"dd":return d+=1===a?"dan":"dana";case"MM":return d+=1===a?"mjesec":2===a||3===a||4===a?"mjeseca":"mjeseci";case"yy":return d+=1===a?"godina":2===a||3===a||4===a?"godine":"godina"}}function Zc(a,b,c,d){var e=a;switch(c){case"s":return d||b?"néhány másodperc":"néhány másodperce";case"m":return"egy"+(d||b?" perc":" perce");case"mm":return e+(d||b?" perc":" perce");case"h":return"egy"+(d||b?" óra":" órája");case"hh":return e+(d||b?" óra":" órája");case"d":return"egy"+(d||b?" nap":" napja");case"dd":return e+(d||b?" nap":" napja");case"M":return"egy"+(d||b?" hónap":" hónapja");case"MM":return e+(d||b?" hónap":" hónapja");case"y":return"egy"+(d||b?" év":" éve");case"yy":return e+(d||b?" év":" éve")}return""}function $c(a){return(a?"":"[múlt] ")+"["+Uf[this.day()]+"] LT[-kor]"}
//! moment.js locale configuration
//! locale : Armenian (hy-am)
//! author : Armendarabyan : https://github.com/armendarabyan
function _c(a,b){var c={nominative:"հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր".split("_"),accusative:"հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function ad(a,b){var c="հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ".split("_");return c[a.month()]}function bd(a,b){var c="կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ".split("_");return c[a.day()]}
//! moment.js locale configuration
//! locale : icelandic (is)
//! author : Hinrik Örn Sigurðsson : https://github.com/hinrik
function cd(a){return a%100===11?!0:a%10===1?!1:!0}function dd(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"nokkrar sekúndur":"nokkrum sekúndum";case"m":return b?"mínúta":"mínútu";case"mm":return cd(a)?e+(b||d?"mínútur":"mínútum"):b?e+"mínúta":e+"mínútu";case"hh":return cd(a)?e+(b||d?"klukkustundir":"klukkustundum"):e+"klukkustund";case"d":return b?"dagur":d?"dag":"degi";case"dd":return cd(a)?b?e+"dagar":e+(d?"daga":"dögum"):b?e+"dagur":e+(d?"dag":"degi");case"M":return b?"mánuður":d?"mánuð":"mánuði";case"MM":return cd(a)?b?e+"mánuðir":e+(d?"mánuði":"mánuðum"):b?e+"mánuður":e+(d?"mánuð":"mánuði");case"y":return b||d?"ár":"ári";case"yy":return cd(a)?e+(b||d?"ár":"árum"):e+(b||d?"ár":"ári")}}
//! moment.js locale configuration
//! locale : Georgian (ka)
//! author : Irakli Janiashvili : https://github.com/irakli-janiashvili
function ed(a,b){var c={nominative:"იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი".split("_"),accusative:"იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს".split("_")},d=/D[oD] *MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function fd(a,b){var c={nominative:"კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი".split("_"),accusative:"კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს".split("_")},d=/(წინა|შემდეგ)/.test(b)?"accusative":"nominative";return c[d][a.day()]}
//! moment.js locale configuration
//! locale : Luxembourgish (lb)
//! author : mweimerskirch : https://github.com/mweimerskirch, David Raison : https://github.com/kwisatz
function gd(a,b,c,d){var e={m:["eng Minutt","enger Minutt"],h:["eng Stonn","enger Stonn"],d:["een Dag","engem Dag"],M:["ee Mount","engem Mount"],y:["ee Joer","engem Joer"]};return b?e[c][0]:e[c][1]}function hd(a){var b=a.substr(0,a.indexOf(" "));return jd(b)?"a "+a:"an "+a}function id(a){var b=a.substr(0,a.indexOf(" "));return jd(b)?"viru "+a:"virun "+a}function jd(a){if(a=parseInt(a,10),isNaN(a))return!1;if(0>a)return!0;if(10>a)return a>=4&&7>=a?!0:!1;if(100>a){var b=a%10,c=a/10;return jd(0===b?c:b)}if(1e4>a){for(;a>=10;)a/=10;return jd(a)}return a/=1e3,jd(a)}function kd(a,b,c,d){return b?"kelios sekundės":d?"kelių sekundžių":"kelias sekundes"}function ld(a,b){var c={nominative:"sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis".split("_"),accusative:"sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function md(a,b,c,d){return b?od(c)[0]:d?od(c)[1]:od(c)[2]}function nd(a){return a%10===0||a>10&&20>a}function od(a){return Vf[a].split("_")}function pd(a,b,c,d){var e=a+" ";return 1===a?e+md(a,b,c[0],d):b?e+(nd(a)?od(c)[1]:od(c)[0]):d?e+od(c)[1]:e+(nd(a)?od(c)[1]:od(c)[2])}function qd(a,b){var c=-1===b.indexOf("dddd HH:mm"),d=Wf[a.day()];return c?d:d.substring(0,d.length-2)+"į"}function rd(a,b,c){return c?b%10===1&&11!==b?a[2]:a[3]:b%10===1&&11!==b?a[0]:a[1]}function sd(a,b,c){return a+" "+rd(Xf[c],a,b)}function td(a,b,c){return rd(Xf[c],a,b)}function ud(a,b){return b?"dažas sekundes":"dažām sekundēm"}function vd(a){return 5>a%10&&a%10>1&&~~(a/10)%10!==1}function wd(a,b,c){var d=a+" ";switch(c){case"m":return b?"minuta":"minutę";case"mm":return d+(vd(a)?"minuty":"minut");case"h":return b?"godzina":"godzinę";case"hh":return d+(vd(a)?"godziny":"godzin");case"MM":return d+(vd(a)?"miesiące":"miesięcy");case"yy":return d+(vd(a)?"lata":"lat")}}
//! moment.js locale configuration
//! locale : romanian (ro)
//! author : Vlad Gurdiga : https://github.com/gurdiga
//! author : Valentin Agachi : https://github.com/avaly
function xd(a,b,c){var d={mm:"minute",hh:"ore",dd:"zile",MM:"luni",yy:"ani"},e=" ";return(a%100>=20||a>=100&&a%100===0)&&(e=" de "),a+e+d[c]}
//! moment.js locale configuration
//! locale : russian (ru)
//! author : Viktorminator : https://github.com/Viktorminator
//! Author : Menelion Elensúle : https://github.com/Oire
function yd(a,b){var c=a.split("_");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function zd(a,b,c){var d={mm:b?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};return"m"===c?b?"минута":"минуту":a+" "+yd(d[c],+a)}function Ad(a,b){var c={nominative:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),accusative:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function Bd(a,b){var c={nominative:"янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек".split("_"),accusative:"янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек".split("_")},d=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function Cd(a,b){var c={nominative:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),accusative:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_")},d=/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/.test(b)?"accusative":"nominative";return c[d][a.day()]}function Dd(a){return a>1&&5>a}function Ed(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"pár sekúnd":"pár sekundami";case"m":return b?"minúta":d?"minútu":"minútou";case"mm":return b||d?e+(Dd(a)?"minúty":"minút"):e+"minútami";break;case"h":return b?"hodina":d?"hodinu":"hodinou";case"hh":return b||d?e+(Dd(a)?"hodiny":"hodín"):e+"hodinami";break;case"d":return b||d?"deň":"dňom";case"dd":return b||d?e+(Dd(a)?"dni":"dní"):e+"dňami";break;case"M":return b||d?"mesiac":"mesiacom";case"MM":return b||d?e+(Dd(a)?"mesiace":"mesiacov"):e+"mesiacmi";break;case"y":return b||d?"rok":"rokom";case"yy":return b||d?e+(Dd(a)?"roky":"rokov"):e+"rokmi"}}
//! moment.js locale configuration
//! locale : slovenian (sl)
//! author : Robert Sedovšek : https://github.com/sedovsek
function Fd(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"nekaj sekund":"nekaj sekundami";case"m":return b?"ena minuta":"eno minuto";case"mm":return e+=1===a?b?"minuta":"minuto":2===a?b||d?"minuti":"minutama":5>a?b||d?"minute":"minutami":b||d?"minut":"minutami";case"h":return b?"ena ura":"eno uro";case"hh":return e+=1===a?b?"ura":"uro":2===a?b||d?"uri":"urama":5>a?b||d?"ure":"urami":b||d?"ur":"urami";case"d":return b||d?"en dan":"enim dnem";case"dd":return e+=1===a?b||d?"dan":"dnem":2===a?b||d?"dni":"dnevoma":b||d?"dni":"dnevi";case"M":return b||d?"en mesec":"enim mesecem";case"MM":return e+=1===a?b||d?"mesec":"mesecem":2===a?b||d?"meseca":"mesecema":5>a?b||d?"mesece":"meseci":b||d?"mesecev":"meseci";case"y":return b||d?"eno leto":"enim letom";case"yy":return e+=1===a?b||d?"leto":"letom":2===a?b||d?"leti":"letoma":5>a?b||d?"leta":"leti":b||d?"let":"leti"}}function Gd(a,b,c,d){var e={s:["viensas secunds","'iensas secunds"],m:["'n míut","'iens míut"],mm:[a+" míuts"," "+a+" míuts"],h:["'n þora","'iensa þora"],hh:[a+" þoras"," "+a+" þoras"],d:["'n ziua","'iensa ziua"],dd:[a+" ziuas"," "+a+" ziuas"],M:["'n mes","'iens mes"],MM:[a+" mesen"," "+a+" mesen"],y:["'n ar","'iens ar"],yy:[a+" ars"," "+a+" ars"]};return d?e[c][0]:b?e[c][0]:e[c][1].trim()}
//! moment.js locale configuration
//! locale : ukrainian (uk)
//! author : zemlanin : https://github.com/zemlanin
//! Author : Menelion Elensúle : https://github.com/Oire
function Hd(a,b){var c=a.split("_");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function Id(a,b,c){var d={mm:"хвилина_хвилини_хвилин",hh:"година_години_годин",dd:"день_дні_днів",MM:"місяць_місяці_місяців",yy:"рік_роки_років"};return"m"===c?b?"хвилина":"хвилину":"h"===c?b?"година":"годину":a+" "+Hd(d[c],+a)}function Jd(a,b){var c={nominative:"січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень".split("_"),accusative:"січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня".split("_")},d=/D[oD]? *MMMM?/.test(b)?"accusative":"nominative";return c[d][a.month()]}function Kd(a,b){var c={nominative:"неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота".split("_"),accusative:"неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу".split("_"),genitive:"неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи".split("_")},d=/(\[[ВвУу]\]) ?dddd/.test(b)?"accusative":/\[?(?:минулої|наступної)? ?\] ?dddd/.test(b)?"genitive":"nominative";return c[d][a.day()]}function Ld(a){return function(){return a+"о"+(11===this.hours()?"б":"")+"] LT"}}var Md,Nd,Od=a.momentProperties=[],Pd=!1,Qd={},Rd={},Sd=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Td=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Ud={},Vd={},Wd=/\d/,Xd=/\d\d/,Yd=/\d{3}/,Zd=/\d{4}/,$d=/[+-]?\d{6}/,_d=/\d\d?/,ae=/\d{1,3}/,be=/\d{1,4}/,ce=/[+-]?\d{1,6}/,de=/\d+/,ee=/[+-]?\d+/,fe=/Z|[+-]\d\d:?\d\d/gi,ge=/[+-]?\d+(\.\d{1,3})?/,he=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,ie={},je={},ke=0,le=1,me=2,ne=3,oe=4,pe=5,qe=6;H("M",["MM",2],"Mo",function(){return this.month()+1}),H("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),H("MMMM",0,0,function(a){return this.localeData().months(this,a)}),z("month","M"),N("M",_d),N("MM",_d,Xd),N("MMM",he),N("MMMM",he),Q(["M","MM"],function(a,b){b[le]=q(a)-1}),Q(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[le]=e:j(c).invalidMonth=a});var re="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),se="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),te={};a.suppressDeprecationWarnings=!1;var ue=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,ve=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],we=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],xe=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=aa("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),H(0,["YY",2],0,function(){return this.year()%100}),H(0,["YYYY",4],0,"year"),H(0,["YYYYY",5],0,"year"),H(0,["YYYYYY",6,!0],0,"year"),z("year","y"),N("Y",ee),N("YY",_d,Xd),N("YYYY",be,Zd),N("YYYYY",ce,$d),N("YYYYYY",ce,$d),Q(["YYYYY","YYYYYY"],ke),Q("YYYY",function(b,c){c[ke]=2===b.length?a.parseTwoDigitYear(b):q(b)}),Q("YY",function(b,c){c[ke]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return q(a)+(q(a)>68?1900:2e3)};var ye=C("FullYear",!1);H("w",["ww",2],"wo","week"),H("W",["WW",2],"Wo","isoWeek"),z("week","w"),z("isoWeek","W"),N("w",_d),N("ww",_d,Xd),N("W",_d),N("WW",_d,Xd),R(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=q(a)});var ze={dow:0,doy:6};H("DDD",["DDDD",3],"DDDo","dayOfYear"),z("dayOfYear","DDD"),N("DDD",ae),N("DDDD",Yd),Q(["DDD","DDDD"],function(a,b,c){c._dayOfYear=q(a)}),a.ISO_8601=function(){};var Ae=aa("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=Da.apply(null,arguments);return this>a?this:a}),Be=aa("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=Da.apply(null,arguments);return a>this?this:a});Ja("Z",":"),Ja("ZZ",""),N("Z",fe),N("ZZ",fe),Q(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ka(a)});var Ce=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var De=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,Ee=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Ya.fn=Ha.prototype;var Fe=ab(1,"add"),Ge=ab(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var He=aa("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});H(0,["gg",2],0,function(){return this.weekYear()%100}),H(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Db("gggg","weekYear"),Db("ggggg","weekYear"),Db("GGGG","isoWeekYear"),Db("GGGGG","isoWeekYear"),z("weekYear","gg"),z("isoWeekYear","GG"),N("G",ee),N("g",ee),N("GG",_d,Xd),N("gg",_d,Xd),N("GGGG",be,Zd),N("gggg",be,Zd),N("GGGGG",ce,$d),N("ggggg",ce,$d),R(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=q(a)}),R(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),H("Q",0,0,"quarter"),z("quarter","Q"),N("Q",Wd),Q("Q",function(a,b){b[le]=3*(q(a)-1)}),H("D",["DD",2],"Do","date"),z("date","D"),N("D",_d),N("DD",_d,Xd),N("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),Q(["D","DD"],me),Q("Do",function(a,b){b[me]=q(a.match(_d)[0],10)});var Ie=C("Date",!0);H("d",0,"do","day"),H("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),H("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),H("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),H("e",0,0,"weekday"),H("E",0,0,"isoWeekday"),z("day","d"),z("weekday","e"),z("isoWeekday","E"),N("d",_d),N("e",_d),N("E",_d),N("dd",he),N("ddd",he),N("dddd",he),R(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:j(c).invalidWeekday=a}),R(["d","e","E"],function(a,b,c,d){b[d]=q(a)});var Je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Ke="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Le="Su_Mo_Tu_We_Th_Fr_Sa".split("_");H("H",["HH",2],0,"hour"),H("h",["hh",2],0,function(){return this.hours()%12||12}),Sb("a",!0),Sb("A",!1),z("hour","h"),N("a",Tb),N("A",Tb),N("H",_d),N("h",_d),N("HH",_d,Xd),N("hh",_d,Xd),Q(["H","HH"],ne),Q(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),Q(["h","hh"],function(a,b,c){b[ne]=q(a),j(c).bigHour=!0});var Me=/[ap]\.?m?\.?/i,Ne=C("Hours",!0);H("m",["mm",2],0,"minute"),z("minute","m"),N("m",_d),N("mm",_d,Xd),Q(["m","mm"],oe);var Oe=C("Minutes",!1);H("s",["ss",2],0,"second"),z("second","s"),N("s",_d),N("ss",_d,Xd),Q(["s","ss"],pe);var Pe=C("Seconds",!1);H("S",0,0,function(){return~~(this.millisecond()/100)}),H(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),H(0,["SSS",3],0,"millisecond"),H(0,["SSSS",4],0,function(){return 10*this.millisecond()}),H(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),H(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),H(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),H(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),H(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),z("millisecond","ms"),N("S",ae,Wd),N("SS",ae,Xd),N("SSS",ae,Yd);var Qe;for(Qe="SSSS";Qe.length<=9;Qe+="S")N(Qe,de);for(Qe="S";Qe.length<=9;Qe+="S")Q(Qe,Wb);var Re=C("Milliseconds",!1);H("z",0,0,"zoneAbbr"),H("zz",0,0,"zoneName");var Se=n.prototype;Se.add=Fe,Se.calendar=cb,Se.clone=db,Se.diff=ib,Se.endOf=ub,Se.format=mb,Se.from=nb,Se.fromNow=ob,Se.to=pb,Se.toNow=qb,Se.get=F,Se.invalidAt=Cb,Se.isAfter=eb,Se.isBefore=fb,Se.isBetween=gb,Se.isSame=hb,Se.isValid=Ab,Se.lang=He,Se.locale=rb,Se.localeData=sb,Se.max=Be,Se.min=Ae,Se.parsingFlags=Bb,Se.set=F,Se.startOf=tb,Se.subtract=Ge,Se.toArray=yb,Se.toObject=zb,Se.toDate=xb,Se.toISOString=lb,Se.toJSON=lb,Se.toString=kb,Se.unix=wb,Se.valueOf=vb,Se.year=ye,Se.isLeapYear=ia,Se.weekYear=Fb,Se.isoWeekYear=Gb,Se.quarter=Se.quarters=Jb,Se.month=Y,Se.daysInMonth=Z,Se.week=Se.weeks=na,Se.isoWeek=Se.isoWeeks=oa,Se.weeksInYear=Ib,Se.isoWeeksInYear=Hb,Se.date=Ie,Se.day=Se.days=Pb,Se.weekday=Qb,Se.isoWeekday=Rb,Se.dayOfYear=qa,Se.hour=Se.hours=Ne,Se.minute=Se.minutes=Oe,Se.second=Se.seconds=Pe,Se.millisecond=Se.milliseconds=Re,Se.utcOffset=Na,Se.utc=Pa,Se.local=Qa,Se.parseZone=Ra,Se.hasAlignedHourOffset=Sa,Se.isDST=Ta,Se.isDSTShifted=Ua,Se.isLocal=Va,Se.isUtcOffset=Wa,Se.isUtc=Xa,Se.isUTC=Xa,Se.zoneAbbr=Xb,Se.zoneName=Yb,Se.dates=aa("dates accessor is deprecated. Use date instead.",Ie),Se.months=aa("months accessor is deprecated. Use month instead",Y),Se.years=aa("years accessor is deprecated. Use year instead",ye),Se.zone=aa("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Oa);var Te=Se,Ue={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Ve={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},We="Invalid date",Xe="%d",Ye=/\d{1,2}/,Ze={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},$e=s.prototype;$e._calendar=Ue,$e.calendar=_b,$e._longDateFormat=Ve,$e.longDateFormat=ac,$e._invalidDate=We,$e.invalidDate=bc,$e._ordinal=Xe,$e.ordinal=cc,$e._ordinalParse=Ye,$e.preparse=dc,$e.postformat=dc,$e._relativeTime=Ze,$e.relativeTime=ec,$e.pastFuture=fc,$e.set=gc,$e.months=U,$e._months=re,$e.monthsShort=V,$e._monthsShort=se,$e.monthsParse=W,$e.week=ka,$e._week=ze,$e.firstDayOfYear=ma,$e.firstDayOfWeek=la,$e.weekdays=Lb,$e._weekdays=Je,$e.weekdaysMin=Nb,$e._weekdaysMin=Le,$e.weekdaysShort=Mb,$e._weekdaysShort=Ke,$e.weekdaysParse=Ob,$e.isPM=Ub,$e._meridiemParse=Me,$e.meridiem=Vb,w("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===q(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=aa("moment.lang is deprecated. Use moment.locale instead.",w),a.langData=aa("moment.langData is deprecated. Use moment.localeData instead.",y);var _e=Math.abs,af=yc("ms"),bf=yc("s"),cf=yc("m"),df=yc("h"),ef=yc("d"),ff=yc("w"),gf=yc("M"),hf=yc("y"),jf=Ac("milliseconds"),kf=Ac("seconds"),lf=Ac("minutes"),mf=Ac("hours"),nf=Ac("days"),of=Ac("months"),pf=Ac("years"),qf=Math.round,rf={s:45,m:45,h:22,d:26,M:11},sf=Math.abs,tf=Ha.prototype;tf.abs=oc,tf.add=qc,tf.subtract=rc,tf.as=wc,tf.asMilliseconds=af,tf.asSeconds=bf,tf.asMinutes=cf,tf.asHours=df,tf.asDays=ef,tf.asWeeks=ff,tf.asMonths=gf,tf.asYears=hf,tf.valueOf=xc,tf._bubble=tc,tf.get=zc,tf.milliseconds=jf,tf.seconds=kf,tf.minutes=lf,tf.hours=mf,tf.days=nf,tf.weeks=Bc,tf.months=of,tf.years=pf,tf.humanize=Fc,tf.toISOString=Gc,tf.toString=Gc,tf.toJSON=Gc,tf.locale=rb,tf.localeData=sb,tf.toIsoString=aa("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Gc),tf.lang=He,H("X",0,0,"unix"),H("x",0,0,"valueOf"),N("x",ee),N("X",ge),Q("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),Q("x",function(a,b,c){c._d=new Date(q(a))}),
//! moment.js
//! version : 2.10.6
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
a.version="2.10.6",b(Da),a.fn=Te,a.min=Fa,a.max=Ga,a.utc=h,a.unix=Zb,a.months=jc,a.isDate=d,a.locale=w,a.invalid=l,a.duration=Ya,a.isMoment=o,a.weekdays=lc,a.parseZone=$b,a.localeData=y,a.isDuration=Ia,a.monthsShort=kc,a.weekdaysMin=nc,a.defineLocale=x,a.weekdaysShort=mc,a.normalizeUnits=A,a.relativeTimeThreshold=Ec;var uf=a,vf=(uf.defineLocale("af",{months:"Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des".split("_"),weekdays:"Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag".split("_"),weekdaysShort:"Son_Maa_Din_Woe_Don_Vry_Sat".split("_"),weekdaysMin:"So_Ma_Di_Wo_Do_Vr_Sa".split("_"),meridiemParse:/vm|nm/i,isPM:function(a){return/^nm$/i.test(a)},meridiem:function(a,b,c){return 12>a?c?"vm":"VM":c?"nm":"NM"},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Vandag om] LT",nextDay:"[Môre om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gister om] LT",lastWeek:"[Laas] dddd [om] LT",sameElse:"L"},relativeTime:{future:"oor %s",past:"%s gelede",s:"'n paar sekondes",m:"'n minuut",mm:"%d minute",h:"'n uur",hh:"%d ure",d:"'n dag",dd:"%d dae",M:"'n maand",MM:"%d maande",y:"'n jaar",yy:"%d jaar"},ordinalParse:/\d{1,2}(ste|de)/,ordinal:function(a){return a+(1===a||8===a||a>=20?"ste":"de")},week:{dow:1,doy:4}}),uf.defineLocale("ar-ma",{months:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),weekdays:"الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:6,doy:12}}),{1:"١",2:"٢",3:"٣",4:"٤",5:"٥",6:"٦",7:"٧",8:"٨",9:"٩",0:"٠"}),wf={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"},xf=(uf.defineLocale("ar-sa",{months:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(a){return"م"===a},meridiem:function(a,b,c){return 12>a?"ص":"م"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},preparse:function(a){return a.replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(a){return wf[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return vf[a]}).replace(/,/g,"،")},week:{dow:6,doy:12}}),uf.defineLocale("ar-tn",{months:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:1,doy:4}}),{1:"١",2:"٢",3:"٣",4:"٤",5:"٥",6:"٦",7:"٧",8:"٨",9:"٩",0:"٠"}),yf={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"},zf=function(a){return 0===a?0:1===a?1:2===a?2:a%100>=3&&10>=a%100?3:a%100>=11?4:5},Af={s:["أقل من ثانية","ثانية واحدة",["ثانيتان","ثانيتين"],"%d ثوان","%d ثانية","%d ثانية"],m:["أقل من دقيقة","دقيقة واحدة",["دقيقتان","دقيقتين"],"%d دقائق","%d دقيقة","%d دقيقة"],h:["أقل من ساعة","ساعة واحدة",["ساعتان","ساعتين"],"%d ساعات","%d ساعة","%d ساعة"],d:["أقل من يوم","يوم واحد",["يومان","يومين"],"%d أيام","%d يومًا","%d يوم"],M:["أقل من شهر","شهر واحد",["شهران","شهرين"],"%d أشهر","%d شهرا","%d شهر"],y:["أقل من عام","عام واحد",["عامان","عامين"],"%d أعوام","%d عامًا","%d عام"]},Bf=function(a){return function(b,c,d,e){var f=zf(b),g=Af[a][zf(b)];return 2===f&&(g=g[c?0:1]),g.replace(/%d/i,b)}},Cf=["كانون الثاني يناير","شباط فبراير","آذار مارس","نيسان أبريل","أيار مايو","حزيران يونيو","تموز يوليو","آب أغسطس","أيلول سبتمبر","تشرين الأول أكتوبر","تشرين الثاني نوفمبر","كانون الأول ديسمبر"],Df=(uf.defineLocale("ar",{months:Cf,monthsShort:Cf,weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"D/‏M/‏YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/ص|م/,isPM:function(a){return"م"===a},meridiem:function(a,b,c){return 12>a?"ص":"م"},calendar:{sameDay:"[اليوم عند الساعة] LT",nextDay:"[غدًا عند الساعة] LT",nextWeek:"dddd [عند الساعة] LT",lastDay:"[أمس عند الساعة] LT",lastWeek:"dddd [عند الساعة] LT",sameElse:"L"},relativeTime:{future:"بعد %s",past:"منذ %s",s:Bf("s"),m:Bf("m"),mm:Bf("m"),h:Bf("h"),hh:Bf("h"),d:Bf("d"),dd:Bf("d"),M:Bf("M"),MM:Bf("M"),y:Bf("y"),yy:Bf("y")},preparse:function(a){return a.replace(/\u200f/g,"").replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(a){return yf[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return xf[a]}).replace(/,/g,"،")},week:{dow:6,doy:12}}),{1:"-inci",5:"-inci",8:"-inci",70:"-inci",80:"-inci",2:"-nci",7:"-nci",20:"-nci",50:"-nci",3:"-üncü",4:"-üncü",100:"-üncü",6:"-ncı",9:"-uncu",10:"-uncu",30:"-uncu",60:"-ıncı",90:"-ıncı"}),Ef=(uf.defineLocale("az",{months:"yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr".split("_"),monthsShort:"yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek".split("_"),weekdays:"Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə".split("_"),weekdaysShort:"Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən".split("_"),weekdaysMin:"Bz_BE_ÇA_Çə_CA_Cü_Şə".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[sabah saat] LT",nextWeek:"[gələn həftə] dddd [saat] LT",lastDay:"[dünən] LT",lastWeek:"[keçən həftə] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s əvvəl",s:"birneçə saniyyə",m:"bir dəqiqə",mm:"%d dəqiqə",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir il",yy:"%d il"},meridiemParse:/gecə|səhər|gündüz|axşam/,isPM:function(a){return/^(gündüz|axşam)$/.test(a)},meridiem:function(a,b,c){return 4>a?"gecə":12>a?"səhər":17>a?"gündüz":"axşam"},ordinalParse:/\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,ordinal:function(a){if(0===a)return a+"-ıncı";var b=a%10,c=a%100-b,d=a>=100?100:null;return a+(Df[b]||Df[c]||Df[d])},week:{dow:1,doy:7}}),uf.defineLocale("be",{months:Jc,monthsShort:"студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж".split("_"),weekdays:Kc,weekdaysShort:"нд_пн_ат_ср_чц_пт_сб".split("_"),weekdaysMin:"нд_пн_ат_ср_чц_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сёння ў] LT",nextDay:"[Заўтра ў] LT",lastDay:"[Учора ў] LT",nextWeek:function(){return"[У] dddd [ў] LT"},lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return"[У мінулую] dddd [ў] LT";case 1:case 2:case 4:return"[У мінулы] dddd [ў] LT"}},sameElse:"L"},relativeTime:{future:"праз %s",past:"%s таму",s:"некалькі секунд",m:Ic,mm:Ic,h:Ic,hh:Ic,d:"дзень",dd:Ic,M:"месяц",MM:Ic,y:"год",yy:Ic},meridiemParse:/ночы|раніцы|дня|вечара/,isPM:function(a){return/^(дня|вечара)$/.test(a)},meridiem:function(a,b,c){return 4>a?"ночы":12>a?"раніцы":17>a?"дня":"вечара"},ordinalParse:/\d{1,2}-(і|ы|га)/,ordinal:function(a,b){switch(b){case"M":case"d":case"DDD":case"w":case"W":return a%10!==2&&a%10!==3||a%100===12||a%100===13?a+"-ы":a+"-і";case"D":return a+"-га";default:return a}},week:{dow:1,doy:7}}),uf.defineLocale("bg",{months:"януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"),monthsShort:"янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"),weekdays:"неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"),weekdaysShort:"нед_пон_вто_сря_чет_пет_съб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"D.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[Днес в] LT",nextDay:"[Утре в] LT",nextWeek:"dddd [в] LT",lastDay:"[Вчера в] LT",lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return"[В изминалата] dddd [в] LT";case 1:case 2:case 4:case 5:return"[В изминалия] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"след %s",past:"преди %s",s:"няколко секунди",m:"минута",mm:"%d минути",h:"час",hh:"%d часа",d:"ден",dd:"%d дни",M:"месец",MM:"%d месеца",y:"година",yy:"%d години"},ordinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(a){var b=a%10,c=a%100;return 0===a?a+"-ев":0===c?a+"-ен":c>10&&20>c?a+"-ти":1===b?a+"-ви":2===b?a+"-ри":7===b||8===b?a+"-ми":a+"-ти"},week:{dow:1,doy:7}}),{1:"১",2:"২",3:"৩",4:"৪",5:"৫",6:"৬",7:"৭",8:"৮",9:"৯",0:"০"}),Ff={"১":"1","২":"2","৩":"3","৪":"4","৫":"5","৬":"6","৭":"7","৮":"8","৯":"9","০":"0"},Gf=(uf.defineLocale("bn",{months:"জানুয়ারী_ফেবুয়ারী_মার্চ_এপ্রিল_মে_জুন_জুলাই_অগাস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর".split("_"),monthsShort:"জানু_ফেব_মার্চ_এপর_মে_জুন_জুল_অগ_সেপ্ট_অক্টো_নভ_ডিসেম্".split("_"),weekdays:"রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পত্তিবার_শুক্রুবার_শনিবার".split("_"),weekdaysShort:"রবি_সোম_মঙ্গল_বুধ_বৃহস্পত্তি_শুক্রু_শনি".split("_"),weekdaysMin:"রব_সম_মঙ্গ_বু_ব্রিহ_শু_শনি".split("_"),longDateFormat:{LT:"A h:mm সময়",LTS:"A h:mm:ss সময়",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm সময়",LLLL:"dddd, D MMMM YYYY, A h:mm সময়"},calendar:{sameDay:"[আজ] LT",nextDay:"[আগামীকাল] LT",nextWeek:"dddd, LT",lastDay:"[গতকাল] LT",lastWeek:"[গত] dddd, LT",sameElse:"L"},relativeTime:{future:"%s পরে",past:"%s আগে",s:"কএক সেকেন্ড",m:"এক মিনিট",mm:"%d মিনিট",h:"এক ঘন্টা",hh:"%d ঘন্টা",d:"এক দিন",dd:"%d দিন",M:"এক মাস",MM:"%d মাস",y:"এক বছর",yy:"%d বছর"},preparse:function(a){return a.replace(/[১২৩৪৫৬৭৮৯০]/g,function(a){return Ff[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Ef[a]})},meridiemParse:/রাত|সকাল|দুপুর|বিকেল|রাত/,isPM:function(a){return/^(দুপুর|বিকেল|রাত)$/.test(a)},meridiem:function(a,b,c){return 4>a?"রাত":10>a?"সকাল":17>a?"দুপুর":20>a?"বিকেল":"রাত"},week:{dow:0,doy:6}}),{1:"༡",2:"༢",3:"༣",4:"༤",5:"༥",6:"༦",7:"༧",8:"༨",9:"༩",0:"༠"}),Hf={"༡":"1","༢":"2","༣":"3","༤":"4","༥":"5","༦":"6","༧":"7","༨":"8","༩":"9","༠":"0"},If=(uf.defineLocale("bo",{months:"ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ".split("_"),monthsShort:"ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ".split("_"),weekdays:"གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་".split("_"),weekdaysShort:"ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་".split("_"),weekdaysMin:"ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་".split("_"),longDateFormat:{LT:"A h:mm",LTS:"A h:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm",LLLL:"dddd, D MMMM YYYY, A h:mm"},calendar:{sameDay:"[དི་རིང] LT",nextDay:"[སང་ཉིན] LT",nextWeek:"[བདུན་ཕྲག་རྗེས་མ], LT",lastDay:"[ཁ་སང] LT",lastWeek:"[བདུན་ཕྲག་མཐའ་མ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s ལ་",past:"%s སྔན་ལ",s:"ལམ་སང",m:"སྐར་མ་གཅིག",mm:"%d སྐར་མ",h:"ཆུ་ཚོད་གཅིག",hh:"%d ཆུ་ཚོད",d:"ཉིན་གཅིག",dd:"%d ཉིན་",M:"ཟླ་བ་གཅིག",MM:"%d ཟླ་བ",y:"ལོ་གཅིག",yy:"%d ལོ"},preparse:function(a){return a.replace(/[༡༢༣༤༥༦༧༨༩༠]/g,function(a){return Hf[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Gf[a]})},meridiemParse:/མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,isPM:function(a){return/^(ཉིན་གུང|དགོང་དག|མཚན་མོ)$/.test(a)},meridiem:function(a,b,c){return 4>a?"མཚན་མོ":10>a?"ཞོགས་ཀས":17>a?"ཉིན་གུང":20>a?"དགོང་དག":"མཚན་མོ"},week:{dow:0,doy:6}}),uf.defineLocale("br",{months:"Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"),monthsShort:"Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"),weekdays:"Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"),weekdaysShort:"Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"),weekdaysMin:"Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"),longDateFormat:{LT:"h[e]mm A",LTS:"h[e]mm:ss A",L:"DD/MM/YYYY",LL:"D [a viz] MMMM YYYY",LLL:"D [a viz] MMMM YYYY h[e]mm A",LLLL:"dddd, D [a viz] MMMM YYYY h[e]mm A"},calendar:{sameDay:"[Hiziv da] LT",nextDay:"[Warc'hoazh da] LT",nextWeek:"dddd [da] LT",lastDay:"[Dec'h da] LT",lastWeek:"dddd [paset da] LT",sameElse:"L"},relativeTime:{future:"a-benn %s",past:"%s 'zo",s:"un nebeud segondennoù",m:"ur vunutenn",mm:Lc,h:"un eur",hh:"%d eur",d:"un devezh",dd:Lc,M:"ur miz",MM:Lc,y:"ur bloaz",yy:Mc},ordinalParse:/\d{1,2}(añ|vet)/,ordinal:function(a){var b=1===a?"añ":"vet";return a+b},week:{dow:1,doy:4}}),uf.defineLocale("bs",{months:"januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar".split("_"),monthsShort:"jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.".split("_"),weekdays:"nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sri._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[jučer u] LT",lastWeek:function(){switch(this.day()){case 0:case 3:return"[prošlu] dddd [u] LT";case 6:return"[prošle] [subote] [u] LT";case 1:case 2:case 4:case 5:return"[prošli] dddd [u] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"par sekundi",m:Qc,mm:Qc,h:Qc,hh:Qc,d:"dan",dd:Qc,M:"mjesec",MM:Qc,y:"godinu",yy:Qc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),uf.defineLocale("ca",{months:"gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"),monthsShort:"gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.".split("_"),weekdays:"diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"),weekdaysShort:"dg._dl._dt._dc._dj._dv._ds.".split("_"),weekdaysMin:"Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),longDateFormat:{LT:"H:mm",LTS:"LT:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd D MMMM YYYY H:mm"},calendar:{sameDay:function(){return"[avui a "+(1!==this.hours()?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+(1!==this.hours()?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+(1!==this.hours()?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+(1!==this.hours()?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+(1!==this.hours()?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},ordinalParse:/\d{1,2}(r|n|t|è|a)/,ordinal:function(a,b){var c=1===a?"r":2===a?"n":3===a?"r":4===a?"t":"è";return("w"===b||"W"===b)&&(c="a"),a+c},week:{dow:1,doy:4}}),"leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_")),Jf="led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro".split("_"),Kf=(uf.defineLocale("cs",{months:If,monthsShort:Jf,monthsParse:function(a,b){var c,d=[];for(c=0;12>c;c++)d[c]=new RegExp("^"+a[c]+"$|^"+b[c]+"$","i");return d}(If,Jf),weekdays:"neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota".split("_"),weekdaysShort:"ne_po_út_st_čt_pá_so".split("_"),weekdaysMin:"ne_po_út_st_čt_pá_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd D. MMMM YYYY H:mm"},calendar:{sameDay:"[dnes v] LT",nextDay:"[zítra v] LT",nextWeek:function(){switch(this.day()){case 0:return"[v neděli v] LT";case 1:case 2:return"[v] dddd [v] LT";case 3:return"[ve středu v] LT";case 4:return"[ve čtvrtek v] LT";case 5:return"[v pátek v] LT";case 6:return"[v sobotu v] LT"}},lastDay:"[včera v] LT",lastWeek:function(){switch(this.day()){case 0:return"[minulou neděli v] LT";case 1:case 2:return"[minulé] dddd [v] LT";case 3:return"[minulou středu v] LT";case 4:case 5:return"[minulý] dddd [v] LT";case 6:return"[minulou sobotu v] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"před %s",s:Sc,m:Sc,mm:Sc,h:Sc,hh:Sc,d:Sc,dd:Sc,M:Sc,MM:Sc,y:Sc,yy:Sc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("cv",{months:"кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав".split("_"),monthsShort:"кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш".split("_"),weekdays:"вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун".split("_"),weekdaysShort:"выр_тун_ытл_юн_кӗҫ_эрн_шӑм".split("_"),weekdaysMin:"вр_тн_ыт_юн_кҫ_эр_шм".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]",LLL:"YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm",LLLL:"dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm"},calendar:{sameDay:"[Паян] LT [сехетре]",nextDay:"[Ыран] LT [сехетре]",lastDay:"[Ӗнер] LT [сехетре]",nextWeek:"[Ҫитес] dddd LT [сехетре]",lastWeek:"[Иртнӗ] dddd LT [сехетре]",sameElse:"L"},relativeTime:{future:function(a){var b=/сехет$/i.exec(a)?"рен":/ҫул$/i.exec(a)?"тан":"ран";return a+b},past:"%s каялла",s:"пӗр-ик ҫеккунт",m:"пӗр минут",mm:"%d минут",h:"пӗр сехет",hh:"%d сехет",d:"пӗр кун",dd:"%d кун",M:"пӗр уйӑх",MM:"%d уйӑх",y:"пӗр ҫул",yy:"%d ҫул"},ordinalParse:/\d{1,2}-мӗш/,ordinal:"%d-мӗш",week:{dow:1,doy:7}}),uf.defineLocale("cy",{months:"Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"),monthsShort:"Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"),weekdays:"Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"),weekdaysShort:"Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"),weekdaysMin:"Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Heddiw am] LT",nextDay:"[Yfory am] LT",nextWeek:"dddd [am] LT",lastDay:"[Ddoe am] LT",lastWeek:"dddd [diwethaf am] LT",sameElse:"L"},relativeTime:{future:"mewn %s",past:"%s yn ôl",s:"ychydig eiliadau",m:"munud",mm:"%d munud",h:"awr",hh:"%d awr",d:"diwrnod",dd:"%d diwrnod",M:"mis",MM:"%d mis",y:"blwyddyn",yy:"%d flynedd"},ordinalParse:/\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,ordinal:function(a){var b=a,c="",d=["","af","il","ydd","ydd","ed","ed","ed","fed","fed","fed","eg","fed","eg","eg","fed","eg","eg","fed","eg","fed"];return b>20?c=40===b||50===b||60===b||80===b||100===b?"fed":"ain":b>0&&(c=d[b]),a+c},week:{dow:1,doy:4}}),uf.defineLocale("da",{months:"januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tir_ons_tor_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd [d.] D. MMMM YYYY HH:mm"},calendar:{sameDay:"[I dag kl.] LT",nextDay:"[I morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[I går kl.] LT",lastWeek:"[sidste] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"få sekunder",m:"et minut",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dage",M:"en måned",MM:"%d måneder",y:"et år",yy:"%d år"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("de-at",{months:"Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd, D. MMMM YYYY HH:mm"},calendar:{sameDay:"[Heute um] LT [Uhr]",sameElse:"L",nextDay:"[Morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[Gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:Tc,mm:"%d Minuten",h:Tc,hh:"%d Stunden",d:Tc,dd:Tc,M:Tc,MM:Tc,y:Tc,yy:Tc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("de",{months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY HH:mm",LLLL:"dddd, D. MMMM YYYY HH:mm"},calendar:{sameDay:"[Heute um] LT [Uhr]",sameElse:"L",nextDay:"[Morgen um] LT [Uhr]",nextWeek:"dddd [um] LT [Uhr]",lastDay:"[Gestern um] LT [Uhr]",lastWeek:"[letzten] dddd [um] LT [Uhr]"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:Uc,mm:"%d Minuten",h:Uc,hh:"%d Stunden",d:Uc,dd:Uc,M:Uc,MM:Uc,y:Uc,yy:Uc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("el",{monthsNominativeEl:"Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"),monthsGenitiveEl:"Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"),months:function(a,b){return/D/.test(b.substring(0,b.indexOf("MMMM")))?this._monthsGenitiveEl[a.month()]:this._monthsNominativeEl[a.month()]},monthsShort:"Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"),weekdays:"Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"),weekdaysShort:"Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"),weekdaysMin:"Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"),meridiem:function(a,b,c){return a>11?c?"μμ":"ΜΜ":c?"πμ":"ΠΜ"},isPM:function(a){return"μ"===(a+"").toLowerCase()[0]},meridiemParse:/[ΠΜ]\.?Μ?\.?/i,longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendarEl:{sameDay:"[Σήμερα {}] LT",nextDay:"[Αύριο {}] LT",nextWeek:"dddd [{}] LT",lastDay:"[Χθες {}] LT",lastWeek:function(){switch(this.day()){case 6:return"[το προηγούμενο] dddd [{}] LT";default:return"[την προηγούμενη] dddd [{}] LT"}},sameElse:"L"},calendar:function(a,b){var c=this._calendarEl[a],d=b&&b.hours();return"function"==typeof c&&(c=c.apply(b)),c.replace("{}",d%12===1?"στη":"στις")},relativeTime:{future:"σε %s",past:"%s πριν",s:"λίγα δευτερόλεπτα",m:"ένα λεπτό",mm:"%d λεπτά",h:"μία ώρα",hh:"%d ώρες",d:"μία μέρα",dd:"%d μέρες",M:"ένας μήνας",MM:"%d μήνες",y:"ένας χρόνος",yy:"%d χρόνια"},ordinalParse:/\d{1,2}η/,ordinal:"%dη",week:{dow:1,doy:4}}),uf.defineLocale("en-au",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c},week:{dow:1,doy:4}}),uf.defineLocale("en-ca",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"YYYY-MM-DD",LL:"D MMMM, YYYY",LLL:"D MMMM, YYYY h:mm A",LLLL:"dddd, D MMMM, YYYY h:mm A"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),uf.defineLocale("en-gb",{months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c},week:{dow:1,doy:4}}),uf.defineLocale("eo",{months:"januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"),weekdays:"Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato".split("_"),weekdaysShort:"Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Ĵa_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D[-an de] MMMM, YYYY",LLL:"D[-an de] MMMM, YYYY HH:mm",LLLL:"dddd, [la] D[-an de] MMMM, YYYY HH:mm"},meridiemParse:/[ap]\.t\.m/i,isPM:function(a){return"p"===a.charAt(0).toLowerCase()},meridiem:function(a,b,c){return a>11?c?"p.t.m.":"P.T.M.":c?"a.t.m.":"A.T.M."},calendar:{sameDay:"[Hodiaŭ je] LT",nextDay:"[Morgaŭ je] LT",nextWeek:"dddd [je] LT",lastDay:"[Hieraŭ je] LT",lastWeek:"[pasinta] dddd [je] LT",sameElse:"L"},relativeTime:{future:"je %s",past:"antaŭ %s",s:"sekundoj",m:"minuto",mm:"%d minutoj",h:"horo",hh:"%d horoj",d:"tago",dd:"%d tagoj",M:"monato",MM:"%d monatoj",y:"jaro",yy:"%d jaroj"},ordinalParse:/\d{1,2}a/,ordinal:"%da",week:{dow:1,doy:7}}),"Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.".split("_")),Lf="Ene_Feb_Mar_Abr_May_Jun_Jul_Ago_Sep_Oct_Nov_Dic".split("_"),Mf=(uf.defineLocale("es",{months:"Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre".split("_"),monthsShort:function(a,b){return/-MMM-/.test(b)?Lf[a.month()]:Kf[a.month()]},weekdays:"Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mié._Jue._Vie._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY H:mm",LLLL:"dddd, D [de] MMMM [de] YYYY H:mm"},calendar:{sameDay:function(){return"[hoy a la"+(1!==this.hours()?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+(1!==this.hours()?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+(1!==this.hours()?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+(1!==this.hours()?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+(1!==this.hours()?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}}),uf.defineLocale("et",{months:"jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"),monthsShort:"jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"),weekdays:"pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"),weekdaysShort:"P_E_T_K_N_R_L".split("_"),weekdaysMin:"P_E_T_K_N_R_L".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[Täna,] LT",nextDay:"[Homme,] LT",nextWeek:"[Järgmine] dddd LT",lastDay:"[Eile,] LT",lastWeek:"[Eelmine] dddd LT",sameElse:"L"},relativeTime:{future:"%s pärast",past:"%s tagasi",s:Vc,m:Vc,mm:Vc,h:Vc,hh:Vc,d:Vc,dd:"%d päeva",M:Vc,MM:Vc,y:Vc,yy:Vc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("eu",{months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"ig_al_ar_az_og_ol_lr".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"YYYY[ko] MMMM[ren] D[a]",LLL:"YYYY[ko] MMMM[ren] D[a] HH:mm",LLLL:"dddd, YYYY[ko] MMMM[ren] D[a] HH:mm",l:"YYYY-M-D",ll:"YYYY[ko] MMM D[a]",lll:"YYYY[ko] MMM D[a] HH:mm",llll:"ddd, YYYY[ko] MMM D[a] HH:mm"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",
lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),{1:"۱",2:"۲",3:"۳",4:"۴",5:"۵",6:"۶",7:"۷",8:"۸",9:"۹",0:"۰"}),Nf={"۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9","۰":"0"},Of=(uf.defineLocale("fa",{months:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),monthsShort:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),weekdays:"یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه".split("_"),weekdaysShort:"یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه".split("_"),weekdaysMin:"ی_د_س_چ_پ_ج_ش".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},meridiemParse:/قبل از ظهر|بعد از ظهر/,isPM:function(a){return/بعد از ظهر/.test(a)},meridiem:function(a,b,c){return 12>a?"قبل از ظهر":"بعد از ظهر"},calendar:{sameDay:"[امروز ساعت] LT",nextDay:"[فردا ساعت] LT",nextWeek:"dddd [ساعت] LT",lastDay:"[دیروز ساعت] LT",lastWeek:"dddd [پیش] [ساعت] LT",sameElse:"L"},relativeTime:{future:"در %s",past:"%s پیش",s:"چندین ثانیه",m:"یک دقیقه",mm:"%d دقیقه",h:"یک ساعت",hh:"%d ساعت",d:"یک روز",dd:"%d روز",M:"یک ماه",MM:"%d ماه",y:"یک سال",yy:"%d سال"},preparse:function(a){return a.replace(/[۰-۹]/g,function(a){return Nf[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return Mf[a]}).replace(/,/g,"،")},ordinalParse:/\d{1,2}م/,ordinal:"%dم",week:{dow:6,doy:12}}),"nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän".split(" ")),Pf=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",Of[7],Of[8],Of[9]],Qf=(uf.defineLocale("fi",{months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"su_ma_ti_ke_to_pe_la".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD.MM.YYYY",LL:"Do MMMM[ta] YYYY",LLL:"Do MMMM[ta] YYYY, [klo] HH.mm",LLLL:"dddd, Do MMMM[ta] YYYY, [klo] HH.mm",l:"D.M.YYYY",ll:"Do MMM YYYY",lll:"Do MMM YYYY, [klo] HH.mm",llll:"ddd, Do MMM YYYY, [klo] HH.mm"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:Wc,m:Wc,mm:Wc,h:Wc,hh:Wc,d:Wc,dd:Wc,M:Wc,MM:Wc,y:Wc,yy:Wc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("fo",{months:"januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"),weekdaysShort:"sun_mán_týs_mik_hós_frí_ley".split("_"),weekdaysMin:"su_má_tý_mi_hó_fr_le".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D. MMMM, YYYY HH:mm"},calendar:{sameDay:"[Í dag kl.] LT",nextDay:"[Í morgin kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[Í gjár kl.] LT",lastWeek:"[síðstu] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"um %s",past:"%s síðani",s:"fá sekund",m:"ein minutt",mm:"%d minuttir",h:"ein tími",hh:"%d tímar",d:"ein dagur",dd:"%d dagar",M:"ein mánaði",MM:"%d mánaðir",y:"eitt ár",yy:"%d ár"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("fr-ca",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},ordinalParse:/\d{1,2}(er|e)/,ordinal:function(a){return a+(1===a?"er":"e")}}),uf.defineLocale("fr",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"un an",yy:"%d ans"},ordinalParse:/\d{1,2}(er|)/,ordinal:function(a){return a+(1===a?"er":"")},week:{dow:1,doy:4}}),"jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.".split("_")),Rf="jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),Sf=(uf.defineLocale("fy",{months:"jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber".split("_"),monthsShort:function(a,b){return/-MMM-/.test(b)?Rf[a.month()]:Qf[a.month()]},weekdays:"snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon".split("_"),weekdaysShort:"si._mo._ti._wo._to._fr._so.".split("_"),weekdaysMin:"Si_Mo_Ti_Wo_To_Fr_So".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[hjoed om] LT",nextDay:"[moarn om] LT",nextWeek:"dddd [om] LT",lastDay:"[juster om] LT",lastWeek:"[ôfrûne] dddd [om] LT",sameElse:"L"},relativeTime:{future:"oer %s",past:"%s lyn",s:"in pear sekonden",m:"ien minút",mm:"%d minuten",h:"ien oere",hh:"%d oeren",d:"ien dei",dd:"%d dagen",M:"ien moanne",MM:"%d moannen",y:"ien jier",yy:"%d jierren"},ordinalParse:/\d{1,2}(ste|de)/,ordinal:function(a){return a+(1===a||8===a||a>=20?"ste":"de")},week:{dow:1,doy:4}}),uf.defineLocale("gl",{months:"Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro".split("_"),monthsShort:"Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"),weekdays:"Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd D MMMM YYYY H:mm"},calendar:{sameDay:function(){return"[hoxe "+(1!==this.hours()?"ás":"á")+"] LT"},nextDay:function(){return"[mañá "+(1!==this.hours()?"ás":"á")+"] LT"},nextWeek:function(){return"dddd ["+(1!==this.hours()?"ás":"a")+"] LT"},lastDay:function(){return"[onte "+(1!==this.hours()?"á":"a")+"] LT"},lastWeek:function(){return"[o] dddd [pasado "+(1!==this.hours()?"ás":"a")+"] LT"},sameElse:"L"},relativeTime:{future:function(a){return"uns segundos"===a?"nuns segundos":"en "+a},past:"hai %s",s:"uns segundos",m:"un minuto",mm:"%d minutos",h:"unha hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un ano",yy:"%d anos"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:7}}),uf.defineLocale("he",{months:"ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"),monthsShort:"ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"),weekdays:"ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"),weekdaysShort:"א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"),weekdaysMin:"א_ב_ג_ד_ה_ו_ש".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [ב]MMMM YYYY",LLL:"D [ב]MMMM YYYY HH:mm",LLLL:"dddd, D [ב]MMMM YYYY HH:mm",l:"D/M/YYYY",ll:"D MMM YYYY",lll:"D MMM YYYY HH:mm",llll:"ddd, D MMM YYYY HH:mm"},calendar:{sameDay:"[היום ב־]LT",nextDay:"[מחר ב־]LT",nextWeek:"dddd [בשעה] LT",lastDay:"[אתמול ב־]LT",lastWeek:"[ביום] dddd [האחרון בשעה] LT",sameElse:"L"},relativeTime:{future:"בעוד %s",past:"לפני %s",s:"מספר שניות",m:"דקה",mm:"%d דקות",h:"שעה",hh:function(a){return 2===a?"שעתיים":a+" שעות"},d:"יום",dd:function(a){return 2===a?"יומיים":a+" ימים"},M:"חודש",MM:function(a){return 2===a?"חודשיים":a+" חודשים"},y:"שנה",yy:function(a){return 2===a?"שנתיים":a%10===0&&10!==a?a+" שנה":a+" שנים"}}}),{1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"}),Tf={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"},Uf=(uf.defineLocale("hi",{months:"जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर".split("_"),monthsShort:"जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.".split("_"),weekdays:"रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm बजे",LTS:"A h:mm:ss बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm बजे",LLLL:"dddd, D MMMM YYYY, A h:mm बजे"},calendar:{sameDay:"[आज] LT",nextDay:"[कल] LT",nextWeek:"dddd, LT",lastDay:"[कल] LT",lastWeek:"[पिछले] dddd, LT",sameElse:"L"},relativeTime:{future:"%s में",past:"%s पहले",s:"कुछ ही क्षण",m:"एक मिनट",mm:"%d मिनट",h:"एक घंटा",hh:"%d घंटे",d:"एक दिन",dd:"%d दिन",M:"एक महीने",MM:"%d महीने",y:"एक वर्ष",yy:"%d वर्ष"},preparse:function(a){return a.replace(/[१२३४५६७८९०]/g,function(a){return Tf[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Sf[a]})},meridiemParse:/रात|सुबह|दोपहर|शाम/,meridiemHour:function(a,b){return 12===a&&(a=0),"रात"===b?4>a?a:a+12:"सुबह"===b?a:"दोपहर"===b?a>=10?a:a+12:"शाम"===b?a+12:void 0},meridiem:function(a,b,c){return 4>a?"रात":10>a?"सुबह":17>a?"दोपहर":20>a?"शाम":"रात"},week:{dow:0,doy:6}}),uf.defineLocale("hr",{months:"siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_"),monthsShort:"sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"),weekdays:"nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"),weekdaysShort:"ned._pon._uto._sri._čet._pet._sub.".split("_"),weekdaysMin:"ne_po_ut_sr_če_pe_su".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[jučer u] LT",lastWeek:function(){switch(this.day()){case 0:case 3:return"[prošlu] dddd [u] LT";case 6:return"[prošle] [subote] [u] LT";case 1:case 2:case 4:case 5:return"[prošli] dddd [u] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"par sekundi",m:Yc,mm:Yc,h:Yc,hh:Yc,d:"dan",dd:Yc,M:"mjesec",MM:Yc,y:"godinu",yy:Yc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),"vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton".split(" ")),Vf=(uf.defineLocale("hu",{months:"január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"),monthsShort:"jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"),weekdays:"vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"),weekdaysShort:"vas_hét_kedd_sze_csüt_pén_szo".split("_"),weekdaysMin:"v_h_k_sze_cs_p_szo".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"YYYY.MM.DD.",LL:"YYYY. MMMM D.",LLL:"YYYY. MMMM D. H:mm",LLLL:"YYYY. MMMM D., dddd H:mm"},meridiemParse:/de|du/i,isPM:function(a){return"u"===a.charAt(1).toLowerCase()},meridiem:function(a,b,c){return 12>a?c===!0?"de":"DE":c===!0?"du":"DU"},calendar:{sameDay:"[ma] LT[-kor]",nextDay:"[holnap] LT[-kor]",nextWeek:function(){return $c.call(this,!0)},lastDay:"[tegnap] LT[-kor]",lastWeek:function(){return $c.call(this,!1)},sameElse:"L"},relativeTime:{future:"%s múlva",past:"%s",s:Zc,m:Zc,mm:Zc,h:Zc,hh:Zc,d:Zc,dd:Zc,M:Zc,MM:Zc,y:Zc,yy:Zc},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),uf.defineLocale("hy-am",{months:_c,monthsShort:ad,weekdays:bd,weekdaysShort:"կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"),weekdaysMin:"կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY թ.",LLL:"D MMMM YYYY թ., HH:mm",LLLL:"dddd, D MMMM YYYY թ., HH:mm"},calendar:{sameDay:"[այսօր] LT",nextDay:"[վաղը] LT",lastDay:"[երեկ] LT",nextWeek:function(){return"dddd [օրը ժամը] LT"},lastWeek:function(){return"[անցած] dddd [օրը ժամը] LT"},sameElse:"L"},relativeTime:{future:"%s հետո",past:"%s առաջ",s:"մի քանի վայրկյան",m:"րոպե",mm:"%d րոպե",h:"ժամ",hh:"%d ժամ",d:"օր",dd:"%d օր",M:"ամիս",MM:"%d ամիս",y:"տարի",yy:"%d տարի"},meridiemParse:/գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,isPM:function(a){return/^(ցերեկվա|երեկոյան)$/.test(a)},meridiem:function(a){return 4>a?"գիշերվա":12>a?"առավոտվա":17>a?"ցերեկվա":"երեկոյան"},ordinalParse:/\d{1,2}|\d{1,2}-(ին|րդ)/,ordinal:function(a,b){switch(b){case"DDD":case"w":case"W":case"DDDo":return 1===a?a+"-ին":a+"-րդ";default:return a}},week:{dow:1,doy:7}}),uf.defineLocale("id",{months:"Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"),weekdays:"Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"),weekdaysShort:"Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"),weekdaysMin:"Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|siang|sore|malam/,meridiemHour:function(a,b){return 12===a&&(a=0),"pagi"===b?a:"siang"===b?a>=11?a:a+12:"sore"===b||"malam"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"pagi":15>a?"siang":19>a?"sore":"malam"},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Besok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kemarin pukul] LT",lastWeek:"dddd [lalu pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lalu",s:"beberapa detik",m:"semenit",mm:"%d menit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}}),uf.defineLocale("is",{months:"janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"),monthsShort:"jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"),weekdays:"sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"),weekdaysShort:"sun_mán_þri_mið_fim_fös_lau".split("_"),weekdaysMin:"Su_Má_Þr_Mi_Fi_Fö_La".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] H:mm",LLLL:"dddd, D. MMMM YYYY [kl.] H:mm"},calendar:{sameDay:"[í dag kl.] LT",nextDay:"[á morgun kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[í gær kl.] LT",lastWeek:"[síðasta] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"eftir %s",past:"fyrir %s síðan",s:dd,m:dd,mm:dd,h:"klukkustund",hh:dd,d:dd,dd:dd,M:dd,MM:dd,y:dd,yy:dd},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("it",{months:"gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre".split("_"),monthsShort:"gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic".split("_"),weekdays:"Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"D_L_Ma_Me_G_V_S".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:function(){switch(this.day()){case 0:return"[la scorsa] dddd [alle] LT";default:return"[lo scorso] dddd [alle] LT"}},sameElse:"L"},relativeTime:{future:function(a){return(/^[0-9].+$/.test(a)?"tra":"in")+" "+a},past:"%s fa",s:"alcuni secondi",m:"un minuto",mm:"%d minuti",h:"un'ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}}),uf.defineLocale("ja",{months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"Ah時m分",LTS:"Ah時m分s秒",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah時m分",LLLL:"YYYY年M月D日Ah時m分 dddd"},meridiemParse:/午前|午後/i,isPM:function(a){return"午後"===a},meridiem:function(a,b,c){return 12>a?"午前":"午後"},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"}}),uf.defineLocale("jv",{months:"Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des".split("_"),weekdays:"Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu".split("_"),weekdaysShort:"Min_Sen_Sel_Reb_Kem_Jem_Sep".split("_"),weekdaysMin:"Mg_Sn_Sl_Rb_Km_Jm_Sp".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/enjing|siyang|sonten|ndalu/,meridiemHour:function(a,b){return 12===a&&(a=0),"enjing"===b?a:"siyang"===b?a>=11?a:a+12:"sonten"===b||"ndalu"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"enjing":15>a?"siyang":19>a?"sonten":"ndalu"},calendar:{sameDay:"[Dinten puniko pukul] LT",nextDay:"[Mbenjang pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kala wingi pukul] LT",lastWeek:"dddd [kepengker pukul] LT",sameElse:"L"},relativeTime:{future:"wonten ing %s",past:"%s ingkang kepengker",s:"sawetawis detik",m:"setunggal menit",mm:"%d menit",h:"setunggal jam",hh:"%d jam",d:"sedinten",dd:"%d dinten",M:"sewulan",MM:"%d wulan",y:"setaun",yy:"%d taun"},week:{dow:1,doy:7}}),uf.defineLocale("ka",{months:ed,monthsShort:"იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"),weekdays:fd,weekdaysShort:"კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"),weekdaysMin:"კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"),longDateFormat:{LT:"h:mm A",LTS:"h:mm:ss A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd, D MMMM YYYY h:mm A"},calendar:{sameDay:"[დღეს] LT[-ზე]",nextDay:"[ხვალ] LT[-ზე]",lastDay:"[გუშინ] LT[-ზე]",nextWeek:"[შემდეგ] dddd LT[-ზე]",lastWeek:"[წინა] dddd LT-ზე",sameElse:"L"},relativeTime:{future:function(a){return/(წამი|წუთი|საათი|წელი)/.test(a)?a.replace(/ი$/,"ში"):a+"ში"},past:function(a){return/(წამი|წუთი|საათი|დღე|თვე)/.test(a)?a.replace(/(ი|ე)$/,"ის წინ"):/წელი/.test(a)?a.replace(/წელი$/,"წლის წინ"):void 0},s:"რამდენიმე წამი",m:"წუთი",mm:"%d წუთი",h:"საათი",hh:"%d საათი",d:"დღე",dd:"%d დღე",M:"თვე",MM:"%d თვე",y:"წელი",yy:"%d წელი"},ordinalParse:/0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/,ordinal:function(a){return 0===a?a:1===a?a+"-ლი":20>a||100>=a&&a%20===0||a%100===0?"მე-"+a:a+"-ე"},week:{dow:1,doy:7}}),uf.defineLocale("km",{months:"មករា_កុម្ភៈ_មិនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ".split("_"),monthsShort:"មករា_កុម្ភៈ_មិនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ".split("_"),weekdays:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),weekdaysShort:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),weekdaysMin:"អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[ថ្ងៃនៈ ម៉ោង] LT",nextDay:"[ស្អែក ម៉ោង] LT",nextWeek:"dddd [ម៉ោង] LT",lastDay:"[ម្សិលមិញ ម៉ោង] LT",lastWeek:"dddd [សប្តាហ៍មុន] [ម៉ោង] LT",sameElse:"L"},relativeTime:{future:"%sទៀត",past:"%sមុន",s:"ប៉ុន្មានវិនាទី",m:"មួយនាទី",mm:"%d នាទី",h:"មួយម៉ោង",hh:"%d ម៉ោង",d:"មួយថ្ងៃ",dd:"%d ថ្ងៃ",M:"មួយខែ",MM:"%d ខែ",y:"មួយឆ្នាំ",yy:"%d ឆ្នាំ"},week:{dow:1,doy:4}}),uf.defineLocale("ko",{months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h시 m분",LTS:"A h시 m분 s초",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 A h시 m분",LLLL:"YYYY년 MMMM D일 dddd A h시 m분"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇초",ss:"%d초",m:"일분",mm:"%d분",h:"한시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한달",MM:"%d달",y:"일년",yy:"%d년"},ordinalParse:/\d{1,2}일/,ordinal:"%d일",meridiemParse:/오전|오후/,isPM:function(a){return"오후"===a},meridiem:function(a,b,c){return 12>a?"오전":"오후"}}),uf.defineLocale("lb",{months:"Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg".split("_"),weekdaysShort:"So._Mé._Dë._Më._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mé_Dë_Më_Do_Fr_Sa".split("_"),longDateFormat:{LT:"H:mm [Auer]",LTS:"H:mm:ss [Auer]",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm [Auer]",LLLL:"dddd, D. MMMM YYYY H:mm [Auer]"},calendar:{sameDay:"[Haut um] LT",sameElse:"L",nextDay:"[Muer um] LT",nextWeek:"dddd [um] LT",lastDay:"[Gëschter um] LT",lastWeek:function(){switch(this.day()){case 2:case 4:return"[Leschten] dddd [um] LT";default:return"[Leschte] dddd [um] LT"}}},relativeTime:{future:hd,past:id,s:"e puer Sekonnen",m:gd,mm:"%d Minutten",h:gd,hh:"%d Stonnen",d:gd,dd:"%d Deeg",M:gd,MM:"%d Méint",y:gd,yy:"%d Joer"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{m:"minutė_minutės_minutę",mm:"minutės_minučių_minutes",h:"valanda_valandos_valandą",hh:"valandos_valandų_valandas",d:"diena_dienos_dieną",dd:"dienos_dienų_dienas",M:"mėnuo_mėnesio_mėnesį",MM:"mėnesiai_mėnesių_mėnesius",y:"metai_metų_metus",yy:"metai_metų_metus"}),Wf="sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis".split("_"),Xf=(uf.defineLocale("lt",{months:ld,monthsShort:"sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"),weekdays:qd,weekdaysShort:"Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"),weekdaysMin:"S_P_A_T_K_Pn_Š".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"YYYY [m.] MMMM D [d.]",LLL:"YYYY [m.] MMMM D [d.], HH:mm [val.]",LLLL:"YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]",l:"YYYY-MM-DD",ll:"YYYY [m.] MMMM D [d.]",lll:"YYYY [m.] MMMM D [d.], HH:mm [val.]",llll:"YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]"},calendar:{sameDay:"[Šiandien] LT",nextDay:"[Rytoj] LT",nextWeek:"dddd LT",lastDay:"[Vakar] LT",lastWeek:"[Praėjusį] dddd LT",sameElse:"L"},relativeTime:{future:"po %s",past:"prieš %s",s:kd,m:md,mm:pd,h:md,hh:pd,d:md,dd:pd,M:md,MM:pd,y:md,yy:pd},ordinalParse:/\d{1,2}-oji/,ordinal:function(a){return a+"-oji"},week:{dow:1,doy:4}}),{m:"minūtes_minūtēm_minūte_minūtes".split("_"),mm:"minūtes_minūtēm_minūte_minūtes".split("_"),h:"stundas_stundām_stunda_stundas".split("_"),hh:"stundas_stundām_stunda_stundas".split("_"),d:"dienas_dienām_diena_dienas".split("_"),dd:"dienas_dienām_diena_dienas".split("_"),M:"mēneša_mēnešiem_mēnesis_mēneši".split("_"),MM:"mēneša_mēnešiem_mēnesis_mēneši".split("_"),y:"gada_gadiem_gads_gadi".split("_"),yy:"gada_gadiem_gads_gadi".split("_")}),Yf=(uf.defineLocale("lv",{months:"janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"),monthsShort:"jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"),weekdays:"svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"),weekdaysShort:"Sv_P_O_T_C_Pk_S".split("_"),weekdaysMin:"Sv_P_O_T_C_Pk_S".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY.",LL:"YYYY. [gada] D. MMMM",LLL:"YYYY. [gada] D. MMMM, HH:mm",LLLL:"YYYY. [gada] D. MMMM, dddd, HH:mm"},calendar:{sameDay:"[Šodien pulksten] LT",nextDay:"[Rīt pulksten] LT",nextWeek:"dddd [pulksten] LT",lastDay:"[Vakar pulksten] LT",lastWeek:"[Pagājušā] dddd [pulksten] LT",sameElse:"L"},relativeTime:{future:"pēc %s",past:"pirms %s",s:ud,m:td,mm:sd,h:td,hh:sd,d:td,dd:sd,M:td,MM:sd,y:td,yy:sd},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{words:{m:["jedan minut","jednog minuta"],mm:["minut","minuta","minuta"],h:["jedan sat","jednog sata"],hh:["sat","sata","sati"],dd:["dan","dana","dana"],MM:["mjesec","mjeseca","mjeseci"],yy:["godina","godine","godina"]},correctGrammaticalCase:function(a,b){return 1===a?b[0]:a>=2&&4>=a?b[1]:b[2]},translate:function(a,b,c){var d=Yf.words[c];return 1===c.length?b?d[0]:d[1]:a+" "+Yf.correctGrammaticalCase(a,d)}}),Zf=(uf.defineLocale("me",{months:["januar","februar","mart","april","maj","jun","jul","avgust","septembar","oktobar","novembar","decembar"],monthsShort:["jan.","feb.","mar.","apr.","maj","jun","jul","avg.","sep.","okt.","nov.","dec."],weekdays:["nedjelja","ponedjeljak","utorak","srijeda","četvrtak","petak","subota"],weekdaysShort:["ned.","pon.","uto.","sri.","čet.","pet.","sub."],weekdaysMin:["ne","po","ut","sr","če","pe","su"],longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sjutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedjelju] [u] LT";case 3:return"[u] [srijedu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[juče u] LT",lastWeek:function(){var a=["[prošle] [nedjelje] [u] LT","[prošlog] [ponedjeljka] [u] LT","[prošlog] [utorka] [u] LT","[prošle] [srijede] [u] LT","[prošlog] [četvrtka] [u] LT","[prošlog] [petka] [u] LT","[prošle] [subote] [u] LT"];return a[this.day()]},sameElse:"L"},relativeTime:{future:"za %s",past:"prije %s",s:"nekoliko sekundi",m:Yf.translate,mm:Yf.translate,h:Yf.translate,hh:Yf.translate,d:"dan",dd:Yf.translate,M:"mjesec",MM:Yf.translate,y:"godinu",yy:Yf.translate},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),uf.defineLocale("mk",{months:"јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"),monthsShort:"јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"),weekdays:"недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"),weekdaysShort:"нед_пон_вто_сре_чет_пет_саб".split("_"),weekdaysMin:"нe_пo_вт_ср_че_пе_сa".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"D.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[Денес во] LT",nextDay:"[Утре во] LT",nextWeek:"dddd [во] LT",lastDay:"[Вчера во] LT",lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return"[Во изминатата] dddd [во] LT";case 1:case 2:case 4:case 5:return"[Во изминатиот] dddd [во] LT"}},sameElse:"L"},relativeTime:{future:"после %s",past:"пред %s",s:"неколку секунди",m:"минута",mm:"%d минути",h:"час",hh:"%d часа",d:"ден",dd:"%d дена",M:"месец",MM:"%d месеци",y:"година",yy:"%d години"},ordinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(a){var b=a%10,c=a%100;return 0===a?a+"-ев":0===c?a+"-ен":c>10&&20>c?a+"-ти":1===b?a+"-ви":2===b?a+"-ри":7===b||8===b?a+"-ми":a+"-ти"},week:{dow:1,doy:7}}),uf.defineLocale("ml",{months:"ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ".split("_"),monthsShort:"ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.".split("_"),weekdays:"ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച".split("_"),weekdaysShort:"ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി".split("_"),weekdaysMin:"ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ".split("_"),longDateFormat:{LT:"A h:mm -നു",LTS:"A h:mm:ss -നു",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm -നു",LLLL:"dddd, D MMMM YYYY, A h:mm -നു"},calendar:{sameDay:"[ഇന്ന്] LT",nextDay:"[നാളെ] LT",nextWeek:"dddd, LT",lastDay:"[ഇന്നലെ] LT",lastWeek:"[കഴിഞ്ഞ] dddd, LT",sameElse:"L"},relativeTime:{future:"%s കഴിഞ്ഞ്",past:"%s മുൻപ്",s:"അൽപ നിമിഷങ്ങൾ",m:"ഒരു മിനിറ്റ്",mm:"%d മിനിറ്റ്",h:"ഒരു മണിക്കൂർ",hh:"%d മണിക്കൂർ",d:"ഒരു ദിവസം",dd:"%d ദിവസം",M:"ഒരു മാസം",MM:"%d മാസം",y:"ഒരു വർഷം",yy:"%d വർഷം"},meridiemParse:/രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i,isPM:function(a){return/^(ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി)$/.test(a)},meridiem:function(a,b,c){return 4>a?"രാത്രി":12>a?"രാവിലെ":17>a?"ഉച്ച കഴിഞ്ഞ്":20>a?"വൈകുന്നേരം":"രാത്രി"}}),{1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"}),$f={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"},_f=(uf.defineLocale("mr",{months:"जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर".split("_"),monthsShort:"जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.".split("_"),weekdays:"रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm वाजता",LTS:"A h:mm:ss वाजता",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, A h:mm वाजता",LLLL:"dddd, D MMMM YYYY, A h:mm वाजता"},calendar:{sameDay:"[आज] LT",nextDay:"[उद्या] LT",nextWeek:"dddd, LT",lastDay:"[काल] LT",lastWeek:"[मागील] dddd, LT",sameElse:"L"},relativeTime:{future:"%s नंतर",past:"%s पूर्वी",s:"सेकंद",m:"एक मिनिट",mm:"%d मिनिटे",h:"एक तास",hh:"%d तास",d:"एक दिवस",dd:"%d दिवस",M:"एक महिना",MM:"%d महिने",y:"एक वर्ष",yy:"%d वर्षे"},preparse:function(a){return a.replace(/[१२३४५६७८९०]/g,function(a){return $f[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return Zf[a]})},meridiemParse:/रात्री|सकाळी|दुपारी|सायंकाळी/,meridiemHour:function(a,b){return 12===a&&(a=0),"रात्री"===b?4>a?a:a+12:"सकाळी"===b?a:"दुपारी"===b?a>=10?a:a+12:"सायंकाळी"===b?a+12:void 0},meridiem:function(a,b,c){return 4>a?"रात्री":10>a?"सकाळी":17>a?"दुपारी":20>a?"सायंकाळी":"रात्री"},week:{dow:0,doy:6}}),uf.defineLocale("ms-my",{months:"Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"),monthsShort:"Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"),weekdays:"Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"),weekdaysShort:"Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"),weekdaysMin:"Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(a,b){return 12===a&&(a=0),"pagi"===b?a:"tengahari"===b?a>=11?a:a+12:"petang"===b||"malam"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"pagi":15>a?"tengahari":19>a?"petang":"malam"},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Esok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kelmarin pukul] LT",
lastWeek:"dddd [lepas pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lepas",s:"beberapa saat",m:"seminit",mm:"%d minit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}}),uf.defineLocale("ms",{months:"Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"),monthsShort:"Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"),weekdays:"Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"),weekdaysShort:"Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"),weekdaysMin:"Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"),longDateFormat:{LT:"HH.mm",LTS:"HH.mm.ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY [pukul] HH.mm",LLLL:"dddd, D MMMM YYYY [pukul] HH.mm"},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(a,b){return 12===a&&(a=0),"pagi"===b?a:"tengahari"===b?a>=11?a:a+12:"petang"===b||"malam"===b?a+12:void 0},meridiem:function(a,b,c){return 11>a?"pagi":15>a?"tengahari":19>a?"petang":"malam"},calendar:{sameDay:"[Hari ini pukul] LT",nextDay:"[Esok pukul] LT",nextWeek:"dddd [pukul] LT",lastDay:"[Kelmarin pukul] LT",lastWeek:"dddd [lepas pukul] LT",sameElse:"L"},relativeTime:{future:"dalam %s",past:"%s yang lepas",s:"beberapa saat",m:"seminit",mm:"%d minit",h:"sejam",hh:"%d jam",d:"sehari",dd:"%d hari",M:"sebulan",MM:"%d bulan",y:"setahun",yy:"%d tahun"},week:{dow:1,doy:7}}),{1:"၁",2:"၂",3:"၃",4:"၄",5:"၅",6:"၆",7:"၇",8:"၈",9:"၉",0:"၀"}),ag={"၁":"1","၂":"2","၃":"3","၄":"4","၅":"5","၆":"6","၇":"7","၈":"8","၉":"9","၀":"0"},bg=(uf.defineLocale("my",{months:"ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ".split("_"),monthsShort:"ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ".split("_"),weekdays:"တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ".split("_"),weekdaysShort:"နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ".split("_"),weekdaysMin:"နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[ယနေ.] LT [မှာ]",nextDay:"[မနက်ဖြန်] LT [မှာ]",nextWeek:"dddd LT [မှာ]",lastDay:"[မနေ.က] LT [မှာ]",lastWeek:"[ပြီးခဲ့သော] dddd LT [မှာ]",sameElse:"L"},relativeTime:{future:"လာမည့် %s မှာ",past:"လွန်ခဲ့သော %s က",s:"စက္ကန်.အနည်းငယ်",m:"တစ်မိနစ်",mm:"%d မိနစ်",h:"တစ်နာရီ",hh:"%d နာရီ",d:"တစ်ရက်",dd:"%d ရက်",M:"တစ်လ",MM:"%d လ",y:"တစ်နှစ်",yy:"%d နှစ်"},preparse:function(a){return a.replace(/[၁၂၃၄၅၆၇၈၉၀]/g,function(a){return ag[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return _f[a]})},week:{dow:1,doy:4}}),uf.defineLocale("nb",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tirs_ons_tors_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"H.mm",LTS:"H.mm.ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] H.mm",LLLL:"dddd D. MMMM YYYY [kl.] H.mm"},calendar:{sameDay:"[i dag kl.] LT",nextDay:"[i morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[i går kl.] LT",lastWeek:"[forrige] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"}),cg={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"},dg=(uf.defineLocale("ne",{months:"जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर".split("_"),monthsShort:"जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.".split("_"),weekdays:"आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार".split("_"),weekdaysShort:"आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.".split("_"),weekdaysMin:"आइ._सो._मङ्_बु._बि._शु._श.".split("_"),longDateFormat:{LT:"Aको h:mm बजे",LTS:"Aको h:mm:ss बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, Aको h:mm बजे",LLLL:"dddd, D MMMM YYYY, Aको h:mm बजे"},preparse:function(a){return a.replace(/[१२३४५६७८९०]/g,function(a){return cg[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return bg[a]})},meridiemParse:/राती|बिहान|दिउँसो|बेलुका|साँझ|राती/,meridiemHour:function(a,b){return 12===a&&(a=0),"राती"===b?3>a?a:a+12:"बिहान"===b?a:"दिउँसो"===b?a>=10?a:a+12:"बेलुका"===b||"साँझ"===b?a+12:void 0},meridiem:function(a,b,c){return 3>a?"राती":10>a?"बिहान":15>a?"दिउँसो":18>a?"बेलुका":20>a?"साँझ":"राती"},calendar:{sameDay:"[आज] LT",nextDay:"[भोली] LT",nextWeek:"[आउँदो] dddd[,] LT",lastDay:"[हिजो] LT",lastWeek:"[गएको] dddd[,] LT",sameElse:"L"},relativeTime:{future:"%sमा",past:"%s अगाडी",s:"केही समय",m:"एक मिनेट",mm:"%d मिनेट",h:"एक घण्टा",hh:"%d घण्टा",d:"एक दिन",dd:"%d दिन",M:"एक महिना",MM:"%d महिना",y:"एक बर्ष",yy:"%d बर्ष"},week:{dow:1,doy:7}}),"jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_")),eg="jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"),fg=(uf.defineLocale("nl",{months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:function(a,b){return/-MMM-/.test(b)?eg[a.month()]:dg[a.month()]},weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[vandaag om] LT",nextDay:"[morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},ordinalParse:/\d{1,2}(ste|de)/,ordinal:function(a){return a+(1===a||8===a||a>=20?"ste":"de")},week:{dow:1,doy:4}}),uf.defineLocale("nn",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"),weekdaysShort:"sun_mån_tys_ons_tor_fre_lau".split("_"),weekdaysMin:"su_må_ty_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[I dag klokka] LT",nextDay:"[I morgon klokka] LT",nextWeek:"dddd [klokka] LT",lastDay:"[I går klokka] LT",lastWeek:"[Føregåande] dddd [klokka] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s sidan",s:"nokre sekund",m:"eit minutt",mm:"%d minutt",h:"ein time",hh:"%d timar",d:"ein dag",dd:"%d dagar",M:"ein månad",MM:"%d månader",y:"eit år",yy:"%d år"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),"styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_")),gg="stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_"),hg=(uf.defineLocale("pl",{months:function(a,b){return""===b?"("+gg[a.month()]+"|"+fg[a.month()]+")":/D MMMM/.test(b)?gg[a.month()]:fg[a.month()]},monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"nie_pon_wt_śr_czw_pt_sb".split("_"),weekdaysMin:"N_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:"[W] dddd [o] LT",lastDay:"[Wczoraj o] LT",lastWeek:function(){switch(this.day()){case 0:return"[W zeszłą niedzielę o] LT";case 3:return"[W zeszłą środę o] LT";case 6:return"[W zeszłą sobotę o] LT";default:return"[W zeszły] dddd [o] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:wd,mm:wd,h:wd,hh:wd,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:wd,y:"rok",yy:wd},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("pt-br",{months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY [às] HH:mm",LLLL:"dddd, D [de] MMMM [de] YYYY [às] HH:mm"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return 0===this.day()||6===this.day()?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"poucos segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinalParse:/\d{1,2}º/,ordinal:"%dº"}),uf.defineLocale("pt",{months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D [de] MMMM [de] YYYY",LLL:"D [de] MMMM [de] YYYY HH:mm",LLLL:"dddd, D [de] MMMM [de] YYYY HH:mm"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return 0===this.day()||6===this.day()?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"há %s",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}}),uf.defineLocale("ro",{months:"ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie".split("_"),monthsShort:"ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.".split("_"),weekdays:"duminică_luni_marți_miercuri_joi_vineri_sâmbătă".split("_"),weekdaysShort:"Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"),weekdaysMin:"Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY H:mm",LLLL:"dddd, D MMMM YYYY H:mm"},calendar:{sameDay:"[azi la] LT",nextDay:"[mâine la] LT",nextWeek:"dddd [la] LT",lastDay:"[ieri la] LT",lastWeek:"[fosta] dddd [la] LT",sameElse:"L"},relativeTime:{future:"peste %s",past:"%s în urmă",s:"câteva secunde",m:"un minut",mm:xd,h:"o oră",hh:xd,d:"o zi",dd:xd,M:"o lună",MM:xd,y:"un an",yy:xd},week:{dow:1,doy:7}}),uf.defineLocale("ru",{months:Ad,monthsShort:Bd,weekdays:Cd,weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[й|я]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i],longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(){return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT"},lastWeek:function(a){if(a.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:zd,mm:zd,h:"час",hh:zd,d:"день",dd:zd,M:"месяц",MM:zd,y:"год",yy:zd},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(a){return/^(дня|вечера)$/.test(a)},meridiem:function(a,b,c){return 4>a?"ночи":12>a?"утра":17>a?"дня":"вечера"},ordinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(a,b){switch(b){case"M":case"d":case"DDD":return a+"-й";case"D":return a+"-го";case"w":case"W":return a+"-я";default:return a}},week:{dow:1,doy:7}}),uf.defineLocale("si",{months:"ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්".split("_"),monthsShort:"ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ".split("_"),weekdays:"ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා".split("_"),weekdaysShort:"ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන".split("_"),weekdaysMin:"ඉ_ස_අ_බ_බ්‍ර_සි_සෙ".split("_"),longDateFormat:{LT:"a h:mm",LTS:"a h:mm:ss",L:"YYYY/MM/DD",LL:"YYYY MMMM D",LLL:"YYYY MMMM D, a h:mm",LLLL:"YYYY MMMM D [වැනි] dddd, a h:mm:ss"},calendar:{sameDay:"[අද] LT[ට]",nextDay:"[හෙට] LT[ට]",nextWeek:"dddd LT[ට]",lastDay:"[ඊයේ] LT[ට]",lastWeek:"[පසුගිය] dddd LT[ට]",sameElse:"L"},relativeTime:{future:"%sකින්",past:"%sකට පෙර",s:"තත්පර කිහිපය",m:"මිනිත්තුව",mm:"මිනිත්තු %d",h:"පැය",hh:"පැය %d",d:"දිනය",dd:"දින %d",M:"මාසය",MM:"මාස %d",y:"වසර",yy:"වසර %d"},ordinalParse:/\d{1,2} වැනි/,ordinal:function(a){return a+" වැනි"},meridiem:function(a,b,c){return a>11?c?"ප.ව.":"පස් වරු":c?"පෙ.ව.":"පෙර වරු"}}),"január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_")),ig="jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_"),jg=(uf.defineLocale("sk",{months:hg,monthsShort:ig,monthsParse:function(a,b){var c,d=[];for(c=0;12>c;c++)d[c]=new RegExp("^"+a[c]+"$|^"+b[c]+"$","i");return d}(hg,ig),weekdays:"nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota".split("_"),weekdaysShort:"ne_po_ut_st_št_pi_so".split("_"),weekdaysMin:"ne_po_ut_st_št_pi_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd D. MMMM YYYY H:mm"},calendar:{sameDay:"[dnes o] LT",nextDay:"[zajtra o] LT",nextWeek:function(){switch(this.day()){case 0:return"[v nedeľu o] LT";case 1:case 2:return"[v] dddd [o] LT";case 3:return"[v stredu o] LT";case 4:return"[vo štvrtok o] LT";case 5:return"[v piatok o] LT";case 6:return"[v sobotu o] LT"}},lastDay:"[včera o] LT",lastWeek:function(){switch(this.day()){case 0:return"[minulú nedeľu o] LT";case 1:case 2:return"[minulý] dddd [o] LT";case 3:return"[minulú stredu o] LT";case 4:case 5:return"[minulý] dddd [o] LT";case 6:return"[minulú sobotu o] LT"}},sameElse:"L"},relativeTime:{future:"za %s",past:"pred %s",s:Ed,m:Ed,mm:Ed,h:Ed,hh:Ed,d:Ed,dd:Ed,M:Ed,MM:Ed,y:Ed,yy:Ed},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("sl",{months:"januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"),monthsShort:"jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"),weekdays:"nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"),weekdaysShort:"ned._pon._tor._sre._čet._pet._sob.".split("_"),weekdaysMin:"ne_po_to_sr_če_pe_so".split("_"),longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danes ob] LT",nextDay:"[jutri ob] LT",nextWeek:function(){switch(this.day()){case 0:return"[v] [nedeljo] [ob] LT";case 3:return"[v] [sredo] [ob] LT";case 6:return"[v] [soboto] [ob] LT";case 1:case 2:case 4:case 5:return"[v] dddd [ob] LT"}},lastDay:"[včeraj ob] LT",lastWeek:function(){switch(this.day()){case 0:return"[prejšnjo] [nedeljo] [ob] LT";case 3:return"[prejšnjo] [sredo] [ob] LT";case 6:return"[prejšnjo] [soboto] [ob] LT";case 1:case 2:case 4:case 5:return"[prejšnji] dddd [ob] LT"}},sameElse:"L"},relativeTime:{future:"čez %s",past:"pred %s",s:Fd,m:Fd,mm:Fd,h:Fd,hh:Fd,d:Fd,dd:Fd,M:Fd,MM:Fd,y:Fd,yy:Fd},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),uf.defineLocale("sq",{months:"Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"),monthsShort:"Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"),weekdays:"E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë".split("_"),weekdaysShort:"Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"),weekdaysMin:"D_H_Ma_Më_E_P_Sh".split("_"),meridiemParse:/PD|MD/,isPM:function(a){return"M"===a.charAt(0)},meridiem:function(a,b,c){return 12>a?"PD":"MD"},longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[Sot në] LT",nextDay:"[Nesër në] LT",nextWeek:"dddd [në] LT",lastDay:"[Dje në] LT",lastWeek:"dddd [e kaluar në] LT",sameElse:"L"},relativeTime:{future:"në %s",past:"%s më parë",s:"disa sekonda",m:"një minutë",mm:"%d minuta",h:"një orë",hh:"%d orë",d:"një ditë",dd:"%d ditë",M:"një muaj",MM:"%d muaj",y:"një vit",yy:"%d vite"},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),{words:{m:["један минут","једне минуте"],mm:["минут","минуте","минута"],h:["један сат","једног сата"],hh:["сат","сата","сати"],dd:["дан","дана","дана"],MM:["месец","месеца","месеци"],yy:["година","године","година"]},correctGrammaticalCase:function(a,b){return 1===a?b[0]:a>=2&&4>=a?b[1]:b[2]},translate:function(a,b,c){var d=jg.words[c];return 1===c.length?b?d[0]:d[1]:a+" "+jg.correctGrammaticalCase(a,d)}}),kg=(uf.defineLocale("sr-cyrl",{months:["јануар","фебруар","март","април","мај","јун","јул","август","септембар","октобар","новембар","децембар"],monthsShort:["јан.","феб.","мар.","апр.","мај","јун","јул","авг.","сеп.","окт.","нов.","дец."],weekdays:["недеља","понедељак","уторак","среда","четвртак","петак","субота"],weekdaysShort:["нед.","пон.","уто.","сре.","чет.","пет.","суб."],weekdaysMin:["не","по","ут","ср","че","пе","су"],longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[данас у] LT",nextDay:"[сутра у] LT",nextWeek:function(){switch(this.day()){case 0:return"[у] [недељу] [у] LT";case 3:return"[у] [среду] [у] LT";case 6:return"[у] [суботу] [у] LT";case 1:case 2:case 4:case 5:return"[у] dddd [у] LT"}},lastDay:"[јуче у] LT",lastWeek:function(){var a=["[прошле] [недеље] [у] LT","[прошлог] [понедељка] [у] LT","[прошлог] [уторка] [у] LT","[прошле] [среде] [у] LT","[прошлог] [четвртка] [у] LT","[прошлог] [петка] [у] LT","[прошле] [суботе] [у] LT"];return a[this.day()]},sameElse:"L"},relativeTime:{future:"за %s",past:"пре %s",s:"неколико секунди",m:jg.translate,mm:jg.translate,h:jg.translate,hh:jg.translate,d:"дан",dd:jg.translate,M:"месец",MM:jg.translate,y:"годину",yy:jg.translate},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),{words:{m:["jedan minut","jedne minute"],mm:["minut","minute","minuta"],h:["jedan sat","jednog sata"],hh:["sat","sata","sati"],dd:["dan","dana","dana"],MM:["mesec","meseca","meseci"],yy:["godina","godine","godina"]},correctGrammaticalCase:function(a,b){return 1===a?b[0]:a>=2&&4>=a?b[1]:b[2]},translate:function(a,b,c){var d=kg.words[c];return 1===c.length?b?d[0]:d[1]:a+" "+kg.correctGrammaticalCase(a,d)}}),lg=(uf.defineLocale("sr",{months:["januar","februar","mart","april","maj","jun","jul","avgust","septembar","oktobar","novembar","decembar"],monthsShort:["jan.","feb.","mar.","apr.","maj","jun","jul","avg.","sep.","okt.","nov.","dec."],weekdays:["nedelja","ponedeljak","utorak","sreda","četvrtak","petak","subota"],weekdaysShort:["ned.","pon.","uto.","sre.","čet.","pet.","sub."],weekdaysMin:["ne","po","ut","sr","če","pe","su"],longDateFormat:{LT:"H:mm",LTS:"H:mm:ss",L:"DD. MM. YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY H:mm",LLLL:"dddd, D. MMMM YYYY H:mm"},calendar:{sameDay:"[danas u] LT",nextDay:"[sutra u] LT",nextWeek:function(){switch(this.day()){case 0:return"[u] [nedelju] [u] LT";case 3:return"[u] [sredu] [u] LT";case 6:return"[u] [subotu] [u] LT";case 1:case 2:case 4:case 5:return"[u] dddd [u] LT"}},lastDay:"[juče u] LT",lastWeek:function(){var a=["[prošle] [nedelje] [u] LT","[prošlog] [ponedeljka] [u] LT","[prošlog] [utorka] [u] LT","[prošle] [srede] [u] LT","[prošlog] [četvrtka] [u] LT","[prošlog] [petka] [u] LT","[prošle] [subote] [u] LT"];return a[this.day()]},sameElse:"L"},relativeTime:{future:"za %s",past:"pre %s",s:"nekoliko sekundi",m:kg.translate,mm:kg.translate,h:kg.translate,hh:kg.translate,d:"dan",dd:kg.translate,M:"mesec",MM:kg.translate,y:"godinu",yy:kg.translate},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:7}}),uf.defineLocale("sv",{months:"januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),weekdaysShort:"sön_mån_tis_ons_tor_fre_lör".split("_"),weekdaysMin:"sö_må_ti_on_to_fr_lö".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[Idag] LT",nextDay:"[Imorgon] LT",lastDay:"[Igår] LT",nextWeek:"[På] dddd LT",lastWeek:"[I] dddd[s] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"för %s sedan",s:"några sekunder",m:"en minut",mm:"%d minuter",h:"en timme",hh:"%d timmar",d:"en dag",dd:"%d dagar",M:"en månad",MM:"%d månader",y:"ett år",yy:"%d år"},ordinalParse:/\d{1,2}(e|a)/,ordinal:function(a){var b=a%10,c=1===~~(a%100/10)?"e":1===b?"a":2===b?"a":"e";return a+c},week:{dow:1,doy:4}}),uf.defineLocale("ta",{months:"ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்".split("_"),monthsShort:"ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்".split("_"),weekdays:"ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை".split("_"),weekdaysShort:"ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி".split("_"),weekdaysMin:"ஞா_தி_செ_பு_வி_வெ_ச".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, HH:mm",LLLL:"dddd, D MMMM YYYY, HH:mm"},calendar:{sameDay:"[இன்று] LT",nextDay:"[நாளை] LT",nextWeek:"dddd, LT",lastDay:"[நேற்று] LT",lastWeek:"[கடந்த வாரம்] dddd, LT",sameElse:"L"},relativeTime:{future:"%s இல்",past:"%s முன்",s:"ஒரு சில விநாடிகள்",m:"ஒரு நிமிடம்",mm:"%d நிமிடங்கள்",h:"ஒரு மணி நேரம்",hh:"%d மணி நேரம்",d:"ஒரு நாள்",dd:"%d நாட்கள்",M:"ஒரு மாதம்",MM:"%d மாதங்கள்",y:"ஒரு வருடம்",yy:"%d ஆண்டுகள்"},ordinalParse:/\d{1,2}வது/,ordinal:function(a){return a+"வது"},meridiemParse:/யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,meridiem:function(a,b,c){return 2>a?" யாமம்":6>a?" வைகறை":10>a?" காலை":14>a?" நண்பகல்":18>a?" எற்பாடு":22>a?" மாலை":" யாமம்"},meridiemHour:function(a,b){return 12===a&&(a=0),"யாமம்"===b?2>a?a:a+12:"வைகறை"===b||"காலை"===b?a:"நண்பகல்"===b&&a>=10?a:a+12},week:{dow:0,doy:6}}),uf.defineLocale("th",{months:"มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"),monthsShort:"มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา".split("_"),weekdays:"อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"),weekdaysShort:"อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"),weekdaysMin:"อา._จ._อ._พ._พฤ._ศ._ส.".split("_"),longDateFormat:{LT:"H นาฬิกา m นาที",LTS:"H นาฬิกา m นาที s วินาที",L:"YYYY/MM/DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY เวลา H นาฬิกา m นาที",LLLL:"วันddddที่ D MMMM YYYY เวลา H นาฬิกา m นาที"},meridiemParse:/ก่อนเที่ยง|หลังเที่ยง/,isPM:function(a){return"หลังเที่ยง"===a},meridiem:function(a,b,c){return 12>a?"ก่อนเที่ยง":"หลังเที่ยง"},calendar:{sameDay:"[วันนี้ เวลา] LT",nextDay:"[พรุ่งนี้ เวลา] LT",nextWeek:"dddd[หน้า เวลา] LT",lastDay:"[เมื่อวานนี้ เวลา] LT",lastWeek:"[วัน]dddd[ที่แล้ว เวลา] LT",sameElse:"L"},relativeTime:{future:"อีก %s",past:"%sที่แล้ว",s:"ไม่กี่วินาที",m:"1 นาที",mm:"%d นาที",h:"1 ชั่วโมง",hh:"%d ชั่วโมง",d:"1 วัน",dd:"%d วัน",M:"1 เดือน",MM:"%d เดือน",y:"1 ปี",yy:"%d ปี"}}),uf.defineLocale("tl-ph",{months:"Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"),monthsShort:"Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"),weekdays:"Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"),weekdaysShort:"Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"),weekdaysMin:"Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"MM/D/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY HH:mm",LLLL:"dddd, MMMM DD, YYYY HH:mm"},calendar:{sameDay:"[Ngayon sa] LT",nextDay:"[Bukas sa] LT",nextWeek:"dddd [sa] LT",lastDay:"[Kahapon sa] LT",lastWeek:"dddd [huling linggo] LT",sameElse:"L"},relativeTime:{future:"sa loob ng %s",past:"%s ang nakalipas",s:"ilang segundo",m:"isang minuto",mm:"%d minuto",h:"isang oras",hh:"%d oras",d:"isang araw",dd:"%d araw",M:"isang buwan",MM:"%d buwan",y:"isang taon",yy:"%d taon"},ordinalParse:/\d{1,2}/,ordinal:function(a){return a},week:{dow:1,doy:4}}),{1:"'inci",5:"'inci",8:"'inci",70:"'inci",80:"'inci",2:"'nci",7:"'nci",20:"'nci",50:"'nci",3:"'üncü",4:"'üncü",100:"'üncü",6:"'ncı",9:"'uncu",10:"'uncu",30:"'uncu",60:"'ıncı",90:"'ıncı"}),mg=(uf.defineLocale("tr",{months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd, D MMMM YYYY HH:mm"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[haftaya] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen hafta] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},ordinalParse:/\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/,ordinal:function(a){if(0===a)return a+"'ıncı";var b=a%10,c=a%100-b,d=a>=100?100:null;return a+(lg[b]||lg[c]||lg[d])},week:{dow:1,doy:7}}),uf.defineLocale("tzl",{months:"Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar".split("_"),monthsShort:"Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec".split("_"),weekdays:"Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi".split("_"),weekdaysShort:"Súl_Lún_Mai_Már_Xhú_Vié_Sát".split("_"),weekdaysMin:"Sú_Lú_Ma_Má_Xh_Vi_Sá".split("_"),longDateFormat:{LT:"HH.mm",LTS:"LT.ss",L:"DD.MM.YYYY",LL:"D. MMMM [dallas] YYYY",LLL:"D. MMMM [dallas] YYYY LT",LLLL:"dddd, [li] D. MMMM [dallas] YYYY LT"},meridiem:function(a,b,c){return a>11?c?"d'o":"D'O":c?"d'a":"D'A"},calendar:{sameDay:"[oxhi à] LT",nextDay:"[demà à] LT",nextWeek:"dddd [à] LT",lastDay:"[ieiri à] LT",lastWeek:"[sür el] dddd [lasteu à] LT",sameElse:"L"},relativeTime:{future:"osprei %s",past:"ja%s",s:Gd,m:Gd,mm:Gd,h:Gd,hh:Gd,d:Gd,dd:Gd,M:Gd,MM:Gd,y:Gd,yy:Gd},ordinalParse:/\d{1,2}\./,ordinal:"%d.",week:{dow:1,doy:4}}),uf.defineLocale("tzm-latn",{months:"innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"),monthsShort:"innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"),weekdays:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),weekdaysShort:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),weekdaysMin:"asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[asdkh g] LT",nextDay:"[aska g] LT",nextWeek:"dddd [g] LT",lastDay:"[assant g] LT",lastWeek:"dddd [g] LT",sameElse:"L"},relativeTime:{future:"dadkh s yan %s",past:"yan %s",s:"imik",m:"minuḍ",mm:"%d minuḍ",h:"saɛa",hh:"%d tassaɛin",d:"ass",dd:"%d ossan",M:"ayowr",MM:"%d iyyirn",y:"asgas",yy:"%d isgasn"},week:{dow:6,doy:12}}),uf.defineLocale("tzm",{months:"ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"),monthsShort:"ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"),weekdays:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),weekdaysShort:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),weekdaysMin:"ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[ⴰⵙⴷⵅ ⴴ] LT",nextDay:"[ⴰⵙⴽⴰ ⴴ] LT",nextWeek:"dddd [ⴴ] LT",lastDay:"[ⴰⵚⴰⵏⵜ ⴴ] LT",lastWeek:"dddd [ⴴ] LT",sameElse:"L"},relativeTime:{future:"ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s",past:"ⵢⴰⵏ %s",s:"ⵉⵎⵉⴽ",m:"ⵎⵉⵏⵓⴺ",mm:"%d ⵎⵉⵏⵓⴺ",h:"ⵙⴰⵄⴰ",hh:"%d ⵜⴰⵙⵙⴰⵄⵉⵏ",d:"ⴰⵙⵙ",dd:"%d oⵙⵙⴰⵏ",M:"ⴰⵢoⵓⵔ",MM:"%d ⵉⵢⵢⵉⵔⵏ",y:"ⴰⵙⴳⴰⵙ",yy:"%d ⵉⵙⴳⴰⵙⵏ"},week:{dow:6,doy:12}}),uf.defineLocale("uk",{months:Jd,monthsShort:"січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"),weekdays:Kd,weekdaysShort:"нд_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"нд_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY р.",LLL:"D MMMM YYYY р., HH:mm",LLLL:"dddd, D MMMM YYYY р., HH:mm"},calendar:{sameDay:Ld("[Сьогодні "),nextDay:Ld("[Завтра "),lastDay:Ld("[Вчора "),nextWeek:Ld("[У] dddd ["),lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return Ld("[Минулої] dddd [").call(this);case 1:case 2:case 4:return Ld("[Минулого] dddd [").call(this)}},sameElse:"L"},relativeTime:{future:"за %s",past:"%s тому",s:"декілька секунд",m:Id,mm:Id,h:"годину",hh:Id,d:"день",dd:Id,M:"місяць",MM:Id,y:"рік",yy:Id},meridiemParse:/ночі|ранку|дня|вечора/,isPM:function(a){return/^(дня|вечора)$/.test(a)},meridiem:function(a,b,c){return 4>a?"ночі":12>a?"ранку":17>a?"дня":"вечора"},ordinalParse:/\d{1,2}-(й|го)/,ordinal:function(a,b){switch(b){case"M":case"d":case"DDD":case"w":case"W":return a+"-й";case"D":return a+"-го";default:return a}},week:{dow:1,doy:7}}),uf.defineLocale("uz",{months:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),monthsShort:"янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),weekdays:"Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"),weekdaysShort:"Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"),weekdaysMin:"Як_Ду_Се_Чо_Па_Жу_Ша".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"D MMMM YYYY, dddd HH:mm"},calendar:{sameDay:"[Бугун соат] LT [да]",nextDay:"[Эртага] LT [да]",nextWeek:"dddd [куни соат] LT [да]",lastDay:"[Кеча соат] LT [да]",lastWeek:"[Утган] dddd [куни соат] LT [да]",sameElse:"L"},relativeTime:{future:"Якин %s ичида",past:"Бир неча %s олдин",s:"фурсат",m:"бир дакика",mm:"%d дакика",h:"бир соат",hh:"%d соат",d:"бир кун",dd:"%d кун",M:"бир ой",MM:"%d ой",y:"бир йил",yy:"%d йил"},week:{dow:1,doy:7}}),uf.defineLocale("vi",{months:"tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"),monthsShort:"Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"),weekdays:"chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"),weekdaysShort:"CN_T2_T3_T4_T5_T6_T7".split("_"),weekdaysMin:"CN_T2_T3_T4_T5_T6_T7".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM [năm] YYYY",LLL:"D MMMM [năm] YYYY HH:mm",LLLL:"dddd, D MMMM [năm] YYYY HH:mm",l:"DD/M/YYYY",ll:"D MMM YYYY",lll:"D MMM YYYY HH:mm",
llll:"ddd, D MMM YYYY HH:mm"},calendar:{sameDay:"[Hôm nay lúc] LT",nextDay:"[Ngày mai lúc] LT",nextWeek:"dddd [tuần tới lúc] LT",lastDay:"[Hôm qua lúc] LT",lastWeek:"dddd [tuần rồi lúc] LT",sameElse:"L"},relativeTime:{future:"%s tới",past:"%s trước",s:"vài giây",m:"một phút",mm:"%d phút",h:"một giờ",hh:"%d giờ",d:"một ngày",dd:"%d ngày",M:"một tháng",MM:"%d tháng",y:"một năm",yy:"%d năm"},ordinalParse:/\d{1,2}/,ordinal:function(a){return a},week:{dow:1,doy:4}}),uf.defineLocale("zh-cn",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah点mm分",LTS:"Ah点m分s秒",L:"YYYY-MM-DD",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日Ah点mm分",LLLL:"YYYY年MMMD日ddddAh点mm分",l:"YYYY-MM-DD",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日Ah点mm分",llll:"YYYY年MMMD日ddddAh点mm分"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(a,b){return 12===a&&(a=0),"凌晨"===b||"早上"===b||"上午"===b?a:"下午"===b||"晚上"===b?a+12:a>=11?a:a+12},meridiem:function(a,b,c){var d=100*a+b;return 600>d?"凌晨":900>d?"早上":1130>d?"上午":1230>d?"中午":1800>d?"下午":"晚上"},calendar:{sameDay:function(){return 0===this.minutes()?"[今天]Ah[点整]":"[今天]LT"},nextDay:function(){return 0===this.minutes()?"[明天]Ah[点整]":"[明天]LT"},lastDay:function(){return 0===this.minutes()?"[昨天]Ah[点整]":"[昨天]LT"},nextWeek:function(){var a,b;return a=uf().startOf("week"),b=this.unix()-a.unix()>=604800?"[下]":"[本]",0===this.minutes()?b+"dddAh点整":b+"dddAh点mm"},lastWeek:function(){var a,b;return a=uf().startOf("week"),b=this.unix()<a.unix()?"[上]":"[本]",0===this.minutes()?b+"dddAh点整":b+"dddAh点mm"},sameElse:"LL"},ordinalParse:/\d{1,2}(日|月|周)/,ordinal:function(a,b){switch(b){case"d":case"D":case"DDD":return a+"日";case"M":return a+"月";case"w":case"W":return a+"周";default:return a}},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},week:{dow:1,doy:4}}),uf.defineLocale("zh-tw",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm分",LTS:"Ah點m分s秒",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日Ah點mm分",LLLL:"YYYY年MMMD日ddddAh點mm分",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日Ah點mm分",llll:"YYYY年MMMD日ddddAh點mm分"},meridiemParse:/早上|上午|中午|下午|晚上/,meridiemHour:function(a,b){return 12===a&&(a=0),"早上"===b||"上午"===b?a:"中午"===b?a>=11?a:a+12:"下午"===b||"晚上"===b?a+12:void 0},meridiem:function(a,b,c){var d=100*a+b;return 900>d?"早上":1130>d?"上午":1230>d?"中午":1800>d?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},ordinalParse:/\d{1,2}(日|月|週)/,ordinal:function(a,b){switch(b){case"d":case"D":case"DDD":return a+"日";case"M":return a+"月";case"w":case"W":return a+"週";default:return a}},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"一分鐘",mm:"%d分鐘",h:"一小時",hh:"%d小時",d:"一天",dd:"%d天",M:"一個月",MM:"%d個月",y:"一年",yy:"%d年"}}),uf);return mg.locale("en"),mg});
define('castle-url/patterns/structure//js/views/tablerow',[
  'jquery',
  'underscore',
  'backbone',
  'castle-url/patterns/structure//js/navigation',
  'castle-url/patterns/structure//js/views/actionmenu',
  'text!castle-url/patterns/structure//templates/tablerow.xml',
  'mockup-utils',
  'translate',
  'moment'
], function($, _, Backbone, Nav, ActionMenuView, TableRowTemplate, utils, _t,
            moment) {
  'use strict';

  var TableRowView = Backbone.View.extend({
    tagName: 'tr',
    className: 'itemRow',
    template: _.template(TableRowTemplate),
    events: {
      'change input': 'itemSelected',
      'click td.title a.manage': 'itemClicked'
    },
    initialize: function(options) {
      this.options = options;
      this.app = options.app;
      this.selectedCollection = this.app.selectedCollection;
      this.table = this.options.table;
      this.now = moment();
    },

    expired: function(data){
      if(!data.attributes.ExpirationDate){
        return false;
      }
      var dt = moment(data.attributes.ExpirationDate);
      return dt.diff(this.now, 'seconds') < 0;
    },

    render: function() {
      var self = this;
      var data = this.model.toJSON();
      data.selected = false;
      if (this.selectedCollection.findWhere({UID: data.UID})) {
        data.selected = true;
      }
      data.attributes = self.model.attributes;
      data.activeColumns = self.app.activeColumns;
      data.availableColumns = self.app.availableColumns;
      data.portal_type = data.portal_type ? data.portal_type : '';
      data.contenttype = data.portal_type.toLowerCase().replace(/\.| /g, '-');
      data._authenticator = utils.getAuthenticator();
      data.iconSize = self.app.iconSize;

      var viewAction = self.app.typeToViewAction && self.app.typeToViewAction[data.attributes.portal_type] || '';
      data.viewURL = data.attributes.getURL + viewAction;

      data._t = _t;
      data.expired = this.expired(data);
      self.$el.html(self.template(data));
      var attrs = self.model.attributes;
      self.$el.addClass('state-' + attrs['review_state']).addClass('type-' + attrs.portal_type); // jshint ignore:line
      if (attrs['is_folderish']) { // jshint ignore:line
        self.$el.addClass('folder');
      }
      self.$el.attr('data-path', data.path);
      self.$el.attr('data-UID', data.UID);
      self.$el.attr('data-id', data.id);
      self.$el.attr('data-type', data.portal_type);
      self.$el.attr('data-folderish', data['is_folderish']); // jshint ignore:line
      self.$el.removeClass('expired');

      if(data.expired){
        self.$el.addClass('expired');
      }

      self.el.model = this.model;

      var canMove = (!(!self.app.options.moveUrl));

      self.menu = new ActionMenuView({
        app: self.app,
        model: self.model,
        menuOptions: self.app.menuOptions,
        menuGenerator: self.app.menuGenerator,
        canMove: canMove
      });

      $('.actionmenu-container', self.$el).append(self.menu.render().el);
      return this;
    },
    itemClicked: function(e) {
      /* check if this should just be opened in new window */
      var self = this;
      var keyEvent = this.app.keyEvent;
      var key;
      // Resolve the correct handler based on these keys.
      // Default handlers live in ../navigation.js (bound to Nav)
      if (keyEvent && keyEvent.ctrlKey ||
          !(this.model.attributes.is_folderish)) {
        // middle/ctrl-click or not a folder content
        key = 'other';  // default Nav.openClicked
      } else {
        key = 'folder';  // default Nav.folderClicked
      }
      var definition = self.app.options.tableRowItemAction[key] || [];
      // a bit of a duplicate from actionmenu.js, but this is calling
      // directly.
      var libName = definition[0],
          method = definition[1];
      if (!((typeof libName === 'string') && (typeof key === 'string'))) {
        return null;
      }
      var ClsLib = require(libName);
      var lib = new ClsLib(self);
      return lib[method] && lib[method](e);
    },
    itemSelected: function() {
      var checkbox = this.$('input')[0];
      if (checkbox.checked) {
        this.app.selectedCollection.add(this.model.clone());
      } else {
        this.app.selectedCollection.removeResult(this.model);
      }

      var selectedCollection = this.selectedCollection;

      /* check for shift click now */
      var keyEvent = this.app.keyEvent;
      if (keyEvent && keyEvent.shiftKey && this.app['last_selected'] && // jshint ignore:line
            this.app['last_selected'].parentNode !== null) { // jshint ignore:line
        var $el = $(this.app['last_selected']); // jshint ignore:line
        var lastCheckedIndex = $el.index();
        var thisIndex = this.$el.index();
        this.app.tableView.$('input[type="checkbox"]').each(function() {
          $el = $(this);
          var index = $el.parents('tr').index();
          if ((index > lastCheckedIndex && index < thisIndex) ||
              (index < lastCheckedIndex && index > thisIndex)) {
            this.checked = checkbox.checked;
            var $tr = $(this).closest('tr.itemRow');
            if($tr.length > 0){
              var model = $tr[0].model;
              var existing = selectedCollection.getByUID(model.attributes.UID);
              if (this.checked) {
                if (!existing) {
                  selectedCollection.add(model.clone());
                }
              } else if (existing) {
                selectedCollection.removeResult(existing);
              }
            }
          }
        });

      }
      this.app['last_selected'] = this.el; // jshint ignore:line
    }
  });

  return TableRowView;
});


define('text!castle-url/patterns/structure//templates/table.xml',[],function () { return '<div class="alert alert-<%- status.type %> status">\n  <strong><%- status.label %></strong>\n  <span><%- status.text %></span>&nbsp;<% // &nbsp; to get correct height for empty alerts %>\n</div>\n\n<table class="table table-striped table-bordered">\n  <thead>\n    <tr class="fc-breadcrumbs-container">\n      <td class="fc-breadcrumbs" colspan="<%- activeColumns.length + 3 %>">\n        <a href="#" data-path="/">\n          <span class="glyphicon glyphicon-home"></span> /\n        </a>\n        <% _.each(pathParts, function(part, idx, list){\n          if(part){\n            if(idx > 0){ %>\n              /\n            <% } %>\n            <a href="#" class="crumb" data-path="<%- part %>"><%- part %></a>\n          <% }\n        }); %>\n      </td>\n    </tr>\n    <tr>\n      <th class="selection"><input type="checkbox" class="select-all" /></th>\n      <th class="title">Title</th>\n      <% _.each(activeColumns, function(column){ %>\n        <% if(_.has(availableColumns, column)) { %>\n          <th><%- availableColumns[column] %></th>\n        <% } %>\n      <% }); %>\n      <th class="actions"><%- _t("Actions") %></th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n';});

/* Sortable pattern.
 *
 * Options:
 *    selector(string): Selector to use to draggable items in pattern ('li')
 *    dragClass(string): Class to apply to original item that is being dragged. ('item-dragging')
 *    cloneClass(string): Class to apply to cloned item that is dragged. ('dragging')
 *    drop(function): callback function for when item is dropped (null)
 *
 * Documentation:
 *    # Default
 *
 *    {{ example-1 }}
 *
 *    # Table
 *
 *    {{ example-2 }}
 *
 * Example: example-1
 *    <ul class="pat-sortable">
 *      <li>One</li>
 *      <li>Two</li>
 *      <li>Three</li>
 *    </ul>
 *
 * Example: example-2
 *    <table class="table table-stripped pat-sortable"
 *           data-pat-sortable="selector:tr;">
 *      <tbody>
 *        <tr>
 *          <td>One One</td>
 *          <td>One Two</td>
 *        </tr>
 *        <tr>
 *          <td>Two One</td>
 *          <td>Two Two</td>
 *        </tr>
 *        <tr>
 *          <td>Three One</td>
 *          <td>Three Two</td>
 *        </tr>
 *      </tbody>
 *    </table>
 *
 */


define('mockup-patterns-sortable',[
  'jquery',
  'pat-base',
  'jquery.event.drop',
  'jquery.event.drag'
], function($, Base, drop) {
  'use strict';

  var SortablePattern = Base.extend({
    name: 'sortable',
    trigger: '.pat-sortable',
    parser: 'mockup',
    defaults: {
      selector: 'li',
      dragClass: 'item-dragging',
      cloneClass: 'dragging',
      createDragItem: function(pattern, $el){
        return $el.clone().
          addClass(pattern.options.cloneClass).
          css({opacity: 0.75, position: 'absolute'}).appendTo(document.body);
      },
      drop: null // function to handle drop event
    },
    init: function() {
      var self = this;
      var start = 0;

      self.$el.find(self.options.selector).drag('start', function(e, dd) {
        var dragged = this;
        var $el = $(this);
        $(dragged).addClass(self.options.dragClass);
        drop({
          tolerance: function(event, proxy, target) {
            if ($(target.elem).closest(self.$el).length === 0) {
              /* prevent dragging conflict over another drag area */
              return;
            }
            var test = event.pageY > (target.top + target.height / 2);
            $.data(target.elem, 'drop+reorder', test ? 'insertAfter' : 'insertBefore' );
            return this.contains(target, [event.pageX, event.pageY]);
          }
        });
        start = $el.index();
        return self.options.createDragItem(self, $el);
      })
      .drag(function(e, dd) {
        /*jshint eqeqeq:false */
        $( dd.proxy ).css({
          top: dd.offsetY,
          left: dd.offsetX
        });
        var drop = dd.drop[0],
            method = $.data(drop || {}, 'drop+reorder');
        /* XXX Cannot use triple equals here */
        if (method && drop && (drop != dd.current || method != dd.method)) {
          $(this)[method](drop);
          dd.current = drop;
          dd.method = method;
          dd.update();
        }
      })
      .drag('end', function(e, dd) {
        var $el = $(this);
        $el.removeClass(self.options.dragClass);
        $(dd.proxy).remove();
        if (self.options.drop) {
          self.options.drop($el, $el.index() - start);
        }
      })
      .drop('init', function(e, dd ) {
        /*jshint eqeqeq:false */
        /* XXX Cannot use triple equals here */
        return (this == dd.drag) ? false: true;
      });

    }
  });

  return SortablePattern;

});



/* Moment pattern.
 *
 * Options:
 *    selector(string): selector to use to look for dates to format (null)
 *    format(string): Format to use to render date. Also available is "relative" and "calendar" formats. (MMMM Do YYYY, h:mm:ss a)
 *    setTitle(boolean): set the title attribute to display the full date and time on hover (false)
 *
 * Documentation:
 *
 *    # Simple
 *
 *    {{ example-1 }}
 *
 *    # Defaults
 *
 *    {{ example-2 }}
 *
 *    # Relative format
 *
 *    {{ example-3 }}
 *
 *    # Calendar format
 *
 *    {{ example-4 }}
 *
 *    # Custom format
 *
 *    {{ example-5 }}
 *
 *    # Setting date by attribute
 *
 *    {{ example-6 }}
 *
 * Example: example-1
 *    <span class="pat-moment">2014-10-30T15:10:00</span>
 *
 * Example: example-2
 *    <ul class="pat-moment" data-pat-moment="selector:li">
 *      <li>2013-10-01T10:00:00-05:00</li>
 *      <li>2013-01-01T22:10:00-05:00</li>
 *      <li>2013-01-05T04:34:00-05:00</li>
 *      <li>2013-02-14T16:55:00-05:00</li>
 *    </ul>
 *
 * Example: example-3
 *    <ul class="pat-moment"
 *        data-pat-moment="selector:li;format:relative;">
 *      <li>2013-10-01T10:00:00-05:00</li>
 *      <li>2013-01-01T22:10:00-05:00</li>
 *      <li>2013-01-05T04:34:00-05:00</li>
 *      <li>2013-02-14T16:55:00-05:00</li>
 *    </ul>
 *
 * Example: example-4
 *    <ul class="pat-moment"
 *        data-pat-moment="selector:li;format:calendar;">
 *      <li>2013-10-01T10:00:00-05:00</li>
 *      <li>2013-10-02T22:10:00-05:00</li>
 *      <li>2013-10-05T04:34:00-05:00</li>
 *      <li>2013-10-03T16:55:00-05:00</li>
 *    </ul>
 *
 * Example: example-5
 *    <ul class="pat-moment"
 *        data-pat-moment="selector:li;format:MMM Do, YYYY h:m a;">
 *      <li>2013-10-01T10:00:00-05:00</li>
 *      <li>2013-01-01T22:10:00-05:00</li>
 *      <li>2013-01-05T04:34:00-05:00</li>
 *      <li>2013-02-14T16:55:00-05:00</li>
 *    </ul>
 *
 * Example: example-6
 *    <ul class="pat-moment"
 *        data-pat-moment="selector:li;format:MMM Do, YYYY h:m a;">
 *      <li data-date="2013-10-01T10:00:00-05:00"></li>
 *      <li data-date="2013-01-01T22:10:00-05:00"></li>
 *      <li data-date="2013-01-05T04:34:00-05:00"></li>
 *      <li data-date="2013-02-14T16:55:00-05:00"></li>
 *    </ul>
 *
 */


define('mockup-patterns-moment',[
  'jquery',
  'pat-base',
  'moment',
  'mockup-i18n'
], function($, Base, moment, i18n) {
  'use strict';

  var Moment = Base.extend({
    name: 'moment',
    trigger: '.pat-moment',
    parser: 'mockup',
    defaults: {
      // selector of elements to format dates for
      selector: null,
      // also available options are relative, calendar
      format: 'LLL',
      setTitle: false
    },
    convert: function($el) {
      var self = this;
      var date = $el.attr('data-date');
      if (!date) {
        date = $.trim($el.html());
      }
      if (!date || date === 'None') {
        return;
      }
      moment.locale([(new i18n()).currentLanguage, 'en']);
      date = moment(date);
      if (!date.isValid()) {
        return;
      }
      if (self.options.setTitle) {
        $el.attr('title', date.format('LLLL'));

      }
      if (self.options.format === 'relative') {
        date = date.fromNow();
      }else if (self.options.format === 'calendar') {
        date = date.calendar();
      } else {
        date = date.format(self.options.format);
      }
      if (date) {
        $el.html(date);
      }
    },
    init: function() {
      var self = this;
      if (self.options.selector) {
        self.$el.find(self.options.selector).each(function() {
          self.convert($(this));
        });
      } else {
        self.convert(self.$el);
      }
    }
  });

  return Moment;

});

(function(root) {
define("bootstrap-alert", ["jquery"], function() {
  return (function() {
/* ========================================================================
 * Bootstrap: alert.js v3.3.4
 * http://getbootstrap.com/javascript/#alerts
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // ALERT CLASS DEFINITION
  // ======================

  var dismiss = '[data-dismiss="alert"]'
  var Alert   = function (el) {
    $(el).on('click', dismiss, this.close)
  }

  Alert.VERSION = '3.3.4'

  Alert.TRANSITION_DURATION = 150

  Alert.prototype.close = function (e) {
    var $this    = $(this)
    var selector = $this.attr('data-target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    var $parent = $(selector)

    if (e) e.preventDefault()

    if (!$parent.length) {
      $parent = $this.closest('.alert')
    }

    $parent.trigger(e = $.Event('close.bs.alert'))

    if (e.isDefaultPrevented()) return

    $parent.removeClass('in')

    function removeElement() {
      // detach from parent, fire event then clean up data
      $parent.detach().trigger('closed.bs.alert').remove()
    }

    $.support.transition && $parent.hasClass('fade') ?
      $parent
        .one('bsTransitionEnd', removeElement)
        .emulateTransitionEnd(Alert.TRANSITION_DURATION) :
      removeElement()
  }


  // ALERT PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.alert')

      if (!data) $this.data('bs.alert', (data = new Alert(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  var old = $.fn.alert

  $.fn.alert             = Plugin
  $.fn.alert.Constructor = Alert


  // ALERT NO CONFLICT
  // =================

  $.fn.alert.noConflict = function () {
    $.fn.alert = old
    return this
  }


  // ALERT DATA-API
  // ==============

  $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)

}(jQuery);


  }).apply(root, arguments);
});
}(this));

define('castle-url/patterns/structure//js/views/table',[
  'jquery',
  'underscore',
  'castle-url/patterns/structure//js/views/tablerow',
  'text!castle-url/patterns/structure//templates/table.xml',
  'mockup-ui-url/views/base',
  'mockup-patterns-sortable',
  'mockup-patterns-moment',
  'castle-url/patterns/structure//js/models/result',
  'castle-url/patterns/structure//js/views/actionmenu',
  'translate',
  'bootstrap-alert'
], function($, _, TableRowView, TableTemplate, BaseView, Sortable,
            patMoment, Result, ActionMenuView, _t) {
  'use strict';

  var TableView = BaseView.extend({
    tagName: 'div',
    template: _.template(TableTemplate),
    initialize: function(options) {
      var self = this;
      BaseView.prototype.initialize.apply(self, [options]);
      self.collection = self.app.collection;
      self.selectedCollection = self.app.selectedCollection;
      self.listenTo(self.collection, 'sync', self.render);
      self.listenTo(self.selectedCollection, 'remove', self.render);
      self.listenTo(self.selectedCollection, 'reset', self.render);
      self.collection.pager();
      self.subsetIds = [];
      self.contextInfo = null;

      self.app.on('context-info-loaded', function(data) {
        self.contextInfo = data;
        /* set default page info */
        self.setContextInfo();
      });

      self.dateColumns = [
        'ModificationDate',
        'EffectiveDate',
        'CreationDate',
        'ExpirationDate',
        'start',
        'end',
        'last_comment_date'
      ];
    },
    events: {
      'click .fc-breadcrumbs a': 'breadcrumbClicked',
      'change .select-all': 'selectAll',
    },
    setContextInfo: function() {
      var self = this;
      var data = self.contextInfo;
      var $defaultPage = self.$('[data-id="' + data.defaultPage + '"]');
      if ($defaultPage.length > 0) {
        $defaultPage.addClass('default-page');
      }
      /* set breadcrumb title info */
      var crumbs = data.breadcrumbs;
      if (crumbs && crumbs.length) {
        var $crumbs = self.$('.fc-breadcrumbs a.crumb');
        _.each(crumbs, function(crumb, idx) {
          $crumbs.eq(idx).html(crumb.title);
        });
      }
    },
    render: function() {
      var self = this;
      self.$el.html(self.template({
        _t: _t,
        pathParts: _.filter(
          self.app.getCurrentPath().split('/').slice(1),
          function(val) {
            return val.length > 0;
          }
        ),
        status: self.app.status,
        activeColumns: self.app.activeColumns,
        availableColumns: self.app.availableColumns
      }));

      if (self.collection.length) {
        var container = self.$('tbody');
        self.collection.each(function(result) {
          self.dateColumns.map(function (col) {
            // empty column instead of displaying "None".
            if (result.attributes.hasOwnProperty(col) && (result.attributes[col] === 'None' || !result.attributes[col] )) {
              result.attributes[col] = '';
            }
          });

          var view = (new TableRowView({
            model: result,
            app: self.app,
            table: self
          })).render();
          container.append(view.el);
        });
      }
      self.moment = new patMoment(self.$el, {
        selector: '.' + self.dateColumns.join(',.'),
        format: self.options.app.momentFormat
      });

      if (self.app.options.moveUrl) {
        self.addReordering();
      }

      self.storeOrder();
      return this;
    },
    breadcrumbClicked: function(e) {
      e.preventDefault();
      var $el = $(e.target);
      if ($el[0].tagName !== 'A') {
        $el = $el.parent('a');
      }
      var path = '';
      $($el.prevAll('a').get().reverse()).each(function() {
        var part = $(this).attr('data-path');
        path += part;
        if (part !== '/') {
          path += '/';
        }
      });
      path += $el.attr('data-path');
      this.app.setCurrentPath(path);
      this.collection.currentPage = 1;
      this.collection.pager();
    },
    selectAll: function(e) {
      if ($(e.target).is(':checked')) {
        $('input[type="checkbox"]', this.$('tbody')).prop('checked', true).change();
      } else {
        /* delaying the re-rendering is much faster in this case */
        this.selectedCollection.remove(this.collection.models, { silent: true });
        this.selectedCollection.trigger('remove');
      }
      this.setContextInfo();
    },
    toggleSelectAll: function(e) {
      var $el = $(e.target);
      if (!$el.is(':checked')) {
        this.$('.select-all').prop('checked', false);
      }
    },
    addReordering: function() {
      var self = this;
      // if we have a custom query going on, we do not allow sorting.
      if (self.app.inQueryMode()) {
        self.app.setStatus({text: _t('Can not order items while querying'), type: 'warning'});
        self.$el.removeClass('order-support');
        return;
      }
      self.$el.addClass('order-support');
      var dd = new Sortable(self.$('tbody'), {
        selector: 'tr',
        createDragItem: function(pattern, $el) {
          var $tr = $el.clone();
          var $table = $('<table><tbody></tbody></table>');
          $('tbody', $table).append($tr);
          $table.addClass('structure-dragging')
            .css({opacity: 0.85, position: 'absolute'});
          $table.width($el.width());
          $table.height($el.height());
          $table.appendTo(document.body);
          return $table;
        },
        drop: function($el, delta) {
          if (delta !== 0){
            self.app.moveItem($el.attr('data-id'), delta, self.subsetIds);
            self.storeOrder();
          }
        }
      });
    },
    storeOrder: function() {
      var self = this;
      var subsetIds = [];
      self.$('tbody tr.itemRow').each(function() {
        subsetIds.push($(this).attr('data-id'));
      });
      self.subsetIds = subsetIds;
    }
  });

  return TableView;
});


define('text!castle-url/patterns/structure//templates/selection_item.xml',[],function () { return '<span class="selected-item">\n  <a href="#" data-uid="<%- UID %>" title="remove" class="remove">\n    <span class="glyphicon glyphicon-remove-circle"></span>\n  </a>\n  <%- Title %>\n</span>\n';});

define('castle-url/patterns/structure//js/views/selectionwell',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/popover',
  'text!castle-url/patterns/structure//templates/selection_item.xml'
], function($, _, PopoverView, ItemTemplate) {
  'use strict';

  var WellView = PopoverView.extend({
    className: 'popover selected-items',
    title: _.template(
      '<input type="text" class="filter" placeholder="Filter" />' +
      '<a href="#" class=" remove-all">' +
      '<span class="glyphicon glyphicon-remove-circle"></span> <%- _t("remove all") %></a>'
    ),
    content: _.template(
      '<% collection.each(function(item) { %>' +
      '<%= item_template(item.toJSON()) %>' +
      '<% }); %>'
    ),
    events: {
      'click a.remove': 'itemRemoved',
      'keyup input.filter': 'filterSelected',
      'click .remove-all': 'removeAll'
    },
    initialize: function(options) {
      PopoverView.prototype.initialize.apply(this, [options]);
      var self = this;
      var timeout = 0;
      this.listenTo(this.collection, 'reset all add remove', function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
          self.render();
        }, 50);
      });
      this.options['item_template'] = _.template(ItemTemplate); // jshint ignore:line
    },
    render: function() {
      PopoverView.prototype.render.call(this);
      if (this.collection.length === 0) {
        this.$el.removeClass('active');
      }
      return this;
    },
    itemRemoved: function(e) {
      e.preventDefault();
      var uid = $(e.currentTarget).data('uid');
      this.collection.removeByUID(uid);
      if (this.collection.length !== 0) {
        // re-rendering causes it to close, reopen
        this.show();
      }
    },
    filterSelected: function(e) {
      var val = $(e.target).val().toLowerCase();
      $('.selected-item', this.$el).each(function() {
        var $el = $(this);
        if ($el.text().toLowerCase().indexOf(val) === -1) {
          $el.hide();
        } else {
          $el.show();
        }
      });
    },
    removeAll: function(e) {
      e.preventDefault();
      this.collection.reset();
      this.hide();
    }
  });

  return WellView;
});

define('castle-url/patterns/structure//js/views/generic-popover',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/popover',
  'translate',
  'pat-registry'
], function($, _, PopoverView, _t, registry) {
  'use strict';

  var PropertiesView = PopoverView.extend({
    events: {
      'click button.applyBtn': 'applyButtonClicked',
      'click button.closeBtn': 'toggle'
    },
    submitText: _t('Apply'),
    initialize: function(options) {
      var self = this;
      self.app = options.app;
      self.className = 'popover ' + options.id;
      self.title = options.form.title || options.title;
      self.submitText = options.form.submitText || _t('Apply');
      self.submitContext = options.form.submitContext || 'primary';
      self.data = {};

      self.options = options;
      self.setContent(options.form.template);

      PopoverView.prototype.initialize.apply(this, [options]);
    },
    setContent: function(content) {
      var self = this;
      var html = '<form>' + content + '</form>';
      html += '<button class="btn btn-block btn-' + self.submitContext + ' applyBtn">' + self.submitText + ' </button>';
      if (self.options.form.closeText) {
        html += '<button class="btn btn-block btn-default closeBtn">' + self.options.form.closeText + ' </button>';
      }
      this.content = _.template(html);
    },
    getTemplateOptions: function() {
      var self = this;
      var items = [];
      self.app.selectedCollection.each(function(item) {
        items.push(item.toJSON());
      });
      return $.extend({}, true, self.options, {
        items: items,
        data: self.data
      });
    },
    applyButtonClicked: function() {
      var self = this;
      var data = {};
      _.each(self.$el.find('form').serializeArray(), function(param) {
        data[param.name] = param.value;
      });

      self.app.buttonClickEvent(this.triggerView, data);
      self.hide();
    },
    afterRender: function() {
      var self = this;
      if (self.options.form.dataUrl) {
        self.$('.popover-content').html(_t('Loading...'));
        self.app.loading.show();
        $.ajax({
          url: self.options.form.dataUrl,
          dataType: 'json',
          type: 'POST',
          cache: false,
          data: {
            selection: JSON.stringify(self.app.getSelectedUids()),
            transitions: true,
            render: 'yes'
          }
        }).done(function(result) {
          self.data = result.data || result;
          self.renderContent();
          registry.scan(self.$el);
        }).fail(function() {
          /* we temporarily set original html to a value here so we can
             render the updated content and then put the original back */
          var originalContent = self.content;
          self.setContent('<p>' + _t('Error loading popover from server.') + '</p>', false);
          self.renderContent();
          self.content = originalContent;
        }).always(function() {
          self.app.loading.hide();
          self.position();
        });
      } else {
        registry.scan(self.$el);
        self.position();
      }
    },
    toggle: function(button, e) {
      PopoverView.prototype.toggle.apply(this, [button, e]);
      var self = this;
      if (!self.opened) {
        return;
      } else {
        this.$el.replaceWith(this.render().el);
        this.position();
      }
    }
  });

  return PropertiesView;
});

define('castle-url/patterns/structure//js/views/rearrange',[
  'underscore',
  'mockup-ui-url/views/popover',
  'translate'
], function(_, PopoverView, _t) {
  'use strict';

  var RearrangeView = PopoverView.extend({
    className: 'popover rearrange',
    title: _.template('<%- _t("Rearrange items in this folder") %>'),
    content: _.template(
      '<div class="form-group">' +
        '<label><%- _t("What to rearrange on") %></label>' +
        '<select name="rearrange_on" class="form-control">' +
          '<% _.each(rearrangeProperties, function(title, property) { %>' +
            '<option value="<%- property %>"><%- title %></option>' +
          '<% }); %>' +
        '</select>' +
        '<p class="help-block">' +
          '<b><%- _t("This permanently changes the order of items in this folder. This operation may take a long time depending on the size of the folder.") %></b>' +
        '</p>' +
      '</div>' +
      '<div>' +
        '<label> <input type="checkbox" name="reversed" /> <%- _t("Reverse") %></label>' +
      '</div>' +
      '<button class="btn btn-block btn-primary"><%- _t("Rearrange") %></button>'
    ),
    events: {
      'click button': 'rearrangeButtonClicked'
    },
    initialize: function(options) {
      this.app = options.app;
      PopoverView.prototype.initialize.apply(this, [options]);
      this.options.rearrangeProperties = this.app.options.rearrange.properties;
    },
    render: function() {
      PopoverView.prototype.render.call(this);
      this.$rearrangeOn = this.$('[name="rearrange_on"]');
      this.$reversed = this.$('[name="reversed"]');
      return this;
    },
    rearrangeButtonClicked: function() {
      if (this.app.collection.queryHelper.getCurrentPath() === '/') {
        if (!window.confirm(_t(
          'Sorting the content on the base of the site ' +
          'could affect your navigation order. ' +
          'Are you certain you want to do this?'))) {
          return;
        }
      }
      var data = {
        'rearrange_on': this.$rearrangeOn.val(),
        reversed: false
      };
      if (this.$reversed[0].checked) {
        data.reversed = true;
      }
      this.app.buttonClickEvent(this.triggerView, data);
      this.hide();
    }
  });

  return RearrangeView;
});


define('text!castle-url/patterns/structure//templates/selection_button.xml',[],function () { return '<span class="glyphicon glyphicon-list"></span>\n<%- title %>\n<span class="label<% if (length > 0) { %> label-success<% } else { %> label-default<% } %>">\n  <%- length %>\n</span>\n';});

define('castle-url/patterns/structure//js/views/selectionbutton',[
  'mockup-ui-url/views/button',
  'text!castle-url/patterns/structure//templates/selection_button.xml'
], function(ButtonView, tplButton) {
  'use strict';

  var SelectionButton = ButtonView.extend({
    collection: null,
    template: tplButton,
    initialize: function(options) {
      ButtonView.prototype.initialize.apply(this, [options]);
      var self = this;
      self.timeout = 0;
      if (this.collection !== null) {
        this.collection.on('add remove reset', function() {
          /* delay it */
          clearTimeout(self.timeout);
          self.timeout = setTimeout(function() {
            self.render();
            if (self.collection.length === 0) {
              self.$el.removeClass('active');
            }
          }, 50);
        }, this);
      }
    },
    serializedModel: function() {
      var obj = {
        icon: '',
        title: this.options.title,
        length: 0
      };
      if (this.collection !== null) {
        obj.length = this.collection.length;
      }
      return obj;
    }
  });

  return SelectionButton;
});


define('text!castle-url/patterns/structure/templates/paging.xml',[],function () { return '  <ul class="pagination pagination-sm pagination-centered">\n    <li class="<% if (currentPage === 1) { %>disabled<% } %>">\n      <a href="#" class="serverfirst">\n        &laquo;\n      </a>\n    </li>\n    <li class="<% if (currentPage === 1) { %>disabled<% } %>">\n      <a href="#" class="serverprevious">\n        &lt;\n      </a>\n    </li>\n    <% _.each(pages, function(p){ %>\n    <li class="<% if (currentPage == p) { %>active<% } %>">\n      <a href="#" class="page"><%- p %></a>\n    </li>\n    <% }); %>\n    <li class="<% if (currentPage === totalPages) { %>disabled<% } %>">\n      <a href="#" class="servernext">\n        &gt;\n      </a>\n    </li>\n    <li class="<% if (currentPage === totalPages) { %>disabled<% } %>">\n      <a href="#" class="serverlast">\n        &raquo;\n      </a>\n    </li>\n  </ul>\n\n  <ul class="pagination pagination-sm">\n    <li class="disabled"><a href="#"><%- _t("Show:") %></a></li>\n    <li class="serverhowmany serverhowmany15 <% if(perPage == 15){ %>disabled<% } %>">\n      <a href="#" class="">15</a>\n    </li>\n    <li class="serverhowmany serverhowmany30 <% if(perPage == 30){ %>disabled<% } %>">\n      <a href="#" class="">30</a>\n    </li>\n    <li class="serverhowmany serverhowmany50 <% if(perPage == 50){ %>disabled<% } %>">\n      <a href="#" class="">50</a>\n    </li>\n    <li class="serverhowmany serverhowmany100000 <% if(perPage == 100000){ %>disabled<% } %>">\n      <a href="#" class="">All</a>\n    </li>\n  </ul>\n\n  <ul class="pagination pagination-sm">\n    <li class="disabled">\n      <a href="#">\n        <%- _t("Page:") %> <span class="current"><%- currentPage %></span>\n        <%- _t("of") %>\n        <span class="total"><%- totalPages %></span>\n              <%- _t("shown") %>\n      </a>\n    </li>\n  </ul>\n';});

define('castle-url/patterns/structure//js/views/paging',[
  'jquery',
  'underscore',
  'backbone',
  'text!castle-url/patterns/structure/templates/paging.xml',
  'translate'
], function($, _, Backbone, PagingTemplate, _t) {
  'use strict';

  var PagingView = Backbone.View.extend({
    events: {
      'click a.servernext': 'nextResultPage',
      'click a.serverprevious': 'previousResultPage',
      'click a.serverlast': 'gotoLast',
      'click a.page': 'gotoPage',
      'click a.serverfirst': 'gotoFirst',
      'click a.serverpage': 'gotoPage',
      'click .serverhowmany a': 'changeCount'
    },

    tagName: 'aside',
    template: _.template(PagingTemplate),
    maxPages: 7,
    MAX_BATCH_SIZE: '100000',
    totalPagesExists: function(){
      return !!totalPages && totalPages === parseInt(totalPages, 10);
    },
    currentPageExists: function(){
      return !!currentPage && currentPage === parseInt(currentPage, 10);
    },
    pagesExist: function(){
      return this.currentPageExists() && this.totalPagesExists();
    },
    initialize: function(options) {
      this.options = options;
      this.app = this.options.app;
      this.collection = this.app.collection;
      this.collection.on('reset', this.render, this);
      this.collection.on('sync', this.render, this);

      this.$el.appendTo('#pagination');
    },

    render: function() {
      var data = this.collection.info();
      data.pages = this.getPages(data);
      var html = this.template($.extend({
        _t: _t
      }, data));
      this.$el.html(html);
      return this;
    },

    getPages: function(data) {
      var totalPages = data.totalPages;
      if (!totalPages) {
        return [];
      }
      var currentPage = data.currentPage;
      var left = 1;
      var right = totalPages;
      if (totalPages > this.maxPages) {
        left = Math.max(1, Math.floor(currentPage - (this.maxPages / 2)));
        right = Math.min(left + this.maxPages, totalPages);
        if ((right - left) < this.maxPages) {
          left = left - Math.floor(this.maxPages / 2);
        }
      }
      var pages = [];
      for (var i = left; i <= right; i = i + 1) {
        pages.push(i);
      }

      /* add before and after */
      if (pages[0] > 1) {
        if (pages[0] > 2) {
          pages = ['...'].concat(pages);
        }
        pages = [1].concat(pages);
      }
      if (pages[pages.length - 1] < (totalPages - 1)) {
        if (pages[pages.length - 2] < totalPages - 2) {
          pages.push('...');
        }
        pages.push(totalPages);
      }
      return pages;
    },
    nextResultPage: function(e) {
      e.preventDefault();
      if (this.pagesExist() && currentPage >= totalPages) {
        return;
      }
      this.collection.requestNextPage();
    },
    previousResultPage: function(e) {
      e.preventDefault();
      this.collection.requestPreviousPage();
    },
    gotoFirst: function(e) {
      e.preventDefault();
      this.collection.goTo(this.collection.information.firstPage);
    },
    gotoLast: function(e) {
      e.preventDefault();
      this.collection.goTo(this.collection.information.totalPages);
    },
    gotoPage: function(e) {
      e.preventDefault();
      var page = $(e.target).text();
      this.collection.goTo(page);
    },
    changeCount: function(e){
      e.preventDefault();
      var text = $(e.target).text();
      var per = text === 'All' ? this.MAX_BATCH_SIZE : text;
      this.collection.howManyPer(per);
      this.app.setCookieSetting('perPage', per);
    },
  });

  return PagingView;
});

define('castle-url/patterns/structure//js/views/columns',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/popover',
  'mockup-patterns-sortable'
], function($, _, PopoverView, Sortable) {
  'use strict';

  var ColumnsView = PopoverView.extend({
    className: 'popover attribute-columns',
    title: _.template('<%- _t("Columns") %>'),
    content: _.template(
      '<label><%- _t("Select columns to show, drag and drop to reorder") %></label>' +
      '<ul>' +
      '</ul>' +
      '<button class="btn btn-block btn-success"><%- _t("Save") %></button>'
    ),
    itemTemplate: _.template(
      '<li>' +
        '<label>' +
          '<input type="checkbox" value="<%- id %>"/>' +
          '<%- title %>' +
        '</label>' +
      '</li>'
    ),
    events: {
      'click button': 'applyButtonClicked'
    },
    initialize: function(options) {
      this.app = options.app;
      PopoverView.prototype.initialize.apply(this, [options]);
    },
    afterRender: function() {
      var self = this;

      var objKeySortCmp = function (a, b) {
        // object key sort compare function
        var ca = self.app.availableColumns[a];
        var cb = self.app.availableColumns[b];
        if (ca < cb) {
          return -1;
        } else if (ca == cb) {
          return 0;
        } else {
          return 1;
        }
      }

      self.$container = self.$('ul');

      _.each(self.app.activeColumns, function(id) {
        var $el = $(self.itemTemplate({
          title: self.app.availableColumns[id],
          id: id
        }));
        $el.find('input')[0].checked = true;
        self.$container.append($el);
      });

      var availableKeys = _.keys(_.omit(self.app.availableColumns, self.app.activeColumns)).sort(objKeySortCmp);
      _.each(availableKeys, function(id) {
          var $el = $(self.itemTemplate({
            title: self.app.availableColumns[id],
            id: id
          }));
          self.$container.append($el);
        });

      var dd = new Sortable(self.$container, {
        selector: 'li'
      });
      return this;
    },
    applyButtonClicked: function() {
      var self = this;
      this.hide();
      self.app.activeColumns = [];
      self.$('input:checked').each(function() {
        self.app.activeColumns.push($(this).val());
      });
      self.app.setCookieSetting(self.app.activeColumnsCookie, this.app.activeColumns);
      self.app.tableView.render();
    }
  });

  return ColumnsView;
});

define('castle-url/patterns/structure//js/views/textfilter',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/base',
  'mockup-ui-url/views/button',
  'mockup-ui-url/views/popover',
  'mockup-patterns-querystring',
  'translate'
], function($, _, BaseView, ButtonView, PopoverView, QueryString, _t) {
  'use strict';

  var TextFilterView = BaseView.extend({
    tagName: 'div',
    className: 'navbar-search form-search ui-offset-parent',
    template: _.template(
      '<div class="input-group">' +
      '<input type="text" class="form-control search-query" placeholder="<%- _t("Filter") %>">' +
      '<span class="input-group-btn">' +
      '</span>' +
      '</div>'
    ),
    popoverContent: _.template(
      '<input class="pat-querystring" />'
    ),
    events: {
      'keyup .search-query': 'filter'
    },
    term: null,
    timeoutId: null,
    keyupDelay: 300,

    initialize: function(options) {
      BaseView.prototype.initialize.apply(this, [options]);
      this.app = this.options.app;
    },

    render: function() {
      this.$el.html(this.template({_t: _t}));
      this.button = new ButtonView({
        title: _t('Query'),
        icon: 'search'
      });
      this.popover = new PopoverView({
        triggerView: this.button,
        id: 'structure-query',
        title: _.template(_t('Query')),
        content: this.popoverContent,
        placement: 'left'
      });
      this.$('.input-group-btn').append(this.button.render().el);
      this.$el.append(this.popover.render().el);
      this.popover.$el.addClass('query');
      this.$queryString = this.popover.$('input.pat-querystring');
      this.queryString = new QueryString(
        this.$queryString, {
          indexOptionsUrl: this.app.options.indexOptionsUrl,
          showPreviews: false
        });
      var self = this;
      self.queryString.$el.on('change', function() {
        if (self.timeoutId) {
          clearTimeout(self.timeoutId);
        }
        self.timeoutId = setTimeout(function() {
          var criterias = $.parseJSON(self.$queryString.val());
          self.app.additionalCriterias = criterias;
          self.app.collection.currentPage = 1;
          self.app.collection.pager();
        }, this.keyupDelay);
      });
      self.queryString.$el.on('initialized', function() {
        self.queryString.$sortOn.on('change', function() {
          self.app['sort_on'] = self.queryString.$sortOn.val(); // jshint ignore:line
          self.app.collection.currentPage = 1;
          self.app.collection.pager();
        });
        self.queryString.$sortOrder.change(function() {
          if (self.queryString.$sortOrder[0].checked) {
            self.app['sort_order'] = 'reverse'; // jshint ignore:line
          } else {
            self.app['sort_order'] = 'ascending'; // jshint ignore:line
          }
          self.app.collection.currentPage = 1;
          self.app.collection.pager();
        });
      });
      return this;
    },

    filter: function(event) {
      var self = this;
      if (self.timeoutId) {
        clearTimeout(self.timeoutId);
      }
      self.timeoutId = setTimeout(function() {
        self.term = $(event.currentTarget).val();
        self.app.collection.currentPage = 1;
        self.app.collection.pager();
      }, this.keyupDelay);
    }
  });

  return TextFilterView;
});

// Uses AMD or browser globals to create a jQuery plugin.
(function (factory) {
  if (typeof define === 'function' && define.amd) {
      // AMD. Register as an anonymous module.
      define('dropzone',['jquery'], factory);
  } else {
      // Browser globals
      factory(jQuery);
  }
} (function (jQuery) {
    var module = { exports: { } }; // Fake component


/*
 *
 * More info at [www.dropzonejs.com](http://www.dropzonejs.com)
 *
 * Copyright (c) 2012, Matias Meno
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

(function() {
  var Dropzone, Emitter, camelize, contentLoaded, detectVerticalSquash, drawImageIOSFix, noop, without,
    __slice = [].slice,
    __hasProp = {}.hasOwnProperty,
    __extends = 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; };

  noop = function() {};

  Emitter = (function() {
    function Emitter() {}

    Emitter.prototype.addEventListener = Emitter.prototype.on;

    Emitter.prototype.on = function(event, fn) {
      this._callbacks = this._callbacks || {};
      if (!this._callbacks[event]) {
        this._callbacks[event] = [];
      }
      this._callbacks[event].push(fn);
      return this;
    };

    Emitter.prototype.emit = function() {
      var args, callback, callbacks, event, _i, _len;
      event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      this._callbacks = this._callbacks || {};
      callbacks = this._callbacks[event];
      if (callbacks) {
        for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
          callback = callbacks[_i];
          callback.apply(this, args);
        }
      }
      return this;
    };

    Emitter.prototype.removeListener = Emitter.prototype.off;

    Emitter.prototype.removeAllListeners = Emitter.prototype.off;

    Emitter.prototype.removeEventListener = Emitter.prototype.off;

    Emitter.prototype.off = function(event, fn) {
      var callback, callbacks, i, _i, _len;
      if (!this._callbacks || arguments.length === 0) {
        this._callbacks = {};
        return this;
      }
      callbacks = this._callbacks[event];
      if (!callbacks) {
        return this;
      }
      if (arguments.length === 1) {
        delete this._callbacks[event];
        return this;
      }
      for (i = _i = 0, _len = callbacks.length; _i < _len; i = ++_i) {
        callback = callbacks[i];
        if (callback === fn) {
          callbacks.splice(i, 1);
          break;
        }
      }
      return this;
    };

    return Emitter;

  })();

  Dropzone = (function(_super) {
    var extend, resolveOption;

    __extends(Dropzone, _super);

    Dropzone.prototype.Emitter = Emitter;


    /*
    This is a list of all available events you can register on a dropzone object.
    
    You can register an event handler like this:
    
        dropzone.on("dragEnter", function() { });
     */

    Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded", "maxfilesreached", "queuecomplete"];

    Dropzone.prototype.defaultOptions = {
      url: null,
      method: "post",
      withCredentials: false,
      parallelUploads: 2,
      uploadMultiple: false,
      maxFilesize: 256,
      paramName: "file",
      createImageThumbnails: true,
      maxThumbnailFilesize: 10,
      thumbnailWidth: 120,
      thumbnailHeight: 120,
      filesizeBase: 1000,
      maxFiles: null,
      filesizeBase: 1000,
      params: {},
      clickable: true,
      ignoreHiddenFiles: true,
      acceptedFiles: null,
      acceptedMimeTypes: null,
      autoProcessQueue: true,
      autoQueue: true,
      addRemoveLinks: false,
      previewsContainer: null,
      capture: null,
      dictDefaultMessage: "Drop files here to upload",
      dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.",
      dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.",
      dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",
      dictInvalidFileType: "You can't upload files of this type.",
      dictResponseError: "Server responded with {{statusCode}} code.",
      dictCancelUpload: "Cancel upload",
      dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
      dictRemoveFile: "Remove file",
      dictRemoveFileConfirmation: null,
      dictMaxFilesExceeded: "You can not upload any more files.",
      accept: function(file, done) {
        return done();
      },
      init: function() {
        return noop;
      },
      forceFallback: false,
      fallback: function() {
        var child, messageElement, span, _i, _len, _ref;
        this.element.className = "" + this.element.className + " dz-browser-not-supported";
        _ref = this.element.getElementsByTagName("div");
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          child = _ref[_i];
          if (/(^| )dz-message($| )/.test(child.className)) {
            messageElement = child;
            child.className = "dz-message";
            continue;
          }
        }
        if (!messageElement) {
          messageElement = Dropzone.createElement("<div class=\"dz-message\"><span></span></div>");
          this.element.appendChild(messageElement);
        }
        span = messageElement.getElementsByTagName("span")[0];
        if (span) {
          span.textContent = this.options.dictFallbackMessage;
        }
        return this.element.appendChild(this.getFallbackForm());
      },
      resize: function(file) {
        var info, srcRatio, trgRatio;
        info = {
          srcX: 0,
          srcY: 0,
          srcWidth: file.width,
          srcHeight: file.height
        };
        srcRatio = file.width / file.height;
        info.optWidth = this.options.thumbnailWidth;
        info.optHeight = this.options.thumbnailHeight;
        if ((info.optWidth == null) && (info.optHeight == null)) {
          info.optWidth = info.srcWidth;
          info.optHeight = info.srcHeight;
        } else if (info.optWidth == null) {
          info.optWidth = srcRatio * info.optHeight;
        } else if (info.optHeight == null) {
          info.optHeight = (1 / srcRatio) * info.optWidth;
        }
        trgRatio = info.optWidth / info.optHeight;
        if (file.height < info.optHeight || file.width < info.optWidth) {
          info.trgHeight = info.srcHeight;
          info.trgWidth = info.srcWidth;
        } else {
          if (srcRatio > trgRatio) {
            info.srcHeight = file.height;
            info.srcWidth = info.srcHeight * trgRatio;
          } else {
            info.srcWidth = file.width;
            info.srcHeight = info.srcWidth / trgRatio;
          }
        }
        info.srcX = (file.width - info.srcWidth) / 2;
        info.srcY = (file.height - info.srcHeight) / 2;
        return info;
      },

      /*
      Those functions register themselves to the events on init and handle all
      the user interface specific stuff. Overwriting them won't break the upload
      but can break the way it's displayed.
      You can overwrite them if you don't like the default behavior. If you just
      want to add an additional event handler, register it on the dropzone object
      and don't overwrite those options.
       */
      drop: function(e) {
        return this.element.classList.remove("dz-drag-hover");
      },
      dragstart: noop,
      dragend: function(e) {
        return this.element.classList.remove("dz-drag-hover");
      },
      dragenter: function(e) {
        return this.element.classList.add("dz-drag-hover");
      },
      dragover: function(e) {
        return this.element.classList.add("dz-drag-hover");
      },
      dragleave: function(e) {
        return this.element.classList.remove("dz-drag-hover");
      },
      paste: noop,
      reset: function() {
        return this.element.classList.remove("dz-started");
      },
      addedfile: function(file) {
        var node, removeFileEvent, removeLink, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results;
        if (this.element === this.previewsContainer) {
          this.element.classList.add("dz-started");
        }
        if (this.previewsContainer) {
          file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim());
          file.previewTemplate = file.previewElement;
          this.previewsContainer.appendChild(file.previewElement);
          _ref = file.previewElement.querySelectorAll("[data-dz-name]");
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            node = _ref[_i];
            node.textContent = file.name;
          }
          _ref1 = file.previewElement.querySelectorAll("[data-dz-size]");
          for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
            node = _ref1[_j];
            node.innerHTML = this.filesize(file.size);
          }
          if (this.options.addRemoveLinks) {
            file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\" data-dz-remove>" + this.options.dictRemoveFile + "</a>");
            file.previewElement.appendChild(file._removeLink);
          }
          removeFileEvent = (function(_this) {
            return function(e) {
              e.preventDefault();
              e.stopPropagation();
              if (file.status === Dropzone.UPLOADING) {
                return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
                  return _this.removeFile(file);
                });
              } else {
                if (_this.options.dictRemoveFileConfirmation) {
                  return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
                    return _this.removeFile(file);
                  });
                } else {
                  return _this.removeFile(file);
                }
              }
            };
          })(this);
          _ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
          _results = [];
          for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
            removeLink = _ref2[_k];
            _results.push(removeLink.addEventListener("click", removeFileEvent));
          }
          return _results;
        }
      },
      removedfile: function(file) {
        var _ref;
        if (file.previewElement) {
          if ((_ref = file.previewElement) != null) {
            _ref.parentNode.removeChild(file.previewElement);
          }
        }
        return this._updateMaxFilesReachedClass();
      },
      thumbnail: function(file, dataUrl) {
        var thumbnailElement, _i, _len, _ref;
        if (file.previewElement) {
          file.previewElement.classList.remove("dz-file-preview");
          _ref = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            thumbnailElement = _ref[_i];
            thumbnailElement.alt = file.name;
            thumbnailElement.src = dataUrl;
          }
          return setTimeout(((function(_this) {
            return function() {
              return file.previewElement.classList.add("dz-image-preview");
            };
          })(this)), 1);
        }
      },
      error: function(file, message) {
        var node, _i, _len, _ref, _results;
        if (file.previewElement) {
          file.previewElement.classList.add("dz-error");
          if (typeof message !== "String" && message.error) {
            message = message.error;
          }
          _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
          _results = [];
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            node = _ref[_i];
            _results.push(node.textContent = message);
          }
          return _results;
        }
      },
      errormultiple: noop,
      processing: function(file) {
        if (file.previewElement) {
          file.previewElement.classList.add("dz-processing");
          if (file._removeLink) {
            return file._removeLink.textContent = this.options.dictCancelUpload;
          }
        }
      },
      processingmultiple: noop,
      uploadprogress: function(file, progress, bytesSent) {
        var node, _i, _len, _ref, _results;
        if (file.previewElement) {
          _ref = file.previewElement.querySelectorAll("[data-dz-uploadprogress]");
          _results = [];
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            node = _ref[_i];
            if (node.nodeName === 'PROGRESS') {
              _results.push(node.value = progress);
            } else {
              _results.push(node.style.width = "" + progress + "%");
            }
          }
          return _results;
        }
      },
      totaluploadprogress: noop,
      sending: noop,
      sendingmultiple: noop,
      success: function(file) {
        if (file.previewElement) {
          return file.previewElement.classList.add("dz-success");
        }
      },
      successmultiple: noop,
      canceled: function(file) {
        return this.emit("error", file, "Upload canceled.");
      },
      canceledmultiple: noop,
      complete: function(file) {
        if (file._removeLink) {
          file._removeLink.textContent = this.options.dictRemoveFile;
        }
        if (file.previewElement) {
          return file.previewElement.classList.add("dz-complete");
        }
      },
      completemultiple: noop,
      maxfilesexceeded: noop,
      maxfilesreached: noop,
      queuecomplete: noop,
      previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-image\"><img data-dz-thumbnail /></div>\n  <div class=\"dz-details\">\n    <div class=\"dz-size\"><span data-dz-size></span></div>\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n  </div>\n  <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n  <div class=\"dz-success-mark\">\n    <svg width=\"54px\" height=\"54px\" viewBox=\"0 0 54 54\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:sketch=\"http://www.bohemiancoding.com/sketch/ns\">\n      <title>Check</title>\n      <defs></defs>\n      <g id=\"Page-1\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\" sketch:type=\"MSPage\">\n        <path d=\"M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z\" id=\"Oval-2\" stroke-opacity=\"0.198794158\" stroke=\"#747474\" fill-opacity=\"0.816519475\" fill=\"#FFFFFF\" sketch:type=\"MSShapeGroup\"></path>\n      </g>\n    </svg>\n  </div>\n  <div class=\"dz-error-mark\">\n    <svg width=\"54px\" height=\"54px\" viewBox=\"0 0 54 54\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:sketch=\"http://www.bohemiancoding.com/sketch/ns\">\n      <title>Error</title>\n      <defs></defs>\n      <g id=\"Page-1\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\" sketch:type=\"MSPage\">\n        <g id=\"Check-+-Oval-2\" sketch:type=\"MSLayerGroup\" stroke=\"#747474\" stroke-opacity=\"0.198794158\" fill=\"#FFFFFF\" fill-opacity=\"0.816519475\">\n          <path d=\"M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z\" id=\"Oval-2\" sketch:type=\"MSShapeGroup\"></path>\n        </g>\n      </g>\n    </svg>\n  </div>\n</div>"
    };

    extend = function() {
      var key, object, objects, target, val, _i, _len;
      target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      for (_i = 0, _len = objects.length; _i < _len; _i++) {
        object = objects[_i];
        for (key in object) {
          val = object[key];
          target[key] = val;
        }
      }
      return target;
    };

    function Dropzone(element, options) {
      var elementOptions, fallback, _ref;
      this.element = element;
      this.version = Dropzone.version;
      this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, "");
      this.clickableElements = [];
      this.listeners = [];
      this.files = [];
      if (typeof this.element === "string") {
        this.element = document.querySelector(this.element);
      }
      if (!(this.element && (this.element.nodeType != null))) {
        throw new Error("Invalid dropzone element.");
      }
      if (this.element.dropzone) {
        throw new Error("Dropzone already attached.");
      }
      Dropzone.instances.push(this);
      this.element.dropzone = this;
      elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {};
      this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {});
      if (this.options.forceFallback || !Dropzone.isBrowserSupported()) {
        return this.options.fallback.call(this);
      }
      if (this.options.url == null) {
        this.options.url = this.element.getAttribute("action");
      }
      if (!this.options.url) {
        throw new Error("No URL provided.");
      }
      if (this.options.acceptedFiles && this.options.acceptedMimeTypes) {
        throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");
      }
      if (this.options.acceptedMimeTypes) {
        this.options.acceptedFiles = this.options.acceptedMimeTypes;
        delete this.options.acceptedMimeTypes;
      }
      this.options.method = this.options.method.toUpperCase();
      if ((fallback = this.getExistingFallback()) && fallback.parentNode) {
        fallback.parentNode.removeChild(fallback);
      }
      if (this.options.previewsContainer !== false) {
        if (this.options.previewsContainer) {
          this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer");
        } else {
          this.previewsContainer = this.element;
        }
      }
      if (this.options.clickable) {
        if (this.options.clickable === true) {
          this.clickableElements = [this.element];
        } else {
          this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable");
        }
      }
      this.init();
    }

    Dropzone.prototype.getAcceptedFiles = function() {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        file = _ref[_i];
        if (file.accepted) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.getRejectedFiles = function() {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        file = _ref[_i];
        if (!file.accepted) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.getFilesWithStatus = function(status) {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        file = _ref[_i];
        if (file.status === status) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.getQueuedFiles = function() {
      return this.getFilesWithStatus(Dropzone.QUEUED);
    };

    Dropzone.prototype.getUploadingFiles = function() {
      return this.getFilesWithStatus(Dropzone.UPLOADING);
    };

    Dropzone.prototype.getActiveFiles = function() {
      var file, _i, _len, _ref, _results;
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        file = _ref[_i];
        if (file.status === Dropzone.UPLOADING || file.status === Dropzone.QUEUED) {
          _results.push(file);
        }
      }
      return _results;
    };

    Dropzone.prototype.init = function() {
      var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1;
      if (this.element.tagName === "form") {
        this.element.setAttribute("enctype", "multipart/form-data");
      }
      if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) {
        this.element.appendChild(Dropzone.createElement("<div class=\"dz-default dz-message\"><span>" + this.options.dictDefaultMessage + "</span></div>"));
      }
      if (this.clickableElements.length) {
        setupHiddenFileInput = (function(_this) {
          return function() {
            if (_this.hiddenFileInput) {
              document.body.removeChild(_this.hiddenFileInput);
            }
            _this.hiddenFileInput = document.createElement("input");
            _this.hiddenFileInput.setAttribute("type", "file");
            if ((_this.options.maxFiles == null) || _this.options.maxFiles > 1) {
              _this.hiddenFileInput.setAttribute("multiple", "multiple");
            }
            _this.hiddenFileInput.className = "dz-hidden-input";
            if (_this.options.acceptedFiles != null) {
              _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles);
            }
            if (_this.options.capture != null) {
              _this.hiddenFileInput.setAttribute("capture", _this.options.capture);
            }
            _this.hiddenFileInput.style.visibility = "hidden";
            _this.hiddenFileInput.style.position = "absolute";
            _this.hiddenFileInput.style.top = "0";
            _this.hiddenFileInput.style.left = "0";
            _this.hiddenFileInput.style.height = "0";
            _this.hiddenFileInput.style.width = "0";
            document.body.appendChild(_this.hiddenFileInput);
            return _this.hiddenFileInput.addEventListener("change", function() {
              var file, files, _i, _len;
              files = _this.hiddenFileInput.files;
              if (files.length) {
                for (_i = 0, _len = files.length; _i < _len; _i++) {
                  file = files[_i];
                  _this.addFile(file);
                }
              }
              return setupHiddenFileInput();
            });
          };
        })(this);
        setupHiddenFileInput();
      }
      this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL;
      _ref1 = this.events;
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        eventName = _ref1[_i];
        this.on(eventName, this.options[eventName]);
      }
      this.on("uploadprogress", (function(_this) {
        return function() {
          return _this.updateTotalUploadProgress();
        };
      })(this));
      this.on("removedfile", (function(_this) {
        return function() {
          return _this.updateTotalUploadProgress();
        };
      })(this));
      this.on("canceled", (function(_this) {
        return function(file) {
          return _this.emit("complete", file);
        };
      })(this));
      this.on("complete", (function(_this) {
        return function(file) {
          if (_this.getUploadingFiles().length === 0 && _this.getQueuedFiles().length === 0) {
            return setTimeout((function() {
              return _this.emit("queuecomplete");
            }), 0);
          }
        };
      })(this));
      noPropagation = function(e) {
        e.stopPropagation();
        if (e.preventDefault) {
          return e.preventDefault();
        } else {
          return e.returnValue = false;
        }
      };
      this.listeners = [
        {
          element: this.element,
          events: {
            "dragstart": (function(_this) {
              return function(e) {
                return _this.emit("dragstart", e);
              };
            })(this),
            "dragenter": (function(_this) {
              return function(e) {
                noPropagation(e);
                return _this.emit("dragenter", e);
              };
            })(this),
            "dragover": (function(_this) {
              return function(e) {
                var efct;
                try {
                  efct = e.dataTransfer.effectAllowed;
                } catch (_error) {}
                e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy';
                noPropagation(e);
                return _this.emit("dragover", e);
              };
            })(this),
            "dragleave": (function(_this) {
              return function(e) {
                return _this.emit("dragleave", e);
              };
            })(this),
            "drop": (function(_this) {
              return function(e) {
                noPropagation(e);
                return _this.drop(e);
              };
            })(this),
            "dragend": (function(_this) {
              return function(e) {
                return _this.emit("dragend", e);
              };
            })(this)
          }
        }
      ];
      this.clickableElements.forEach((function(_this) {
        return function(clickableElement) {
          return _this.listeners.push({
            element: clickableElement,
            events: {
              "click": function(evt) {
                if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) {
                  return _this.hiddenFileInput.click();
                }
              }
            }
          });
        };
      })(this));
      this.enable();
      return this.options.init.call(this);
    };

    Dropzone.prototype.destroy = function() {
      var _ref;
      this.disable();
      this.removeAllFiles(true);
      if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) {
        this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput);
        this.hiddenFileInput = null;
      }
      delete this.element.dropzone;
      return Dropzone.instances.splice(Dropzone.instances.indexOf(this), 1);
    };

    Dropzone.prototype.updateTotalUploadProgress = function() {
      var activeFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref;
      totalBytesSent = 0;
      totalBytes = 0;
      activeFiles = this.getActiveFiles();
      if (activeFiles.length) {
        _ref = this.getActiveFiles();
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          file = _ref[_i];
          totalBytesSent += file.upload.bytesSent;
          totalBytes += file.upload.total;
        }
        totalUploadProgress = 100 * totalBytesSent / totalBytes;
      } else {
        totalUploadProgress = 100;
      }
      return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent);
    };

    Dropzone.prototype._getParamName = function(n) {
      if (typeof this.options.paramName === "function") {
        return this.options.paramName(n);
      } else {
        return "" + this.options.paramName + (this.options.uploadMultiple ? "[" + n + "]" : "");
      }
    };

    Dropzone.prototype.getFallbackForm = function() {
      var existingFallback, fields, fieldsString, form;
      if (existingFallback = this.getExistingFallback()) {
        return existingFallback;
      }
      fieldsString = "<div class=\"dz-fallback\">";
      if (this.options.dictFallbackText) {
        fieldsString += "<p>" + this.options.dictFallbackText + "</p>";
      }
      fieldsString += "<input type=\"file\" name=\"" + (this._getParamName(0)) + "\" " + (this.options.uploadMultiple ? 'multiple="multiple"' : void 0) + " /><input type=\"submit\" value=\"Upload!\"></div>";
      fields = Dropzone.createElement(fieldsString);
      if (this.element.tagName !== "FORM") {
        form = Dropzone.createElement("<form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"" + this.options.method + "\"></form>");
        form.appendChild(fields);
      } else {
        this.element.setAttribute("enctype", "multipart/form-data");
        this.element.setAttribute("method", this.options.method);
      }
      return form != null ? form : fields;
    };

    Dropzone.prototype.getExistingFallback = function() {
      var fallback, getFallback, tagName, _i, _len, _ref;
      getFallback = function(elements) {
        var el, _i, _len;
        for (_i = 0, _len = elements.length; _i < _len; _i++) {
          el = elements[_i];
          if (/(^| )fallback($| )/.test(el.className)) {
            return el;
          }
        }
      };
      _ref = ["div", "form"];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        tagName = _ref[_i];
        if (fallback = getFallback(this.element.getElementsByTagName(tagName))) {
          return fallback;
        }
      }
    };

    Dropzone.prototype.setupEventListeners = function() {
      var elementListeners, event, listener, _i, _len, _ref, _results;
      _ref = this.listeners;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        elementListeners = _ref[_i];
        _results.push((function() {
          var _ref1, _results1;
          _ref1 = elementListeners.events;
          _results1 = [];
          for (event in _ref1) {
            listener = _ref1[event];
            _results1.push(elementListeners.element.addEventListener(event, listener, false));
          }
          return _results1;
        })());
      }
      return _results;
    };

    Dropzone.prototype.removeEventListeners = function() {
      var elementListeners, event, listener, _i, _len, _ref, _results;
      _ref = this.listeners;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        elementListeners = _ref[_i];
        _results.push((function() {
          var _ref1, _results1;
          _ref1 = elementListeners.events;
          _results1 = [];
          for (event in _ref1) {
            listener = _ref1[event];
            _results1.push(elementListeners.element.removeEventListener(event, listener, false));
          }
          return _results1;
        })());
      }
      return _results;
    };

    Dropzone.prototype.disable = function() {
      var file, _i, _len, _ref, _results;
      this.clickableElements.forEach(function(element) {
        return element.classList.remove("dz-clickable");
      });
      this.removeEventListeners();
      _ref = this.files;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        file = _ref[_i];
        _results.push(this.cancelUpload(file));
      }
      return _results;
    };

    Dropzone.prototype.enable = function() {
      this.clickableElements.forEach(function(element) {
        return element.classList.add("dz-clickable");
      });
      return this.setupEventListeners();
    };

    Dropzone.prototype.filesize = function(size) {
      var cutoff, i, selectedSize, selectedUnit, unit, units, _i, _len;
      units = ['TB', 'GB', 'MB', 'KB', 'b'];
      selectedSize = selectedUnit = null;
      for (i = _i = 0, _len = units.length; _i < _len; i = ++_i) {
        unit = units[i];
        cutoff = Math.pow(this.options.filesizeBase, 4 - i) / 10;
        if (size >= cutoff) {
          selectedSize = size / Math.pow(this.options.filesizeBase, 4 - i);
          selectedUnit = unit;
          break;
        }
      }
      selectedSize = Math.round(10 * selectedSize) / 10;
      return "<strong>" + selectedSize + "</strong> " + selectedUnit;
    };

    Dropzone.prototype._updateMaxFilesReachedClass = function() {
      if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) {
        if (this.getAcceptedFiles().length === this.options.maxFiles) {
          this.emit('maxfilesreached', this.files);
        }
        return this.element.classList.add("dz-max-files-reached");
      } else {
        return this.element.classList.remove("dz-max-files-reached");
      }
    };

    Dropzone.prototype.drop = function(e) {
      var files, items;
      if (!e.dataTransfer) {
        return;
      }
      this.emit("drop", e);
      files = e.dataTransfer.files;
      if (files.length) {
        items = e.dataTransfer.items;
        if (items && items.length && (items[0].webkitGetAsEntry != null)) {
          this._addFilesFromItems(items);
        } else {
          this.handleFiles(files);
        }
      }
    };

    Dropzone.prototype.paste = function(e) {
      var items, _ref;
      if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) {
        return;
      }
      this.emit("paste", e);
      items = e.clipboardData.items;
      if (items.length) {
        return this._addFilesFromItems(items);
      }
    };

    Dropzone.prototype.handleFiles = function(files) {
      var file, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        _results.push(this.addFile(file));
      }
      return _results;
    };

    Dropzone.prototype._addFilesFromItems = function(items) {
      var entry, item, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = items.length; _i < _len; _i++) {
        item = items[_i];
        if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) {
          if (entry.isFile) {
            _results.push(this.addFile(item.getAsFile()));
          } else if (entry.isDirectory) {
            _results.push(this._addFilesFromDirectory(entry, entry.name));
          } else {
            _results.push(void 0);
          }
        } else if (item.getAsFile != null) {
          if ((item.kind == null) || item.kind === "file") {
            _results.push(this.addFile(item.getAsFile()));
          } else {
            _results.push(void 0);
          }
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    };

    Dropzone.prototype._addFilesFromDirectory = function(directory, path) {
      var dirReader, entriesReader;
      dirReader = directory.createReader();
      entriesReader = (function(_this) {
        return function(entries) {
          var entry, _i, _len;
          for (_i = 0, _len = entries.length; _i < _len; _i++) {
            entry = entries[_i];
            if (entry.isFile) {
              entry.file(function(file) {
                if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') {
                  return;
                }
                file.fullPath = "" + path + "/" + file.name;
                return _this.addFile(file);
              });
            } else if (entry.isDirectory) {
              _this._addFilesFromDirectory(entry, "" + path + "/" + entry.name);
            }
          }
        };
      })(this);
      return dirReader.readEntries(entriesReader, function(error) {
        return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0;
      });
    };

    Dropzone.prototype.accept = function(file, done) {
      if (file.size > this.options.maxFilesize * 1024 * 1024) {
        return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize));
      } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) {
        return done(this.options.dictInvalidFileType);
      } else if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) {
        done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles));
        return this.emit("maxfilesexceeded", file);
      } else {
        return this.options.accept.call(this, file, done);
      }
    };

    Dropzone.prototype.addFile = function(file) {
      file.upload = {
        progress: 0,
        total: file.size,
        bytesSent: 0
      };
      this.files.push(file);
      file.status = Dropzone.ADDED;
      this.emit("addedfile", file);
      this._enqueueThumbnail(file);
      return this.accept(file, (function(_this) {
        return function(error) {
          if (error) {
            file.accepted = false;
            _this._errorProcessing([file], error);
          } else {
            file.accepted = true;
            if (_this.options.autoQueue) {
              _this.enqueueFile(file);
            }
          }
          return _this._updateMaxFilesReachedClass();
        };
      })(this));
    };

    Dropzone.prototype.enqueueFiles = function(files) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        this.enqueueFile(file);
      }
      return null;
    };

    Dropzone.prototype.enqueueFile = function(file) {
      if (file.status === Dropzone.ADDED && file.accepted === true) {
        file.status = Dropzone.QUEUED;
        if (this.options.autoProcessQueue) {
          return setTimeout(((function(_this) {
            return function() {
              return _this.processQueue();
            };
          })(this)), 0);
        }
      } else {
        throw new Error("This file can't be queued because it has already been processed or was rejected.");
      }
    };

    Dropzone.prototype._thumbnailQueue = [];

    Dropzone.prototype._processingThumbnail = false;

    Dropzone.prototype._enqueueThumbnail = function(file) {
      if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) {
        this._thumbnailQueue.push(file);
        return setTimeout(((function(_this) {
          return function() {
            return _this._processThumbnailQueue();
          };
        })(this)), 0);
      }
    };

    Dropzone.prototype._processThumbnailQueue = function() {
      if (this._processingThumbnail || this._thumbnailQueue.length === 0) {
        return;
      }
      this._processingThumbnail = true;
      return this.createThumbnail(this._thumbnailQueue.shift(), (function(_this) {
        return function() {
          _this._processingThumbnail = false;
          return _this._processThumbnailQueue();
        };
      })(this));
    };

    Dropzone.prototype.removeFile = function(file) {
      if (file.status === Dropzone.UPLOADING) {
        this.cancelUpload(file);
      }
      this.files = without(this.files, file);
      this.emit("removedfile", file);
      if (this.files.length === 0) {
        return this.emit("reset");
      }
    };

    Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) {
      var file, _i, _len, _ref;
      if (cancelIfNecessary == null) {
        cancelIfNecessary = false;
      }
      _ref = this.files.slice();
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        file = _ref[_i];
        if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) {
          this.removeFile(file);
        }
      }
      return null;
    };

    Dropzone.prototype.createThumbnail = function(file, callback) {
      var fileReader;
      fileReader = new FileReader;
      fileReader.onload = (function(_this) {
        return function() {
          if (file.type === "image/svg+xml") {
            _this.emit("thumbnail", file, fileReader.result);
            if (callback != null) {
              callback();
            }
            return;
          }
          return _this.createThumbnailFromUrl(file, fileReader.result, callback);
        };
      })(this);
      return fileReader.readAsDataURL(file);
    };

    Dropzone.prototype.createThumbnailFromUrl = function(file, imageUrl, callback) {
      var img;
      img = document.createElement("img");
      img.onload = (function(_this) {
        return function() {
          var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3;
          file.width = img.width;
          file.height = img.height;
          resizeInfo = _this.options.resize.call(_this, file);
          if (resizeInfo.trgWidth == null) {
            resizeInfo.trgWidth = resizeInfo.optWidth;
          }
          if (resizeInfo.trgHeight == null) {
            resizeInfo.trgHeight = resizeInfo.optHeight;
          }
          canvas = document.createElement("canvas");
          ctx = canvas.getContext("2d");
          canvas.width = resizeInfo.trgWidth;
          canvas.height = resizeInfo.trgHeight;
          drawImageIOSFix(ctx, img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight);
          thumbnail = canvas.toDataURL("image/png");
          _this.emit("thumbnail", file, thumbnail);
          if (callback != null) {
            return callback();
          }
        };
      })(this);
      if (callback != null) {
        img.onerror = callback;
      }
      return img.src = imageUrl;
    };

    Dropzone.prototype.processQueue = function() {
      var i, parallelUploads, processingLength, queuedFiles;
      parallelUploads = this.options.parallelUploads;
      processingLength = this.getUploadingFiles().length;
      i = processingLength;
      if (processingLength >= parallelUploads) {
        return;
      }
      queuedFiles = this.getQueuedFiles();
      if (!(queuedFiles.length > 0)) {
        return;
      }
      if (this.options.uploadMultiple) {
        return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength));
      } else {
        while (i < parallelUploads) {
          if (!queuedFiles.length) {
            return;
          }
          this.processFile(queuedFiles.shift());
          i++;
        }
      }
    };

    Dropzone.prototype.processFile = function(file) {
      return this.processFiles([file]);
    };

    Dropzone.prototype.processFiles = function(files) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        file.processing = true;
        file.status = Dropzone.UPLOADING;
        this.emit("processing", file);
      }
      if (this.options.uploadMultiple) {
        this.emit("processingmultiple", files);
      }
      return this.uploadFiles(files);
    };

    Dropzone.prototype._getFilesWithXhr = function(xhr) {
      var file, files;
      return files = (function() {
        var _i, _len, _ref, _results;
        _ref = this.files;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          file = _ref[_i];
          if (file.xhr === xhr) {
            _results.push(file);
          }
        }
        return _results;
      }).call(this);
    };

    Dropzone.prototype.cancelUpload = function(file) {
      var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref;
      if (file.status === Dropzone.UPLOADING) {
        groupedFiles = this._getFilesWithXhr(file.xhr);
        for (_i = 0, _len = groupedFiles.length; _i < _len; _i++) {
          groupedFile = groupedFiles[_i];
          groupedFile.status = Dropzone.CANCELED;
        }
        file.xhr.abort();
        for (_j = 0, _len1 = groupedFiles.length; _j < _len1; _j++) {
          groupedFile = groupedFiles[_j];
          this.emit("canceled", groupedFile);
        }
        if (this.options.uploadMultiple) {
          this.emit("canceledmultiple", groupedFiles);
        }
      } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) {
        file.status = Dropzone.CANCELED;
        this.emit("canceled", file);
        if (this.options.uploadMultiple) {
          this.emit("canceledmultiple", [file]);
        }
      }
      if (this.options.autoProcessQueue) {
        return this.processQueue();
      }
    };

    resolveOption = function() {
      var args, option;
      option = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      if (typeof option === 'function') {
        return option.apply(this, args);
      }
      return option;
    };

    Dropzone.prototype.uploadFile = function(file) {
      return this.uploadFiles([file]);
    };

    Dropzone.prototype.uploadFiles = function(files) {
      var file, formData, handleError, headerName, headerValue, headers, i, input, inputName, inputType, key, method, option, progressObj, response, updateProgress, url, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _m, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
      xhr = new XMLHttpRequest();
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        file.xhr = xhr;
      }
      method = resolveOption(this.options.method, files);
      url = resolveOption(this.options.url, files);
      xhr.open(method, url, true);
      xhr.withCredentials = !!this.options.withCredentials;
      response = null;
      handleError = (function(_this) {
        return function() {
          var _j, _len1, _results;
          _results = [];
          for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
            file = files[_j];
            _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr));
          }
          return _results;
        };
      })(this);
      updateProgress = (function(_this) {
        return function(e) {
          var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results;
          if (e != null) {
            progress = 100 * e.loaded / e.total;
            for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
              file = files[_j];
              file.upload = {
                progress: progress,
                total: e.total,
                bytesSent: e.loaded
              };
            }
          } else {
            allFilesFinished = true;
            progress = 100;
            for (_k = 0, _len2 = files.length; _k < _len2; _k++) {
              file = files[_k];
              if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) {
                allFilesFinished = false;
              }
              file.upload.progress = progress;
              file.upload.bytesSent = file.upload.total;
            }
            if (allFilesFinished) {
              return;
            }
          }
          _results = [];
          for (_l = 0, _len3 = files.length; _l < _len3; _l++) {
            file = files[_l];
            _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent));
          }
          return _results;
        };
      })(this);
      xhr.onload = (function(_this) {
        return function(e) {
          var _ref;
          if (files[0].status === Dropzone.CANCELED) {
            return;
          }
          if (xhr.readyState !== 4) {
            return;
          }
          response = xhr.responseText;
          if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) {
            try {
              response = JSON.parse(response);
            } catch (_error) {
              e = _error;
              response = "Invalid JSON response from server.";
            }
          }
          updateProgress();
          if (!((200 <= (_ref = xhr.status) && _ref < 300))) {
            return handleError();
          } else {
            return _this._finished(files, response, e);
          }
        };
      })(this);
      xhr.onerror = (function(_this) {
        return function() {
          if (files[0].status === Dropzone.CANCELED) {
            return;
          }
          return handleError();
        };
      })(this);
      progressObj = (_ref = xhr.upload) != null ? _ref : xhr;
      progressObj.onprogress = updateProgress;
      headers = {
        "Accept": "application/json",
        "Cache-Control": "no-cache",
        "X-Requested-With": "XMLHttpRequest"
      };
      if (this.options.headers) {
        extend(headers, this.options.headers);
      }
      for (headerName in headers) {
        headerValue = headers[headerName];
        xhr.setRequestHeader(headerName, headerValue);
      }
      formData = new FormData();
      if (this.options.params) {
        _ref1 = this.options.params;
        for (key in _ref1) {
          value = _ref1[key];
          formData.append(key, value);
        }
      }
      for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
        file = files[_j];
        this.emit("sending", file, xhr, formData);
      }
      if (this.options.uploadMultiple) {
        this.emit("sendingmultiple", files, xhr, formData);
      }
      if (this.element.tagName === "FORM") {
        _ref2 = this.element.querySelectorAll("input, textarea, select, button");
        for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
          input = _ref2[_k];
          inputName = input.getAttribute("name");
          inputType = input.getAttribute("type");
          if (input.tagName === "SELECT" && input.hasAttribute("multiple")) {
            _ref3 = input.options;
            for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
              option = _ref3[_l];
              if (option.selected) {
                formData.append(inputName, option.value);
              }
            }
          } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" && _ref4 !== "radio") || input.checked) {
            formData.append(inputName, input.value);
          }
        }
      }
      for (i = _m = 0, _ref5 = files.length - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; i = 0 <= _ref5 ? ++_m : --_m) {
        formData.append(this._getParamName(i), files[i], files[i].name);
      }
      return xhr.send(formData);
    };

    Dropzone.prototype._finished = function(files, responseText, e) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        file.status = Dropzone.SUCCESS;
        this.emit("success", file, responseText, e);
        this.emit("complete", file);
      }
      if (this.options.uploadMultiple) {
        this.emit("successmultiple", files, responseText, e);
        this.emit("completemultiple", files);
      }
      if (this.options.autoProcessQueue) {
        return this.processQueue();
      }
    };

    Dropzone.prototype._errorProcessing = function(files, message, xhr) {
      var file, _i, _len;
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        file.status = Dropzone.ERROR;
        this.emit("error", file, message, xhr);
        this.emit("complete", file);
      }
      if (this.options.uploadMultiple) {
        this.emit("errormultiple", files, message, xhr);
        this.emit("completemultiple", files);
      }
      if (this.options.autoProcessQueue) {
        return this.processQueue();
      }
    };

    return Dropzone;

  })(Emitter);

  Dropzone.version = "4.0.1";

  Dropzone.options = {};

  Dropzone.optionsForElement = function(element) {
    if (element.getAttribute("id")) {
      return Dropzone.options[camelize(element.getAttribute("id"))];
    } else {
      return void 0;
    }
  };

  Dropzone.instances = [];

  Dropzone.forElement = function(element) {
    if (typeof element === "string") {
      element = document.querySelector(element);
    }
    if ((element != null ? element.dropzone : void 0) == null) {
      throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");
    }
    return element.dropzone;
  };

  Dropzone.autoDiscover = true;

  Dropzone.discover = function() {
    var checkElements, dropzone, dropzones, _i, _len, _results;
    if (document.querySelectorAll) {
      dropzones = document.querySelectorAll(".dropzone");
    } else {
      dropzones = [];
      checkElements = function(elements) {
        var el, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = elements.length; _i < _len; _i++) {
          el = elements[_i];
          if (/(^| )dropzone($| )/.test(el.className)) {
            _results.push(dropzones.push(el));
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };
      checkElements(document.getElementsByTagName("div"));
      checkElements(document.getElementsByTagName("form"));
    }
    _results = [];
    for (_i = 0, _len = dropzones.length; _i < _len; _i++) {
      dropzone = dropzones[_i];
      if (Dropzone.optionsForElement(dropzone) !== false) {
        _results.push(new Dropzone(dropzone));
      } else {
        _results.push(void 0);
      }
    }
    return _results;
  };

  Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i];

  Dropzone.isBrowserSupported = function() {
    var capableBrowser, regex, _i, _len, _ref;
    capableBrowser = true;
    if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) {
      if (!("classList" in document.createElement("a"))) {
        capableBrowser = false;
      } else {
        _ref = Dropzone.blacklistedBrowsers;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          regex = _ref[_i];
          if (regex.test(navigator.userAgent)) {
            capableBrowser = false;
            continue;
          }
        }
      }
    } else {
      capableBrowser = false;
    }
    return capableBrowser;
  };

  without = function(list, rejectedItem) {
    var item, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = list.length; _i < _len; _i++) {
      item = list[_i];
      if (item !== rejectedItem) {
        _results.push(item);
      }
    }
    return _results;
  };

  camelize = function(str) {
    return str.replace(/[\-_](\w)/g, function(match) {
      return match.charAt(1).toUpperCase();
    });
  };

  Dropzone.createElement = function(string) {
    var div;
    div = document.createElement("div");
    div.innerHTML = string;
    return div.childNodes[0];
  };

  Dropzone.elementInside = function(element, container) {
    if (element === container) {
      return true;
    }
    while (element = element.parentNode) {
      if (element === container) {
        return true;
      }
    }
    return false;
  };

  Dropzone.getElement = function(el, name) {
    var element;
    if (typeof el === "string") {
      element = document.querySelector(el);
    } else if (el.nodeType != null) {
      element = el;
    }
    if (element == null) {
      throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element.");
    }
    return element;
  };

  Dropzone.getElements = function(els, name) {
    var e, el, elements, _i, _j, _len, _len1, _ref;
    if (els instanceof Array) {
      elements = [];
      try {
        for (_i = 0, _len = els.length; _i < _len; _i++) {
          el = els[_i];
          elements.push(this.getElement(el, name));
        }
      } catch (_error) {
        e = _error;
        elements = null;
      }
    } else if (typeof els === "string") {
      elements = [];
      _ref = document.querySelectorAll(els);
      for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
        el = _ref[_j];
        elements.push(el);
      }
    } else if (els.nodeType != null) {
      elements = [els];
    }
    if (!((elements != null) && elements.length)) {
      throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");
    }
    return elements;
  };

  Dropzone.confirm = function(question, accepted, rejected) {
    if (window.confirm(question)) {
      return accepted();
    } else if (rejected != null) {
      return rejected();
    }
  };

  Dropzone.isValidFile = function(file, acceptedFiles) {
    var baseMimeType, mimeType, validType, _i, _len;
    if (!acceptedFiles) {
      return true;
    }
    acceptedFiles = acceptedFiles.split(",");
    mimeType = file.type;
    baseMimeType = mimeType.replace(/\/.*$/, "");
    for (_i = 0, _len = acceptedFiles.length; _i < _len; _i++) {
      validType = acceptedFiles[_i];
      validType = validType.trim();
      if (validType.charAt(0) === ".") {
        if (file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) {
          return true;
        }
      } else if (/\/\*$/.test(validType)) {
        if (baseMimeType === validType.replace(/\/.*$/, "")) {
          return true;
        }
      } else {
        if (mimeType === validType) {
          return true;
        }
      }
    }
    return false;
  };

  if (typeof jQuery !== "undefined" && jQuery !== null) {
    jQuery.fn.dropzone = function(options) {
      return this.each(function() {
        return new Dropzone(this, options);
      });
    };
  }

  if (typeof module !== "undefined" && module !== null) {
    module.exports = Dropzone;
  } else {
    window.Dropzone = Dropzone;
  }

  Dropzone.ADDED = "added";

  Dropzone.QUEUED = "queued";

  Dropzone.ACCEPTED = Dropzone.QUEUED;

  Dropzone.UPLOADING = "uploading";

  Dropzone.PROCESSING = Dropzone.UPLOADING;

  Dropzone.CANCELED = "canceled";

  Dropzone.ERROR = "error";

  Dropzone.SUCCESS = "success";


  /*
  
  Bugfix for iOS 6 and 7
  Source: http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios
  based on the work of https://github.com/stomita/ios-imagefile-megapixel
   */

  detectVerticalSquash = function(img) {
    var alpha, canvas, ctx, data, ey, ih, iw, py, ratio, sy;
    iw = img.naturalWidth;
    ih = img.naturalHeight;
    canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = ih;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    data = ctx.getImageData(0, 0, 1, ih).data;
    sy = 0;
    ey = ih;
    py = ih;
    while (py > sy) {
      alpha = data[(py - 1) * 4 + 3];
      if (alpha === 0) {
        ey = py;
      } else {
        sy = py;
      }
      py = (ey + sy) >> 1;
    }
    ratio = py / ih;
    if (ratio === 0) {
      return 1;
    } else {
      return ratio;
    }
  };

  drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
    var vertSquashRatio;
    vertSquashRatio = detectVerticalSquash(img);
    return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
  };


  /*
   * contentloaded.js
   *
   * Author: Diego Perini (diego.perini at gmail.com)
   * Summary: cross-browser wrapper for DOMContentLoaded
   * Updated: 20101020
   * License: MIT
   * Version: 1.2
   *
   * URL:
   * http://javascript.nwbox.com/ContentLoaded/
   * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
   */

  contentLoaded = function(win, fn) {
    var add, doc, done, init, poll, pre, rem, root, top;
    done = false;
    top = true;
    doc = win.document;
    root = doc.documentElement;
    add = (doc.addEventListener ? "addEventListener" : "attachEvent");
    rem = (doc.addEventListener ? "removeEventListener" : "detachEvent");
    pre = (doc.addEventListener ? "" : "on");
    init = function(e) {
      if (e.type === "readystatechange" && doc.readyState !== "complete") {
        return;
      }
      (e.type === "load" ? win : doc)[rem](pre + e.type, init, false);
      if (!done && (done = true)) {
        return fn.call(win, e.type || e);
      }
    };
    poll = function() {
      var e;
      try {
        root.doScroll("left");
      } catch (_error) {
        e = _error;
        setTimeout(poll, 50);
        return;
      }
      return init("poll");
    };
    if (doc.readyState !== "complete") {
      if (doc.createEventObject && root.doScroll) {
        try {
          top = !win.frameElement;
        } catch (_error) {}
        if (top) {
          poll();
        }
      }
      doc[add](pre + "DOMContentLoaded", init, false);
      doc[add](pre + "readystatechange", init, false);
      return win[add](pre + "load", init, false);
    }
  };

  Dropzone._autoDiscoverFunction = function() {
    if (Dropzone.autoDiscover) {
      return Dropzone.discover();
    }
  };

  contentLoaded(window, Dropzone._autoDiscoverFunction);

}).call(this);

    return module.exports;
}));

define('text!mockup-patterns-upload-url/templates/upload.xml',[],function () { return '<div class="upload-container upload-multiple">\n    <h2 class="title"><%- _t("Upload here") %></h2>\n    <p class="help">\n        <%- _t(\'Drag and drop files from your computer onto the area below or click the "Browse" button.\') %>\n    </p>\n    <div class="upload-area">\n        <div class="fallback">\n            <input name="file" type="file" multiple />\n        </div>\n        <div class="dz-message"><p><%-_t("Drop files here...")%></p></div>\n        <div class="row browse-select">\n            <div class="col-md-9">\n                <input\n                    id="fakeUploadFile"\n                    placeholder="<%- _t("Choose File") %>"\n                    disabled="disabled"\n                    />\n            </div>\n            <div class="col-md-3">\n                <button\n                    type="button"\n                    class="btn btn-primary browse">\n                    Browse\n                </button>\n            </div>\n        </div>\n        <div class="upload-queue">\n            <div class="previews">\n            </div>\n            <div class="controls">\n                <% if (allowPathSelection) { %>\n                <div class="path">\n                    <label><%- _t("Upload to...") %></label>\n                    <p class="form-help">\n                        <%- _t("Select another destination folder or leave blank to add files to the current location.") %>\n                    </p>\n                    <input\n                        type="text"\n                        name="location"\n                        />\n                </div>\n                <% } %>\n                <div class="actions row">\n                    <div class="col-md-9">\n                        <div class="progress progress-striped active">\n                            <div class="progress-bar progress-bar-success"\n                                 role="progressbar"\n                                 aria-valuenow="0"\n                                 aria-valuemin="0"\n                                 aria-valuemax="100"\n                                 style="width: 0%">\n                                <span class="sr-only">40% Complete (success)</span>\n                            </div>\n                        </div>\n                    </div>\n                    <div class="col-md-3 align-right">\n                        <button\n                            type="button"\n                            class="btn btn-primary upload-all">\n                            <%- _t("Upload") %>\n                        </button>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n</div>\n';});


define('text!mockup-patterns-upload-url/templates/preview.xml',[],function () { return '<div class="row item form-inline">\n    <div class="col-md-1 action">\n        <button\n            type="button"\n            class="btn btn-danger btn-xs remove-item"\n            data-dz-remove=""\n            href="javascript:undefined;">\n            <span class="glyphicon glyphicon-remove"></span>\n        </button>\n    </div>\n    <div class="col-md-8 title">\n        <div class="dz-preview">\n          <div class="dz-details">\n            <div class="dz-filename"><span data-dz-name></span></div>\n          </div>\n          <div class="dz-error-message"><span data-dz-errormessage></span></div>\n        </div>\n        <div class="dz-progress">\n            <span class="dz-upload" data-dz-uploadprogress></span>\n        </div>\n    </div>\n    <div class="col-md-3 info">\n        <div class="dz-size" data-dz-size></div>\n        <img data-dz-thumbnail />\n    </div>\n</div>\n';});

/* Upload pattern.
 *
 * Options:
 *    showTitle(boolean): show/hide the h1 title (true)
 *    url(string): If not used with a form, this option must provide the URL to submit to or baseUrl with relativePath needs to be used (null)
 *    baseUrl(string): to be used in conjunction with relativePath to generate submission urls based on related items (null)
 *    relativePath(string): again, to be used with baseUrl to create upload url (null)
 *    initialFolder(string): UID of initial folder related items widget should have selected (null)
 *    currentPath(string): Current path related items is starting with (null)
 *    className(string): value for class attribute in the form element ('upload')
 *    paramName(string): value for name attribute in the file input element ('file')
 *    ajaxUpload(boolean): true or false for letting the widget upload the files via ajax. If false the form will act like a normal form. (true)
 *    wrap(boolean): true or false for wrapping this element using the value of wrapperTemplate. (false)
 *    wrapperTemplate(string): HTML template for wrapping around with this element. ('<div class="upload-container"/>')
 *    resultTemplate(string): HTML template for the element that will contain file information. ('<div class="dz-notice"><p>Drop files here...</p></div><div class="upload-previews"/>')
 *    autoCleanResults(boolean): condition value for the file preview in div element to fadeout after file upload is completed. (true)
 *    previewsContainer(selector): JavaScript selector for file preview in div element. (.upload-previews)
 *    container(selector): JavaScript selector for where to put upload stuff into in case of form. If not provided it will be place before the first submit button. ('')
 *    allowPathSelection(boolean): Use relatedItems to set a different path from the current path. (true, if baseUrl and relativePath are set)
 *    relatedItems(object): Related items pattern options. Will only be used if allowPathSelection is true. ({ attributes: ["UID", "Title", "Description", "getURL", "portal_type", "path", "ModificationDate"], batchSize: 20, basePath: "/", vocabularyUrl: null, width: 500, maximumSelectionSize: 1, placeholder: "Search for item on site..." })
 *
 * Documentation:
 *
 *    # On a div element
 *
 *    {{ example-1 }}
 *
 * Example: example-1
 *    <div class="pat-upload" data-pat-upload='{"url": "/upload",
 *                                              "relatedItems": {
 *                                                  "vocabularyUrl": "/relateditems-test.json"
 *                                              }}'>
 *      <div>
 *        <p>Something here that is useful</p>
 *        <p>Something else here that is useful</p>
 *        <p>Another thing here that is useful</p>
 *      </div>
 *    </div>
 *
 */


define('mockup-patterns-upload',[
  'jquery',
  'underscore',
  'pat-base',
  'mockup-patterns-relateditems',
  'dropzone',
  'text!mockup-patterns-upload-url/templates/upload.xml',
  'text!mockup-patterns-upload-url/templates/preview.xml',
  'translate'
], function($, _, Base, RelatedItems, Dropzone,
            UploadTemplate, PreviewTemplate, _t) {
  'use strict';

  /* we do not want this plugin to auto discover */
  Dropzone.autoDiscover = false;

  var UploadPattern = Base.extend({
    name: 'upload',
    trigger: '.pat-upload',
    parser: 'mockup',
    defaults: {
      showTitle: true,
      url: null, // XXX MUST provide url to submit to OR be in a form
      className: 'upload',
      wrap: false,
      wrapperTemplate: '<div class="upload-wrapper"/>',
      fileaddedClassName: 'dropping',
      useTus: false,
      container: '',
      ajaxUpload: true,

      paramName: 'file',
      addRemoveLinks: false,
      autoCleanResults: true,
      previewsContainer: '.previews',
      previewTemplate: null,
      maxFiles: null,
      maxFilesize: 99999999, // let's not have a max by default...

      allowPathSelection: undefined,
      relatedItems: {
        // UID attribute is required here since we're working with related items
        attributes: ['UID', 'Title', 'Description', 'getURL', 'portal_type', 'path', 'ModificationDate'],
        batchSize: 20,
        basePath: '/',
        vocabularyUrl: null,
        width: 500,
        maximumSelectionSize: 1,
        selectableTypes: ['Folder']
      }
    },

    init: function() {
      var self = this,
          template = UploadTemplate;

      if (typeof self.options.allowPathSelection === 'undefined') {
        // Set allowPathSelection to true, if we can use path based urls.
        self.options.allowPathSelection = self.options.baseUrl && self.options.relativePath;
      }

      // TODO: find a way to make this work in firefox (and IE)
      $(document).bind('paste', function(e) {
        var oe = e.originalEvent;
        var items = oe.clipboardData.items;
        if (items) {
          for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf('image') !== -1) {
              var blob = items[i].getAsFile();
              self.dropzone.addFile(blob);
            }
          }
        }
      });
      // values that will change current processing
      self.currentPath = self.options.currentPath;
      self.currentFile = 0;

      template = _.template(template)({
        _t: _t,
        allowPathSelection: self.options.allowPathSelection
      });
      self.$el.addClass(self.options.className);
      self.$el.append(template);

      self.$progress = $('.progress-bar-success', self.$el);

      if (!self.options.showTitle) {
        self.$el.find('h2.title').hide();
      }

      if (!self.options.ajaxUpload) {
        // no ajax upload, drop the fallback
        $('.fallback', this.$el).remove();
        if (this.$el.hasClass('.upload-container')) {
          this.$el.addClass('no-ajax-upload');
        } else {
          this.$el.closest('.upload-container').addClass('no-ajax-upload');
        }
      }

      if (self.options.wrap) {
        self.$el.wrap(self.options.wrapperTemplate);
        self.$el = self.$el.parent();
      }

      if (self.options.allowPathSelection) {
        // only use related items if we can generate path based urls and if it's not turned off.
        self.$pathInput = $('input[name="location"]', self.$el);
        self.relatedItems = self.setupRelatedItems(self.$pathInput);
      } else {
        $('input[name="location"]', self.$el).parent().remove();
        self.relatedItems = null;
      }

      self.$dropzone = $('.upload-area', self.$el);

      $('div.browse-select button.browse', self.$el).click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        if(!self.options.maxFiles || self.dropzone.files.length < self.options.maxFiles){
          self.dropzone.hiddenFileInput.click();
        }
      });

      var dzoneOptions = this.getDzoneOptions();

      try {
        // if init of Dropzone fails it says nothing and
        // it fails silently. Using this block we make sure
        // that if you break it w/ some weird or missing option
        // you can get a proper log of it
        //
        self.dropzone = new Dropzone(self.$dropzone[0], dzoneOptions);
      } catch (e) {
        if (window.DEBUG) {
          // log it!
          console.log(e);
        }
        throw e;
      }

      self.dropzone.on('maxfilesreached', function(){
        self.showHideControls();
      });

      self.dropzone.on('addedfile', function(/* file */) {
        self.showHideControls();
      });

      self.dropzone.on('removedfile', function() {
        self.showHideControls();
      });

      self.dropzone.on('success', function(e, response){
        // Trigger event 'uploadAllCompleted' and pass the server's reponse and
        // the path uid. This event can be listened to by patterns using the
        // upload pattern, e.g. the TinyMCE pattern's link plugin.
        var data;
        try{
          data = $.parseJSON(response);
        }catch(ex){
          data = response;
        }
        self.$el.trigger('uploadAllCompleted', {
          'data': data,
          'path_uid': (self.$pathInput) ? self.$pathInput.val() : null
        });
      });

      if (self.options.autoCleanResults) {
        self.dropzone.on('complete', function(file) {
          if (file.status === Dropzone.SUCCESS){
            setTimeout(function() {
              $(file.previewElement).fadeOut();
            }, 3000);
          }
        });
      }

      self.dropzone.on('complete', function(file) {
        if (file.status === Dropzone.SUCCESS && self.dropzone.files.length === 1) {
          self.showHideControls();
        }
      });

      self.dropzone.on('error', function(file, response, xmlhr) {
        if (typeof(xmlhr) !== 'undefined' && xmlhr.status !== 403){
          // If error other than 403, just print a generic message
          $('.dz-error-message span', file.previewElement).html(_t('The file transfer failed'));
        }
      });

      self.dropzone.on('totaluploadprogress', function(pct) {
        // need to caclulate total pct here in reality since we're manually
        // processing each file one at a time.
        pct = ((((self.currentFile - 1) * 100) + pct) / (self.dropzone.files.length * 100)) * 100;
        self.$progress.attr('aria-valuenow', pct).css('width', pct + '%');
      });

      $('.upload-all', self.$el).click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        self.processUpload({
          finished: function() {
            self.$progress.attr('aria-valuenow', 0).css('width', '0%');
          }
        });
      });
      if(self.options.clipboardfile){
        self.dropzone.addFile(self.options.clipboardfile);
      }
    },

    showHideControls: function(){
      /* we do this delayed because this can be called multiple times
         AND we need to do this hide/show AFTER dropzone is done with
         all it's own events. This is NASTY but the only way we can
         enforce some numFiles with dropzone! */
      var self = this;
      if(self._showHideTimeout){
        clearTimeout(self._showHideTimeout);
      }
      self._showHideTimeout = setTimeout(function(){
        self._showHideControls();
      }, 50);
    },

    _showHideControls: function(){
      var self = this;
      var $controls = $('.controls', self.$el);
      var $browse = $('.browse-select', self.$el);
      var $input = $('.dz-hidden-input');

      if(self.options.maxFiles){
        if(self.dropzone.files.length < self.options.maxFiles){
          $browse.show();
          $input.prop('disabled', false);
        }else{
          $browse.hide();
          $input.prop('disabled', true);
        }
      }
      if(self.dropzone.files.length > 0){
        $controls.fadeIn('slow');
        var file = self.dropzone.files[0];
        $('.dz-error-message span', file.previewElement).html('');
      }else{
        $controls.fadeOut('slow');
      }
    },

    pathJoin: function() {
      var parts = [];
      _.each(arguments, function(part) {
        if (!part){
          return;
        }
        if (part[0] === '/'){
          part = part.substring(1);
        }
        if (part[part.length - 1] === '/'){
          part = part.substring(0, part.length - 1);
        }
        parts.push(part);
      });
      return parts.join('/');
    },

    getUrl: function() {

      var self = this;
      var url = self.options.url;
      if (!url) {
        if (self.options.baseUrl && self.options.relativePath){
          url = self.options.baseUrl;
          if (url[url.length - 1] !== '/'){
            url = url + '/';
          }
          url = url + self.pathJoin(self.currentPath, self.options.relativePath);
        } else {
          var $form = self.$el.parents('form');
          if ($form.length > 0){
            url = $form.attr('action');
          } else {
            url = window.location.href;
          }
        }
      }
      return url;
    },

    getDzoneOptions: function() {
      var self = this;

      // This pattern REQUIRE dropzone to be clickable
      self.options.clickable = true;

      var options = $.extend({}, self.options);
      options.url = self.getUrl();

      // XXX force to only upload one to the server at a time,
      // right now we don't support multiple for backends
      options.uploadMultiple = false;

      delete options.wrap;
      delete options.wrapperTemplate;
      delete options.resultTemplate;
      delete options.autoCleanResults;
      delete options.fileaddedClassName;
      delete options.useTus;

      if (self.options.previewsContainer) {
        /*
         * if they have a select but it's not an id, let's make an id selector
         * so we can target the correct container. dropzone is weird here...
         */
        var $preview = self.$el.find(self.options.previewsContainer);
        if ($preview.length > 0) {
          options.previewsContainer = $preview[0];
        }
      }

      // XXX: do we need to allow this?
      options.autoProcessQueue = false;
      // options.addRemoveLinks = true;  // we show them in the template
      options.previewTemplate = PreviewTemplate;

      // if our element is a form we should force some values
      // https://github.com/enyo/dropzone/wiki/Combine-normal-form-with-Dropzone
      return options;
    },

    processUpload: function(options) {
      if (!options){
        options = {};
      }

      var self = this,
          processing = false,
          useTus = self.options.useTus,
          fileaddedClassName = self.options.fileaddedClassName,
          finished = options.finished;

      self.currentFile = 0;

      function process() {
        processing = true;
        if (self.dropzone.files.length === 0) {
          processing = false;
        }

        var file = self.dropzone.files[0];
        if (processing && file.status === Dropzone.ERROR){
          // Put the file back as "queued" for retrying
          file.status = Dropzone.QUEUED;
          processing = false;
        }

        if (!processing){
          self.$el.removeClass(fileaddedClassName);
          if (finished !== undefined && typeof(finished) === 'function'){
            finished();
          }
          return;
        }

        if ([Dropzone.SUCCESS, Dropzone.CANCELED]
            .indexOf(file.status) !== -1) {
          // remove it
          self.dropzone.removeFile(file);
          process();
        } else if (file.status !== Dropzone.UPLOADING) {
          // start processing file
          if (useTus && window.tus) {
            // use tus upload if installed
            self.handleTusUpload(file);
          } else {
            // otherwise, just use dropzone to process
            self.currentFile += 1;
            self.dropzone.processFile(file);
          }
          setTimeout(process, 100);
        } else {
          // currently processing
          setTimeout(process, 100);
        }
      }
      process();
    },

    handleTusUpload: function(file) {
      /* this needs fixing... */
      var self = this,
          $preview = $(file.previewElement),
          chunkSize = 1024 * 1024 * 5; // 5mb chunk size

      file.status = Dropzone.UPLOADING;

      window.tus.upload(file, {
        endpoint: self.dropzone.options.url,
        headers: {
          'FILENAME': file.name
        },
        chunkSize: chunkSize
      }).fail(function() {
        if(window.DEBUG){
          console.alert(_t('Error uploading with TUS resumable uploads'));
        }
        file.status = Dropzone.ERROR;
      }).progress(function(e, bytesUploaded, bytesTotal) {
        var percentage = (bytesUploaded / bytesTotal * 100);
        self.$progress.attr('aria-valuenow', percentage).css('width', percentage + '%');
        self.$progress.html(_t('uploading...') + '<br />' +
                            self.formatBytes(bytesUploaded) +
                            ' / ' + self.formatBytes(bytesTotal));
      }).done(function(url, file) {
        file.status = Dropzone.SUCCESS;
        self.dropzone.emit('success', file);
        self.dropzone.emit('complete', file);
      });
    },

    formatBytes: function(bytes) {
      var kb = Math.round(bytes / 1024);
      if (kb < 1024) {
        return kb + ' KiB';
      }
      var mb = Math.round(kb / 1024);
      if (mb < 1024) {
        return mb + ' MB';
      }
      return Math.round(mb / 1024) + ' GB';
    },

    setPath: function(path){
      var self = this;
      self.currentPath = path;
      self.options.url = null;
      self.options.url = self.dropzone.options.url = self.getUrl();
    },

    setupRelatedItems: function($input) {
      var self = this;
      var options = self.options.relatedItems;
      options.upload = false;  // ensure that related items upload is off.
      if (self.options.initialFolder){
        $input.attr('value', self.options.initialFolder);
      }
      var ri = new RelatedItems($input, options);
      ri.$el.on('change', function() {
        var result = $(this).select2('data');
        var path = null;
        if (result.length > 0){
          path = result[0].path;
        }
        self.setPath(path);
      });
      return ri;
    }

  });

  return UploadPattern;

});

define('castle-url/patterns/structure//js/views/upload',[
  'underscore',
  'mockup-ui-url/views/popover',
  'mockup-patterns-upload'
], function(_, PopoverView, Upload) {
  'use strict';

  var UploadView = PopoverView.extend({
    className: 'popover upload',
    title: _.template('<%- _t("Upload files") %>'),
    content: _.template(
      '<input type="text" name="upload" style="display:none" />' +
      '<div class="uploadify-me"></div>'),

    initialize: function(options) {
      var self = this;
      self.app = options.app;
      PopoverView.prototype.initialize.apply(self, [options]);
      self.currentPathData = null;
      self.app.on('context-info-loaded', function(data) {
        self.currentPathData = data;
      });
    },

    render: function() {
      var self = this;
      PopoverView.prototype.render.call(this);
      var options = self.app.options.upload;
      options.success = function() {
        self.app.collection.pager();
      };
      options.currentPath = self.app.getCurrentPath();
      options.allowPathSelection = false;
      self.upload = new Upload(self.$('.uploadify-me').addClass('pat-upload'), options);
      return this;
    },

    toggle: function(button, e) {
      /* we need to be able to change the current default upload directory */
      PopoverView.prototype.toggle.apply(this, [button, e]);
      var self = this;
      if (!this.opened) {
        return;
      }
      var currentPath = self.app.getCurrentPath();
      if (self.currentPathData && currentPath !== self.upload.currentPath){
        self.upload.setPath(currentPath);
      }
    }

  });

  return UploadView;
});

(function(root) {
define("backbone.paginator", ["backbone"], function() {
  return (function() {
/*globals Backbone:true, _:true, jQuery:true*/
Backbone.Paginator = (function ( Backbone, _, $ ) {
  "use strict";


  var bbVer = _.map(Backbone.VERSION.split('.'), function(digit) {
    return parseInt(digit, 10);
  });

  var Paginator = {};
  Paginator.version = "<%= pkg.version %>";

  // @name: clientPager
  //
  // @tagline: Paginator for client-side data
  //
  // @description:
  // This paginator is responsible for providing pagination
  // and sort capabilities for a single payload of data
  // we wish to paginate by the UI for easier browsering.
  //
  Paginator.clientPager = Backbone.Collection.extend({

    // DEFAULTS FOR SORTING & FILTERING
    useDiacriticsPlugin: true, // use diacritics plugin if available
    useLevenshteinPlugin: true, // use levenshtein plugin if available
    sortColumn: "",
    sortDirection: "desc",
    lastSortColumn: "",
    fieldFilterRules: [],
    lastFieldFilterRules: [],
    filterFields: "",
    filterExpression: "",
    lastFilterExpression: "",

    //DEFAULT PAGINATOR UI VALUES
    defaults_ui: {
      firstPage: 0,
      currentPage: 1,
      perPage: 5,
      totalPages: 10,
      pagesInRange: 4
    },

    // Default values used when sorting and/or filtering.
    initialize: function(){
      //LISTEN FOR ADD & REMOVE EVENTS THEN REMOVE MODELS FROM ORGINAL MODELS
      this.on('add', this.addModel, this);
      this.on('remove', this.removeModel, this);

      // SET DEFAULT VALUES (ALLOWS YOU TO POPULATE PAGINATOR MAUNALLY)
      this.setDefaults();
    },


    setDefaults: function() {
      // SET DEFAULT UI SETTINGS
      var options = _.defaults(this.paginator_ui, this.defaults_ui);

      //UPDATE GLOBAL UI SETTINGS
      _.defaults(this, options);
    },

    addModel: function(model) {
      this.origModels.push(model);
    },

    removeModel: function(model) {
      var index = _.indexOf(this.origModels, model);

      this.origModels.splice(index, 1);
    },

    sync: function ( method, model, options ) {
      var self = this;

      // SET DEFAULT VALUES
      this.setDefaults();

      // Some values could be functions, let's make sure
      // to change their scope too and run them
      var queryAttributes = {};
      _.each(_.result(self, "server_api"), function(value, key){
        if( _.isFunction(value) ) {
          value = _.bind(value, self);
          value = value();
        }
        queryAttributes[key] = value;
      });

      var queryOptions = _.clone(self.paginator_core);
      _.each(queryOptions, function(value, key){
        if( _.isFunction(value) ) {
          value = _.bind(value, self);
          value = value();
        }
        queryOptions[key] = value;
      });

      // Create default values if no others are specified
      queryOptions = _.defaults(queryOptions, {
        timeout: 25000,
        cache: false,
        type: 'GET',
        dataType: 'jsonp'
      });

      queryOptions = _.extend(queryOptions, {
        data: decodeURIComponent($.param(queryAttributes)),
        processData: false,
        url: _.result(queryOptions, 'url')
      }, options);

      var promiseSuccessFormat = !(bbVer[0] === 0 &&
                                   bbVer[1] === 9 &&
                                   bbVer[2] === 10);

      var success = queryOptions.success;
      queryOptions.success = function ( resp, status, xhr ) {
        if ( success ) {
          // This is to keep compatibility with Backbone 0.9.10
          if (promiseSuccessFormat) {
            success( resp, status, xhr );
          } else {
            success( model, resp, queryOptions );
          }
        }
        if ( model && model.trigger ) {
          model.trigger( 'sync', model, resp, queryOptions );
        }
      };

      var error = queryOptions.error;
      queryOptions.error = function ( xhr ) {
        if ( error ) {
          error( model, xhr, queryOptions );
        }
        if ( model && model.trigger ) {
          model.trigger( 'error', model, xhr, queryOptions );
        }
      };

      var xhr = queryOptions.xhr = Backbone.ajax( queryOptions );
      if ( model && model.trigger ) {
        model.trigger('request', model, xhr, queryOptions);
      }
      return xhr;
    },

    nextPage: function (options) {
      if(this.currentPage < this.information.totalPages) {
        this.currentPage = ++this.currentPage;
        this.pager(options);
      }
    },

    previousPage: function (options) {
      if(this.currentPage > 1) {
        this.currentPage = --this.currentPage;
        this.pager(options);
      }
    },

    goTo: function ( page, options ) {
      if(page !== undefined){
        this.currentPage = parseInt(page, 10);
        this.pager(options);
      }
    },

    howManyPer: function ( perPage ) {
      if(perPage !== undefined){
        var lastPerPage = this.perPage;
        this.perPage = parseInt(perPage, 10);
        this.currentPage = Math.ceil( ( lastPerPage * ( this.currentPage - 1 ) + 1 ) / perPage);
        this.pager();
      }
    },


    // setSort is used to sort the current model. After
    // passing 'column', which is the model's field you want
    // to filter and 'direction', which is the direction
    // desired for the ordering ('asc' or 'desc'), pager()
    // and info() will be called automatically.
    setSort: function ( column, direction ) {
      if(column !== undefined && direction !== undefined){
        this.lastSortColumn = this.sortColumn;
        this.sortColumn = column;
        this.sortDirection = direction;
        this.pager();
        this.info();
      }
    },

    // setFieldFilter is used to filter each value of each model
    // according to `rules` that you pass as argument.
    // Example: You have a collection of books with 'release year' and 'author'.
    // You can filter only the books that were released between 1999 and 2003
    // And then you can add another `rule` that will filter those books only to
    // authors who's name start with 'A'.
    setFieldFilter: function ( fieldFilterRules ) {
      if( !_.isEmpty( fieldFilterRules ) ) {
        this.lastFieldFilterRules = this.fieldFilterRules;
        this.fieldFilterRules = fieldFilterRules;
        this.pager();
        this.info();
        // if all the filters are removed, we should save the last filter
        // and then let the list reset to it's original state.
      } else {
        this.lastFieldFilterRules = this.fieldFilterRules;
        this.fieldFilterRules = '';
        this.pager();
        this.info();
      }
    },

    // doFakeFieldFilter can be used to get the number of models that will remain
    // after calling setFieldFilter with a filter rule(s)
    doFakeFieldFilter: function ( rules ) {
      if( !_.isEmpty( rules ) ) {
        var testModels = this.origModels;
        if (testModels === undefined) {
          testModels = this.models;
        }

        testModels = this._fieldFilter(testModels, rules);

        // To comply with current behavior, also filter by any previously defined setFilter rules.
        if ( this.filterExpression !== "" ) {
          testModels = this._filter(testModels, this.filterFields, this.filterExpression);
        }

        // Return size
        return testModels.length;
      }

    },

    // setFilter is used to filter the current model. After
    // passing 'fields', which can be a string referring to
    // the model's field, an array of strings representing
    // each of the model's fields or an object with the name
    // of the model's field(s) and comparing options (see docs)
    // you wish to filter by and
    // 'filter', which is the word or words you wish to
    // filter by, pager() and info() will be called automatically.
    setFilter: function ( fields, filter ) {
      if( fields !== undefined && filter !== undefined ){
        this.filterFields = fields;
        this.lastFilterExpression = this.filterExpression;
        this.filterExpression = filter;
        this.pager();
        this.info();
      }
    },

    // doFakeFilter can be used to get the number of models that will
    // remain after calling setFilter with a `fields` and `filter` args.
    doFakeFilter: function ( fields, filter ) {
      if( fields !== undefined && filter !== undefined ){
        var testModels = this.origModels;
        if (testModels === undefined) {
          testModels = this.models;
        }

        // To comply with current behavior, first filter by any previously defined setFieldFilter rules.
        if ( !_.isEmpty( this.fieldFilterRules ) ) {
          testModels = this._fieldFilter(testModels, this.fieldFilterRules);
        }

        testModels = this._filter(testModels, fields, filter);

        // Return size
        return testModels.length;
      }
    },


    // pager is used to sort, filter and show the data
    // you expect the library to display.
    pager: function (options) {
      var self = this,
      disp = this.perPage,
      start = (self.currentPage - 1) * disp,
      stop = start + disp;
      // Saving the original models collection is important
      // as we could need to sort or filter, and we don't want
      // to loose the data we fetched from the server.
      if (self.origModels === undefined) {
        self.origModels = self.models;
      }

      self.models = self.origModels.slice();

      // Check if sorting was set using setSort.
      if ( this.sortColumn !== "" ) {
        self.models = self._sort(self.models, this.sortColumn, this.sortDirection);
      }

      // Check if field-filtering was set using setFieldFilter
      if ( !_.isEmpty( this.fieldFilterRules ) ) {
        self.models = self._fieldFilter(self.models, this.fieldFilterRules);
      }

      // Check if filtering was set using setFilter.
      if ( this.filterExpression !== "" ) {
        self.models = self._filter(self.models, this.filterFields, this.filterExpression);
      }

      // If the sorting or the filtering was changed go to the first page
      if ( this.lastSortColumn !== this.sortColumn || this.lastFilterExpression !== this.filterExpression || !_.isEqual(this.fieldFilterRules, this.lastFieldFilterRules) ) {
        start = 0;
        stop = start + disp;
        self.currentPage = 1;

        this.lastSortColumn = this.sortColumn;
        this.lastFieldFilterRules = this.fieldFilterRules;
        this.lastFilterExpression = this.filterExpression;
      }

      // We need to save the sorted and filtered models collection
      // because we'll use that sorted and filtered collection in info().
      self.sortedAndFilteredModels = self.models.slice();
      self.info();
      self.reset(self.models.slice(start, stop));

      // This is somewhat of a hack to get all the nextPage, prevPage, and goTo methods
      // to work with a success callback (as in the requestPager). Realistically there is no failure case here,
      // but maybe we could catch exception and trigger a failure callback?
      _.result(options, 'success');
    },

    // The actual place where the collection is sorted.
    // Check setSort for arguments explicacion.
    _sort: function ( models, sort, direction ) {
      models = models.sort(function (a, b) {
        var ac = a.get(sort),
        bc = b.get(sort);

        if ( _.isUndefined(ac) || _.isUndefined(bc) || ac === null || bc === null ) {
          return 0;
        } else {
          /* Make sure that both ac and bc are lowercase strings.
           * .toString() first so we don't have to worry if ac or bc
           * have other String-only methods.
           */
          ac = ac.toString().toLowerCase();
          bc = bc.toString().toLowerCase();
        }

        if (direction === 'desc') {

          // We need to know if there aren't any non-number characters
          // and that there are numbers-only characters and maybe a dot
          // if we have a float.
          // Oh, also a '-' for negative numbers!
          if((!ac.match(/[^\-\d\.]/) && ac.match(/-?[\d\.]+/)) &&
               (!bc.match(/[^\-\d\.]/) && bc.match(/-?[\d\.]+/))){

            if( (ac - 0) < (bc - 0) ) {
              return 1;
            }
            if( (ac - 0) > (bc - 0) ) {
              return -1;
            }
          } else {
            if (ac < bc) {
              return 1;
            }
            if (ac > bc) {
              return -1;
            }
          }

        } else {

          //Same as the regexp check in the 'if' part.
          if((!ac.match(/[^\-\d\.]/) && ac.match(/-?[\d\.]+/)) &&
             (!bc.match(/[^\-\d\.]/) && bc.match(/-?[\d\.]+/))){
            if( (ac - 0) < (bc - 0) ) {
              return -1;
            }
            if( (ac - 0) > (bc - 0) ) {
              return 1;
            }
          } else {
            if (ac < bc) {
              return -1;
            }
            if (ac > bc) {
              return 1;
            }
          }

        }

        if (a.cid && b.cid){
          var aId = a.cid,
          bId = b.cid;

          if (aId < bId) {
            return -1;
          }
          if (aId > bId) {
            return 1;
          }
        }

        return 0;
      });

      return models;
    },

    // The actual place where the collection is field-filtered.
    // Check setFieldFilter for arguments explicacion.
    _fieldFilter: function( models, rules ) {

      // Check if there are any rules
      if ( _.isEmpty(rules) ) {
        return models;
      }

      var filteredModels = [];

      // Iterate over each rule
      _.each(models, function(model){

        var should_push = true;

        // Apply each rule to each model in the collection
        _.each(rules, function(rule){

          // Don't go inside the switch if we're already sure that the model won't be included in the results
          if( !should_push ){
            return false;
          }

          should_push = false;

          // The field's value will be passed to a custom function, which should
          // return true (if model should be included) or false (model should be ignored)
          if(rule.type === "function"){
            var f = _.wrap(rule.value, function(func){
              return func( model.get(rule.field) );
            });
            if( f() ){
              should_push = true;
            }

            // The field's value is required to be non-empty
          }else if(rule.type === "required"){
            if( !_.isEmpty( model.get(rule.field).toString() ) ) {
              should_push = true;
            }

            // The field's value is required to be greater tan N (numbers only)
          }else if(rule.type === "min"){
            if( !_.isNaN( Number( model.get(rule.field) ) ) &&
               !_.isNaN( Number( rule.value ) ) &&
                 Number( model.get(rule.field) ) >= Number( rule.value ) ) {
              should_push = true;
            }

            // The field's value is required to be smaller tan N (numbers only)
          }else if(rule.type === "max"){
            if( !_.isNaN( Number( model.get(rule.field) ) ) &&
               !_.isNaN( Number( rule.value ) ) &&
                 Number( model.get(rule.field) ) <= Number( rule.value ) ) {
              should_push = true;
            }

            // The field's value is required to be between N and M (numbers only)
          }else if(rule.type === "range"){
            if( !_.isNaN( Number( model.get(rule.field) ) ) &&
               _.isObject( rule.value ) &&
                 !_.isNaN( Number( rule.value.min ) ) &&
                   !_.isNaN( Number( rule.value.max ) ) &&
                     Number( model.get(rule.field) ) >= Number( rule.value.min ) &&
                       Number( model.get(rule.field) ) <= Number( rule.value.max ) ) {
              should_push = true;
            }

            // The field's value is required to be more than N chars long
          }else if(rule.type === "minLength"){
            if( model.get(rule.field).toString().length >= rule.value ) {
              should_push = true;
            }

            // The field's value is required to be no more than N chars long
          }else if(rule.type === "maxLength"){
            if( model.get(rule.field).toString().length <= rule.value ) {
              should_push = true;
            }

            // The field's value is required to be more than N chars long and no more than M chars long
          }else if(rule.type === "rangeLength"){
            if( _.isObject( rule.value ) &&
               !_.isNaN( Number( rule.value.min ) ) &&
                 !_.isNaN( Number( rule.value.max ) ) &&
                   model.get(rule.field).toString().length >= rule.value.min &&
                     model.get(rule.field).toString().length <= rule.value.max ) {
              should_push = true;
            }

            // The field's value is required to be equal to one of the values in rules.value
          }else if(rule.type === "oneOf"){
            if( _.isArray( rule.value ) &&
               _.include( rule.value, model.get(rule.field) ) ) {
              should_push = true;
            }

            // The field's value is required to be equal to the value in rules.value
          }else if(rule.type === "equalTo"){
            if( rule.value === model.get(rule.field) ) {
              should_push = true;
            }

          }else if(rule.type === "containsAllOf"){
            if( _.isArray( rule.value ) &&
                _.isArray(model.get(rule.field)) &&
                _.intersection( rule.value, model.get(rule.field)).length === rule.value.length) {
              should_push = true;
            }

              // The field's value is required to match the regular expression
          }else if(rule.type === "pattern"){
            if( model.get(rule.field).toString().match(rule.value) ) {
              should_push = true;
            }

            //Unknown type
          }else{
            should_push = false;
          }

        });

        if( should_push ){
          filteredModels.push(model);
        }

      });

      return filteredModels;
    },

    // The actual place where the collection is filtered.
    // Check setFilter for arguments explicacion.
    _filter: function ( models, fields, filter ) {

      //  For example, if you had a data model containing cars like { color: '', description: '', hp: '' },
      //  your fields was set to ['color', 'description', 'hp'] and your filter was set
      //  to "Black Mustang 300", the word "Black" will match all the cars that have black color, then
      //  "Mustang" in the description and then the HP in the 'hp' field.
      //  NOTE: "Black Musta 300" will return the same as "Black Mustang 300"

      // We accept fields to be a string, an array or an object
      // but if string or array is passed we need to convert it
      // to an object.

      var self = this;

      var obj_fields = {};

      if( _.isString( fields ) ) {
        obj_fields[fields] = {cmp_method: 'regexp'};
      }else if( _.isArray( fields ) ) {
        _.each(fields, function(field){
          obj_fields[field] = {cmp_method: 'regexp'};
        });
      }else{
        _.each(fields, function( cmp_opts, field ) {
          obj_fields[field] = _.defaults(cmp_opts, { cmp_method: 'regexp' });
        });
      }

      fields = obj_fields;

      //Remove diacritic characters if diacritic plugin is loaded
      if( _.has(Backbone.Paginator, 'removeDiacritics') && self.useDiacriticsPlugin ){
        filter = Backbone.Paginator.removeDiacritics(filter);
      }

      // 'filter' can be only a string.
      // If 'filter' is string we need to convert it to
      // a regular expression.
      // For example, if 'filter' is 'black dog' we need
      // to find every single word, remove duplicated ones (if any)
      // and transform the result to '(black|dog)'
      if( filter === '' || !_.isString(filter) ) {
        return models;
      } else {
        var words = _.map(filter.match(/\w+/ig), function(element) { return element.toLowerCase(); });
        var pattern = "(" + _.uniq(words).join("|") + ")";
        var regexp = new RegExp(pattern, "igm");
      }

      var filteredModels = [];

      // We need to iterate over each model
      _.each( models, function( model ) {

        var matchesPerModel = [];

        // and over each field of each model
        _.each( fields, function( cmp_opts, field ) {

          var value = model.get( field );

          if( value ) {

            // The regular expression we created earlier let's us detect if a
            // given string contains each and all of the words in the regular expression
            // or not, but in both cases match() will return an array containing all
            // the words it matched.
            var matchesPerField = [];

            if( _.has(Backbone.Paginator, 'removeDiacritics') && self.useDiacriticsPlugin ){
              value = Backbone.Paginator.removeDiacritics(value.toString());
            }else{
              value = value.toString();
            }

            // Levenshtein cmp
            if( cmp_opts.cmp_method === 'levenshtein' && _.has(Backbone.Paginator, 'levenshtein') && self.useLevenshteinPlugin ) {
              var distance = Backbone.Paginator.levenshtein(value, filter);

              _.defaults(cmp_opts, { max_distance: 0 });

              if( distance <= cmp_opts.max_distance ) {
                matchesPerField = _.uniq(words);
              }

              // Default (RegExp) cmp
            }else{
              matchesPerField = value.match( regexp );
            }

            matchesPerField = _.map(matchesPerField, function(match) {
              return match.toString().toLowerCase();
            });

            _.each(matchesPerField, function(match){
              matchesPerModel.push(match);
            });

          }

        });

        // We just need to check if the returned array contains all the words in our
        // regex, and if it does, it means that we have a match, so we should save it.
        matchesPerModel = _.uniq( _.without(matchesPerModel, "") );

        if(  _.isEmpty( _.difference(words, matchesPerModel) ) ) {
          filteredModels.push(model);
        }

      });

      return filteredModels;
    },

    // You shouldn't need to call info() as this method is used to
    // calculate internal data as first/prev/next/last page...
    info: function () {
      var self = this,
      info = {},
      totalRecords = (self.sortedAndFilteredModels) ? self.sortedAndFilteredModels.length : self.length,
      totalPages = Math.ceil(totalRecords / self.perPage);

      info = {
        totalUnfilteredRecords: self.origModels.length,
        totalRecords: totalRecords,
        currentPage: self.currentPage,
        perPage: this.perPage,
        totalPages: totalPages,
        lastPage: totalPages,
        previous: false,
        next: false,
        startRecord: totalRecords === 0 ? 0 : (self.currentPage - 1) * this.perPage + 1,
        endRecord: Math.min(totalRecords, self.currentPage * this.perPage)
      };

      if (self.currentPage > 1) {
        info.previous = self.currentPage - 1;
      }

      if (self.currentPage < info.totalPages) {
        info.next = self.currentPage + 1;
      }

      info.pageSet = self.setPagination(info);

      self.information = info;
      return info;
    },


    // setPagination also is an internal function that shouldn't be called directly.
    // It will create an array containing the pages right before and right after the
    // actual page.
    setPagination: function ( info ) {

      var pages = [], i = 0, l = 0;

      // How many adjacent pages should be shown on each side?
      var ADJACENTx2 = this.pagesInRange * 2,
      LASTPAGE = Math.ceil(info.totalRecords / info.perPage);

      if (LASTPAGE > 1) {

        // not enough pages to bother breaking it up
        if (LASTPAGE <= (1 + ADJACENTx2)) {
          for (i = 1, l = LASTPAGE; i <= l; i++) {
            pages.push(i);
          }
        }

        // enough pages to hide some
        else {

          //close to beginning; only hide later pages
          if (info.currentPage <=  (this.pagesInRange + 1)) {
            for (i = 1, l = 2 + ADJACENTx2; i < l; i++) {
              pages.push(i);
            }
          }

          // in middle; hide some front and some back
          else if (LASTPAGE - this.pagesInRange > info.currentPage && info.currentPage > this.pagesInRange) {
            for (i = info.currentPage - this.pagesInRange; i <= info.currentPage + this.pagesInRange; i++) {
              pages.push(i);
            }
          }

          // close to end; only hide early pages
          else {
            for (i = LASTPAGE - ADJACENTx2; i <= LASTPAGE; i++) {
              pages.push(i);
            }
          }
        }

      }

      return pages;

    },

    bootstrap: function(options) {
      _.extend(this, options);
      this.goTo(1);
      this.info();
      return this;
    }

  });

  // function aliasing
  Paginator.clientPager.prototype.prevPage = Paginator.clientPager.prototype.previousPage;

  // Helper function to generate rejected Deferred
  var reject = function () {
    var response = new $.Deferred();
    response.reject();
    return response.promise();
  };

  // @name: requestPager
  //
  // Paginator for server-side data being requested from a backend/API
  //
  // @description:
  // This paginator is responsible for providing pagination
  // and sort capabilities for requests to a server-side
  // data service (e.g an API)
  //
  Paginator.requestPager = Backbone.Collection.extend({

    sync: function ( method, model, options ) {

      var self = this;

      self.setDefaults();

      // Some values could be functions, let's make sure
      // to change their scope too and run them
      var queryAttributes = {};
      _.each(_.result(self, "server_api"), function(value, key){
        if( _.isFunction(value) ) {
          value = _.bind(value, self);
          value = value();
        }
        queryAttributes[key] = value;
      });

      var queryOptions = _.clone(self.paginator_core);
      _.each(queryOptions, function(value, key){
        if( _.isFunction(value) ) {
          value = _.bind(value, self);
          value = value();
        }
        queryOptions[key] = value;
      });

      // Create default values if no others are specified
      queryOptions = _.defaults(queryOptions, {
        timeout: 25000,
        cache: false,
        type: 'GET',
        dataType: 'jsonp'
      });

      // Allows the passing in of {data: {foo: 'bar'}} at request time to overwrite server_api defaults
      if( options.data ){
        options.data = decodeURIComponent($.param(_.extend(queryAttributes,options.data)));
      }else{
        options.data = decodeURIComponent($.param(queryAttributes));
      }

      queryOptions = _.extend(queryOptions, {
        data: decodeURIComponent($.param(queryAttributes)),
        processData: false,
        url: _.result(queryOptions, 'url')
      }, options);

      var promiseSuccessFormat = !(bbVer[0] === 0 &&
                                   bbVer[1] === 9 &&
                                   bbVer[2] === 10);

      var success = queryOptions.success;
      queryOptions.success = function ( resp, status, xhr ) {

        if ( success ) {
          // This is to keep compatibility with Backbone 0.9.10
          if (promiseSuccessFormat) {
            success( resp, status, xhr );
          } else {
            success( model, resp, queryOptions );
          }
        }
        if (bbVer[0] < 1 && model && model.trigger ) {
          model.trigger( 'sync', model, resp, queryOptions );
        }
      };

      var error = queryOptions.error;
      queryOptions.error = function ( xhr ) {
        if ( error ) {
          error( xhr );
        }
        if ( model && model.trigger ) {
          model.trigger( 'error', model, xhr, queryOptions );
        }
      };

      var xhr = queryOptions.xhr = Backbone.ajax( queryOptions );
      if ( model && model.trigger ) {
        model.trigger('request', model, xhr, queryOptions);
      }
      return xhr;
    },

    setDefaults: function() {
      var self = this;

      // Create default values if no others are specified
      _.defaults(self.paginator_ui, {
        firstPage: 0,
        currentPage: 1,
        perPage: 5,
        totalPages: 10,
        pagesInRange: 4
      });

      // Change scope of 'paginator_ui' object values
      _.each(self.paginator_ui, function(value, key) {
        if (_.isUndefined(self[key])) {
          self[key] = self.paginator_ui[key];
        }
      });
    },

    requestNextPage: function ( options ) {
      if ( this.currentPage !== undefined ) {
        this.currentPage += 1;
        return this.pager( options );
      } else {
        return reject();
      }
    },

    requestPreviousPage: function ( options ) {
      if ( this.currentPage !== undefined ) {
        this.currentPage -= 1;
        return this.pager( options );
      } else {
        return reject();
      }
    },

    updateOrder: function ( column, options ) {
      if (column !== undefined) {
        this.sortField = column;
        return this.pager( options );
      } else {
        return reject();
      }
    },

    goTo: function ( page, options ) {
      if ( page !== undefined ) {
        this.currentPage = parseInt(page, 10);
        return this.pager( options );
      } else {
        return reject();
      }
    },

    howManyPer: function ( count, options ) {
      if ( count !== undefined ) {
        this.currentPage = this.firstPage;
        this.perPage = count;
        return this.pager( options );
      } else {
        return reject();
      }
    },

    info: function () {

      var info = {
        // If parse() method is implemented and totalRecords is set to the length
        // of the records returned, make it available. Else, default it to 0
        totalRecords: this.totalRecords || 0,

        currentPage: this.currentPage,
        firstPage: this.firstPage,
        totalPages: Math.ceil(this.totalRecords / this.perPage),
        lastPage: this.totalPages, // should use totalPages in template
        perPage: this.perPage,
        previous:false,
        next:false
      };

      if (this.currentPage > 1) {
        info.previous = this.currentPage - 1;
      }

      if (this.currentPage < info.totalPages) {
        info.next = this.currentPage + 1;
      }

      // left around for backwards compatibility
      info.hasNext = info.next;
      info.hasPrevious = info.next;

      info.pageSet = this.setPagination(info);

      this.information = info;
      return info;
    },

    setPagination: function ( info ) {

      var pages = [], i = 0, l = 0;

      // How many adjacent pages should be shown on each side?
      var ADJACENTx2 = this.pagesInRange * 2,
      LASTPAGE = Math.ceil(info.totalRecords / info.perPage);

      if (LASTPAGE > 1) {

        // not enough pages to bother breaking it up
        if (LASTPAGE <= (1 + ADJACENTx2)) {
          for (i = 1, l = LASTPAGE; i <= l; i++) {
            pages.push(i);
          }
        }

        // enough pages to hide some
        else {

          //close to beginning; only hide later pages
          if (info.currentPage <=  (this.pagesInRange + 1)) {
            for (i = 1, l = 2 + ADJACENTx2; i < l; i++) {
              pages.push(i);
            }
          }

          // in middle; hide some front and some back
          else if (LASTPAGE - this.pagesInRange > info.currentPage && info.currentPage > this.pagesInRange) {
            for (i = info.currentPage - this.pagesInRange; i <= info.currentPage + this.pagesInRange; i++) {
              pages.push(i);
            }
          }

          // close to end; only hide early pages
          else {
            for (i = LASTPAGE - ADJACENTx2; i <= LASTPAGE; i++) {
              pages.push(i);
            }
          }
        }

      }

      return pages;

    },

    // fetches the latest results from the server
    pager: function ( options ) {
      if ( !_.isObject(options) ) {
        options = {};
      }
      return this.fetch( options );
    },

    url: function(){
      // Expose url parameter enclosed in this.paginator_core.url to properly
      // extend Collection and allow Collection CRUD
      if(this.paginator_core !== undefined && this.paginator_core.url !== undefined){
        return this.paginator_core.url;
      } else {
        return null;
      }
    },

    bootstrap: function(options) {
      _.extend(this, options);
      this.setDefaults();
      this.info();
      return this;
    }
  });

  // function aliasing
  Paginator.requestPager.prototype.nextPage = Paginator.requestPager.prototype.requestNextPage;
  Paginator.requestPager.prototype.prevPage = Paginator.requestPager.prototype.requestPreviousPage;

  return Paginator;

}( Backbone, _, jQuery ));

return window.Backbone.Paginator;
  }).apply(root, arguments);
});
}(this));

define('castle-url/patterns/structure//js/collections/result',[
  'jquery',
  'underscore',
  'backbone',
  'castle-url/patterns/structure//js/models/result',
  'mockup-utils',
  'backbone.paginator'
], function($, _, Backbone, Result, Utils) {
  'use strict';

  var ResultCollection = Backbone.Paginator.requestPager.extend({
    model: Result,
    initialize: function(models, options) {
      this.options = options;
      this.view = options.view;
      this.url = options.url;

      this.queryHelper = Utils.QueryHelper(
        $.extend(true, {}, this.view.options, {
          attributes: this.view.options.queryHelperAttributes
        }));

      this.queryParser = function(options) {
        var self = this;
        if (options === undefined) {
          options = {};
        }
        var term = null;
        if (self.view.toolbar) {
          term = self.view.toolbar.get('filter').term;
        }
        var sortOn = self.view.sort_on; // jshint ignore:line
        var sortOrder = self.view.sort_order; // jshint ignore:line
        if (!sortOn) {
          sortOn = 'getObjPositionInParent';
        }
        return JSON.stringify({
          criteria: self.queryHelper.getCriterias(term, $.extend({}, options, {
            additionalCriterias: self.view.additionalCriterias
          })),
          sort_on: sortOn,
          sort_order: sortOrder
        });
      };

      // check and see if a hash is provided for initial path
      if (window.location.hash.substring(0, 2) === '#/') {
        this.queryHelper.currentPath = window.location.hash.substring(1);
      }

      Backbone.Paginator.requestPager.prototype.initialize.apply(this, [models, options]);
    },
    getCurrentPath: function() {
      return this.queryHelper.getCurrentPath();
    },
    setCurrentPath: function(path) {
      this.queryHelper.currentPath = path;
    },
    pager: function() {
      this.trigger('pager');
      Backbone.Paginator.requestPager.prototype.pager.apply(this, []);
    },
    paginator_core: {
      // the type of the request (GET by default)
      type: 'GET',
      // the type of reply (jsonp by default)
      dataType: 'json',
      url: function() {
        return this.url;
      }
    },
    paginator_ui: {
      // the lowest page index your API allows to be accessed
      firstPage: 1,
      // which page should the paginator start from
      // (also, the actual page the paginator is on)
      currentPage: 1,
      // how many items per page should be shown
      perPage: 15
    },
    // server_api are query parameters passed directly (currently GET
    // parameters).  These are currently generated using following
    // functions.  Renamed to queryParams in Backbone.Paginator 2.0.
    server_api: {
      query: function() {
        return this.queryParser();
      },
      batch: function() {
        this.queryHelper.options.batchSize = this.perPage;
        return JSON.stringify(this.queryHelper.getBatch(this.currentPage));
      },
      attributes: function() {
        return JSON.stringify(this.queryHelper.options.attributes);
      }
    },
    parse: function(response, baseSortIdx) {
      if (baseSortIdx === undefined) {
        baseSortIdx = 0;
      }
      this.totalRecords = response.total;
      var results = response.results;
      // XXX manually set sort order here since backbone will otherwise
      // do arbitrary sorting?
      _.each(results, function(item, idx) {
        item._sort = idx;
      });
      return results;
    },
    comparator: '_sort'
  });

  return ResultCollection;
});

define('castle-url/patterns/structure//js/collections/selected',[
  'backbone',
  'castle-url/patterns/structure//js/models/result'
], function(Backbone, Result) {
  'use strict';

  var SelectedCollection = Backbone.Collection.extend({
    model: Result,
    removeResult: function(model) {
      return this.removeByUID(model.uid());
    },
    removeByUID: function(uid) {
      var found = this.getByUID(uid);
      if (found) {
        this.remove(found);
      }
      return found;
    },
    getByUID: function(uid) {
      return this.findWhere({UID: uid});
    }
  });

  return SelectedCollection;
});

/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD
		define('jquery.cookie',['jquery'], factory);
	} else if (typeof exports === 'object') {
		// CommonJS
		factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\+/g;

	function encode(s) {
		return config.raw ? s : encodeURIComponent(s);
	}

	function decode(s) {
		return config.raw ? s : decodeURIComponent(s);
	}

	function stringifyCookieValue(value) {
		return encode(config.json ? JSON.stringify(value) : String(value));
	}

	function parseCookieValue(s) {
		if (s.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape...
			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
		}

		try {
			// Replace server-side written pluses with spaces.
			// If we can't decode the cookie, ignore it, it's unusable.
			// If we can't parse the cookie, ignore it, it's unusable.
			s = decodeURIComponent(s.replace(pluses, ' '));
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

	function read(s, converter) {
		var value = config.raw ? s : parseCookieValue(s);
		return $.isFunction(converter) ? converter(value) : value;
	}

	var config = $.cookie = function (key, value, options) {

		// Write

		if (value !== undefined && !$.isFunction(value)) {
			options = $.extend({}, config.defaults, options);

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setTime(+t + days * 864e+5);
			}

			return (document.cookie = [
				encode(key), '=', stringifyCookieValue(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// Read

		var result = key ? undefined : {};

		// To prevent the for loop in the first place assign an empty array
		// in case there are no cookies at all. Also prevents odd result when
		// calling $.cookie().
		var cookies = document.cookie ? document.cookie.split('; ') : [];

		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decode(parts.shift());
			var cookie = parts.join('=');

			if (key && key === name) {
				// If second argument (value) is a function it's a converter...
				result = read(cookie, value);
				break;
			}

			// Prevent storing a cookie that we couldn't decode.
			if (!key && (cookie = read(cookie)) !== undefined) {
				result[name] = cookie;
			}
		}

		return result;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		if ($.cookie(key) === undefined) {
			return false;
		}

		// Must not alter options, thus extending a fresh object...
		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
		return !$.cookie(key);
	};

}));

define('castle-url/patterns/structure/js/views/app',[
  'jquery',
  'underscore',
  'mockup-ui-url/views/toolbar',
  'mockup-ui-url/views/buttongroup',
  'mockup-ui-url/views/button',
  'mockup-ui-url/views/base',
  'castle-url/patterns/structure//js/views/table',
  'castle-url/patterns/structure//js/views/selectionwell',
  'castle-url/patterns/structure//js/views/generic-popover',
  'castle-url/patterns/structure//js/views/rearrange',
  'castle-url/patterns/structure//js/views/selectionbutton',
  'castle-url/patterns/structure//js/views/paging',
  'castle-url/patterns/structure//js/views/columns',
  'castle-url/patterns/structure//js/views/textfilter',
  'castle-url/patterns/structure//js/views/upload',
  'castle-url/patterns/structure//js/collections/result',
  'castle-url/patterns/structure//js/collections/selected',
  'mockup-utils',
  'translate',
  'pat-logger',
  'jquery.cookie'
], function($, _, Toolbar, ButtonGroup, ButtonView, BaseView,
  TableView, SelectionWellView,
  GenericPopover, RearrangeView, SelectionButtonView,
  PagingView, ColumnsView, TextFilterView, UploadView,
  _ResultCollection, SelectedCollection, utils, _t, logger) {
  'use strict';

  var log = logger.getLogger('pat-structure');

  var AppView = BaseView.extend({
    tagName: 'div',
    status: {
      type: 'none',
      text: '',
      label: ''
    },
    pasteAllowed: !!$.cookie('__cp'),
    sort_on: 'getObjPositionInParent',
    sort_order: 'ascending',
    additionalCriterias: [],
    cookieSettingPrefix: '_fc_',
    initialize: function(options) {
      var self = this;
      BaseView.prototype.initialize.apply(self, [options]);
      self.loading = new utils.Loading();
      self.loading.show();
      self.pasteAllowed = !!$.cookie('__cp');

      /* close popovers when clicking away */
      $(document).click(function(e) {
        var $el = $(e.target);
        if (!$el.is(':visible') || $el.css('visibility') === 'hidden' || $el.css('opacity') === '0') {
          // ignore this, fake event trigger to element that is not visible
          return;
        }
        if ($el.is('a') || $el.parent().is('a')) {
          return;
        }
        var $popover = $('.popover:visible');
        if ($popover.length > 0 && !$.contains($popover[0], $el[0])) {
          var popover = $popover.data('component');
          if (popover) {
            popover.hide();
          }
        }
      });

      var ResultCollection = require(options.collectionConstructor);

      self.collection = new ResultCollection([], {
        // Due to default implementation need to poke at things in here,
        // view is passed.
        view: self,
        url: self.options.collectionUrl,
      });

      self.setAllCookieSettings();

      self.selectedCollection = new SelectedCollection();
      self.tableView = new TableView({app: self});
      self.pagingView = new PagingView({app: self});

      /* initialize buttons */
      self.setupButtons();

      self.wellView = new SelectionWellView({
        collection: self.selectedCollection,
        triggerView: self.toolbar.get('selected-items'),
        app: self,
        id: 'structure-well'
      });

      self.toolbar.get('selected-items').disable();
      self.buttons.disable();

      var timeout = 0;
      self.selectedCollection.on('add remove reset', function( /*modal, collection*/ ) {
        /* delay rendering since this can happen in batching */
        clearTimeout(timeout);
        timeout = setTimeout(function() {
          self.updateButtons();
        }, 100);
      }, self);

      self.collection.on('sync', function() {
        if (self.contextInfoUrl) {
          $.ajax({
            url: self.getAjaxUrl(self.contextInfoUrl),
            dataType: 'json',
            success: function(data) {
              self.trigger('context-info-loaded', data);
            },
            error: function(response) {
              // XXX handle error?
              if (response.status === 404) {
                log.info('context info url not found');
              }
            }
          });
        }
        self.loading.hide();
      });

      self.collection.on('pager', function() {
        self.loading.show();
        self.updateButtons();

        // the remaining calls are related to window.pushstate.
        // abort if feature unavailable.
        if (!(window.history && window.history.pushState)) {
          return;
        }

        // undo the flag set by popState to prevent the push state
        // from being triggered here, and early abort out of the
        // function to not execute the folowing pushState logic.
        if (self.doNotPushState) {
          self.doNotPushState = false;
          return;
        }

        var path = self.getCurrentPath();
        var url;
        if (path === '/') {
          path = '';
        }
        /* maintain history here */
        if (self.options.pushStateUrl) {
          // permit an extra slash in pattern, but strip that if there
          // as path always will be prefixed with a `/`
          var pushStateUrl = self.options.pushStateUrl.replace(
            '/{path}', '{path}');
          url = pushStateUrl.replace('{path}', path);
          window.history.pushState(null, null, url);
        } else if (self.options.urlStructure) {
          // fallback to urlStructure specification
          url = self.options.urlStructure.base + path + self.options.urlStructure.appended;
          window.history.pushState(null, null, url);
        }

        if (self.options.traverseView) {
          // flag specifies that the context view implements a traverse
          // view (i.e. IPublishTraverse) and the path is a virtual path
          // of some kind - use the base object instead for that by not
          // specifying a path.
          path = '';
          // TODO figure out whether the following event after this is
          // needed at all.
        }
        $('body').trigger('structure-url-changed', path);

      });

      if ((self.options.pushStateUrl || self.options.urlStructure) && utils.featureSupport.history()) {
        $(window).bind('popstate', function() {
          /* normalize this url first... */
          var win = utils.getWindow();
          var url = win.location.href;
          var base, appended;
          if (url.indexOf('?') !== -1) {
            url = url.split('?')[0];
          }
          if (url.indexOf('#') !== -1) {
            url = url.split('#')[0];
          }
          if (self.options.pushStateUrl) {
            var tmp = self.options.pushStateUrl.split('{path}');
            base = tmp[0];
            appended = tmp[1];
          } else {
            base = self.options.urlStructure.base;
            appended = self.options.urlStructure.appended;
          }
          // take off the base url
          var path = url.substring(base.length);
          if (path.substring(path.length - appended.length) === appended) {
            /* check that it ends with appended value */
            path = path.substring(0, path.length - appended.length);
          }
          if (!path) {
            path = '/';
          }
          self.setCurrentPath(path);
          $('body').trigger('structure-url-changed', path);
          // since this next call causes state to be pushed...
          self.doNotPushState = true;
          self.collection.goTo(self.collection.information.firstPage);
        });
        /* detect key events */
        $(document).bind('keyup keydown', function(e) {
          self.keyEvent = e;
        });
      }

      self.togglePasteBtn();
    },
    updateButtons: function() {
      var self = this;
      if (self.selectedCollection.length) {
        self.toolbar.get('selected-items').enable();
        self.buttons.enable();
      } else {
        this.toolbar.get('selected-items').disable();
        self.buttons.disable();
      }

      self.togglePasteBtn();
    },
    togglePasteBtn: function(){
      var self = this;
      if (_.find(self.buttons.items, function(btn){ return btn.id === 'paste'; })) {
        self.pasteAllowed = !!$.cookie('__cp');
        if (self.pasteAllowed) {
          self.buttons.get('paste').enable();
        } else {
          self.buttons.get('paste').disable();
        }
      }
    },
    inQueryMode: function() {
      if (this.additionalCriterias.length > 0) {
        return true;
      }
      if (this.sort_on && this.sort_on !== 'getObjPositionInParent') { // jshint ignore:line
        return true;
      }
      if (this.sort_order !== 'ascending') { // jshint ignore:line
        return true;
      }
      return false;
    },
    getSelectedUids: function(collection) {
      var self = this;
      if (collection === undefined) {
        collection = self.selectedCollection;
      }
      var uids = [];
      collection.each(function(item) {
        uids.push(item.uid());
      });
      return uids;
    },
    getCurrentPath: function() {
      return this.collection.getCurrentPath();
    },
    setCurrentPath: function(path) {
      this.collection.setCurrentPath(path);
    },
    getAjaxUrl: function(url) {
      return url.replace('{path}', this.getCurrentPath());
    },
    buttonClickEvent: function(button) {
      var self = this;
      var data = null;
      var callback = null;

      if (button.url) {
        self.loading.show();
        // handle ajax now

        if (arguments.length > 1) {
          var arg1 = arguments[1];
          if (!arg1.preventDefault) {
            data = arg1;
          }
        }
        if (arguments.length > 2) {
          var arg2 = arguments[2];
          if (typeof(arg2) === 'function') {
            callback = arg2;
          }
        }
        if (data === null) {
          data = {};
        }
        if (data.selection === undefined) {
          // if selection is overridden by another mechanism
          data.selection = JSON.stringify(self.getSelectedUids());
        }
        data._authenticator = utils.getAuthenticator();
        if (data.folder === undefined) {
          data.folder = self.getCurrentPath();
        }

        var url = self.getAjaxUrl(button.url);
        $.ajax({
          url: url,
          type: 'POST',
          data: data,
          success: function(data) {
            self.ajaxSuccessResponse.apply(self, [data, callback]);
            self.loading.hide();
          },
          error: function(response) {
            self.ajaxErrorResponse.apply(self, [response, url]);
            self.loading.hide();
          }
        }, self);
      }
    },
    ajaxSuccessResponse: function(data, callback) {
      var self = this;
      self.selectedCollection.reset();
      if (data.status === 'success') {
        self.collection.reset();
      }
      if (data.msg) {
        // give status message somewhere...
        self.setStatus(data.msg, data.status || 'warning');
      }
      if (callback !== null && callback !== undefined) {
        callback(data);
      }
      self.collection.pager();
    },
    ajaxErrorResponse: function(response, url) {
      if (response.status === 404) {
        window.alert(_t('operation url ${url} is not valid', {url: url}));
      } else {
        window.alert(_t('there was an error performing action'));
      }
    },
    setupButtons: function() {
      var self = this;
      var items = [];

      var columnsBtn = new ButtonView({
        id: 'attribute-columns',
        tooltip: _t('Configure displayed columns'),
        icon: 'th'
      });

      self.columnsView = new ColumnsView({
        app: self,
        triggerView: columnsBtn,
        id: 'structure-columns'
      });
      items.push(columnsBtn);

      items.push(new SelectionButtonView({
        title: _t('Selected'),
        id: 'selected-items',
        collection: this.selectedCollection
      }));

      if (self.options.rearrange) {
        var rearrangeButton = new ButtonView({
          id: 'rearrange',
          title: _t('Rearrange'),
          icon: 'sort-by-attributes',
          tooltip: _t('Rearrange folder contents'),
          url: self.options.rearrange.url
        });
        self.rearrangeView = new RearrangeView({
          triggerView: rearrangeButton,
          app: self,
          id: 'structure-rearrange'
        });
        items.push(rearrangeButton);
      }
      if (self.options.upload && utils.featureSupport.dragAndDrop() && utils.featureSupport.fileApi()) {
        var uploadButton = new ButtonView({
          id: 'upload',
          title: _t('Upload'),
          tooltip: _t('Upload files'),
          icon: 'upload'
        });
        self.uploadView = new UploadView({
          triggerView: uploadButton,
          app: self
        });
        items.push(uploadButton);
      }

      var buttons = [];
      _.each(self.options.buttons, function(buttonOptions) {
        try {
          var button = new ButtonView(buttonOptions);
          buttons.push(button);

          if (button.form) {
            buttonOptions.triggerView = button;
            buttonOptions.app = self;
            var view = new GenericPopover(buttonOptions);
            self.$el.append(view.el);
          } else {
            button.on('button:click', self.buttonClickEvent, self);
          }
        } catch (err) {
          log.error('Error initializing button ' + buttonOptions.title + ' ' + err);
        }
      });
      self.buttons = new ButtonGroup({
        items: buttons,
        id: 'mainbuttons',
        app: self
      });
      items.push(self.buttons);

      items.push(new TextFilterView({
        id: 'filter',
        app: this
      }));
      this.toolbar = new Toolbar({
        items: items
      });
    },
    moveItem: function(id, delta, subsetIds) {
      var self = this;
      $.ajax({
        url: this.getAjaxUrl(this.options.moveUrl),
        type: 'POST',
        data: {
          delta: delta,
          id: id,
          _authenticator: utils.getAuthenticator(),
          subsetIds: JSON.stringify(subsetIds)
        },
        dataType: 'json',
        success: function(data) {
          if (data.msg) {
            self.setStatus(data.msg);
          } else if (data.status !== 'success') {
            // XXX handle error here with something?
            self.setStatus({text: 'error moving item', type: 'error'});
          }
          self.collection.pager(); // reload it all
        },
        error: function() {
          self.setStatus({text: 'error moving item', type: 'error'});
        }
      });
    },
    setStatus: function(msg, type) {
      if (!msg) {
        // clear it
        this.status.text = '';
        this.status.label = '';
        this.status.type = 'none';
      } else if (typeof(msg) === 'string') {
        this.status.text = msg;
        this.status.label = '';
        this.status.type = type || 'warning';
      } else {
        // support setting portal status messages here
        this.status.label = msg.label || '';
        this.status.text = msg.text;
        this.status.type = msg.type || 'warning';
      }
      // still need to manually set in case rendering isn't done(especially true for tests)
      var $status = this.$('.status');
      $status[0].className = 'alert alert-' + this.status.type + ' status';
      var $text = $('<span></span>');
      $text.text(this.status.text);
      var $label = $('<strong></strong>');
      $label.text(this.status.label);
      $status.empty().append($label).append($text);
    },
    render: function() {
      var self = this;

      self.$el.append(self.toolbar.render().el);
      self.$el.append(self.wellView.render().el);
      self.$el.append(self.columnsView.render().el);
      if (self.rearrangeView) {
        self.$el.append(self.rearrangeView.render().el);
      }
      if (self.uploadView) {
        self.$el.append(self.uploadView.render().el);
      }

      self.$el.append(self.tableView.render().el);
      self.$el.append(self.pagingView.render().el);

      // Backdrop class
      if (self.options.backdropSelector !== null) {
        $(self.options.backdropSelector).addClass('ui-backdrop-element');
      } else {
        self.$el.addClass('ui-backdrop-element');
      }

      return self;
    },
    getCookieSetting: function(name, _default) {
      if (_default === undefined) {
        _default = null;
      }
      var val;
      try {
        val = $.cookie(this.cookieSettingPrefix + name);
        val = $.parseJSON(val).value;
      } catch (e) {
        /* error parsing json, load default here now */
        return _default;
      }
      if (val === undefined || val === null) {
        return _default;
      }
      return val;
    },
    setCookieSetting: function(name, val) {
      $.cookie(this.cookieSettingPrefix + name,
        JSON.stringify({
          'value': val
        })
      );
    },
    setAllCookieSettings: function() {
      this.activeColumns = this.getCookieSetting(
        this.activeColumnsCookie,
        this.activeColumns
      );
      var perPage = this.getCookieSetting('perPage', 15);
      if (typeof(perPage) === 'string') {
        perPage = parseInt(perPage);
      }
      this.collection.howManyPer(perPage);
    }
  });

  return AppView;
});

/* Structure pattern.
 *
 * Options:
 *    vocabularyUrl(string): Url to return query results (null)
 *    indexOptionsUrl(string): Url to configure querystring widget with (null)
 *    upload(string): upload configuration settings(null)
 *    moveUrl(string): For supporting drag drop reordering (null)
 *    contextInfoUrl(string): For supporting add menu (null)
 *
 * Documentation:
 *    # Example
 *
 *    {{ example-1 }}
 *
 * Example: example-1
 *    <div class="pat-structure"
 *         data-pat-structure="vocabularyUrl:/relateditems-test.json;
 *                             uploadUrl:/upload;
 *                             moveUrl:/moveitem;
 *                             indexOptionsUrl:/tests/json/queryStringCriteria.json;
 *                             contextInfoUrl:{path}/context-info;"></div>
 */

define('castle-url/patterns/structure/pattern',[
  'jquery',
  'underscore',
  'pat-base',
  'castle-url/patterns/structure/js/views/app'
], function($, _, Base, AppView) {
  'use strict';

  var Structure = Base.extend({
    name: 'structure',
    trigger: '.pat-structure',
    parser: 'mockup',
    defaults: {
      // for implementing history changes
      // Example: {base: 'http://mysite.com', appended: '/folder_contents'}
      urlStructure: null,
      vocabularyUrl: null,
      indexOptionsUrl: null, // for querystring widget
      contextInfoUrl: null, // for add new dropdown and other info
      setDefaultPageUrl: null,
      menuOptions: null, // default action menu options per item.
      // default menu generator
      menuGenerator: 'castle-url/patterns/structure//js/actionmenu',
      backdropSelector: '.plone-modal', // Element upon which to apply backdrops used for popovers

      activeColumnsCookie: 'activeColumns',

      iconSize: 'thumb',

      /*
        As the options operate on a merging basis per new attribute
        (key/value pairs) on the option Object in a recursive fashion,
        array items are also treated as Objects so that custom options
        are replaced starting from index 0 up to the length of the
        array.  In the case of buttons, custom buttons are simply
        replaced starting from the first one.  The following defines the
        customized attributes that should be replaced wholesale, with
        the default version prefixed with `_default_`.
      */

      attributes: null,
      _default_attributes: [
        'CreationDate',
        'EffectiveDate',
        'ExpirationDate',
        'exclude_from_nav',
        'getIcon',
        'getObjSize',
        'getURL',
        'id',
        'is_folderish',
        'last_comment_date',
        'ModificationDate',
        'path',
        'portal_type',
        'review_state',
        'Subject',
        'Title',
        'total_comments',
        'UID'
      ],

      activeColumns: null,
      _default_activeColumns: [
        'ModificationDate',
        'EffectiveDate',
        'review_state'
      ],

      availableColumns: null,
      _default_availableColumns: {
        'id': 'ID',
        'ModificationDate': 'Last modified',
        'EffectiveDate': 'Published',
        'ExpirationDate': 'Expiration',
        'CreationDate': 'Created',
        'review_state': 'Review state',
        'Subject': 'Tags',
        'portal_type': 'Type',
        'is_folderish': 'Folder',
        'exclude_from_nav': 'Excluded from navigation',
        'getObjSize': 'Object Size',
        'last_comment_date': 'Last comment date',
        'total_comments': 'Total comments'
      },

      // action triggered for the primary link for each table row.
      tableRowItemAction: null,
      _default_tableRowItemAction: {
        folder: ['castle-url/patterns/structure//js/navigation', 'folderClicked'],
        other: []
      },

      typeToViewAction: null,
      _default_typeToViewAction: {
          'File': '/view',
          'Image': '/view',
          'Blob': '/view'
      },

      collectionConstructor:
        'castle-url/patterns/structure//js/collections/result',

      momentFormat: 'L LT',
      rearrange: {
        properties: {
          'id': 'ID',
          'sortable_title': 'Title'
        },
        url: '/rearrange'
      },
      moveUrl: null,

      buttons: null,
      _default_buttons: [{
        title: 'Cut',
        url: '/cut'
      },{
        title: 'Copy',
        url: '/copy'
      },{
        title: 'Paste',
        url: '/paste'
      },{
        title: 'Delete',
        url: '/delete',
        context: 'danger',
        icon: 'trash'
      },{
        title: 'Workflow',
        url: '/workflow'
      },{
        title: 'Tags',
        url: '/tags'
      },{
        title: 'Properties',
        url: '/properties'
      },{
        title: 'Rename',
        url: '/rename'
      },{
        title: 'Template',
        url: '/convert_template'
      }],

      upload: {
        uploadMultiple: true,
        showTitle: true
      }

    },
    init: function() {
      var self = this;

      /*
        This part replaces the undefined (null) values in the user
        modifiable attributes with the default values.

        May want to consider moving the _default_* values out of the
        options object.
      */
      var replaceDefaults = ['attributes', 'activeColumns', 'availableColumns', 'buttons', 'typeToViewAction'];
      _.each(replaceDefaults, function(idx) {
        if (self.options[idx] === null) {
          self.options[idx] = self.options['_default_' + idx];
        }
      });

      var mergeDefaults = ['tableRowItemAction'];
      _.each(mergeDefaults, function(idx) {
        var old = self.options[idx];
        self.options[idx] = $.extend(
          false, self.options['_default_' + idx], old
        );
      });

      self.browsing = true; // so all queries will be correct with QueryHelper
      self.options.collectionUrl = self.options.vocabularyUrl;
      self.options.pattern = self;

      // the ``attributes`` options key is not compatible with backbone,
      // but queryHelper that will be constructed by the default
      // ResultCollection will expect this to be passed into it.
      self.options.queryHelperAttributes = self.options.attributes;
      delete self.options.attributes;

      self.view = new AppView(self.options);
      self.$el.append(self.view.render().$el);
    }
  });

  return Structure;

});

require([
    'castle-url/patterns/structure/pattern',
    'pat-registry'
  ], function(
     Structure,
     registry
    ) {
    'use strict';

    return Structure;
  });

define("castle-url/patterns/structure", function(){});

/* global localStorage */

define('castle-url/patterns/toolbar/menu-item',[
  'jquery',
  'mockup-patterns-base',
  'pat-registry',
  'mockup-utils',
  'castle-url/components/utils',
  'castle-url/libs/react/react.min',
  'mockup-patterns-modal',
], function ($, Base, Registry, utils, cutils, R, ModalPattern) {
  'use strict';

  var D = R.DOM;

  var MenuItemBase = {
    getDefaultProps: function(){
      return {
        showIcon: true
      };
    },
    getInitialState: function(){
      return {
        hovered: false,
        focussed: false
      }
    },
    onClick: undefined,
    getLabel: function(){
      return this.props.item.title;
    },
    getClassName: function(){
      return 'castle-toolbar-item castle-toolbar-' + this.props.item.id;
    },
    stripQS: function(s){
      return s.split('?')[0];
    },
    isActive: function(){
      return this.stripQS(window.location.href) === this.stripQS(this.props.item.url);
    },
    render: function(){
      var item = this.props.item;
      var className = this.getClassName();
      if(this.isActive()){
        className += ' active';
      }
      var icon = '';
      if(this.props.showIcon === undefined || this.props.showIcon){
        icon = D.span({ className: item.icon_class, 'aria-hidden': true });
      }
      return D.li(
        { className: className}, [
          D.span({ className: 'simpletooltip_container'}, [
            D.a({ href: item.url, onClick: this.onClick,
                  ref: 'a', className: 'js-simple-tooltip',
                  onFocus: function(){
                    this.setState({
                      focussed: true
                    });
                  }.bind(this),
                  onMouseEnter: function(){
                    this.setState({
                      hovered: true
                    });
                  }.bind(this),
                  onBlur: function(){
                    this.setState({
                      focussed: false
                    });
                  }.bind(this),
                  onMouseLeave: function(){
                    this.setState({
                      hovered: false
                    });
                  }.bind(this),
                  onKeyDown: function(){
                    if (event.keyCode == 27) { // esc
                      this.setState({
                        focussed: false
                      });
                    }
                  }.bind(this),
                  'aria-describedby': 'label_simpletooltip_' + this.props.item.id}, [
            icon,
            this.getLabel()
          ]),
          D.span({ className: 'js-simpletooltip simpletooltip',
                   id: 'label_simpletooltip_' + this.props.item.id,
                   'aria-hidden': !this.state.focussed && !this.state.hovered,
                   'role': 'tooltip'},
            this.props.item.description)
          ])
      ]);
    }
  };
  return MenuItemBase;
});

/* global localStorage */

define('castle-url/patterns/toolbar/modal-item',[
  'jquery',
  'mockup-patterns-base',
  'pat-registry',
  'mockup-utils',
  'castle-url/components/utils',
  'castle-url/libs/react/react.min',
  'mockup-patterns-modal',
  'castle-url/patterns/toolbar/menu-item'
], function ($, Base, Registry, utils, cutils, R, ModalPattern, MenuItemBase) {
  'use strict';

  var D = R.DOM;

  var ModalMenuItemBase = cutils.extend(MenuItemBase, {
    onClick: function(e){
      e.preventDefault();
      cutils.createModalComponent(this.props.ModalComponent, this.props.id, this.getSettings());
    },
    getSettings: function(){
      return {
        parent: this.props.parent
      };
    }
  });

  return ModalMenuItemBase;
});

/* global define */

define('castle-url/components/preview-content-modal',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-url/components/utils'
], function($, Base, _, R, utils, Modal, cutils) {
  'use strict';
  var D = R.DOM;

  var PreviewModalComponent = cutils.Class([Modal], {
    getInitialState: function(){
      return {
        size: 'full'
      };
    },
    componentDidMount: function(){
      utils.loading.show();
      var that = this;
      Modal.componentDidMount.apply(this);
      // calc height as it is loading

      var setHeight = function(){
        var $iframe = $(that.refs.iframe.getDOMNode());
        var newHeight = 0;
        $iframe.contents().find('body > *').each(function(){
          newHeight += $(this).height();
        });
        if(newHeight > $iframe.height()){
          $iframe.height(newHeight);
          utils.loading.hide();
        }
        that.props.timeout = setTimeout(setHeight, 500);
      };
      that.props.timeout = setTimeout(setHeight, 500);
    },
    componentWillUnmount: function(){
      clearTimeout(this.props.timeout);
    },
    componentDidUpdate: function(){
      clearTimeout(this.props.timeout);
      this.componentDidMount();
    },
    sizeChanged: function(e){
      var val = e.target.value;
      if(val === 'full'){
        this.props.width = null;
      }else if(val === 'phone'){
        this.props.width = '500px';
      }else if(val === 'phablet'){
        this.props.width = '680px';
      }else if(val === 'tablet'){
        this.props.width = '800px';
      }
      this.setState({
        size: val
      });
    },
    renderContent: function(){
      var that = this;
      return D.div({ className: 'castle-preview form-horizontal'}, [
        D.div({ className: 'form-group'}, [
          D.label({ className: 'col-sm-4 control-label'}, 'Select device size'),
          D.div({ className: "col-sm-6" },
            D.select({value: that.state.size, onChange: that.sizeChanged, className: 'form-control'}, [
              D.option({value: 'full'}, 'Full Size'),
              D.option({value: 'tablet'}, 'Tablet'),
              D.option({value: 'phablet'}, 'Phablet'),
              D.option({value: 'phone'}, 'Phone')
            ])
          )
        ]),
        D.iframe({ src: $('body').attr('data-view-url') + '?VIEW_AS_ANONYMOUS_VIEW=true',
                   width: '100%', ref: 'iframe', key: this.props.width})
      ]);
    },
    renderFooter: function(){
      var buttons = [D.button({ type: 'button', className: 'plone-btn plone-btn-primary',
                                'data-dismiss': 'modal'}, 'Done')];
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'preview-content-modal',
        title: 'Preview content',
        timeout: 0
      });
    }
  });

  return PreviewModalComponent;
});

/* global define */

define('castle-quality-check',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils'
], function($, Base, _, R, utils) {
  'use strict';
  var D = R.DOM;

  var countWords = function(string){
    var words = [];
    _.each(string.split(' '), function(word){
      if(word.length > 3){
        words.push(word);
      }
    });
    return words.length;
  };

  var CHECKS = [{
    name: 'Short name format',
    warning: 'starts with "copy", contains a space or contains a capital letter',
    run: function(data, callback){
      if(/copy_?/.test(data.id)){
        return callback(false);
      }
      if(data.id.indexOf(' ') !== -1){
        return callback(false);
      }
      if(data.id.toLowerCase() !== data.id){
        return callback(false);
      }
      return callback(true);
    }
  }, {
    name: 'Title length',
    warning: 'should have no more than 8 significant words',
    run: function(data, callback){
      return callback(countWords(data.title) <= 8);
    }
  }, {
    name: 'Title format',
    warning: 'should begin with upper case letter',
    run: function(data, callback){
      if(data.title[0].toUpperCase() != data.title[0]){
        return callback(false);
      }
      return callback(true);
    }
  }, {
    name: 'Summary length',
    warning: 'should not be empty or have no more than 25 significant words',
    run: function(data, callback){
      if(!data.description){
        return callback(false);
      }
      return callback(countWords(data.description) <= 25);
    }
  }, {
    name: 'Summary format',
    warning: 'should begin with upper case letter',
    run: function(data, callback){
      if(!data.description || data.description[0].toUpperCase() != data.description[0]){
        return callback(false);
      }
      return callback(true);
    }
  }, {
    name: 'Links',
    warning: 'You have links in the content that are referencing unpublished content',
    run: function(data, callback){
      return callback(data.linksValid);
    }
  }, {
    name: 'Headers',
    warning: 'You have headers that are out of order. ' +
             'Headers should be in order of h1, h2, h3, etc and not skip a level.',
    run: function(data, callback){
      return callback(data.headersOrdered);
    }
  }, {
    name: 'Template',
    warning: 'This object is a template and is unpublishable.',
    run: function(data, callback){
      return callback(!data.template);
    }
  }];

  var ATDCheck = {
    name: 'Spelling/Grammar',
    warning: function(component){
      if(component.state.data.atdError){
        return D.span({}, ': Error connecting to AtD to check spelling/grammar.');
      }
      var lis = [];
      component.state.data.atdResponse.forEach(function(error){
        lis.push(D.li({}, [
          D.span({ className: 'desc'}, error.description),
          ': ',
          D.span({ className: 'quote pre'}, '"'),
          D.span({ className: 'string'}, error.string),
          D.span({ className: 'quote post'}, '"'),
        ]));
      });
      return D.ul({className: 'atd-errors'}, lis);
    },
    run: function(data, callback){
      data.atdError = false;
      data.atdResponse = [];
      $.ajax({
        method: 'POST',
        url: $('body').attr('data-base-url') + '/checkDocument',
        data: {
          data: data.html,
          key: 'castle-qualitycheck'
        }
      }).done(function(result){
        var errors = [];
        $(result).find('error').each(function(idx, el){
          var $el = $(el);
          errors.push({
            string: $el.find('string')[0].innerHTML,
            description: $el.find('description')[0].innerHTML,
            precontext: $el.find('precontext')[0].innerHTML,
            type: $el.find('type')[0].innerHTML
          });
        });
        data.atdResponse = errors;
        callback(errors > 0);
      }).fail(function(){
        console.log('Error checking after the deadline');
        data.atdError = true;
        callback(false);
      });
    }
  };

  var QualityCheckComponent = R.createClass({
    getInitialState: function(){
      return {
        checked: {},
        data: {}
      };
    },
    getDefaultProps: function(){
      var checks = CHECKS.slice();
      var tinySettings = $('body').attr('data-pat-tinymce');
      if(tinySettings){
        tinySettings = JSON.parse(tinySettings);
        if(tinySettings.tiny.atd_rpc_url){
          // atd activated for this site...
          checks.push(ATDCheck);
        }
      }

      return {
        delay: false,
        onFinished: function(){},
        checks: checks
      };
    },
    componentDidMount: function(){
      var that = this;
      utils.loading.show();
      var url = $('body').attr('data-base-url');
      if(url === $('body').attr('data-portal-url')){
        url += '/' + $('body').attr('data-site-default');
      }
      $.ajax({
        url: url + '/@@quality-check',
        dataType: 'json',
        cache: false
      }).done(function(data){
        that.check(data);
      }).fail(function(){
        alert('Error checking content');
      }).always(function(){
        utils.loading.hide();
      });
    },
    check: function(data){
      var that = this;
      that.state.data = data;

      var doCheck = function(){
        for(var i=0; i<that.props.checks.length; i++){
          var check = that.props.checks[i];
          if(that.state.checked[check.name] === undefined){
            check.run(data, function(result){
              that.state.checked[check.name] = result;
              that.forceUpdate();
              if(_.size(that.state.checked) !== that.props.checks.length){
                if(that.props.delay){
                  setTimeout(doCheck, [250, 500, 750, 1000][Math.floor(Math.random()*4)]);
                }else{
                  doCheck();
                }
              }else{
                that.props.onFinished();
              }
            });
            break;
          }
        }
      };
      doCheck();
    },
    done: function(){
      return _.size(this.state.checked) === this.props.checks.length;
    },
    isValid: function(){
      var that = this;
      for(var i=0; i<that.props.checks.length; i++){
        var check = that.props.checks[i];
        if(!this.state.checked[check.name]){
          return false;
        }
      }
      return true;
    },
    render: function(){
      var that = this;
      var info = '';
      if(that.done()){
        if(that.isValid()){
          info = D.div({ className: 'portalMessage info'}, [
            D.strong({}, 'Success'),
            'All checks are successful.'
          ]);
        }else{
          info = D.div({ className: 'portalMessage error'}, [
            D.strong({}, 'Double check'),
            'Problems have been detected. It is recommended you fix them.'
          ]);
        }
      }
      return D.div({ className: 'castle-quality'}, [D.ul({}, that.props.checks.map(function(check){
        var className = '';
        var label = check.name;
        var labelExtra = '';
        var value = that.state.checked[check.name];
        if(value !== undefined){
          if(value){
            className = 'glyphicon glyphicon-ok';
          }else{
            className = 'glyphicon glyphicon-remove';
            if(typeof(check.warning) != 'function'){
              label += ': ' + check.warning;
            }else{
              labelExtra = check.warning(that);
            }
          }
        }
        return D.li({}, [
          D.span({ className: className}),
          label,
          labelExtra
        ]);
      })),
        info
      ]);
    },
  });

  return QualityCheckComponent;
});

/* global define */

define('castle-url/components/quality-check-modal',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-quality-check',
  'castle-url/components/utils'
], function($, Base, _, R, utils, Modal, QualityCheck, cutils) {
  'use strict';
  var D = R.DOM;

  var QualityCheckModalComponent = cutils.Class([Modal], {
    renderContent: function(){
      return R.createElement(QualityCheck, {});
    },
    renderFooter: function(){
      var buttons = [D.button({ type: 'button', className: 'plone-btn plone-btn-default pull-right',
                                'data-dismiss': 'modal'}, 'Done')];
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'quality-content-modal',
        title: 'Quality Check'
      });
    }
  });

  return QualityCheckModalComponent;
});

/* global define, google */

define('castle-url/components/analytics-modal',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-url/components/utils',
  'moment',
  'castle-url/libs/script'
], function($, Base, _, R, utils, Modal, cutils, moment, $script) {
  'use strict';
  var D = R.DOM;

  var Chart = R.createClass({
    getDefaultProps: function(){
      return {
        height: '500px'
      };
    },
    componentDidMount: function(){
      var chart = new this.props.Type(this.refs.chart.getDOMNode());
      chart.draw(this.props.data, this.props.options);
    },
    componentDidUpdate: function(){
      this.componentDidMount();
    },
    render: function(){
      return D.div({ ref: 'chart', key: this.props.key || this.props.name,
                     style: { height: this.props.height} });
    }
  });


  var BaseTab = {
    type: 'realtime',

    labels: {
      'referralPath': 'Referral',
      'deviceCategory': 'Device type',
      'pagePath': 'Page'
    },

    dimensionOptions: [],
    metricOptions: [],

    translate: function(name){
      if(this.labels[name]){
        return this.labels[name];
      }else{
        name = name.replace('rt:', '').replace('ga:', '');
        if(this.labels[name]){
          return this.labels[name];
        }
      }
      name = name.replace('avg', 'average').replace('pageviews', 'pageViews');
      var label = name.substring(0, 1).toUpperCase();
      name.substring(1).split('').forEach(function(letter){
        if(letter === letter.toUpperCase()){
          label += ' ' + letter.toLowerCase();
        }else{
          label += letter;
        }
      });
      return label;
    },

    getInitialState: function(){
      return {
        loading: true,
        chartsLoaded: false,
        metrics: this.metricOptions[0],
        dimensions: null,
        sort: null,
        max_results: 5,
        global: false,
        data: {},
        paths: [],
        chartType: 'column'
      };
    },

    componentDidMount: function(){
      var that = this;
      this.load();

      // because callbacks are fun
      if(window.google && window.google.charts){
        that.setState({
          chartsLoaded: true
        });
        return;
      }
      $script('https://www.gstatic.com/charts/loader.js', function(){
        google.charts.load('current', {'packages':['corechart', 'bar']});
        google.charts.setOnLoadCallback(function(){
          that.setState({
            chartsLoaded: true
          });
        });
      });
    },

    getQueryData: function(){
      var query = {
        metrics: this.state.metrics,
        'global': this.state.global,
        sort: '-' + this.state.metrics
      };
      if(this.state.dimensions){
        query.dimensions = this.state.dimensions;
      }
      if(this.state.max_results){
        query.max_results = this.state.max_results;
      }
      return query;
    },

    load: function(){
      var that = this;
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-base-url') + '/@@content-analytics',
        data: {
          api: 'ga',
          type: this.type,
          params: JSON.stringify(that.getQueryData()),
          cache_duration: 60 * 5
        }
      }).done(function(data){
        data.loading = false;
        that.setState({
          loading: false,
          data: data.data,
          paths: data.paths
        });
      }).fail(function(){
        alert('failed to load analytic data');
      }).always(function(){
        utils.loading.hide();
      });
    },

    timedLoad: function(){
      var that = this;
      if(this._timeout){
        clearTimeout(this._timeout);
      }
      this._timeout = setTimeout(function(){
        that.load();
      }, 500);
    },

    changeValue: function(param, e){
      var value = e.target.value;
      this.state[param] = value;
      this.forceUpdate();
      this.timedLoad();
    },

    globalClicked: function(e){
      this.setState({
        global: e.target.checked
      });
      this.timedLoad();
    },

    createOption: function(val, name){
      if(!name){
        name = this.translate(val);
      }
      return D.option({ value: val}, name);
    },

    render: function(){
      var that = this;

      if(that.state.loading || !that.state.chartsLoaded){
        return D.p({}, 'Loading data...');
      }
      if(!this.state.data){
        return D.p({}, 'No data could be retrieved. Google Analytics API support may not be configured.');
      }
      var cdata = [['Count', this.translate(this.state.metrics)]];
      _.each(this.state.data.rows, function(result){
        if(result.length > 1) {
          cdata.push([result[0] + '', parseInt(result[1])]);
        } else {
          cdata.push([result[0], parseInt(result[0])]);
        }
      });
      cdata = google.visualization.arrayToDataTable(cdata);

      // Set chart options
      var options = {
        title: 'Real time statistics',
        hAxis: {
          title: 'Count',
          minValue: 0
        },
        vAxis: {
          title: this.translate(this.state.metrics)
        }
      };

      var chartType = google.visualization.ColumnChart;
      if(this.state.chartType === 'pie'){
        chartType = google.visualization.PieChart;
      }
      var chart = 'No data found';
      if(this.state.data.rows){
        chart = R.createElement(Chart, {
          name: 'context',
          data: cdata,
          options: options,
          Type: chartType
        });
      }

      return D.div({},
        this.renderFields(),
        chart,
        D.div({ className: 'checkbox pull-right'}, D.label({}, [
          D.input({ type: 'checkbox', checked: this.state.global,
                    onClick: this.globalClicked }),
          'Analyze entire site'
        ])),
        D.p({ className: 'discreet'}, 'Totals for current page: ' + $('body').attr('data-base-url'))
      );
    },
    renderFields: function(){
      var that = this;

      var dimensions = [that.createOption('', 'N/A')];
      this.dimensionOptions.forEach(function(dim){
        dimensions.push(that.createOption(dim));
      });
      var metrics = [];
      this.metricOptions.forEach(function(metric){
        metrics.push(that.createOption(metric));
      });

      var fields = [
        D.div({ className: "form-group col-md-2" }, [
          D.label({ }, 'Aggregate'),
          D.select({ className: 'form-control',
                     value: this.state.metrics,
                     onChange: this.changeValue.bind(this, 'metrics')}, metrics)
        ]),
        D.div({ className: "form-group col-md-2" }, [
          D.label({ }, 'Dimensions'),
          D.select({ className: 'form-control',
                     value: this.state.dimensions,
                     onChange: this.changeValue.bind(this, 'dimensions')}, dimensions)
        ]),
        D.div({ className: "form-group col-md-2" }, [
          D.label({ }, 'Max results'),
          D.select({ className: 'form-control',
                     value: this.state.max_results,
                     onChange: this.changeValue.bind(this, 'max_results')}, [
            D.option({ value: '5'}, '5'),
            D.option({ value: '10'}, '10'),
            D.option({ value: '15'}, '15')
          ])
        ]),
        D.div({ className: "form-group col-md-2" }, [
          D.label({ }, 'Chart type'),
          D.select({ className: 'form-control',
                     value: this.state.chartType,
                     onChange: this.changeValue.bind(this, 'chartType')}, [
            D.option({ value: 'column'}, 'Columns'),
            D.option({ value: 'pie'}, 'Pie')
          ])
        ])
      ].concat(this.renderAdditionalFields());
      return D.div({ className: "row" }, fields);
    },
    renderAdditionalFields: function(){
      // to add custom fields, override
      return [];
    }
  };


  var RealtimeTab = cutils.Class([BaseTab], {
    type: 'realtime',
    dimensionOptions: [
      'rt:userType',
      'rt:medium',
      'rt:trafficType',
      'rt:browser',
      'rt:operatingSystem',
      'rt:deviceCategory',
      'rt:country',
      'rt:region',
      'rt:pagePath'
    ],
    metricOptions: [
      'rt:pageViews',
      'rt:activeUsers'
    ]
  });

  var HistoryTab = cutils.Class([BaseTab], {
    type: 'ga',
    dimensionOptions: [
      'ga:userType',
      'ga:sessionCount',
      'ga:socialNetwork',
      'ga:hasSocialSourceReferral',
      'ga:medium',
      'ga:trafficType',
      'ga:browser',
      'ga:operatingSystem',
      'ga:deviceCategory',
      'ga:pagePath',
      'ga:country',
      'ga:region',
      'ga:continent',
      'ga:subContinent',
      'ga:metro',
      'ga:city',
      'ga:flashVersion',
      'ga:javaEnabled',
      'ga:language',
      'ga:exitPagePath'
    ],
    metricOptions: [
      'ga:hits',
      'ga:users',
      'ga:newUsers',
      'ga:sessions',
      'ga:pageviews',
      'ga:bounces',
      'ga:bounceRate',
      'ga:avgSessionDuration',
      'ga:entranceRate',
      'ga:pageviewsPerSession',
      'ga:avgTimeOnPage',
      'ga:avgPageLoadTime'
    ],

    getInitialState: function(){
      var state = BaseTab.getInitialState.call(this);
      state.to = moment().local().format('YYYY-MM-DD');
      state.from = moment().local().subtract(7, 'days').format('YYYY-MM-DD');
      return state;
    },

    componentDidUpdate: function(){
      var that = this;
      if(this.refs.from){
        $(this.refs.from.getDOMNode()).pickadate({
          format: 'yyyy-mm-dd',
          formatSubmit: 'yyyy-mm-dd',
          onSet: function(context){
            that.state.from = moment(context.select).local().format('YYYY-MM-DD');
            that.timedLoad();
          }
        });
        $(this.refs.to.getDOMNode()).pickadate({
          format: 'yyyy-mm-dd',
          formatSubmit: 'yyyy-mm-dd',
          onSet: function(context){
            that.state.to = moment(context.select).local().format('YYYY-MM-DD');
            that.timedLoad();
          }
        });
      }
    },

    getQueryData: function(){
      var data = BaseTab.getQueryData.call(this);
      var now = moment().local();
      var dfrom = moment(this.state.from, "YYYY-MM-DD").local();
      var dto = moment(this.state.to, "YYYY-MM-DD").local();
      data.start_date = parseInt((now - dfrom) / 1000 / 60 / 60 / 24) + 'daysAgo';
      data.end_date = parseInt((now - dto) / 1000 / 60 / 60 / 24) + 'daysAgo';
      return data;
    },

    renderAdditionalFields: function(){
      return [
        D.div({ className: "form-group col-md-2" }, [
          D.label({ }, 'From'),
          D.input({ className: 'form-control', ref: 'from',
                    value: this.state.from })
        ]),
        D.div({ className: "form-group col-md-2" }, [
          D.label({ }, 'To'),
          D.input({ className: 'form-control', ref: 'to',
                    value: this.state.to })
        ])
      ];
    }
  });


  var AnalyticsModalComponent = cutils.Class([Modal], {
    dataMappings: {
      pinterest: 'Pinterest',
      twitter_matomo: 'Twitter (Matomo)',
      facebook_matomo: 'Facebook (Matomo)'
    },
    getInitialState: function(){
      return {
        social: null,
        analytics: null,
        tab: 'realtime',
        loading: false
      };
    },
    componentDidMount: function(){
      Modal.componentDidMount.call(this);
      var that = this;
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-base-url') + '/@@content-analytics',
        data: {
          api: 'social'
        }
      }).done(function(data){
        that.setState({
          social: data.data
        });
      }).fail(function(){
        alert('failed to load analytic data');
      }).always(function(){
        utils.loading.hide();
      });
    },
    tabClicked: function(tab){
      this.setState({
        tab: tab
      });
    },
    renderTabItem: function(tab, label){
      return D.a({ href: '#' + tab, className: this.state.tab === tab && 'active' || '',
                   onClick: this.tabClicked.bind(this, tab)}, label);
    },
    renderContent: function(){
      var that = this;
      if(that.state.loading){
        return D.div({ className: 'castle-analytics'}, [
          D.p({ className: 'discreet'}, 'Loading analytic data...')
        ]);
      }
      return D.div({ className: 'castle-analytics pat-autotoc autotabs'}, [
        D.nav({ className: 'autotoc-nav'}, [
          that.renderTabItem('realtime', 'Real time'),
          that.renderTabItem('history', 'Historical'),
          that.renderTabItem('social', 'Social')
        ]),
        that.renderTab()
      ]);
    },
    renderTab: function(){
      if(this.state.tab === 'realtime'){
        return R.createElement(RealtimeTab, {
          parent: this
        });
      }
      if(this.state.tab === 'history'){
        return R.createElement(HistoryTab, {
          parent: this
        });
      }
      if(this.state.tab === 'social'){
        return this.renderSocialTab();
      }
    },
    renderSiteTab: function(){
      if(this.state.analytics === null){
        return D.p({ className: 'discreet' }, 'Analytics API not configured');
      }

      var data = this.state.analytics;
      var cdata = google.visualization.arrayToDataTable([
        ['Type', 'Count', { role: 'style' }, { role: 'annotation' }],
        ['Users', data.activeUsers, 'color: gray', data.activeUsers],
        ['Page Views', data.activePageViews, 'color: #76A7FA', data.activePageViews]
      ]);

      // Set chart options
      var options = {
        title: 'Real-time data'
      };
      return R.createElement(Chart, {
        name: 'site',
        data: cdata,
        options: options,
        Type: google.visualization.ColumnChart
      });
    },
    renderSocialTab: function(){
      var that = this;
      if(this.state.social === null){
        return D.p(
          { className: 'discreet' },
          'No social data found (Make sure social count monitoring is configured)');
      }
      var extra = '';
      var data = this.state.social;
      var cdata= [
        ['Platform', 'Shares']
      ];
      Object.keys(this.dataMappings).forEach(function(dataKey){
        if(data[dataKey]){
          cdata.push([that.dataMappings[dataKey], data[dataKey]]);
        }
      });

      if(data.twitter){
        cdata.push(['Twitter', data.twitter]);
        extra = D.p(
          { className: 'discreet'},
          'Twitter shares as reported via Twitter\'s streaming API');
      }else if(!data.twitter_matomo){
        extra = D.p(
          { className: 'discreet'},
          'Twitter API keys may not be set (Make sure twitter monitoring is configured)');
      }

      cdata = google.visualization.arrayToDataTable(cdata);

      // Set chart options
      var options = {
        title: 'Social media shares',
        hAxis: {
          title: 'Platform',
          minValue: 0
        },
        vAxis: {
          title: 'Shares'
        }
      };
      return [
        R.createElement(Chart, {
          name: 'realtime',
          key: 'realtime-' + this.state.metrics + this.state.dimensions +
               this.state.max_results + this.state.chartType,
          data: cdata,
          options: options,
          Type: google.visualization.ColumnChart
        }),
        extra];
    },
    renderFooter: function(){
      var buttons = [D.button({ type: 'button', className: 'plone-btn plone-btn-primary',
                                'data-dismiss': 'modal'}, 'Done')];
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'analytics-content-modal',
        title: 'Content Analytics',
        width: '95%'
      });
    }
  });

  return AnalyticsModalComponent;
});

/* global define */

define('castle-url/components/workflow-modal',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-quality-check',
  'castle-url/components/utils'
], function($, Base, _, R, utils, Modal, QualityCheck, cutils) {
  'use strict';
  var D = R.DOM;

  var QualityCheckWrapper = R.createClass({
    // for being able to toggle open and closed
    getInitialState: function(){
      return {
        checked: false,
        open: false,
        valid: false
      };
    },
    getDefaultProps: function(){
      return {
        onQACheck: function(){}
      };
    },
    onChecked: function(){
      if(this.refs.qa){
        var valid = this.refs.qa.isValid();
        this.setState({
          checked: true,
          valid: valid
        });
        if (!valid && !this.state.open) {
          // open automatically only if not already open and error
          this.setState({
            open: true
          });
        }
        this.props.onQACheck(valid);
      }
    },
    onToggleClicked: function(e){
      e.preventDefault();
      this.setState({
        open: !this.state.open
      });
    },
    render: function(){
      var qa = R.createElement(QualityCheck, {
        delay: false, onFinished: this.onChecked, ref: 'qa' });
      var toggleText = 'Show Quality Check';
      if(this.state.open){
        toggleText = 'Hide Quality Check';
      }
      var btnIconClass = '';
      var btnClass = 'plone-btn plone-btn-warning';
      if(this.state.valid){
        //btnIconClass = 'glyphicon glyphicon-ok';
        btnClass = 'plone-btn plone-btn-default';
      }
      return D.div({className: 'quality-check-wrapper'}, [
        D.button({ className: btnClass,
                   onClick: this.onToggleClicked}, [
          D.span({ className: btnIconClass}),
          toggleText
        ]),
        D.div({ style: {display: this.state.open && 'block' || 'none'}}, [
          qa
        ])
      ]);
    }
  });

  var WorkflowModalComponent = cutils.Class([Modal], {
    getInitialState: function(){
      return {
        transition: '',
        comment: '',
        qaValid: false
      };
    },

    transitionClicked: function(e){
      var data = {
        transition: e.target.value
      };
      // set early here..
      this.state.transition = e.target.value;
      if(this.isQARequired()){
         if(this.state.comment.length === 0){
           data.comment = 'OVERRIDE: ';
         }else if(this.state.comment.indexOf('OVERRIDE:') === -1){
            data.comment = 'OVERRIDE: ' + this.state.comment;
         }
      }else{
        if(this.state.comment.trim() === 'OVERRIDE:'){
          // we can remove now
          data.comment = '';
        }
      }
      this.setState(data);
    },

    commentChanged: function(e){
      var data = {
        comment: e.target.value
      };
      if(this.isQARequired()){
        if(data.comment.indexOf('OVERRIDE:') === -1){
          return; // do not allow edit. They can *not* edit "OVERRIDE:" out
        }
      }
      this.setState(data);
    },

    qaDone: function(valid){
      this.setState({
        qaValid: valid
      });
    },

    renderContent: function(){
      var that = this;
      var transitionComps = [D.div({ className: 'radio'}, D.label({}, [
        D.input({ type: 'radio', value: '',
                  name: 'transition',
                  checked: that.state.transition === '',
                  onClick: that.transitionClicked}),
        'No change'
      ]))];

      transitionComps = transitionComps.concat(
        that.props.workflow.transitions.map(function(transition){
          return D.div({ className: 'radio'}, D.label({}, [
            D.input({ type: 'radio', value: transition.id,
                      name: 'transition',
                      checked: that.state.transition === transition.id,
                      onClick: that.transitionClicked}),
            transition.title
          ]));
        }));

      var commentClassName = 'form-group ';
      if(this.isQARequired()){
        commentClassName += 'has-error';
      }
      return D.div({ className: 'castle-preview form-horizontal'}, [
        R.createElement(QualityCheckWrapper, {delay: false, ref: 'qa',
                                              onQACheck: this.qaDone }),
        D.hr({}),
        D.div({className: 'form-group'}, [
          D.label({ htmlFor: '' }, 'Change state'),
          D.div({ className: 'formHelp'}, "Select the transition to be used for modifying the item's state."),
          transitionComps
        ]),
        D.div({className: commentClassName}, [
          D.label({}, 'Comment'),
          D.div({ className: 'formHelp'}, 'Comments will be added to the publishing history. ' +
                                          'Comments are required when quality check does not pass and you are attempting to publish.'),
          D.textarea({ className: 'form-control', value: that.state.comment,
                       onChange: that.commentChanged})
        ])
      ]);
    },

    onChangeClicked: function(e){
      e.preventDefault();
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-base-url') + '/@@content-workflow',
        data: {
          _authenticator: utils.getAuthenticator(),
          transition_id: this.state.transition,
          comment: this.state.comment,
          action: 'transition'
        }
      }).always(function(){
        utils.loading.hide();
      }).fail(function(){
        alert('Error performing transition');
      }).done(function(){
        window.location.reload();
      });
      this.hide();
    },

    isQARequired: function(){
      return (!this.state.qaValid &&
              this.state.transition === 'publish' &&
              this.props.workflow.publishRequireQualityCheck);
    },

    renderFooter: function(){
      var buttons = [
        D.button({ type: 'button', className: 'plone-btn plone-btn-default', 'data-dismiss': 'modal'}, 'Cancel'),
        D.button({
          type: 'button', className: 'plone-btn plone-btn-primary pull-right',
          disabled: (this.isQARequired() &&
                     this.state.comment.trim().length <= 'OVERRIDE:'.length) ||
                    !this.state.transition,
          onClick: this.onChangeClicked}, 'Change')
      ];
      return D.div({ className: 'btn-container'}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'workflow-content-modal',
        title: 'Publishing Process',
        workflow: {}
      });
    }
  });

  return WorkflowModalComponent;
});

/* global define */

define('castle-url/components/slot-manager-modal',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-url/components/utils',
  'mockup-patterns-modal',
  'pat-registry',
  'moment',
  'jquery.cookie'
], function($, Base, _, R, utils, Modal, cutils, ModalPattern, Registry, moment) {
  'use strict';
  var D = R.DOM;

  var SlotManagerComponent = R.createClass({
    getInitialState: function(){

      var url = $('body').attr('data-base-url').replace($('body').attr('data-portal-url'), '');
      if(!url || url[0] !== '/'){
        url = '/' + url;
      }
      return {
        current: url,
        mode: 'parent',
        effective_tiles: [],
        tiles: [],
        dirty: false
      };
    },

    componentDidMount: function(){
      var that = this;
      if(!that.props.slot.workingId){
        that.startEditing();
      }else{
        that.doAction({});
      }
    },

    startEditing: function(override){
      var that = this;
      var data = {
        action: 'copymeta',
        metaId: that.props.slot.id,
        _authenticator: utils.getAuthenticator()
      };
      if(override){
        data.override = 'yes';
      }
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-portal-url') + that.state.current + '/@@meta-tile-manager',
        data: data
      }).done(function(data){
        if(data.success){
          that.props.slot.workingId = data.newId;
          that.doAction({});
        }else if(data.locked){
          var info = data.lock_data;
          if(confirm('This slot currently has an unfinished edit started by ' + info.user +
                     ' ' + moment(info.when).fromNow() + '. Do you want to override this ' +
                     "person's edit? This will destroy of the other user's changes.")){
            that.startEditing(true);
          }
        }else{
          alert('unknown error occurred');
        }
      }).always(function(){
        utils.loading.hide();
      });
    },

    doAction: function(data, success){
      var that = this;
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-portal-url') + that.state.current + '/@@meta-tile-manager',
        data: $.extend({}, true, {
          metaId: that.props.slot.id,
          _authenticator: utils.getAuthenticator()
        }, data)
      }).done(function(data){
        data.loading = false;
        that.setState(data);
        if(success){
          success(data);
        }
      }).always(function(){
        utils.loading.hide();
      });
    },

    _editTile: function(tile){
      utils.loading.show();
      // Get url
      var tile_edit_url = this.state.current_url + '/@@edit-tile/' +
                          tile.type + '/' + tile.id + '?X-Tile-Persistent=yes';

      var modal = new ModalPattern($(this.getDOMNode()), {
        ajaxUrl: tile_edit_url,
        loadLinksWithinModal: true,
        buttons: '.formControls > input[type="submit"], .actionButtons > input[type="submit"]'
      });

      modal.$el.off('after-render');
      var $html = null;
      var tinymce = null;
      utils.loading.show();
      modal.on('after-render', function() {
        modal.$modal.parents('.plone-modal-wrapper').css('z-index', '9998');
        $('input[name*="cancel"]', modal.$modal).off('click').on('click', function() {
            // Close overlay
            modal.hide();
        });
        /* make sure it is saved persistently */
        $('form', modal.$modal).append($('<input type="hidden" name="X-Tile-Persistent" value="yes" />'));

        // setup tile mce for raw html tile
        $html = $('[name="plone.app.standardtiles.rawhtml.content"]', modal.$modal);
        if($html.size() > 0){
          var options = $.parseJSON($('body').attr('data-pat-tinymce'));
          if(options.tiny.external_plugins){
            _.each(_.keys(options.tiny.external_plugins), function(plugin){
              options.tiny.external_plugins[plugin] = $('body').attr('data-portal-url') +
                '/' +options.tiny.external_plugins[plugin];
            });
          }
          tinymce = new Registry.patterns.tinymce($html, options);
        }
        utils.loading.hide();
      });
      modal.show();
      modal.$el.off('formActionSuccess');
      modal.on('hide', function(){
        if($html){
          try{
            $html.data("pattern-tinymce").destroy();
          }catch(e){
            //
          }
          $html.removeData("pattern-tinymce");
        }
        if(tinymce && tinymce.tiny){
          tinymce.tiny.remove();
        }
      });
      modal.on('formActionSuccess', function () {
        //var tileUrl = xhr.getResponseHeader('X-Tile-Url');
        modal.hide();
      });
    },

    addTileSelected: function(e){
      var that = this;
      that.state.dirty = true;
      that.doAction({
        type: e.target.value,
        action: 'addtile'
      }, function(data){
        // XXX after it is added, go into edit mode for it immediately
        that._editTile(data.tiles[data.tiles.length - 1]);
      });
    },

    deleteTile: function(idx, e){
      var that = this;
      that.state.dirty = true;
      e.preventDefault();
      that.doAction({
        type: e.target.value,
        action: 'deletetile',
        idx: idx
      });
    },

    moveUp: function(idx, e){
      var that = this;
      that.state.dirty = true;
      e.preventDefault();
      that.doAction({
        type: e.target.value,
        action: 'moveup',
        idx: idx
      });
    },

    moveDown: function(idx, e){
      var that = this;
      that.state.dirty = true;
      e.preventDefault();
      that.doAction({
        type: e.target.value,
        action: 'movedown',
        idx: idx
      });
    },

    modeClicked: function(e){
      var that = this;
      that.state.dirty = true;
      e.preventDefault();
      that.doAction({
        value: e.target.value,
        action: 'mode'
      });
    },

    editTile: function(idx, e){
      e.preventDefault();
      this.state.dirty = true;
      this._editTile(this.state.tiles[idx]);
    },

    renderLinkedPath: function(path){
      if(path === '/'){
        return D.a({ href: $('body').attr('data-portal-url'), target: '_blank',
                     className: 'slot-manager-link-path'}, [
          D.span({ className: 'glyphicon glyphicon-home'}),
          ' /'
        ]);
      }else{
        return D.a({ href: $('body').attr('data-portal-url') + path + '/view',
                     target: '_blank', className: 'slot-manager-link-path'}, path);
      }
    },

    renderTileListing: function(){
      var that = this;
      if(this.state.mode === 'hide'){
        return D.p({ className: 'discreet'}, 'This slot is hidden');
      }

      var content = [];
      if(this.state.mode === 'parent' || this.state.mode === 'add'){
        var showParents = [];
        that.state.effective_tiles.forEach(function(effective_tile){
          if(effective_tile.path === that.state.current ||
             effective_tile.data.length === 0){
            return;
          }
          showParents.push(D.table({className: 'table listing slot-manager-showing-parent'}, [
            D.thead({}, [
              D.th({className: 'slot-manager-parent-location'}, [
                D.span({ className: 'slot-manager-location-label' }, 'Location: '),
                that.renderLinkedPath(effective_tile.path)
              ]),
            ]),
            D.tbody({}, effective_tile.data.map(function(tile, idx){
              return D.tr({}, D.td({}, [
                idx + 1,
                ': ',
                tile.label
              ]));
            }))
          ]));
        });
        if(showParents.length > 0){
          content.push(D.div({ className: 'slot-manager-parents' }, [
            D.h3({}, 'Parent tiles'),
            showParents
          ]));
        }else{
          content.push(D.div({}, [
            D.p({ className: 'discreet'}, 'There are no tiles assign here.')
          ]));
        }
      }
      if(that.state.mode === 'show' || that.state.mode === 'add'){
        var inner = [];
        if(this.state.tiles.length > 0){
          inner.push(D.h3({}, [
            'Tiles rendered here',
          ]));
          inner.push(D.table({ className: 'listing table', style: { width: '100%'}}, [
            D.thead({}, [
              D.th({}, 'Tile'),
              D.th({}, 'Actions'),
            ]),
            D.tbody({}, this.state.tiles.map(function(tile, idx){
              return D.tr({}, [
                D.td({}, [
                  idx + 1,
                  ': ',
                  tile.label
                ]),
                D.td({}, [
                  D.a({ href: '#', className: 'btn btn-default icon-move-up',
                        onClick: that.moveUp.bind(this, idx) }, 'Up'),
                  D.a({ href: '#', className: 'btn btn-default icon-move-down',
                        onClick: that.moveDown.bind(this, idx) }, 'Down'),
                  D.a({ href: '#', onClick: that.editTile.bind(this, idx),
                        className: 'btn btn-default icon-edit' }, 'Edit'),
                  D.a({ href: '#', onClick: that.deleteTile.bind(this, idx),
                        className: 'btn btn-default icon-trash' }, 'Delete')
                ])
              ]);
            }))
          ]));
        }
        content.push(D.div({ className: 'slot-manager-render-here'}, [
          D.div({}, inner),
          D.div({ className: 'form-group'}, [
            D.label({ className: ''}, 'Select a Tile'),
            D.select({ onChange: this.addTileSelected, value: 'add' },
                   this.getAvailableSlots())
          ])
        ]));
      }
      return content;
    },

    getAvailableSlots: function(){
      var slots = [D.option({ value: 'add'}, 'Select Tile...')];
      var available = $('body').attr('data-available-slots');
      if(available){
        available = $.parseJSON(available);
        _.each(_.keys(available).sort(), function(groupName){
          var items = [];
          var tiles = _.sortBy(available[groupName], function(tile){
            return tile.label;
          });
          _.each(tiles, function(tile){
            items.push(D.option({value: tile.id}, tile.label));
          });
          slots.push(D.optgroup({ label: groupName}, items));
        });
      }else{
        slots.push(D.optgroup({ label: 'Structure'}, [
          D.option({value: 'plone.app.standardtiles.rawhtml'}, 'Text'),
        ]));
      }
      return slots;
    },

    clickSelected: function(selected, e){
      e.preventDefault();
      this.state.selected = selected;
      this.doAction({});
    },

    renderMode: function(){
      var that = this;
      var options = [];
      if(that.state.current !== '/'){
        options.push(D.label({className: 'checkbox-inline'}, [
          D.input({ type: 'radio', name: 'slotMode', value: 'parent',
                    checked: that.state.mode == 'parent', onClick: that.modeClicked }),
          'Inherit'
        ]));
      }
      options.push(D.label({ className: 'checkbox-inline'}, [
        D.input({ type: 'radio', name: 'slotMode', value: 'hide',
                  checked: that.state.mode == 'hide', onClick: that.modeClicked }),
        'Hide'
      ]));
      options.push(D.label({className: 'checkbox-inline'}, [
        D.input({ type: 'radio', name: 'slotMode', value: 'show',
                  checked: that.state.mode == 'show', onClick: that.modeClicked }),
        'Replace'
      ]));
      options.push(D.label({className: 'checkbox-inline'}, [
        D.input({ type: 'radio', name: 'slotMode', value: 'add',
                  checked: that.state.mode == 'add', onClick: that.modeClicked }),
        'Add'
      ]));
      return D.div({ className: 'form-group radio-group slot-manager-display-mode'}, [
        D.label({ }, 'Display Mode'),
        D.div({ className: 'radio' }, options)
      ]);
    },

    cancelEdit: function(callback){
      var that = this;
      var data = {
        action: 'cancelcopy',
        metaId: that.props.slot.id,
        _authenticator: utils.getAuthenticator()
      };
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-portal-url') + that.state.current + '/@@meta-tile-manager',
        data: data
      }).done(function(){
        callback();
      }).always(function(){
        utils.loading.hide();
      }).fail(function(){
        alert('Unknown error');
      });
    },

    editRoot: function(e){
      e.preventDefault();
      var that = this;
      // that.cancelEdit(function(){
        that.setState({
          current: '/'
        }, function(){
          that.props.slot.workingId = undefined;
          that.startEditing();
        });
      // });
    },

    editHomepage: function(e){
      e.preventDefault();
      var that = this;
      // that.cancelEdit(function(){
        that.setState({
          current: '/' + that.props.defaultPage,
        }, function(){
          that.props.slot.workingId = undefined;
          that.startEditing();
        });
      // });
    },

    renderCurrentLocation: function(){
      var that = this;
      var extra = '';
      if(that.state.current === '/' + that.props.defaultPage){
        extra = D.div({ className: "portalMessage info" }, [
          D.strong({}, 'Info'),
          ' You are managing slots from the home page of the site. ',
          D.a({ href: '#', onClick: that.editRoot }, 'Click here'),
          ' to manage slots that apply to the entire site. '
        ]);
      }else if(that.state.current === '/'){
        extra = D.div({ className: "portalMessage info" }, [
          D.strong({}, 'Info'),
          ' You are managing slots from the root of the site. ',
          D.a({ href: '#', onClick: that.editHomepage }, 'Click here'),
          ' to manage slots that only apply at the homepage. '
        ]);
      }
      return D.div({ className: 'castle-slot-location-container' }, [
        extra,
        D.div({ className: 'input-group location'}, [
          D.span({ className: 'input-group-addon' }, 'Location'),
          D.span({ className: 'form-control' }, that.state.current)
        ])
      ]);
    },

    render: function(){
      var that = this;
      return D.div({ className: 'castle-slots'},[
        that.renderCurrentLocation(),
        that.renderMode(),
        that.renderTileListing()
      ]);
    },
    getDefaultProps: function(){
      return {
        slot: {},
        defaultPage: $('body').attr('data-site-default')
      };
    }
  });

  var SlotManagerModalComponent = cutils.Class([Modal], {
    getInitialState: function(){
      return {
        slot: null,
        layout: null
      };
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'slot-manager-modal',
        title: 'Choose slot to manage',
        slots: []
      });
    },

    // on select... title: 'Manage ' + slot.replace('meta-', '') + ' slot', tileId: slot

    componentDidMount: function(){
      var that = this;
      Modal.componentDidMount.apply(that);
      var $el = that.getModalEl();
      $el.on('hidden.bs.modal', function(){
        if(that.refs.manager.state.dirty){
          window.location.reload();
        }
      });
      //   if(that.refs.manager && that.refs.manager.state.dirty){
      //     if(confirm('Do you want to save your changes?')){
      //       that.saveEditClicked();
      //     }else{
      //       that.cancelEditClicked();
      //     }
      //   }
      // });

      // prevent weird draft support issues...
      var path = $.cookie('plone.app.drafts.path');
      if(path){
        $.removeCookie('plone.app.drafts.path', {path: path});
        $.removeCookie('plone.app.drafts.draftName', {path: path});
        $.removeCookie('plone.app.drafts.targetKey', {path: path});
        $.removeCookie('plone.app.drafts.userId', {path: path});
      }
      that.bindIframe();
    },
    componentDidUpdate: function(){
      this.bindIframe();
    },

    bindIframe: function(){
      var that = this;
      if(!that.refs.iframe){
        return;
      }

      var $iframe = $(that.refs.iframe.getDOMNode());
      $iframe.load(function(){
        var newHeight = 0;
        $iframe.contents().find('body > *').each(function(){
          newHeight += $(this).height();
        });
        $iframe.height(newHeight);
        $('.castle-tile-container', $iframe.contents()).off('click').on('click', function(){
          var $el = $(this);
          that.props.title = 'Manage ' + $el.attr('data-tile-title') + ' Slot';
          that.setState({
            slot: {
              id: $el.attr('data-tile-id'),
              title: $el.attr('data-tile-title')
            }
          });
        });
      });
    },

    renderContent: function(){
      var that = this;
      if(that.state.slot){
        return R.createElement(SlotManagerComponent, {
          slot: this.state.slot,
          key: that.state.slot.id,
          ref: 'manager'});
      }else{
        return D.div({ className: 'slot-chooser'}, [
          D.p({ className: 'discreet'}, 'Slots are areas in the theme where you can place tiles into that are outside the main content area.'),
          D.iframe({ src: $('body').attr('data-portal-url') + '/@@render-slots-site-layout?layout=' + $('body').attr('data-site-layout'),
                     width: '100%', style: {'min-height': '400px'}, className: 'castle-slot-selector', ref: 'iframe', name: 'choose_slot'})
        ]);
      }
    },

    cancelEditClicked: function(e, forced){
      var that = this;
      if(e){
        e.preventDefault();
      }
      if(!that.refs.manager){
        return that.setState({
          slot: null
        });
      }
      var state = that.refs.manager.state;

      if(!forced){
        // check if the user really wants to lose changes
        if(!confirm("You have unsaved changes. Are you certain you want to cancel those changes?")){
          return;
        }
      }
      var data = {
        action: 'cancelcopy',
        metaId: that.state.slot.id,
        _authenticator: utils.getAuthenticator()
      };
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-portal-url') + state.current + '/@@meta-tile-manager',
        data: data
      }).done(function(){
        that.refs.manager.state.dirty = false;
        that.setState({
          slot: null
        });
      }).always(function(){
        utils.loading.hide();
      });
    },

    saveEditClicked: function(e){
      var that = this;
      if(e){
        e.preventDefault();
      }
      if(!that.refs.manager){
        return that.hide();
      }
      var state = that.refs.manager.state;

      var data = {
        action: 'savecopy',
        metaId: that.state.slot.id,
        _authenticator: utils.getAuthenticator()
      };
      utils.loading.show();
      $.ajax({
        url: $('body').attr('data-portal-url') + state.current + '/@@meta-tile-manager',
        data: data
      }).done(function(){
        that.refs.manager.state.dirty = false;
        that.hide();
        window.location.reload();
      }).always(function(){
        utils.loading.hide();
      }).fail(function(){
        alert('Error saving slot changes.');
      });
    },

    renderFooter: function(){
      var that = this;
      var buttons = [];
      if(that.state.slot){
        buttons.push(D.button({
          type: 'button', className: 'plone-btn plone-btn-primary pull-right',
          onClick: that.saveEditClicked }, 'Save'));
        // buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-default pull-right',
        //                         onClick: that.cancelEditClicked }, 'Cancel'));
      } else {
        buttons.push(D.button({ type: 'button', className: 'plone-btn plone-btn-default pull-right',
                                onClick: that.hide}, 'Close'));
      }
      return D.div({}, buttons);
    }
  });

  return SlotManagerModalComponent;
});

/* global define */

/* notes on implementation!

  To the user, layout is now *design*
  but all backend related info, layout stays layout in terms of functionality
*/

define('castle-url/components/design-modal',[
  'jquery',
  'mockup-patterns-base',
  'underscore',
  'castle-url/libs/react/react.min',
  'mockup-utils',
  'castle-url/components/modal',
  'castle-url/components/utils'
], function($, Base, _, R, utils, Modal, cutils) {
  'use strict';
  var D = R.DOM;

  var DesignModalComponent = cutils.Class([Modal], {
    getInitialState: function(){
      return {
        loading: true,
        available: [],
        applied: null,
        context: null,
        applied_context: null,
        page_layout: null,
        section_layout: null,
        folder: null,
        dirtyPage: false,
        dirtySection: false
      };
    },
    componentDidMount: function(){
      utils.loading.show();
      var that = this;
      Modal.componentDidMount.apply(this);
      $.ajax({
        url: $('body').attr('data-base-url') + '/@@page-layout-selector'
      }).done(function(data){
        if(!data.available[data.page_layout]){
          data.page_layout = null;
        }
        data.original_page_layout = data.page_layout;
        data.original_applied_context = data.applied_context;
        data.original_applied = data.applied;
        that.setState(data);
      }).fail(function(){
        alert('error loading design data');
      }).always(function(){
        utils.loading.hide();
      });
    },

    renderSelected: function(){
      var selectedName = this.state.available[this.state.applied];
      if(!selectedName){
        selectedName = 'Default';
      }
      var selected = D.span({ className: 'selected-design default'}, 'Default site design');

      if(this.state.applied_context !== '/'){
        if(this.state.applied_context !== this.state.context){
          selected = D.span({ className: 'selected-design'}, [
            '"' + selectedName + '" applied from ',
            D.span({ className: 'selected-design-path'}, this.state.applied_context),
          ]);
        }else{
          selected = D.span({ className: 'selected-design'}, selectedName);
        }
      }
      return D.p({ className: 'selected-design-container'}, [
        D.span({ className: 'selected-design-label'}, 'Selected Design'),
        ': ',
        selected
      ]);
    },

    renderAvailableOptions: function(){
      var that = this;
      var options = [
        D.option({ value: ''}, ' - Use parent setting'),
        D.option({ value: 'index.html'}, 'Default')
      ];
      _.keys(this.state.available).sort().forEach(function(id){
        if(id === 'index.html'){
          return;
        }
        options.push(D.option({ value: id }, that.state.available[id]));
      });
      return options;
    },

    pageChanged: function(e){
      if(!e.target.value && this.state.dirtyPage){
        // revert
        this.setState({
          page_layout: this.state.original_page_layout,
          applied_context: this.state.original_applied_context,
          applied: this.state.original_applied
        });
      }else{
        this.setState({
          page_layout: e.target.value,
          applied_context: this.state.context,
          applied: e.target.value,
          dirtyPage: true
        });
      }
    },

    renderPageSelection: function(){
      return D.div({ className: 'form-group'}, [
        D.label({}, [
          'Page Design',
          D.span({ className: 'formHelp'}, 'Design that will be applied to this page only.')
        ]),
        D.select({ className: 'form-control', value: this.state.page_layout,
                   onChange: this.pageChanged}, this.renderAvailableOptions())
      ]);
    },

    sectionChanged: function(e){
      this.setState({
        section_layout: e.target.value,
        dirtySection: true
      });
    },

    renderSectionSelection: function(){
      return D.div({ className: 'form-group'}, [
        D.label({}, [
          'Section Design',
          D.span({ className: 'formHelp'}, 'Design that will be applied to all pages inside this folder.')
        ]),
        D.select({ className: 'form-control', value: this.state.section_layout,
                   onChange: this.sectionChanged}, this.renderAvailableOptions())
      ]);
    },

    renderContent: function(){
      var that = this;
      return D.div({ className: 'castle-design-container'}, [
        that.renderSelected(),
        that.renderPageSelection(),
        that.renderSectionSelection()
      ]);
    },

    saveClicked: function(e){
      e.preventDefault();
      utils.loading.show();
      var that = this;
      $.ajax({
        url: $('body').attr('data-base-url') + '/@@page-layout-selector',
        type: 'POST',
        data: {
          action: 'save',
          _authenticator: utils.getAuthenticator(),
          data: JSON.stringify(this.state)
        }
      }).done(function(data){
        if(!data.success){
          return alert('Error saving design change');
        }
        if(that.state.dirtyPage){
          window.location.reload();
        }else{
          that.hide();
        }
      }).fail(function(){
        alert('error loading design data');
      }).always(function(){
        utils.loading.hide();
      });
    },

    renderFooter: function(){
      var buttons = [
        D.button({ type: 'button', className: 'plone-btn plone-btn-default',
                   onClick: this.hide}, 'Cancel'),
        D.button({ type: 'button', className: 'plone-btn plone-btn-primary',
                   onClick: this.saveClicked,
                   disabled: !this.state.dirtyPage && !this.state.dirtySection}, 'Save')];
      return D.div({}, buttons);
    },
    getDefaultProps: function(){
      return $.extend({}, true, Modal.getDefaultProps.apply(this), {
        id: 'design-modal',
        title: 'Design'
      });
    }
  });

  return DesignModalComponent;
});

/* global localStorage */

define('castle-url/patterns/toolbar',[
  'jquery',
  'mockup-patterns-base',
  'pat-registry',
  'mockup-utils',
  'castle-url/components/utils',
  'castle-url/libs/react/react.min',
  'mockup-patterns-modal',
  'castle-url/patterns/toolbar/menu-item',
  'castle-url/patterns/toolbar/modal-item',
  'castle-url/components/add-content-modal',
  'castle-url/components/preview-content-modal',
  'castle-url/components/quality-check-modal',
  'castle-url/components/analytics-modal',
  'castle-url/components/workflow-modal',
  'castle-url/components/slot-manager-modal',
  'castle-url/components/design-modal',
  'moment'
], function ($, Base, Registry, utils, cutils, R, ModalPattern, MenuItemBase,
             ModalMenuItemBase, AddContentModal, PreviewContentModal, QualityCheckModal,
             AnalyticsModal, WorkflowModal, SlotManagerModal, DesignModal,
             moment) {
  'use strict';

  var D = R.DOM;
  var included_items = [];

  var MenuItem = R.createClass(MenuItemBase);

  var ViewPageMenuItem = cutils.Class([MenuItemBase], {
    isActive: function(){
      return ($('body').attr('data-base-url') === window.location.href ||
              MenuItemBase.isActive.apply(this));
    }
  });


  var ModalMenuItemFactory = function(Component, id){
    return cutils.Class([ModalMenuItemBase], {
      getDefaultProps: function(){
        return cutils.extend(ModalMenuItemBase.getDefaultProps.apply(this), {
          ModalComponent: Component,
          id: id
        });
      }
    });
  };

  var PatternModalItemBase = cutils.extend(MenuItemBase, {
    componentDidMount: function(){
      var modal = new ModalPattern($(this.refs.a.getDOMNode()), this.props);
      modal.$el.off('after-render');
      modal.on('after-render', function(){
        $('input[name*="cancel"]', modal.$modal).off('click').on('click', function() {
          // Close overlay
          modal.hide();
        });
      });
    }
  });
  var PatternModalItemFactory = function(opts){
    return cutils.Class([PatternModalItemBase], {
      getDefaultProps: function(){
        return opts;
      }
    });
  };

  var AddMenuItem = cutils.Class([ModalMenuItemBase], {
    getSettings: function(){
      return cutils.extend(this.props.parent.props.add, {
        parent: this.props.parent
      });
    },
    getDefaultProps: function(){
      return cutils.extend(ModalMenuItemBase.getDefaultProps.apply(this), {
        ModalComponent: AddContentModal,
        id: 'add-modal-react-container'
      });
    }
  });
  var WorkflowMenuItem = cutils.Class([ModalMenuItemBase], {
    getSettings: function(){
      return {
        parent: this.props.parent,
        workflow: this.props.parent.props.workflow
      };
    },
    getWorkflow: function(){
      return this.props.parent.props.workflow;
    },
    getClassName: function(){
      var className = MenuItemBase.getClassName.apply(this);
      var workflow = this.getWorkflow();
      if(workflow){
        className += ' state-' + workflow.state.id;
      }
      return className;
    },
    getLabel: function(){
      var workflow = this.getWorkflow();
      if(workflow){
        return this.props.item.title + ': ' + workflow.state.title;
      }else{
        return this.props.item.title;
      }
    },
    getDefaultProps: function(){
      return cutils.extend(ModalMenuItemBase.getDefaultProps.apply(this), {
        ModalComponent: WorkflowModal,
        id: 'workflow-modal-react-container'
      });
    }
  });

  var SlotsMenuItem = cutils.Class([ModalMenuItemBase], {
    getSettings: function(){
      return {
        parent: this.props.parent
      };
    },
    getDefaultProps: function(){
      return cutils.extend(ModalMenuItemBase.getDefaultProps.apply(this), {
        ModalComponent: SlotManagerModal,
        id: 'slot-manager-modal-react-container'
      });
    }
  });

  var DesignMenuItem = cutils.Class([ModalMenuItemBase], {
    getSettings: function(){
      return {
        parent: this.props.parent
      };
    },
    getDefaultProps: function(){
      return cutils.extend(ModalMenuItemBase.getDefaultProps.apply(this), {
        ModalComponent: DesignModal,
        id: 'design-modal-react-container'
      });
    }
  });


  var MenuItemRenderer = {
    getDefaultProps: function(){
      return {
        showIcon: true,
        modal: false,
        itemMapping: {
        }
      };
    },
    addAdditionalMenuItems: function(items) {
      // Include menu items from external add-ons and
      // incorporate them into the toolbar
      var itemMapping = this.state.itemMapping;
      var menu_items = Object.keys(items);
      menu_items.forEach(function(key) {
        itemMapping[key] = items[key];
      });

      this.setState({
        'itemMapping': itemMapping
      });

    },
    renderMenuItem: function(item){
      if(item === 'spacer'){
        return D.li({ className: 'spacer'});
      }

      var Component = MenuItem;
      if(this.state.itemMapping !== undefined && this.state.itemMapping[item.id]){
        Component = this.state.itemMapping[item.id];
      }else if(item.modal){
        Component = PatternModalItemFactory(item.modalAttributes);
      }
      return R.createElement(Component, {
        parent: this,
        item: item,
        showIcon: this.props.showIcon
      });
    }
  };


  var Dropdown = cutils.Class([MenuItemRenderer], {
    itemMapping: {
      impersonate: PatternModalItemFactory({
        actionOptions: {disableAjaxFormSubmit: true, redirectOnResponse:true}}),
    },
    getInitialState: function(){
      return {
        open: false
      };
    },
    getDefaultProps: function(){
      return {
        name: '',
        items: [],
        title: '',
        icon: '',
        onClick: function(){},
        showIcon: false
      };
    },
    btnClicked: function(e){
      e.preventDefault();
      this.props.onClick(this);
      this.setState({
        open: !this.state.open
      });
    },
    render: function(){
      var that = this;
      var className = 'castle-btn-dropdown castle-btn-dropdown-' + this.props.name;
      var content = [D.button({ className: 'icon-' + this.props.icon + ' plone-btn plone-btn-default',
                                onClick: this.btnClicked}, [D.span({}, this.props.title)] )];
      if(this.state.open){
        className += 'opened';
        content.push(D.ul({}, that.props.items.map(function(item){
          return that.renderMenuItem(item);
        })));
      }
      return D.div({ className: className}, content);
    }
  });

  var ChatDropdown = cutils.Class([Dropdown], {
    getInitialState: function() {

      if( this.props.chat_info === null ) {
        return {};
      }

      this.checkMissedMessages();

      return {
        token: this.props.chat_info.token,
        open: false,
        missed: false
      };
    },
    checkMissedMessages: function() {

      var frontpage = this.props.chat_info.frontpage;
      if( frontpage === undefined || frontpage === null ) {
        return;
      }

      if( frontpage.lastIndexOf('/') !== frontpage.length - 1 ) {
        frontpage += '/';
      }

      var url = frontpage + 'api/messageWaiting';

      var data = {
        token: this.props.chat_info.token,
        user: {
          email: this.props.chat_info.email,
          name: this.props.username
        }
      };

      $.ajax({
        url: url,
        data: data,
        method: 'POST'
      }).done(function(res) {
        this.setState({
          missed: res
        });
      }.bind(this));
    },
    renderChannels: function() {

      var that = this;
      var missed = this.state.missed;
      var rooms = Object.keys(this.state.missed);

      var output = [];

      for( var room in rooms ) {
        room = rooms[room];
        var messageClass = '';

        output.push(D.li({
          className: 'castle-chat-missed-channel'
        }, [
          D.div({className: 'castle-chat-channel-header' }, [
            room,
            D.span({className: 'castle-chat-missed'}, missed[room].length.toString()),
          ]),
          D.ul({}, that.renderMessages(missed[room]))
        ]));
      }

      return output;
    },
    renderMessages: function(messages) {
      var output = [];
      var count = 0;
      var previousAuthor = '';

      for( var message in messages ) {
        count += 1;

        //Put a cap on the # of missed messages
        if( count == 10 ) {
          output.push(
          D.div({className: 'castle-chat-divider-link'},
            D.a({
              className: 'castle-chat-missed-message',
              href: this.props.chat_info.frontpage + 'plone/' + this.state.token,
              target: '_blank'
            }, 'View more'))
          );
          return output;
        }

        message = messages[message];
        var author = [];

        //Don't keep repeating the username if they're
        //sending multiple messages.
        if( previousAuthor !== message.u.username ) {
          author = D.div({className: 'castle-chat-username'}, message.u.username + ': ');
        }

        previousAuthor = message.u.username;

        output.push(
          D.li(
            {
              className: 'castle-chat-missed-message'
            }, [
              author,
              message.msg])
        );
      }

      return output;
    },
    render: function() {

      if( this.props.chat_info === null ) {
        return null;
      }

      if( window.location.href.indexOf('/chat') >= 0 ) {
        return null;
      }

      if( this.props.chat_info.frontpage === null || this.props.chat_info.chat_url === null ) {
        return null;
      }

      var classList = 'plone-btn plone-btn-default chat-link';
      var rooms = '';

      if( this.state.missed ) {
        classList += ' chat-alert';
      }

      var content = [
        D.button({
          className: classList,
          onClick: this.btnClicked
        }, 'Chat')
      ];

      if( this.state.open ) {
        var dropdownContent = [];
        var message = 'No new messages';
        var broken = false;

        if( this.props.chat_info.email === "" ) {
          broken = true;
          message = 'A valid email must be associated with your profile before using chat';
        }

        if( this.state.missed ) {
          var roomNames = Object.keys(this.state.missed);
          var missed = this.state.missed;

          var roomMessages = this.renderChannels();

          dropdownContent.push(
            D.ul({className: 'castle-chat-preview'}, roomMessages)
          );
        }else{
          dropdownContent.push(D.div({className: 'castle-chat-empty'}, message));
        }
        var href = this.props.chat_info.frontpage + 'plone/' + this.state.token;
        href += '/' + this.props.username + '/' + this.props.chat_info.email;

        if( !broken ) {
          dropdownContent.push(
            D.div({className: 'castle-chat-goto-link'},
              D.a({
                href: href,
                disabled: broken,
                target: '_blank',
                className: 'castle-chat-bottom-link'
              }, 'Open chat')
            )
          );
        }

        content.push(D.div({className: 'castle-chat-dropdown'}, dropdownContent));
      }

      return D.div({
        className: 'castle-btn-dropdown',
        id: 'castle-chat-menu-item'
      }, content);
    }
  });

  var MessagesDropdown = cutils.Class([Dropdown], {
    // use local storage to track read messages
    // a read message is one that is shown
    infoIcon: D.svg({ id: "557c1826-141b-488e-8cbf-023297e947fc", 'data-name': "Layer 1",
                      xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20"}, [
      D.defs({}, D.style({}, '.\\37 41286a0-08da-4764-b1d8-fc4a2fdaf01d{fill:#5bc0de;}')),
      D.path({ className: "741286a0-08da-4764-b1d8-fc4a2fdaf01d",
               d: "M10,.1A9.9,9.9,0,1,0,19.9,10,9.9,9.9,0,0,0,10,.1ZM9.8,15.5h.5a6,6,0,0,0,1.1-1.3l.3.2q-1.5,2.6-3.2,2.6a1.4,1.4,0,0,1-1-.4,1.2,1.2,0,0,1-.4-.9,3.4,3.4,0,0,1,.2-.9l1.4-4.7a4,4,0,0,0,.2-1,.5.5,0,0,0-.2-.4l-.5-.2H7.9V8.1l3.3-.5h.6l-2,7a3.9,3.9,0,0,0-.2.8Zm2.5-10a1.4,1.4,0,0,1-2.5-1,1.4,1.4,0,0,1,.4-1,1.4,1.4,0,0,1,2,0,1.4,1.4,0,0,1,.4,1A1.4,1.4,0,0,1,12.4,5.5Z"
             })
    ]),
    warningIcon: D.svg({ id: "43116b3f-bcf4-4eff-a6a9-4ce4def2b718", 'data-name': "Layer 1",
                      xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20"}, [
      D.defs({}, D.style({}, '.\\32 928bb63-e350-4856-b63e-f748b9d2849c{fill:#efac4c;}')),
      D.path({ className: "2928bb63-e350-4856-b63e-f748b9d2849c",
               d: "M10,1.1.1,18.2H19.9ZM9,5.7a1.4,1.4,0,0,1,2,0,1.3,1.3,0,0,1,.4,1A12.2,12.2,0,0,1,10.9,9l-.4,1.8a14.8,14.8,0,0,0-.3,2.2H9.8a13.4,13.4,0,0,0-.4-2.2L9,9a11.3,11.3,0,0,1-.4-2.3A1.4,1.4,0,0,1,9,5.7Zm1.9,10.7a1.3,1.3,0,0,1-2.3-.9,1.3,1.3,0,0,1,.4-.9,1.3,1.3,0,0,1,1.9,0,1.3,1.3,0,0,1,0,1.9Z"
             })
    ]),
    errorIcon: D.svg({ id: "28e26966-46bc-480e-ae10-740701234303", 'data-name': "Layer 1",
                      xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20"}, [
      D.defs({}, D.style({}, '.\\35 80fe009-4c8c-460f-b362-42cfa88ea0f5{fill:#d85450;}')),
      D.path({ className: "580fe009-4c8c-460f-b362-42cfa88ea0f5",
               d: "M14.1.1H5.9L.1,5.9v8.2l5.8,5.8h8.2l5.8-5.8V5.9ZM11.2,16.6a1.6,1.6,0,0,1-2.8-1.1,1.6,1.6,0,0,1,.5-1.2,1.6,1.6,0,0,1,2.3,0,1.6,1.6,0,0,1,0,2.3Zm0-9.2-.5,2.2a18.2,18.2,0,0,0-.4,2.8H9.8a16.5,16.5,0,0,0-.5-2.8L8.8,7.4a13.9,13.9,0,0,1-.5-2.8,1.7,1.7,0,0,1,.5-1.2A1.6,1.6,0,0,1,10,2.9a1.6,1.6,0,0,1,1.7,1.7A15,15,0,0,1,11.2,7.4Z"
             })
    ]),

    maxMessages: 50,

    getInitialState: function(){
      return {
        open: false,
        messages: this.props.items,
        unread: [],
        showUnread: false
      };
    },

    getDataKey: function(){
      return $('body').attr('data-portal-url') + this.props.user_id + 'readmessages';
    },

    getStoredData: function(){
      var key = this.getDataKey();
      var data = localStorage.getItem(key);
      if(!data){
        data = {
          messages: [],
          timestamps: []
        };
      }else{
        data = JSON.parse(data);
      }
      return data;
    },

    componentDidMount: function(){
      // load local storage data
      // set info on unread messages
      // show fade open unread if possible
      var that = this;
      var data = this.getStoredData();
      var unread = [];
      this.props.items.forEach(function(item){
        var timestamp = item.timestamp + '';
        if(data.timestamps.indexOf(timestamp) === -1){
          data.timestamps.push(timestamp);
          data.messages.unshift(item);
          unread.push(timestamp);
        }
      });

      // finally, trim messages
      var removed = data.messages.splice(this.maxMessages, data.messages.length + 1);
      removed.forEach(function(item){
        var timestamp = item.timestamp + '';
        var idx = data.timestamps.indexOf(timestamp);
        if(idx === -1){
          data.timestamps.splice(idx, 1);
        }
      });

      if(unread.length > 0){
        this.setState({
          showUnread: true,
          unread: unread,
          open: true,
          messages: data.messages
        }, function(){
          // fade out and close after some time
          setTimeout(function(){
            if(!that.refs.menuItems){
              return;
            }
            $(that.refs.menuItems.getDOMNode()).fadeOut(function(){
              that.setState({
                open: false,
                showUnread: false
              });
            });
          }, 3000);
        });
      }else{
        this.setState({
          messages: data.messages
        });
      }
      localStorage.setItem(this.getDataKey(), JSON.stringify(data));
    },

    getIcon: function(item){
      if(item.type === 'info'){
        return this.infoIcon;
      }
      if(item.type === 'warning'){
        return this.warningIcon;
      }
      if(item.type === 'error'){
        return this.errorIcon;
      }
    },

    btnClicked: function(e){
      e.preventDefault();
      this.props.onClick(this);
      this.setState({
        open: !this.state.open,
        showUnread: false
      });
    },

    renderMenuItem: function(item){
      var loc = '';
      if(item.context){
        loc = D.div({ className: 'location' }, [
          D.span({}, 'Location: '),
          D.span({ className: 'link' },
            D.a({ href: $('body').attr('data-portal-url') + item.context }, item.context || '/'))
        ]);
      }
      return D.li({ className: 'castle-status-message-item ' + item.type}, [
        D.div({ className: 'row'}, [
          D.div({ className: 'col-md-1 svg-container'}, this.getIcon(item)),
          D.div({ className: 'col-md-11'}, [
            D.div({ className: 'date' }, moment(new Date(item.timestamp * 1000)).fromNow()),
            D.div({ className: 'text' }, item.text),
            loc
          ])
        ])
      ]);
    },

    render: function(){
      var that = this;
      var className = 'castle-btn-dropdown castle-btn-dropdown-' + this.props.name;
      var unread = '';
      if(that.state.unread.length > 0){
        unread = D.span({ className: 'castle-toolbar-unread-message-count'}, that.state.unread.length);
      }
      var content = [D.button({ className: ' plone-btn plone-btn-default',
                                onClick: this.btnClicked}, [
          unread,
          'Notifications'
        ])];
      if(this.state.open){
        className += 'opened';
        var messages = [];
        that.state.messages.forEach(function(item){
          if(!that.state.showUnread || that.state.unread.indexOf(item.timestamp + '') !== -1){
            messages.push(item);
          }
        });
        content.push(D.ul({ ref: 'menuItems'}, messages.map(function(item){
          return that.renderMenuItem(item);
        })));
      }
      return D.div({ className: className}, content);
    }
  });

  var TopToolbar = R.createClass({
    renderBreadcrumbs: function(){
      var that = this;
      return D.ol({ className: 'castle-toolbar-breadcrumbs'}, [
        D.li({ className: 'castle-toolbar-crumb castle-toolbar-crumb-home'}, D.a({ href: $('body').attr('data-portal-url')}, 'Home'))
      ].concat(that.props.breadcrumbs.map(function(crumb){
        var className = 'castle-toolbar-crumb castle-toolbar-crumb-' + crumb.Title.toLowerCase().split(' ').join('-');
        if(crumb.state){
          className += ' crumb-state-' + crumb.state;
        }
        return D.li({ className: className}, D.a({ href: crumb.absolute_url }, crumb.Title));
      })));
    },
    btnClicked: function(btn){
      // close if open
      if(this.refs.cog && 'cog' !== btn.props.icon && this.refs.cog.state.open){
        this.refs.cog.setState({
          open: false
        });
      }
      if(this.refs.chat && 'chat' !== btn.props.name && this.refs.chat.state.open){
        this.refs.chat.setState({
          open: false
        });
      }
      if(this.refs.user && 'user' !== btn.props.name && this.refs.user.state.open){
        this.refs.user.setState({
          open: false
        });
      }
      if(this.refs.messages && 'messages' !== btn.props.name && this.refs.messages.state.open){
        this.refs.messages.setState({
          open: false
        });
      }
    },
    render: function(){
      var imgSrc = [D.img({ src: $('body').attr('data-portal-url') + '/++plone++castle/images/castle-logo.png', alt:'CastleCMS'})];
      return D.div({className: 'castle-toolbar-container-top'}, [
         D.a({ href:$('body').attr('data-portal-url'), className: 'castle-toolbar-logo'}, imgSrc),
        this.renderBreadcrumbs(),
        D.div({ className: 'castle-toolbar-buttons', onClick: function(e){
            e.stopPropagation();
          }}, [
          R.createElement(ChatDropdown, {
            chat_info: this.props.chat_info,
            username: this.props.user.name,
            onClick: this.btnClicked,
            ref: 'chat',
            name: 'chat'
          }),
          R.createElement(MessagesDropdown, { items: this.props.messages,
                                              user_id: this.props.user_id,
                                              ref: 'messages', onClick: this.btnClicked, name: 'messages'}),
          R.createElement(Dropdown, {icon: 'cog', items: this.props.management_menu,
                                     ref: 'cog', onClick: this.btnClicked, name: 'cog', title: 'Site Settings'}),
          R.createElement(Dropdown, {icon: 'user', title: this.props.user.name, ref: 'user',
                                     items: this.props.user_menu, onClick: this.btnClicked,
                                     name: 'user'})
        ])
      ]);
    }
  });


  var SideToolbar = cutils.Class([MenuItemRenderer], {
    getInitialState: function() {
      return {
        'hideButtons': true,
        'itemMapping': {
          'view-page': ViewPageMenuItem,
          add: AddMenuItem,
          quality: ModalMenuItemFactory(QualityCheckModal, 'quality-modal-react-container'),
          preview: ModalMenuItemFactory(PreviewContentModal, 'preview-modal-react-container'),
          analytics: ModalMenuItemFactory(AnalyticsModal, 'analytics-modal-react-container'),
          slots: SlotsMenuItem,
          design: DesignMenuItem,
          state: WorkflowMenuItem,
          rename: PatternModalItemFactory({
            actionOptions: {disableAjaxFormSubmit: true, redirectOnResponse:true}}),
          delete: PatternModalItemFactory({
            loadLinksWithinModal: false,
            actionOptions: {disableAjaxFormSubmit: true, redirectOnResponse:true, displayInModal: false}}),
          trash: PatternModalItemFactory({
            actionOptions: {disableAjaxFormSubmit: true, redirectOnResponse:true}}),
          invalidate: PatternModalItemFactory({}),
          aliases: PatternModalItemFactory({}),
          syndication: PatternModalItemFactory({
            actionOptions: {disableAjaxFormSubmit: true, redirectOnResponse:true}}),
          convert_template: PatternModalItemFactory({
            actionOptions: {disableAjaxFormSubmit: true, redirectOnResponse:true}})
        }
      };
    },
    getMore: function(items) {
      var visible = 'none';

      if( !this.state.hideButtons ) {
        visible = 'inherit';
      }

      if( items.length === 0 ) {
        // below rendered a empty span tag when it wasn't in the more ul
        return null;
      }

      return D.li({
        ref: 'moreMenu',
        className: 'castle-toolbar-item'
      }, [
        D.a({
          href: '#',
          onClick: function(e) {
            e.preventDefault();
            this.setState({
              hideButtons: !this.state.hideButtons
            });
          }.bind(this)
        }, [ D.span({className: 'icon-add'}), D.span({}, 'More')]),
        D.ul({
          className: 'castle-toolbar-btn-container',
          style: {
            'display': visible
          }
        }, items)
      ]);
    },
    render: function(){
      var that = this;
      var hidden = [];
      var count = that.props.main_menu.length;

      var numHidden = that.props.hidden || 0;

      var buttons = that.props.main_menu.map(function(item){
        count -= 1;
        if( count < numHidden ) {

          hidden.push( that.renderMenuItem(item) );
          return;
        }
        return that.renderMenuItem(item);
      });
      buttons.push(this.getMore(hidden));
      return D.div({ className: 'castle-toolbar-container-side'}, D.ul({}, buttons));
    }
  });

  var Toolbar = R.createClass({
    getInitialState: function() {
      return {
        'hiddenButtons': 0
      };
    },
    render: function(){
      return D.div({ className: 'castle-toolbar-container'}, [
        R.createElement(TopToolbar, cutils.extend(this.props, { ref: 'top'})),
        R.createElement(SideToolbar, cutils.extend(this.props,
          {
            ref: 'side',
            hidden: this.state.hiddenButtons
          }
        ))
      ]);
    },
    calculateHidden: function() {
      var sideMenu = this.refs.side;
      var buttons = {};

      try {
        buttons = $(sideMenu.getDOMNode()).find('li');
      } catch(e){
        return;
      }

      var toolbarHeight = 0;

      // Need to account for the top menu bar
      var windowHeight = $(window).height() - $(this.refs.top.getDOMNode()).height();

      // If there are already hidden buttons, their height appears as 0
      // so we need to account for their real height.
      var buttonHeight = $(buttons[0]).height() - 2;

      var hidden = 0;

      $(buttons).each(function() {
          var addheight = $(this).height();

          if( addheight === 0 && !$(this).hasClass('spacer') ) {
            addheight = buttonHeight;
          }

          toolbarHeight += addheight;

          if( toolbarHeight > windowHeight ) {
            hidden += 1;

            if( addheight > 0 && (toolbarHeight - addheight) < windowHeight ) {
              // This catches the case where the bottom edge is
              // part way through a button. We don't want the More
              // button to be partially cut off
              hidden += 1;
            }
          }
      });
      this.setState({
        'hiddenButtons': hidden
      });
    },
    loadAddonButtons: function () {
      // Include additional buttons from JS files registered by
      // add-ons
      //
      // currently this only works for the side toolbar.
      // The top toolbar is a lot more difficult to make extensible
      var buttons = this.props.addon_buttons;
      var paths = [];

      if(buttons.side_toolbar !== undefined) {
        paths = paths.concat(buttons.side_toolbar);
      }

      // if(buttons.top_toolbar !== undefined) {
      //   paths = paths.concat(buttons.top_toolbar);
      // }

      require(paths, function() {
        var buttons = {
          'top': {},
          'side': {}
        };

        var button_interface = ['name', 'menu', 'renderer'];

        // We have no idea how many add-ons we're getting,
        // so we can't define them ahead of time. So, for loop:
        for(var i = 0; i<arguments.length; i++) {
          var item = arguments[i];

          // check that the argument object meets our interface
          var props = Object.keys(item);
          if( button_interface.every(function(key) { return props.indexOf(key) >= 0; }) ) {
            var menu = this.refs[item.menu];
            var itemMapping = buttons[item.menu];
            itemMapping[item.name] = item.renderer;
          }else{
            continue;
          }
        }

        // this.refs.top.addAdditionalMenuItems(buttons.top);
        this.refs.side.addAdditionalMenuItems(buttons.side);

      }.bind(this)).bind(this);
    },
    componentDidMount: function() {
      this.calculateHidden();
      this.loadAddonButtons();
      window.addEventListener('resize', this.calculateHidden);
    },
    componentWillUnmount: function() {
      window.removeEventListener('resize', this.calculateHidden);
    }
  });

  var ToolbarPattern = Base.extend({
    name: 'castletoolbar',
    trigger: '.pat-castletoolbar',
    parser: 'mockup',
    defaults: {},
    init: function () {
      var that = this;

      var component = R.render(R.createElement(Toolbar, that.options), that.$el[0], function(){
        if(document.body.className.indexOf('toolbar-initialized') === -1){
          document.body.className += ' toolbar-initialized';
        }
        $('body').trigger('toolbar-initialized', that, component);
      });

      $(window).on('click', function(){
        component.refs.top.refs.cog.setState({
          open: false
        });
        component.refs.top.refs.user.setState({
          open: false
        });
        component.refs.top.refs.messages.setState({
          open: false,
          showUnread: false
        });
        try {
          component.refs.top.refs.chat.setState({
            open: false
          });
        }
        catch(e) {
          // couldn't set state for chat integration DOM element?
          // this is likely caused by a bug somewhere -- seems to happen after the
          // first time its done. perhaps something isn't being updated.
        }
      });

      /* folder contents changes the context.
         This is for usability so the menu changes along with
         the folder contents context */
      $('body').off('structure-url-changed').on('structure-url-changed', function (e, path) {
        /* reload toolbar and slots */
        $.ajax({
          url: $('body').attr('data-portal-url') + path + '/@@castle-toolbar',
          data: {
            'fc-reload': 'yes'
          },
          dataType: 'json'
        }).done(function(data){
          /* update body attributes */
          $('body').attr(
            'data-base-url', data['data-base-url']).attr(
            'data-view-url', data['data-view-url']);

          /* reload toolbar now */
          that.$el.empty();
          R.render(R.createElement(Toolbar, data), that.$el[0]);
        });
      });
    }

  });

  return ToolbarPattern;
});

define('castle-url/patterns/upload-update',[
  'jquery',
  'mockup-patterns-base',
  'castle-url/libs/react/react.min',
  'castle-url/components/add-content-modal',
  'mockup-utils',
], function($, Base, R, AddContentModal, utils) {
  'use strict';

  var UploadPattern = Base.extend({
    name: 'upload-update',
    trigger: '.pat-upload-update',
    parser: 'mockup',
    defaults: {
      uid: null,
      tmp_field_id: null
    },

    bytesToSize: function(bytes) {
      var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      if (bytes == 0) return '0 Byte';
      var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
      return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    },

    updateReplacement: function(name, type, size){
      var $widget = $(this.$el);
      $widget.find('.new-value').remove();
      var $newValue = $('<p class="discreet new-value"/>');
      $widget.append($newValue);
      $newValue.html(name + '(' + type + '): ' + this.bytesToSize(size));
      var $replace = $widget.find('#form-widgets-file-replace');
      if($replace.size() === 0){
        // no file to start with, let's just add hidden input here...
        $replace = $('<input id="form-widgets-file-replace" name="form.widgets.file.action" type="hidden"/>')
        $widget.append($replace);
      }
      $replace.attr('value', JSON.stringify({
        replace: true,
        name: name,
        type: type,
        size: size,
        tmp_field_id: this.options.tmp_field_id
      }));
    },

    init: function () {
      var self = this;
      self.component = null;
      if(!self.options.tmp_field_id){
        self.tmp_field_id = 'tmp_' + utils.generateId();
      }

      var $widget = $(this.$el);

      var $replace = $widget.find('#form-widgets-file-replace');
      var existingValue = $replace.attr('value');
      if(existingValue && existingValue.indexOf('{') !== -1){
        // already had an existing value but error on form, update...
        try{
          var data = JSON.parse(existingValue);
          if(data.replace){
            self.updateReplacement(data.name, data.type, data.size);
            self.options.tmp_field_id = data.tmp_field_id;
          }
        }catch(e){
          // handle json issues
        }
      }
      $widget.find('#form-widgets-file-input').click(function(evt){
        evt.preventDefault();

        var $div = $('<div/>');
        $widget.append($div);

        var data = {
          update: true,
          content: self.options.uid,
          field: self.options.tmp_field_id,
          autoUpload: true,
          onUploadFinished: function(item, component){
            // do something here...
            var file = component.state.files[0];
            self.component.hide();
            $div.remove();
            $('.modal-backdrop').remove();
            $('body').removeClass('modal-open');
            $('#form-widgets-file').css('opacity', '0.2');

            self.updateReplacement(file.name, file.type, file.size);
          }
        };
        self.el = R.createElement(AddContentModal, data);
        self.component = R.render(self.el, $div[0]);
        $('.modal-backdrop').css('z-index', 'auto');
        $('.modal-content').css('margin-top', '100px');
      });
    }
  });

  return UploadPattern

});

/*

  Miscellaneous edit widgets

*/
define('castle-url/patterns/widgets',[
  'jquery',
  'pat-base',
  'castle-url/libs/react/react.min',
], function($, Base, R) {
  "use strict";
  
  var D = R.DOM;

  var UploadFieldsWidgetComponent = R.createClass({
    getDefaultProps: function(){
      return {
        'changeEvent': function(value){}
      };
    },

    getInitialState: function(){
      return {
        value: []
      };
    },

    notifyChange: function(){
      this.setState({
        value: this.state.value
      });
      this.props.changeEvent(this.state.value);
    },

    valueChanged: function(idx, name, widget, evt){
      if(widget == 'checkbox'){
        this.state.value[idx][name] = evt.target.checked;
      }else{
        this.state.value[idx][name] = evt.target.value;
      }
      this.notifyChange();
    },

    renderFieldField: function(name, label, value, fieldIdx){
      // "field" is top level value taht is being described
      var id = 'upload-fields-' + name + '-' + fieldIdx;

      var input;
      if(name === 'widget'){
        input = D.select({
          id: id, value: value,
          onChange: this.valueChanged.bind(this, fieldIdx, name, 'select') }, [
              D.option({ value: 'text' }, 'Text'),
              D.option({ value: 'textarea' }, 'Textarea'),
              D.option({ value: 'tags' }, 'Tags'),
              D.option({ value: 'checkbox' }, 'Checkbox'),
          ]);
      }else if(name === 'required'){
        if(typeof(value) == "string"){
          value = value === 'true';
        }
        input = D.input({
          id: id, type: 'checkbox', checked: value,
          onChange: this.valueChanged.bind(this, fieldIdx, name, 'checkbox') });
      }else{
        input = D.input({
          id: id, value: value,
          onChange: this.valueChanged.bind(this, fieldIdx, name, 'text') });
      }
      return D.li ({
        className: 'field', id: id + '-container'
      }, [
        D.label({ htmlFor: id }, label),
        input,
      ]);
    },

    removeClicked: function(idx, evt){
      evt.preventDefault();
      this.state.value.splice(idx, 1);
      this.notifyChange();
    },

    renderField: function(field, idx){
      return D.div({className: 'file-upload-field-container'}, [
        D.h4({}, field['label']),
        D.ul({ className: 'file-upload-fields'}, [
          this.renderFieldField('name', 'Name', field['name'], idx),
          this.renderFieldField('label', 'Label', field['label'], idx),
          this.renderFieldField('widget', 'Widget', field['widget'], idx),
          this.renderFieldField('required', 'Required', field['required'], idx),
          this.renderFieldField('for-file-types', 'For types', field['for-file-types'], idx)
        ]),
        D.button({ className: 'btn btn-danger btn-xs remove-btn',
                   onClick: this.removeClicked.bind(this, idx) }, 'Remove')
      ]);
    },

    addClicked: function(evt){
      evt.preventDefault();
      this.state.value.push({
        'name': 'fieldname',
        'label': 'Field label',
        'widget': 'text',
        'for-file-types': '*',
        'required': false
      })
      this.notifyChange();
    },

    render: function(){
      var items = [];
      var self = this;
      this.state.value.forEach(function(field, fieldIdx){
        items.push(self.renderField(field, fieldIdx))
      });
      return D.div({className: 'file-upload-fields-container'}, [
        D.div({}, items),
        D.button({ className: 'btn btn-primary btn-xs add-btn',
                   onClick: this.addClicked }, 'Add')
      ]);
    }
  });

  var UploadFieldsWidget = Base.extend({
    name: 'fileuploadfieldswidget',
    trigger: '.pat-fileuploadfieldswidget',
    parser: 'mockup',
    defaults: {
      timeout: 0
    },

    init: function() {
      var self = this;
      self.$el.hide();
      var $div = $('<div/>');
      self.$el.after($div);
      self.component = R.render(R.createElement(
        UploadFieldsWidgetComponent, {
          changeEvent: function(value){
            clearTimeout(self.options.timeout);
            self.options.timeout = setTimeout(function(){
              self.$el[0].setAttribute('value', JSON.stringify(value));
            }, 100);
          }
        }), $div[0]);

      var value = JSON.parse(self.$el.val());
      self.component.setState({
          value: value
      });
    }
  });

  return UploadFieldsWidget;

});

  



function createElement(tag, options){
  var el = document.createElement(tag);
  if(options.className){
    if (el.classList)
      el.classList.add(options.className);
    else
      el.className += ' ' + options.className;
  }
  if(options.text){
    el.textContent = options.text;
  }
  if(options.children){
    for(var i=0; i<options.children.length; i++){
      el.appendChild(options.children[i]);
    }
  }
   return el;
}

require([
  'jquery',
  'mockup-patterns-modal',
], function($, Modal) {
  if(Modal.prototype._init === undefined){
    Modal.prototype._init = Modal.prototype.init;
    Modal.prototype.init = function(){
      this.options.loadLinksWithinModal = false;
      this.options.backdropOptions.closeOnClick = false;
      this.options.backdropOptions.closeOnEsc = false;
      Modal.prototype._init.apply(this, []);
    };
  }

  if($('#formfield-form-widgets-ILayoutAware-content').size() > 0){
    // Show form errors in the interface so user knows if there
    // are required fields missing or errors in fields
    var $errors = $('.portalMessage.error');
    if($errors.size() > 0){
      var container = createElement('div', {
        className: 'castle-editor-errors'
      });
      $('body').append(container);
      $errors.each(function(){
        container.appendChild(this);
      });
      var $errorFields = $('.field.error');
      if($errorFields.size() > 0){
        var ul = document.createElement('ul');
        $errors.find('dd').append(ul);
        $errorFields.each(function(){
          var $this = $(this);
          if($this.find('label').size() > 0 && $this.find('.fieldErrorBox .error').size() > 0){
            var li = createElement('li', {
              children: [
                createElement('span', {
                  className: 'title',
                  text: $this.find('label')[0].textContent.trim()
                }),
                createElement('span', {
                  className: 'details',
                  text: $this.find('.fieldErrorBox .error')[0].textContent
                }),
              ]
            });
            ul.appendChild(li);
          }
        });
      }
    }
  }

  $(document).ready(function() {
    var cookieNegotiation = (
      $("#form-widgets-use_cookie_negotiation > input").value === 'selected');
    if (cookieNegotiation !== true) {
      $("#formfield-form-widgets-authenticated_users_only").hide();
    }else{
      $("#formfield-form-widgets-authenticated_users_only").show();
    }

    $('#form-widgets-upload_to_youtube-0').on('change', function(){
      var ytUrl = document.getElementById('form-widgets-youtube_url');
      if (this.checked) {
        ytUrl.setAttribute('readonly', true);
        ytUrl.value = '';
      } else {
        ytUrl.removeAttribute('readonly');
      }
    });
  });
});

define("castle-url/scripts/patches", function(){});

//
// Script used to ping draft support while a user is editing so it doesn't get cleaned
//

require([
  'jquery',
  'mockup-utils'
], function($, utils){
  'use strict';

  $(document).ready(function() {
    if($('.template-edit').size() > 0){
      // we are currently editing a mosaic form, ping draft support every 5 minutes
      // to make sure it increments draft edit time so it doesn't get cleaned
      // when a user it working on it
      var pingDraft = function(){
        setTimeout(function(){
          $.ajax({
            url: $('body').attr('data-base-url') + '/@@ping-draft',
            method: 'POST',
            data: {
              _authenticator: utils.getAuthenticator()
            }
          }).done(function(){
            pingDraft();
          });
        }, 1000 * 60 * 5);
      };
      pingDraft();
    }
  });
});

define("castle-url/scripts/drafts", function(){});

/* global localStorage */
//
// Script used to refresh user session to make sure if there is user activity,
// they aren't logged out...
//

require([
  'jquery'
], function($){
  'use strict';

  var timeout = 5 * 60 * 1000; // ping every 5 minutes
  var storageKey = 'sessionRefreshLastCheck';

  var store = function(){
    localStorage.setItem(storageKey, (new Date()).getTime());
  };

  var check = function(){
    var lastChecked = localStorage.getItem(storageKey);
    var now = (new Date()).getTime();
    if(lastChecked){
      try{
        lastChecked = parseInt(lastChecked);
        if((now - lastChecked) > timeout){
          return ping();
        }
      }catch(e){
        store();
      }
    }else{
      store();
    }
  };

  var ping = function(){
    setTimeout(function(){
      $.ajax({
        url: $('body').attr('data-portal-url') + '/acl_users/session/refresh'
      }).done(function(){
        store();
        check();
      });
    }, 5000);
  };

  var _checkTimeout = -1;
  $('body').bind('mouseover click keydown', function(){
    clearTimeout(_checkTimeout);
    _checkTimeout = setTimeout(check, 400);
  });

});

define("castle-url/scripts/session", function(){});

// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

if (window.jQuery) {
  define( 'jquery', [], function () {
    'use strict';
    return window.jQuery;
  } );
}

require([
  'jquery',
  'mockup-patterns-inlinevalidation',
  'mockup-patterns-modal',
  'mockup-patterns-querystring',
  'mockup-patterns-recurrence',
  'mockup-patterns-relateditems',
  'mockup-patterns-textareamimetypeselector',
  'mockup-patterns-tinymce',
  'castle-url/patterns/castledynamicform',
  'castle-url/patterns/edittile',
  'castle-url/patterns/focalpointselect',
  'castle-url/patterns/imagewidget',
  'castle-url/patterns/mapselect',
  'castle-url/patterns/previewselect',
  'castle-url/patterns/structure',
  'castle-url/patterns/toolbar',
  'castle-url/patterns/upload-update',
  'castle-url/patterns/widgets',

  // scripts
  'castle-url/scripts/patches',
  'castle-url/scripts/drafts',
  'castle-url/scripts/session'
], function($) {
  'use strict';

  if($(window).width() > 1040){
    $(document).ready(function(){
      if($('body').attr('data-show-tour')){
        require(['castle-url/components/tour'], function(){});
      }
    });
  }
});

define("/Users/joel/src/github.com/castlecms/castle.cms/castle/cms/static/plone-logged-in.js", function(){});

