lady_josephine 0.6.2 → 0.6.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 7ea18300abde267e1c3b52400365a5891e9ad2cd
4
- data.tar.gz: 5b734125f7ce546a5b096391e66c615f6b40ddaf
3
+ metadata.gz: c9dfbffd2cf6d1ccb08a877fbf91ac26c69313c9
4
+ data.tar.gz: 3ac7be8cf7a39d88119c7ed0a0a773ba0768e508
5
5
  SHA512:
6
- metadata.gz: 4bc38490008bbabe186ab90c8f3dc2d2beb3f68628aac44150f5346c4bfe36c0f27dee16fcfced73bbc967a7ad3604e0f8ea458a1e51ada33c581f8d8f56fbd3
7
- data.tar.gz: 16a034100e9bad0c067875d4935f5ccf35c5df6a5d51551b3871a919885214e1f0621196570ada9be64b2b425fff76aba10846894e91f9068230550961706674
6
+ metadata.gz: 34b269f263c06bb69b1d9dfcf4323bc261281842a9059685f40290ab8db46e17234dd75b4fa4690aebb457f50b0cf8713e9322c63a30a2aea11ff514109e8b00
7
+ data.tar.gz: a1854f89709b7c6baae89aa50cee84f5b0becf4900bba16c5a3a1022730c81551343483add4a1c1b8394634021d5256cf05e27de57a9a9129f5f8c4d064a703f
@@ -1,3 +1,3 @@
1
1
  module LadyJosephine
2
- VERSION = "0.6.2"
2
+ VERSION = "0.6.3"
3
3
  end
@@ -4,7 +4,7 @@
4
4
  * Released under the MIT license
5
5
  * www.opensource.org/licenses/MIT
6
6
  *
7
- * 2016-02-09
7
+ * 2016-03-24
8
8
  */
9
9
 
10
10
  (function ($, _){
@@ -51,8 +51,7 @@
51
51
  errorsContainer: undefined,
52
52
  toMarkdown: {
53
53
  aggresiveHTMLStrip: false
54
- },
55
- escapeHTML: false
54
+ }
56
55
  };
57
56
 
58
57
  SirTrevor.BlockMixins = {};
@@ -1119,12 +1118,6 @@
1119
1118
  var html = markdown,
1120
1119
  shouldWrap = type === "Text";
1121
1120
 
1122
- var options = SirTrevor.getInstance().options;
1123
-
1124
- if (options && options.escapeHTML) {
1125
- html = $("<div>").text(html).html().replace(/\&gt\;/g,">");
1126
- }
1127
-
1128
1121
  if(_.isUndefined(shouldWrap)) { shouldWrap = false; }
1129
1122
 
1130
1123
  if (shouldWrap) {
@@ -3120,11 +3113,6 @@
3120
3113
  this.$('.js-term-input').val(data.term);
3121
3114
  },
3122
3115
 
3123
- onContentPasted: function(event, target){
3124
- target.html(this.pastedMarkdownToHTML(target[0].innerHTML));
3125
- this.getTextBlock().caretToEnd();
3126
- }
3127
-
3128
3116
  });
3129
3117
 
3130
3118
  })();
@@ -4,10 +4,10 @@
4
4
  * Released under the MIT license
5
5
  * www.opensource.org/licenses/MIT
6
6
  *
7
- * 2016-02-09
7
+ * 2016-03-24
8
8
  */
9
9
 
10
- !function($,_){function $element(el){return el instanceof $?el:$(el)}var SirTrevor,root=this;SirTrevor=root.SirTrevor={},SirTrevor.DEBUG=!1,SirTrevor.SKIP_VALIDATION=!1,SirTrevor.version="0.3.0",SirTrevor.LANGUAGE="de",SirTrevor.DEFAULTS={defaultType:!1,spinner:{className:"st-spinner",lines:9,length:8,width:3,radius:6,color:"#000",speed:1.4,trail:57,shadow:!1,left:"50%",top:"50%"},blockLimit:0,blockTypeLimits:{},required:[],uploadUrl:"/attachments",baseImageUrl:"/sir-trevor-uploads/",errorsContainer:void 0,toMarkdown:{aggresiveHTMLStrip:!1},escapeHTML:!1},SirTrevor.BlockMixins={},SirTrevor.Blocks={},SirTrevor.Formatters={},SirTrevor.instances=[],SirTrevor.Events=Eventable;var formBound=!1,FunctionBind={bound:[],_bindFunctions:function(){this.bound.length>0&&_.bindAll.apply(null,_.union([this],this.bound))}},Renderable={tagName:"div",className:"sir-trevor__view",attributes:{},$:function(selector){return this.$el.find(selector)},render:function(){return this},destroy:function(){_.isUndefined(this.stopListening)||this.stopListening(),this.$el.remove()},_ensureElement:function(){if(this.el)this._setElement(this.el);else{var html,attrs=_.extend({},_.result(this,"attributes"));this.id&&(attrs.id=this.id),this.className&&(attrs["class"]=this.className),attrs.html&&(html=attrs.html,delete attrs.html);var $el=$("<"+this.tagName+">").attr(attrs);html&&$el.html(html),this._setElement($el)}},_setElement:function(element){return this.$el=$element(element),this.el=this.$el[0],this}};!function($){function dragEnter(e){e.preventDefault()}function dragOver(e){e.originalEvent.dataTransfer.dropEffect="copy",$(e.currentTarget).addClass("st-drag-over"),e.preventDefault()}function dragLeave(e){$(e.currentTarget).removeClass("st-drag-over"),e.preventDefault()}function setCaret(collapseToStart){return function(){var range,selection;return range=document.createRange(),range.selectNodeContents(this[0]),range.collapse(collapseToStart),selection=window.getSelection(),selection.removeAllRanges(),selection.addRange(range),this}}$.fn.dropArea=function(){return this.bind("dragenter",dragEnter).bind("dragover",dragOver).bind("dragleave",dragLeave),this},$.fn.noDropArea=function(){return this.unbind("dragenter").unbind("dragover").unbind("dragleave"),this},$.fn.caretToEnd=setCaret(!1),$.fn.caretToStart=setCaret(!0)}(jQuery);var extend=function(protoProps,staticProps){var child,parent=this;child=protoProps&&_.has(protoProps,"constructor")?protoProps.constructor:function(){return parent.apply(this,arguments)},_.extend(child,parent,staticProps);var Surrogate=function(){this.constructor=child};return Surrogate.prototype=parent.prototype,child.prototype=new Surrogate,protoProps&&_.extend(child.prototype,protoProps),child.__super__=parent.prototype,child};SirTrevor.log=function(message){!_.isUndefined(console)&&SirTrevor.DEBUG&&console.log(message)},SirTrevor.generateUUID=function(){return"aaaaaaaa-aaaa-4aaa-baaa-aaaaaaaaaaaa".replace(/[ab]/g,function(c){var random=16*Math.random()%16|0;return"b"===c&&(random=7&random|8),random.toString(16)})},SirTrevor.Locales={en:{general:{add:"Add Content",deleteElement:"Delete Element","delete":"Delete?",drop:"Drag __block__ here",paste:"Or paste URL here",upload:"…or choose a file",close:"close",position:"Change position",wait:"Please wait…",link:"Enter a link",note:"Note",style:"Style",source:"Source"},errors:{title:"You have the following errors:",validation_fail:"__type__ block is invalid",block_empty:"__name__ must not be empty",type_missing:"You must have a block of type __type__",required_type_empty:"A required block type __type__ is empty",load_fail:"There was a problem loading the contents of the document"},autosave:{longExplanation:"This article was loaded from your browsers cache. It was changed locally and not saved on the server. You can keep the changes by saving or discard them.",discard:"Discard changes"},blocks:{text:{title:"Text"},list:{title:"List"},quote:{title:"Cite",credit_field:"Credit"},extended_quote:{title:"Extended Cite",credit_field:"Credit"},extended_image:{title:"Image",caption_field:"Caption",caption_placeholder:"Caption",target_url_field:"Link target URL",target_url_placeholder:"Link target URL",copyright_field:"Copyright",copyright_placeholder:"Copyright",upload_error:"There was a problem with your upload",fullwidth:"Page width",bodywidth:"Article width","default":"Small"},image:{title:"Image",upload_error:"There was a problem with your upload"},definition:{title:"Glossary",term:"Term",description:"Description"},divider:{title:"Divider"},reward_list:{title:"Reward List"},audio:{title:"Audio"},infographic:{title:"Infographic"},video:{title:"Video"},facebookpost:{title:"Facebook Post"},tweet:{title:"Tweet",fetch_error:"There was a problem fetching your tweet"},embedly:{title:"Embedly",fetch_error:"There was a problem fetching your embed",key_missing:"An Embedly API key must be present"},heading:{title:"Heading"},remote_list:{fetch_error:"There was a problem fetching the list!",maximumselected:"You can not select any more items!"},html:{title:"Html"},instagram:{title:"Instagram"}}},de:{general:{add:"Absatz hinzufügen",deleteElement:"Absatz löschen","delete":"Löschen?",drop:"__block__ hierher bewegen",paste:"Oder URL hier einfügen",upload:"…oder Datei auswählen",close:"Schließen",position:"Absatz verschieben",wait:"Bitte warten…",link:"Link eingeben",note:"Anmerkung",style:"Darstellung",source:"Quelle"},errors:{title:"Folgende Fehler sind aufgetreten:",validation_fail:"__type__ Block ist nicht gültig",block_empty:"__name__ darf nicht leer sein",type_missing:"Es wird ein Block vom Typ __type__ benötigt",required_type_empty:"Ein benötigter Block vom Typ __type__ ist leer",load_fail:"Es gab ein Problem beim Laden der Daten für dieses Dokument"},autosave:{longExplanation:"Dieser Artikel wurde aus dem Zwischenspeicher dieses Browsers geladen. Er wurde zuvor geändert und nicht auf dem Server gesichert. Du kannst die Änderungen beibehalten indem du speicherst oder die Änderungen verwerfen.",discard:"Verwerfen"},blocks:{text:{title:"Lauftext"},list:{title:"Liste"},quote:{title:"Zitat",credit_field:"Quelle"},extended_quote:{title:"Erweitertes Zitat",credit_field:"Quelle"},extended_image:{title:"Bild",caption_field:"Bildunterzeile",caption_placeholder:"Bildunterzeile",target_url_field:"URL für das Linkziel",target_url_placeholder:"URL für das Linkziel",copyright_field:"Fotograf",copyright_placeholder:"Fotograf",upload_error:"es gab ein problem beim hochladen",fullwidth:"Seitenbreite",bodywidth:"Artikelbreite","default":"Kleine"},image:{title:"Bild",upload_error:"es gab ein problem beim hochladen"},definition:{title:"Glossar",term:"Begriff",description:"Beschreibung"},divider:{title:"Trenner"},reward_list:{title:"Prämienliste"},audio:{title:"Audio"},infographic:{title:"Infografik"},video:{title:"Video"},facebookpost:{title:"Facebook Post"},tweet:{title:"Tweet",fetch_error:"There was a problem fetching your tweet"},embedly:{title:"Embedly",fetch_error:"There was a problem fetching your embed",key_missing:"An Embedly API key must be present"},heading:{title:"Überschrift"},remote_list:{fetch_error:"Liste konnte nicht geladen werden!",maximumselected:"Du kannst nicht mehr Elemente auswählen!"},html:{title:"Html"},instagram:{title:"Instagram"}}}},void 0===window.i18n||void 0===window.i18n.init?(SirTrevor.log("Using i18n stub"),window.i18n={t:function(key,options){var str,obj,part,i,parts=key.split(":");for(obj="undefined"!=typeof SirTrevorUserLanguage?SirTrevor.Locales[SirTrevorUserLanguage]||SirTrevor.Locales[SirTrevor.LANGUAGE]:SirTrevor.Locales[SirTrevor.LANGUAGE],i=0;i<parts.length;i++)part=parts[i],_.isUndefined(obj[part])||(obj=obj[part]);return str=obj,_.isString(str)?(str.indexOf("__")>=0&&_.each(options,function(value,opt){str=str.replace("__"+opt+"__",value)}),str):""}}):(SirTrevor.log("Using i18next"),i18n.init({resStore:SirTrevor.Locales,fallbackLng:SirTrevor.LANGUAGE,ns:{namespaces:["general","blocks"],defaultNs:"general"}})),function(a,b,c){function g(a,c){var e,d=b.createElement(a||"div");for(e in c)d[e]=c[e];return d}function h(a){for(var b=1,c=arguments.length;c>b;b++)a.appendChild(arguments[b]);return a}function j(a,b,c,d){var g=["opacity",b,~~(100*a),c,d].join("-"),h=.01+c/d*100,j=Math.max(1-(1-a)/b*(100-h),a),k=f.substring(0,f.indexOf("Animation")).toLowerCase(),l=k&&"-"+k+"-"||"";return e[g]||(i.insertRule("@"+l+"keyframes "+g+"{0%{opacity:"+j+"}"+h+"%{opacity:"+a+"}"+(h+.01)+"%{opacity:1}"+(h+b)%100+"%{opacity:"+a+"}100%{opacity:"+j+"}}",0),e[g]=1),g}function k(a,b){var f,g,e=a.style;if(e[b]!==c)return b;for(b=b.charAt(0).toUpperCase()+b.slice(1),g=0;g<d.length;g++)if(f=d[g]+b,e[f]!==c)return f}function l(a,b){for(var c in b)a.style[k(a,c)||c]=b[c];return a}function m(a){for(var b=1;b<arguments.length;b++){var d=arguments[b];for(var e in d)a[e]===c&&(a[e]=d[e])}return a}function n(a){for(var b={x:a.offsetLeft,y:a.offsetTop};a=a.offsetParent;)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}var f,d=["webkit","Moz","ms","O"],e={},i=function(){var a=g("style");return h(b.getElementsByTagName("head")[0],a),a.sheet||a.styleSheet}(),o={lines:12,length:7,width:5,radius:10,rotate:0,color:"#000",speed:1,trail:100,opacity:.25,fps:20,zIndex:2e9,className:"spinner",top:"auto",left:"auto"},p=function q(a){return this.spin?void(this.opts=m(a||{},q.defaults,o)):new q(a)};p.defaults={},m(p.prototype,{spin:function(a){this.stop();var h,i,b=this,c=b.opts,d=b.el=l(g(0,{className:c.className}),{position:"relative",zIndex:c.zIndex}),e=c.radius+c.length+c.width;if(a&&(a.insertBefore(d,a.firstChild||null),i=n(a),h=n(d),l(d,{left:("auto"==c.left?i.x-h.x+(a.offsetWidth>>1):c.left+e)+"px",top:("auto"==c.top?i.y-h.y+(a.offsetHeight>>1):c.top+e)+"px"})),d.setAttribute("aria-role","progressbar"),b.lines(d,b.opts),!f){var j=0,k=c.fps,m=k/c.speed,o=(1-c.opacity)/(m*c.trail/100),p=m/c.lines;!function q(){j++;for(var a=c.lines;a;a--){var e=Math.max(1-(j+a*p)%m*o,c.opacity);b.opacity(d,c.lines-a,e,c)}b.timeout=b.el&&setTimeout(q,~~(1e3/k))}()}return b},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=c),this},lines:function(a,b){function e(a,d){return l(g(),{position:"absolute",width:b.length+b.width+"px",height:b.width+"px",background:a,boxShadow:d,transformOrigin:"left",transform:"rotate("+~~(360/b.lines*c+b.rotate)+"deg) translate("+b.radius+"px,0)",borderRadius:(b.width>>1)+"px"})}for(var d,c=0;c<b.lines;c++)d=l(g(),{position:"absolute",top:1+~(b.width/2)+"px",transform:b.hwaccel?"translate3d(0,0,0)":"",opacity:b.opacity,animation:f&&j(b.opacity,b.trail,c,b.lines)+" "+1/b.speed+"s linear infinite"}),b.shadow&&h(d,l(e("#000","0 0 4px #000"),{top:"2px"})),h(a,h(d,e(b.color,"0 0 1px rgba(0,0,0,.1)")));return a},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}}),!function(){function a(a,b){return g("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',b)}var b=l(g("group"),{behavior:"url(#default#VML)"});!k(b,"transform")&&b.adj?(i.addRule(".spin-vml","behavior:url(#default#VML)"),p.prototype.lines=function(b,c){function f(){return l(a("group",{coordsize:e+" "+e,coordorigin:-d+" "+-d}),{width:e,height:e})}function k(b,e,g){h(i,h(l(f(),{rotation:360/c.lines*b+"deg",left:~~e}),h(l(a("roundrect",{arcsize:1}),{width:d,height:c.width,left:c.radius,top:-c.width>>1,filter:g}),a("fill",{color:c.color,opacity:c.opacity}),a("stroke",{opacity:0}))))}var j,d=c.length+c.width,e=2*d,g=2*-(c.width+c.length)+"px",i=l(f(),{position:"absolute",top:g,left:g});if(c.shadow)for(j=1;j<=c.lines;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;j<=c.lines;j++)k(j);return h(b,i)},p.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}):f=k(b,"animation")}(),a.Spinner=p}(window,document),SirTrevor.editorStore=function(editor,method,options){var resp;options=options||{},Version=function(version){var results;try{results=/(\d+)\.(\d+)/.exec(version),this.version=results[0],this.major=results[1],this.minor=results[2]}catch(e){results=/(\d+)/.exec(version),this.version=results[0],this.major=results[1],this.minor="0",this.recreateVersion()}return this},Version.prototype={minorVersion:function(){return parseInt(this.minor,10)},incrementMinorVersion:function(){return this.minor=(this.minorVersion()+1).toString(),this.recreateVersion()},majorVersion:function(){return parseInt(this.major,10)},incrementMajorVersion:function(){return this.major=(this.majorVersion()+1).toString(),this.minor="0",this.recreateVersion()},recreateVersion:function(){return this.version=this.major+"."+this.minor,this},gt:function(version){return this.majorVersion()>version.majorVersion()?!0:this.majorVersion()===version.majorVersion()&&this.minorVersion()>version.minorVersion()?!0:!1},toString:function(){return this.version}};var newVersion,reset=function(){var oldDataStore=editor.dataStore;editor.dataStore={data:[]},void 0!==oldDataStore&&(editor.dataStore.version=oldDataStore.version,editor.dataStore.uuid=oldDataStore.uuid,editor.dataStore.server_version=oldDataStore.server_version,editor.dataStore.server_uuid=oldDataStore.server_uuid),ensureMetadata()},ensureMetadata=function(){ensureUUID(),ensureVersion(),ensureModelName()},ensureModelName=function(){void 0===editor.dataStore.modelName&&(editor.dataStore.modelName=editor.options.modelName)},ensureUUID=function(){void 0===editor.dataStore.uuid&&(editor.dataStore.uuid=SirTrevor.generateUUID())},ensureVersion=function(){void 0===editor.dataStore.version&&(editor.dataStore.version="0.0")},isNewArticle=function(){var content=_.trim(editor.$el.val());return""===content||void 0===JSON.parse(content).server_uuid},getLatestUnsavedFromUUIDs=function(uuids){var name=editor.options.modelName,urlPrefix=editor.options.baseURL;return _.find(uuids,function(uuid){var result=$.ajax({type:"GET",url:urlPrefix+uuid+"/version",async:!1});return!(result.responseJSON&&result.responseJSON[name]&&result.responseJSON[name].server_version)})},parseKeyData=function(key){try{return JSON.parse(localStorage.getItem(key))}catch(e){return{}}},getAllKeys=function(prefix){return prefix=prefix||"st-",_.filter(Object.keys(localStorage),function(key){var modelName=parseKeyData(key).modelName||editor.options.modelName;return 0===key.lastIndexOf(prefix)&&modelName===editor.options.modelName})},getKeysWithoutServerUUID=function(){return _.filter(getAllKeys(),function(key){return void 0===parseKeyData(key).server_uuid}).map(getUUIDFromKey)},newestDocumentForUUID=function(uuid){if(editor.options.localStorage!==!0)return{};var i,prefix="st-"+uuid,versions=getAllKeys(prefix).map(function(e){return new Version(/version-(\d+(?:\.\d+)?)/.exec(e)[1])}),result=versions[0];for(i=0;i<versions.length;i++)versions[i].gt(result)&&(result=versions[i]);return void 0===result?null:{version:result.toString(),dataStore:localStorage[prefix+"-version-"+result.toString()]}},getUUIDFromKey=function(key){return/st-(.*)-version-(\d+(?:\.\d+)?)/.exec(key)[1]},getAllUUIDs=function(){return _.uniq(getAllKeys().map(getUUIDFromKey))},removeAllForUUID=function(uuid){for(var key,document,stop=!1;!stop&&(document=newestDocumentForUUID(uuid),null!==document);)key="st-"+uuid+"-version-"+document.version,stop=!localStorage.hasOwnProperty(key),localStorage.removeItem(key)},removeOldAutosaves=function(){var uuids=getAllUUIDs(),keysToKeep=uuids.map(function(uuid){return"st-"+uuid+"-version-"+newestDocumentForUUID(uuid).version});_.each(getAllKeys(),function(key){-1===$.inArray(key,keysToKeep)&&localStorage.removeItem(key)})},askUserForConfirmation=function(){return!0},promptRestoration=function(){var warn=$('<div class="st-autoload-info">'+i18n.t("autosave:longExplanation")+"<br></div>"),discard=$('<a href="#" class="st-autoload-discard-button">'+i18n.t("autosave:discard")+"</a>"),close=$('<a href="#" class="st-autoload-close-button"><span class="icon--close" aria-hidden="true"></span><span class="visuallyhidden>close</span></a>');warn.append(discard),warn.append(close),close.on("click",function(e){return e.preventDefault(),warn.remove(),!1}),discard.on("click",function(e){return e.preventDefault(),editor.store("restore"),warn.remove(),!1}),editor.$outer.prepend(warn)};switch(method){case"autosave":newVersion=new Version(editor.dataStore.version).incrementMinorVersion().toString(),editor.dataStore.version=newVersion;var store=editor.dataStore,value=store.data.length>0?JSON.stringify(editor.dataStore):"",key="st-"+store.uuid+"-version-"+store.version;window.localStorage.setItem(key,value),removeOldAutosaves();break;case"restore":removeAllForUUID(editor.dataStore.uuid),editor.reinitialize();break;case"create":var document,str,uuids,unsaved,parsedStore,documentVersion,dataStoreVersion,content=_.trim(editor.$el.val());reset();try{str=JSON.parse(content),_.isUndefined(str.data)||(editor.dataStore=str,ensureMetadata())}catch(e){}if(isNewArticle())uuids=getKeysWithoutServerUUID(),unsaved=getLatestUnsavedFromUUIDs(uuids),void 0!==unsaved&&(document=newestDocumentForUUID(unsaved),null!==document&&(parsedStore=JSON.parse(document.dataStore),documentVersion=new Version(parsedStore.version),dataStoreVersion=new Version(editor.dataStore.version),documentVersion.gt(dataStoreVersion)&&askUserForConfirmation()&&(editor.dataStore=JSON.parse(document.dataStore),promptRestoration())));else try{document=newestDocumentForUUID(editor.dataStore.uuid),null!==document&&(parsedStore=JSON.parse(document.dataStore),documentVersion=new Version(parsedStore.version),dataStoreVersion=new Version(editor.dataStore.version),documentVersion.gt(dataStoreVersion)&&askUserForConfirmation()&&-1===document.dataStore.indexOf(JSON.stringify(editor.dataStore.data))&&(editor.dataStore=JSON.parse(document.dataStore),promptRestoration()))}catch(e){editor.errors.push({text:i18n.t("errors:load_fail")}),editor.renderErrors(),SirTrevor.log("Sorry there has been a problem with parsing the JSON"),SirTrevor.log(e)}break;case"reset":reset();break;case"add":options.data&&(editor.dataStore.data.push(options.data),resp=editor.dataStore);break;case"save":editor.dataStore.version=new Version(editor.dataStore.version).incrementMajorVersion().toString(),editor.$el.val(editor.dataStore.data.length>0?JSON.stringify(editor.dataStore):"");break;case"read":resp=editor.dataStore}return resp?resp:void 0},SirTrevor.Submittable=function($form){this.$form=$form,this.intialize()},_.extend(SirTrevor.Submittable.prototype,{intialize:function(){this.$submitBtn=this.$form.find("input[type='submit']");var btnTitles=[];_.each(this.$submitBtn,function(btn){btnTitles.push($(btn).attr("value"))}),this.submitBtnTitles=btnTitles,this.canSubmit=!0,this.globalUploadCount=0,this._bindEvents()},setSubmitButton:function(e,message){this.$submitBtn.attr("value",message)},resetSubmitButton:function(){_.each(this.$submitBtn,function(item,index){$(item).attr("value",this.submitBtnTitles[index])},this)},onUploadStart:function(e){this.globalUploadCount++,SirTrevor.log("onUploadStart called "+this.globalUploadCount),1===this.globalUploadCount&&this._disableSubmitButton()},onUploadStop:function(e){this.globalUploadCount=this.globalUploadCount<=0?0:this.globalUploadCount-1,SirTrevor.log("onUploadStop called "+this.globalUploadCount),0===this.globalUploadCount&&this._enableSubmitButton()},onError:function(e){SirTrevor.log("onError called"),this.canSubmit=!1},_disableSubmitButton:function(message){this.setSubmitButton(null,message||i18n.t("general:wait")),this.$submitBtn.attr("disabled","disabled").addClass("disabled")},_enableSubmitButton:function(){this.resetSubmitButton(),this.$submitBtn.removeAttr("disabled").removeClass("disabled")},_events:{disableSubmitButton:"_disableSubmitButton",enableSubmitButton:"_enableSubmitButton",setSubmitButton:"setSubmitButton",resetSubmitButton:"resetSubmitButton",onError:"onError",onUploadStart:"onUploadStart",onUploadStop:"onUploadStop"},_bindEvents:function(){_.forEach(this._events,function(callback,type){SirTrevor.EventBus.on(type,this[callback],this)},this)}}),SirTrevor.fileUploader=function(block,file,success,error){var uid=[block.blockID,(new Date).getTime(),"raw"].join("-"),data=new FormData,blockData=block.getData(),instance=SirTrevor.getInstance(block.instanceID);data.append("attachment[name]",file.name),data.append("attachment[file]",file),data.append("attachment[uid]",uid),void 0!==blockData&&data.append("block-uuid",blockData.uuid),void 0!==instance.dataStore&&data.append("article-uuid",instance.dataStore.uuid),void 0!==instance.options&&(data.append("model-name",instance.options.modelName),data.append("column-name",instance.options.columnName)),block.resetMessages();var callbackSuccess=function(){SirTrevor.log("Upload callback called"),!_.isUndefined(success)&&_.isFunction(success)&&success.apply(block,arguments)},callbackError=function(){SirTrevor.log("Upload callback error called"),!_.isUndefined(error)&&_.isFunction(error)&&error.apply(block,arguments)},xhr=$.ajax({url:SirTrevor.DEFAULTS.uploadUrl,data:data,cache:!1,contentType:!1,processData:!1,dataType:"json",type:"POST"});return block.addQueuedItem(uid,xhr),xhr.done(callbackSuccess).fail(callbackError).always(_.bind(block.removeQueuedItem,block,uid)),xhr};var url_regex=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;_.mixin({isURI:function(string){return url_regex.test(string)},titleize:function(str){return null===str?"":(str=String(str).toLowerCase(),str.replace(/(?:^|\s|-)\S/g,function(c){return c.toUpperCase()}))},classify:function(str){return _.titleize(String(str).replace(/[\W_]/g," ")).replace(/\s/g,"")},classifyList:function(a){return _.map(a,function(i){return _.classify(i)})},capitalize:function(string){return string.charAt(0).toUpperCase()+string.substring(1).toLowerCase()},underscored:function(str){return _.trim(str).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},trim:function(string){return string.replace(/^\s\s*/,"").replace(/\s\s*$/,"")},reverse:function(str){return str.split("").reverse().join("")},flattern:function(obj){var x={};return _.each(obj,function(a,b){x[_.isArray(obj)?a:b]=!0}),x},to_slug:function(str){return str.toLowerCase().replace(/[^\w ]+/g,"").replace(/ +/g,"-")}}),SirTrevor.toHTML=function(markdown,type){type=_.classify(type);var html=markdown,shouldWrap="Text"===type,options=SirTrevor.getInstance().options;options&&options.escapeHTML&&(html=$("<div>").text(html).html().replace(/\&gt\;/g,">")),_.isUndefined(shouldWrap)&&(shouldWrap=!1),shouldWrap&&(html="<div>"+html),html=html.replace(/\[([^\]]+)\]\(([^\)]+)\)/gm,function(match,p1,p2){return"<a href='"+p2+"'>"+p1.replace(/\r?\n/g,"")+"</a>"}),html=_.reverse(_.reverse(html).replace(/_(?!\\)((_\\|[^_])*)_(?=$|[^\\])/gm,function(match,p1){return">i/<"+p1.replace(/\r?\n/g,"").replace(/[\s]+$/,"")+">i<"}).replace(/\*\*(?!\\)((\*\*\\|[^\*\*])*)\*\*(?=$|[^\\])/gm,function(match,p1){return">b/<"+p1.replace(/\r?\n/g,"").replace(/[\s]+$/,"")+">b<"})),html=html.replace(/^\> (.+)$/gm,"$1");var formatName,format;for(formatName in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(formatName)&&(format=SirTrevor.Formatters[formatName],!_.isUndefined(format.toHTML)&&_.isFunction(format.toHTML)&&(html=format.toHTML(html)));var block;return SirTrevor.Blocks.hasOwnProperty(type)&&(block=SirTrevor.Blocks[type],!_.isUndefined(block.prototype.toHTML)&&_.isFunction(block.prototype.toHTML)&&(html=block.prototype.toHTML(html))),shouldWrap&&(html=html.replace(/\r?\n\r?\n/gm,"</div><div><br></div><div>"),html=html.replace(/\r?\n/gm,"</div><div>")),html=html.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;").replace(/\r?\n/g,"<br>").replace(/\*\*/,"").replace(/__/,""),html=html.replace(/\\\*/g,"*").replace(/\\\[/g,"[").replace(/\\\]/g,"]").replace(/\\\_/g,"_").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\-/g,"-"),shouldWrap&&(html+="</div>"),html},SirTrevor.toMarkdown=function(content,type){function replaceBolds(match,p1,p2,p3){return _.isUndefined(p3)&&(p3=""),p1+"**"+p2.replace(/<(.)?br(.)?>/g,"")+"**"+p3}function replaceItalics(match,p1,p2,p3){return _.isUndefined(p3)&&(p3=""),p1+"_"+p2.replace(/<(.)?br(.)?>/g,"")+"_"+p3}function replaceHyperlinks(match,p1,p2,p3,p4){return p2+"["+p3.trim().replace(/<(.)?br(.)?>/g,"")+"]("+p1+")"+p4}type=_.classify(type);var markdown=content;markdown=markdown.replace(/&nbsp;/g," "),markdown=markdown.replace(/( class=(")?Mso[a-zA-Z]+(")?)/g,"").replace(/<!--(.*?)-->/g,"").replace(/\/\*(.*?)\*\//g,"").replace(/<(\/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>/gi,"");var tagStripper,i,badTags=["style","script","applet","embed","noframes","noscript"];for(i=0;i<badTags.length;i++)tagStripper=new RegExp("<"+badTags[i]+".*?"+badTags[i]+"(.*?)>","gi"),markdown=markdown.replace(tagStripper,"");markdown=markdown.replace(/\*/g,"\\*").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/\_/g,"\\_").replace(/\(/g,"\\(").replace(/\)/g,"\\)").replace(/\-/g,"\\-");var inlineTags=["em","i","strong","b"];for(i=0;i<inlineTags.length;i++)tagStripper=new RegExp("<"+inlineTags[i]+"><br></"+inlineTags[i]+">","gi"),markdown=markdown.replace(tagStripper,"<br>");markdown=markdown.replace(/<(\w+)(?:\s+\w+="[^"]+(?:"\$[^"]+"[^"]+)?")*>\s*<\/\1>/gim,"").replace(/\n/gm," ").replace(/<a.*?href=[""'](.*?)[""'].*?>(\s*)(.*?)(\s*)<\/a>/gim,replaceHyperlinks).replace(/<strong>(\s*)(.*?)(\s)*?<\/strong>/gim,replaceBolds).replace(/<b>(\s*)(.*?)(\s*)?<\/b>/gim,replaceBolds).replace(/<em>(\s*)(.*?)(\s*)?<\/em>/gim,replaceItalics).replace(/<i>(\s*)(.*?)(\s*)?<\/i>/gim,replaceItalics);var formatName,format;for(formatName in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(formatName)&&(format=SirTrevor.Formatters[formatName],!_.isUndefined(format.toMarkdown)&&_.isFunction(format.toMarkdown)&&(markdown=format.toMarkdown(markdown)));markdown=markdown.replace(/([^<>]+)(<div>)/g,"$1\n$2").replace(/<div><div>/g,"\n<div>").replace(/(?:<div>)([^<>]+)(?:<div>)/g,"$1\n").replace(/(?:<div>)(?:<br>)?([^<>]+)(?:<br>)?(?:<\/div>)/g,"$1\n").replace(/<\/p>/g,"\n\n").replace(/<(.)?br(.)?>/g,"\n").replace(/&lt;/g,"<").replace(/&gt;/g,">");var block;return SirTrevor.Blocks.hasOwnProperty(type)&&(block=SirTrevor.Blocks[type],!_.isUndefined(block.prototype.toMarkdown)&&_.isFunction(block.prototype.toMarkdown)&&(markdown=block.prototype.toMarkdown(markdown))),markdown=SirTrevor.DEFAULTS.toMarkdown.aggresiveHTMLStrip?markdown.replace(/<\/?[^>]+(>|$)/g,""):markdown.replace(/<(?=\S)\/?[^>]+(>|$)/gi,"")},SirTrevor.EventBus=_.extend({},SirTrevor.Events),SirTrevor.BlockMixins.Ajaxable={mixinName:"Ajaxable",ajaxable:!0,initializeAjaxable:function(){this._queued=[]},addQueuedItem:function(name,deferred){SirTrevor.log("Adding queued item for "+this.blockID+" called "+name),SirTrevor.EventBus.trigger("onUploadStart",this.blockID),this._queued.push({name:name,deferred:deferred})},removeQueuedItem:function(name){SirTrevor.log("Removing queued item for "+this.blockID+" called "+name),SirTrevor.EventBus.trigger("onUploadStop",this.blockID),this._queued=_.reject(this._queued,function(queued){return queued.name==name})},hasItemsInQueue:function(){return this._queued.length>0},resolveAllInQueue:function(){_.each(this._queued,function(item){SirTrevor.log("Aborting queued request: "+item.name),item.deferred.abort()},this)}},SirTrevor.BlockMixins.Controllable={mixinName:"Controllable",initializeControllable:function(){SirTrevor.log("Adding controllable to block "+this.blockID),this.$control_ui=$("<div>",{"class":"st-block__control-ui"}),_.each(this.controls,function(handler,cmd){this.addUiControl(cmd,_.bind(handler,this))},this),this.$inner.append(this.$control_ui)},getControlTemplate:function(cmd){return $("<a>",{"data-icon":cmd,"class":"st-icon st-block-control-ui-btn st-block-control-ui-btn--"+cmd})},addUiControl:function(cmd,handler){this.$control_ui.append(this.getControlTemplate(cmd)),this.$control_ui.on("click",".st-block-control-ui-btn--"+cmd,handler)}},SirTrevor.BlockMixins.Droppable={mixinName:"Droppable",valid_drop_file_types:["File","Files","text/plain","text/uri-list"],initializeDroppable:function(){SirTrevor.log("Adding droppable to block "+this.blockID),this.drop_options=_.extend({},SirTrevor.DEFAULTS.Block.drop_options,this.drop_options);var drop_html=$(_.template(this.drop_options.html,{block:this}));this.$editor.hide(),this.$inputs.append(drop_html),this.$dropzone=drop_html,this.$dropzone.dropArea().bind("drop",_.bind(this._handleDrop,this)),this.$inner.addClass("st-block__inner--droppable")},_handleDrop:function(e){e.preventDefault(),e=e.originalEvent;var el=$(e.target),types=e.dataTransfer.types;el.removeClass("st-dropzone--dragover"),!_.isUndefined(types)&&_.some(types,function(type){return _.include(this.valid_drop_file_types,type)},this)&&this.onDrop(e.dataTransfer),SirTrevor.EventBus.trigger("block:content:dropped",this.blockID)}},SirTrevor.BlockMixins.Fetchable={mixinName:"Fetchable",initializeFetchable:function(){this.withMixin(SirTrevor.BlockMixins.Ajaxable)},fetch:function(options,success,failure){var uid=_.uniqueId(this.blockID+"_fetch"),xhr=$.ajax(options);return this.resetMessages(),this.addQueuedItem(uid,xhr),_.isUndefined(success)||xhr.done(_.bind(success,this)),_.isUndefined(failure)||xhr.fail(_.bind(failure,this)),xhr.always(_.bind(this.removeQueuedItem,this,uid)),xhr}},SirTrevor.BlockMixins.Pastable={mixinName:"Pastable",initializePastable:function(){SirTrevor.log("Adding pastable to block "+this.blockID),this.paste_options=_.extend({},SirTrevor.DEFAULTS.Block.paste_options,this.paste_options),this.$inputs.append(_.template(this.paste_options.html,this)),this.$(".st-paste-block").bind("click",function(){$(this).select()}).bind("paste",this._handleContentPaste).bind("submit",this._handleContentPaste)}},SirTrevor.BlockMixins.Uploadable={mixinName:"Uploadable",uploadsCount:0,initializeUploadable:function(){SirTrevor.log("Adding uploadable to block "+this.blockID),this.withMixin(SirTrevor.BlockMixins.Ajaxable),this.upload_options=_.extend({},SirTrevor.DEFAULTS.Block.upload_options,this.upload_options),this.$inputs.append(_.template(this.upload_options.html,this))},uploader:function(file,success,failure){return SirTrevor.fileUploader(this,file,success,failure)}},SirTrevor.BlockNotes=function(){var BlockNotes=function(block_element,instance_id,block){this.$block=block_element,this.instanceID=instance_id,this.block=block,this.changeable=block.changeable,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockNotes.prototype,FunctionBind,Renderable,{bound:["toggle"],notesClassName:"st-block-is-note",className:"btn--editor-panel",visibleClass:"st-block-notes--is-visible",attributes:{html:'<span class="icon--note" aria-hidden="true"></span><span class="btn__label">'+i18n.t("general:note")+"</span>"},OFF_STATE:"no",ON_STATE:"yes",toggle:function(){var val=this.hiddenInput.val();return this.$block.toggleClass(this.notesClassName),this.hiddenInput.val(val===this.ON_STATE?this.OFF_STATE:this.ON_STATE)},instrumentBlock:function(){var data=this.block.getData();this.hiddenInput=$("<input class='st-input-string js-note-input' name='note' type='hidden' value='"+this.OFF_STATE+"'></input>"),this.block.$el.append(this.hiddenInput),data.note===this.ON_STATE&&this.toggle()},initialize:function(){this.instrumentBlock(),this.$el.on("click",this,this.toggle)}}),BlockNotes}(),SirTrevor.BlockReorder=function(){var BlockReorder=function(block_element,instance_id){this.$block=block_element,this.blockID=this.$block.attr("id"),this.instanceID=instance_id,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockReorder.prototype,FunctionBind,Renderable,{bound:["onMouseDown","onClick","onDragStart","onDragEnd","onDrag","onDrop"],className:"btn--editor-panel btn--with-rocker",tagName:"div",attributes:function(){return{html:'<span class="btn--rocker"><button type="button" class="btn--rocker__up"><span class="icon--dropup"></span></button><button type="button" class="btn--rocker__down"><span class="icon--dropdown"></span></button></span><span class="btn__label">'+i18n.t("general:position")+"</span>",
11
- draggable:"true"}},initialize:function(){this.$el.bind("mousedown touchstart",this.onMouseDown).bind("click",this.onClick).bind("dragstart",this.onDragStart).bind("dragend touchend",this.onDragEnd).bind("drag touchmove",this.onDrag),this.$block.dropArea().bind("drop",this.onDrop)},onMouseDown:function(){SirTrevor.EventBus.trigger("block:reorder:down",this.blockID)},onDrop:function(ev){ev.preventDefault();var dropped_on=this.$block,item_id=ev.originalEvent.dataTransfer.getData("text/plain"),block=$("#"+item_id);_.isUndefined(item_id)||_.isEmpty(block)||dropped_on.attr("id")==item_id||dropped_on.attr("data-instance")!=block.attr("data-instance")||dropped_on.after(block),SirTrevor.EventBus.trigger("block:reorder:dropped",item_id)},onDragStart:function(ev){var btn=$(ev.currentTarget).parent(),self=this,scrollTop=$("body").scrollTop(),position=this.$block.position();ev.originalEvent.dataTransfer.setDragImage(this.$block[0],btn.position().left,btn.position().top),ev.originalEvent.dataTransfer.setData("Text",this.blockID),window.setTimeout(function(){SirTrevor.EventBus.trigger("block:reorder:dragstart",self.blockID),self.$block.addClass("st-block--dragging"),$("body").scrollTop(scrollTop-position.top+self.$block.position().top)},0)},onDragEnd:function(ev){var scrollTop=$("body").scrollTop(),position=this.$block.position();SirTrevor.EventBus.trigger("block:reorder:dragend",this.blockID),this.$block.removeClass("st-block--dragging"),$("body").scrollTop(scrollTop-position.top+this.$block.position().top)},onDrag:function(ev){},onClick:function(event){var $target,idx;event.preventDefault(),$target=$(event.target).closest("button"),idx=this.$block.index(".st-block"),$target.hasClass("btn--rocker__up")?SirTrevor.EventBus.trigger(this.instanceID+":blocks:change_position",this.$block,idx,"before"):$target.hasClass("btn--rocker__down")&&SirTrevor.EventBus.trigger(this.instanceID+":blocks:change_position",this.$block,idx+2,"before")},render:function(){return this}}),BlockReorder}(),SirTrevor.BlockAdd=function(){var BlockAdd=function(block_element){this.$block=block_element,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockAdd.prototype,FunctionBind,Renderable,SirTrevor.Events,{tagName:"a",className:"btn--editor-panel",attributes:{html:'<span class="icon--plus" aria-hidden="true"></span><span class="btn__label">'+i18n.t("general:add")+"</span>"},bound:["create"],create:function(e){SirTrevor.EventBus.trigger("showBlockControls",this.$block)},initialize:function(){this.$el.on("click",this,this.create)}}),BlockAdd}(),SirTrevor.BlockStyles=function(){var BlockStyles=function(block_element,instance_id,block){return block.styleable?(this.$block=block_element,this.instanceID=instance_id,this.block=block,this._ensureElement(),this._bindFunctions(),void this.initialize()):!1};return _.extend(BlockStyles.prototype,FunctionBind,Renderable,SirTrevor.Events,{tagName:"a",className:"btn--editor-panel",attributes:{html:' <span class="btn__label">'+i18n.t("general:style")+"</span>"},bound:["updateValue","onSelectChange"],create:function(e){SirTrevor.EventBus.trigger("showBlockControls",this.$block)},instrumentBlock:function(){var data=this.block.getData();this.hiddenInput=$("<input class='st-input-string js-style-input' name='style' type='hidden' value=''></input>"),this.block.$el.append(this.hiddenInput),this.$el.find("select").val(data.style),this.updateValue(data.style)},availableStyles:function(){return this.block.styles},updateValue:function(val){this.hiddenInput.val(val),this.updateClass(val)},updateClass:function(val){var styles=this.availableStyles(),$el=this.block.$el,classNames=styles.map(function(e){return e.className});$el.removeClass(classNames.join(" "));try{var targetClassName=styles.filter(function(e){return e.value===val}).pop().className;$el.addClass(targetClassName)}catch(e){console.log("Ignoring a style that seems obsolete in current configuration")}},onSelectChange:function(event){var value=event.target.value;this.updateValue(value)},initialize:function(){for(var styles=this.availableStyles(),select="<select>",i=0;i<styles.length;i++)select+='<option value="'+styles[i].value+'">'+styles[i].name+"</option>";select+="</select>",select=$(select),select.on("change",this.onSelectChange),this.$el.prepend(select),this.instrumentBlock()}}),BlockStyles}(),SirTrevor.BlockDeletion=function(){var BlockDeletion=function(){this._ensureElement(),this._bindFunctions()};return _.extend(BlockDeletion.prototype,FunctionBind,Renderable,{tagName:"a",className:"btn--editor-panel btn--editor-panel--delete",attributes:{html:'<span class="icon--bin" aria-hidden="true"></span><span class="btn__label">'+i18n.t("general:deleteElement")+"</span>"}}),BlockDeletion}();var bestNameFromField=function(field){var msg=field.attr("data-st-name")||field.attr("name");return msg||(msg="Field"),_.capitalize(msg)};SirTrevor.BlockValidations={errors:[],valid:function(){return this.performValidations(),0===this.errors.length},performValidations:function(){this.resetErrors();var required_fields=this.$(".st-required");_.each(required_fields,this.validateField,this),_.each(this.validations,this.runValidator,this),this.$el.toggleClass("st-block--with-errors",this.errors.length>0)},validations:[],validateField:function(field){field=$(field);var content=field.attr("contenteditable")?field.text():field.val();0===content.length&&this.setError(field,i18n.t("errors:block_empty",{name:bestNameFromField(field)}))},runValidator:function(validator){_.isUndefined(this[validator])||this[validator].call(this)},setError:function(field,reason){var $msg=this.addMessage(reason,"st-msg--error");field.addClass("st-error"),this.errors.push({field:field,reason:reason,msg:$msg})},resetErrors:function(){_.each(this.errors,function(error){error.field.removeClass("st-error"),error.msg.remove()}),this.$messages.removeClass("st-block__messages--is-visible"),this.errors=[]}},SirTrevor.BlockStore={blockStorage:{},createStore:function(blockData){this.blockStorage={type:_.underscored(this.type),data:blockData||{}}},save:function(){this.toData()},saveAndReturnData:function(){return this.save(),this.blockStorage},saveAndGetData:function(){var store=this.saveAndReturnData();return store.data||store},getData:function(){return this.blockStorage.data},setData:function(blockData){SirTrevor.log("Setting data for block "+this.blockID),_.extend(this.blockStorage.data,blockData||{})},setAndRetrieveData:function(blockData){return this.setData(blockData),this.getData()},setAndLoadData:function(blockData){this.setData(blockData),this.beforeLoadingData()},toData:function(){},loadData:function(){},beforeLoadingData:function(){SirTrevor.log("loadData for "+this.blockID),SirTrevor.EventBus.trigger("block:loadData",this.blockID),this.loadData(this.getData())},_loadData:function(){SirTrevor.log("_loadData is deprecated and will be removed in the future. Please use beforeLoadingData instead."),this.beforeLoadingData()},checkAndLoadData:function(){_.isEmpty(this.getData())||this.beforeLoadingData()}},SirTrevor.SimpleBlock=function(){var SimpleBlock=function(data,instance_id){this.createStore(data),this.blockID=_.uniqueId("st-block-"),this.instanceID=instance_id,this._ensureElement(),this._bindFunctions(),this.initialize.apply(this,arguments)};return _.extend(SimpleBlock.prototype,FunctionBind,SirTrevor.Events,Renderable,SirTrevor.BlockStore,{focus:function(){},valid:function(){return!0},className:"st-block",block_template:_.template("<div class='st-block__inner'><%= editor_html %></div>"),attributes:function(){return{id:this.blockID,"data-type":this.type,"data-instance":this.instanceID}},title:function(){return _.titleize(this.type.replace(/[\W_]/g," "))},blockCSSClass:function(){return this.blockCSSClass=_.to_slug(this.type),this.blockCSSClass},type:"","class":function(){return _.classify(this.type)},editorHTML:"",initialize:function(){},onBlockRender:function(){},beforeBlockRender:function(){},_setBlockInner:function(){var editor_html=_.result(this,"editorHTML");this.$el.append(this.block_template({editor_html:editor_html})),this.$inner=this.$el.find(".st-block__inner"),this.$inner.bind("click",function(e){e.stopPropagation()})},render:function(){return this.beforeBlockRender(),this._setBlockInner(),this._blockPrepare(),this},_blockPrepare:function(){this._initUI(),this._initMessages(),this.checkAndLoadData(),this._initUUID(),this.$el.addClass("st-item-ready"),this.on("onRender",this.onBlockRender),this.save()},_initUUID:function(){var uuid=this.getData().uuid||SirTrevor.generateUUID();this.$el.append($("<input class='st-input-string js-uuid-input' name='uuid' type='hidden' value='"+uuid+"'></input>"))},_withUIComponent:function(component,className,callback){this.$ui.append(component.render().$el),className&&callback&&this.$ui.on("click",className,callback)},_initUI:function(){var ui_element=$("<div>",{"class":"st-block__ui"});this.$inner.append(ui_element),this.$ui=ui_element,this._initUIComponents()},_initMessages:function(){var msgs_element=$("<div>",{"class":"st-block__messages"});this.$inner.prepend(msgs_element),this.$messages=msgs_element},addMessage:function(msg,additionalClass){var $msg=$("<span>",{html:msg,"class":"st-msg "+additionalClass});return this.$messages.append($msg).addClass("st-block__messages--is-visible"),$msg},resetMessages:function(){this.$messages.html("").removeClass("st-block__messages--is-visible")},_initUIComponents:function(){this._withUIComponent(new SirTrevor.BlockReorder(this.$el))}}),SimpleBlock.fn=SimpleBlock.prototype,SimpleBlock.extend=extend,SimpleBlock}(),SirTrevor.Block=function(){var Block=function(data,instance_id){SirTrevor.SimpleBlock.apply(this,arguments)},delete_template=["<div class='st-block__ui-delete-controls'>","<a class='btn--confirm-delete'><span class='icon--tick' aria-hidden='true'></span><span class='visuallyhidden'>Confirm delete</span></a>","<a class='btn--deny-delete'><span class='icon--cross' aria-hidden='true'></span><span class='visuallyhidden'>Do not delete</span></a>","<label class='st-block__delete-label'>","<%= i18n.t('general:delete') %>","</label>","</div>"].join("\n"),drop_options={html:['<div class="st-block__dropzone">','<span class="st-icon"><%= _.result(block, "icon_name") %></span>','<p><%= i18n.t("general:drop", { block: "<span>" + _.result(block, "title") + "</span>" }) %>',"</p></div>"].join("\n"),re_render_on_reorder:!1},paste_options={html:['<input type="text" placeholder="<%= i18n.t("general:paste") %>"',' class="st-block__paste-input st-paste-block">'].join("")},upload_options={html:['<div class="st-block__upload-container">','<input type="file" type="st-file-upload">','<button class="st-upload-btn"><%= i18n.t("general:upload") %></button>',"</div>"].join("\n")};return SirTrevor.DEFAULTS.Block={drop_options:drop_options,paste_options:paste_options,upload_options:upload_options},_.extend(Block.prototype,SirTrevor.SimpleBlock.fn,SirTrevor.BlockValidations,{bound:["_checkArrowKeysUp","_checkArrowKeysDown","_checkReturn","_checkBackspaceAtStartKeyDown","_checkBackspaceAtStartKeyUp","_handleContentPaste","_onFocus","_onBlur","onDrop","onDeleteClick","clearInsertedStyles","getSelectionForFormatter","onBlockRender"],className:"st-block st-icon--add",attributes:function(){return _.extend(SirTrevor.SimpleBlock.fn.attributes.call(this),{"data-icon-after":"add"})},icon_name:"default",validationFailMsg:function(){return i18n.t("errors:validation_fail",{type:this.title()})},editorHTML:'<div class="st-block__editor"></div>',toolbarEnabled:!0,droppable:!1,pastable:!1,uploadable:!1,fetchable:!1,ajaxable:!1,styleable:!1,drop_options:{},paste_options:{},upload_options:{},formattable:!0,removeEmpty:!1,_previousSelection:"",initialize:function(){},toMarkdown:function(markdown){return markdown},toHTML:function(html){return html},withMixin:function(mixin){if(_.isObject(mixin)){var initializeMethod="initialize"+mixin.mixinName;_.isUndefined(this[initializeMethod])&&(_.extend(this,mixin),this[initializeMethod]())}},render:function(){if(this.beforeBlockRender(),this._setBlockInner(),this.$editor=this.$inner.children().first(),this.droppable||this.pastable||this.uploadable){var input_html=$("<div>",{"class":"st-block__inputs"});this.$inner.append(input_html),this.$inputs=input_html}return this.hasTextBlock&&this._initTextBlocks(),this.droppable&&this.withMixin(SirTrevor.BlockMixins.Droppable),this.pastable&&this.withMixin(SirTrevor.BlockMixins.Pastable),this.uploadable&&this.withMixin(SirTrevor.BlockMixins.Uploadable),this.fetchable&&this.withMixin(SirTrevor.BlockMixins.Fetchable),this.controllable&&this.withMixin(SirTrevor.BlockMixins.Controllable),this.formattable&&this._initFormatting(),this.removeEmpty&&this._registerRemoveListener(),this._blockPrepare(),this},_registerRemoveListener:function(){var removeOnOutsideClick=function(){this.isEmpty()&&!this.spinner&&this.trigger("removeBlock",this.blockID)}.bind(this);$(window).on("click",removeOnOutsideClick),this.listenTo(this,"removeBlock",function(){$(window).off("click",removeOnOutsideClick)})},remove:function(){this.ajaxable&&this.resolveAllInQueue(),this.$el.remove()},loading:function(){_.isUndefined(this.spinner)||this.ready(),this.spinner=new Spinner(SirTrevor.DEFAULTS.spinner),this.spinner.spin(this.$el[0]),this.$el.addClass("st--is-loading")},ready:function(){this.$el.removeClass("st--is-loading"),_.isUndefined(this.spinner)||(this.spinner.stop(),delete this.spinner)},toData:function(){SirTrevor.log("toData for "+this.blockID);var dataObj=(this.$el,{});if(this.hasTextBlock()){var content=this.getTextBlock().html();content.length>0&&(dataObj.text=SirTrevor.toMarkdown(content,this.type))}this.$(":input").not(".st-paste-block").length>0&&this.$(":input").each(function(index,input){input.getAttribute("name")&&(dataObj[input.getAttribute("name")]=input.value)}),_.isEmpty(dataObj)||this.setData(dataObj)},focus:function(){this.getTextBlock().focus()},blur:function(){this.getTextBlock().blur()},onFocus:function(){this.getTextBlock().bind("focus",this._onFocus)},onBlur:function(){this.getTextBlock().bind("blur",this._onBlur)},_onFocus:function(){this.trigger("blockFocus",this.$el)},_onBlur:function(){},onDrop:function(dataTransferObj){},onDeleteClick:function(ev){ev.preventDefault();var onDeleteConfirm=function(e){e.preventDefault(),this.trigger("removeBlock",this.blockID)},onDeleteDeny=function(e){e.preventDefault(),this.$el.removeClass("st-block--delete-active"),$delete_el.remove()};if(this.isEmpty())return void onDeleteConfirm.call(this,new Event("click"));this.$inner.find(".btn--editor-panel--delete").append(_.template(delete_template)),this.$el.addClass("st-block--delete-active");var $delete_el=this.$inner.find(".st-block__ui-delete-controls");this.$inner.on("click",".btn--confirm-delete",_.bind(onDeleteConfirm,this)).on("click",".btn--deny-delete",_.bind(onDeleteDeny,this))},pastedMarkdownToHTML:function(content){return SirTrevor.toHTML(SirTrevor.toMarkdown(content,this.type),this.type)},onContentPasted:function(event,target){target.html(this.pastedMarkdownToHTML(target[0].innerHTML)),this.getTextBlock().caretToEnd(),this.splitAtReturns()},beforeLoadingData:function(){this.loading(),(this.droppable||this.uploadable||this.pastable)&&(this.$editor.show(),this.$inputs.hide()),SirTrevor.SimpleBlock.fn.beforeLoadingData.call(this),this.ready()},_handleContentPaste:function(ev){var target=$(ev.currentTarget);_.delay(_.bind(this.onContentPasted,this,ev,target),0)},_getBlockClass:function(){return"st-block--"+this.className},_initUIComponents:function(){this._withUIComponent(new SirTrevor.BlockReorder(this.$el,this.instanceID));var notes=new SirTrevor.BlockNotes(this.$el,this.instanceID,this);this._withUIComponent(notes,".st-block-ui-btn--type-notes"),this._withUIComponent(new SirTrevor.BlockDeletion,".btn--editor-panel--delete",this.onDeleteClick),this._withUIComponent(new SirTrevor.BlockStyles(this.$el,this.instanceID,this)),this._withUIComponent(new SirTrevor.BlockAdd(this.$el)),this.onFocus(),this.onBlur()},_initFormatting:function(){var formatter;for(var name in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(name)&&(formatter=SirTrevor.Formatters[name],_.isUndefined(formatter.keyCode)||formatter._bindToBlock(this.$el))},_initTextBlocks:function(){this.getTextBlock().bind("paste",this._handleContentPaste).bind("keyup",this._checkReturn).bind("keydown",this._checkArrowKeysDown).bind("keyup",this._checkArrowKeysUp).bind("keydown",this._checkBackspaceAtStartKeyDown).bind("keyup",this._checkBackspaceAtStartKeyUp).bind("keyup",this.getSelectionForFormatter).bind("mouseup",this.getSelectionForFormatter).bind("DOMNodeInserted",this.clearInsertedStyles)},_previousCaretOffset:void 0,_checkArrowKeysDown:function(ev){ev.target;if(void 0!==ev&&-1!==[37,38,39,40].indexOf(ev.keyCode)){if(!window.getSelection().isCollapsed)return;try{var marker=this.insertSplitMarker();this._previousCaretOffset=marker.offset()}finally{this.removeSplitMarker()}}},_checkArrowKeysUp:function(ev){ev.target;if(-1===$.inArray(this.type,["Heading","text","Quote","list"]))return!0;if(void 0!==ev&&-1!==$.inArray(ev.keyCode,[37,38,39,40])){if(!window.getSelection().isCollapsed)return;try{var marker=this.insertSplitMarker(),offset=marker.offset();if(offset.top===this._previousCaretOffset.top){if(38===ev.keyCode)return this.focusPreviousBlock(),!1;if(40===ev.keyCode)return this.focusNextBlock(),!1;if(offset.left===this._previousCaretOffset.left){if(37==ev.keyCode)return this.focusPreviousBlock(),!1;if(39==ev.keyCode)return this.focusNextBlock(),!1}}}finally{this.removeSplitMarker()}}return!0},focusPreviousBlock:function(){var instance=SirTrevor.getInstance(this.instanceID),currentPosition=instance.getBlockPosition(this.$el);if(1>currentPosition)return void console.log("Can't focus previous block: no previous block.");var previousBlock=instance.blocks.filter(function(block){return instance.getBlockPosition(block.$el)===currentPosition-1})[0];return void 0===previousBlock?void console.log("Can't merge with previous block: can't find by position"):-1===$.inArray(previousBlock.type,["Heading","text","Quote","list"])?void console.log("Can't focus previous block: not a text block. ("+previousBlock.type+")"):(previousBlock.focus(),void previousBlock.$editor.caretToEnd())},focusNextBlock:function(){var instance=SirTrevor.getInstance(this.instanceID),currentPosition=instance.getBlockPosition(this.$el);if(currentPosition>=instance.blocks.length)return void console.log("Can't focus next block: no next block.");var nextBlock=instance.blocks.filter(function(block){return instance.getBlockPosition(block.$el)===currentPosition+1})[0];return void 0===nextBlock?void console.log("Can't merge with next block: can't find by position"):-1===$.inArray(nextBlock.type,["Heading","text","Quote","list"])?void console.log("Can't focus next block: not a text block. ("+nextBlock.type+")"):(nextBlock.focus(),void nextBlock.$editor.caretToStart())},_checkReturn:function(ev){var target=ev.target;void 0===ev||ev.altKey||13!==ev.keyCode||_.defer(this.onReturn.bind(this,ev,target),0)},_previousContent:null,_checkBackspaceAtStartKeyUp:function(ev){var currentContent,target=ev.target;void 0!==ev&&8===ev.keyCode&&(currentContent=this.$editor[0].innerHTML,currentContent===this._previousContent&&_.defer(this.onBackspaceAtStart.bind(this,ev,target),0))},_checkBackspaceAtStartKeyDown:function(ev){void 0!==ev&&8===ev.keyCode&&(this._previousContent=this.$editor[0].innerHTML)},onBackspaceAtStart:function(event,target){if(-1!==$.inArray(this.type,["Heading","text"])){var instance=SirTrevor.getInstance(this.instanceID),currentPosition=instance.getBlockPosition(this.$el);if(1>currentPosition)return void console.log("Can't merge with previous block: no previous block.");var previousBlock=instance.blocks.filter(function(block){return instance.getBlockPosition(block.$el)===currentPosition-1})[0];if(void 0===previousBlock)return void console.log("Can't merge with previous block: can't find by position");if(-1===$.inArray(previousBlock.type,["Heading","text"]))return void console.log("Can't merge with previous block: not a text block.");previousBlock.focus(),previousBlock.$editor.caretToEnd(),previousBlock.$editor.append(this.$editor.contents()),instance.removeBlock(this.blockID)}},insertSplitMarker:function(html){var selection,range,element,fragment,node,lastNode,marker='<i id="split-marker"></i>';if(window.getSelection){if(selection=window.getSelection(),selection.getRangeAt&&selection.rangeCount){for(range=selection.getRangeAt(0),range.deleteContents(),element=document.createElement("div"),element.innerHTML=marker,fragment=document.createDocumentFragment();node=element.firstChild;)lastNode=fragment.appendChild(node);range.insertNode(fragment)}}else document.selection&&"Control"!=document.selection.type&&document.selection.createRange().pasteHTML(marker);return $("#split-marker")},removeSplitMarker:function(){var marker=$("#split-marker"),parent=marker.parent();marker.remove();var range=window.getSelection().getRangeAt(0);range.startOffset+range.endOffset!==0&&parent[0].normalize()},removeStartingReturns:function(block){var node,returns,selector="> div:first-child > br:first-child, > br:first-child";for(void 0===block&&(block=this),node=block.$editor,returns=node.find(selector);returns.length>0;)returns.remove(),returns=node.find(selector),node.find("div:empty").remove()},removeTrailingReturns:function(block){var node,returns,selector="div:last-child br:last-child, br:last-child";for(void 0===block&&(block=this),node=block.$editor,node.find("div:empty").remove(),returns=node.find(selector);returns.length>0;)returns.remove(),node.find("div:empty").remove(),returns=node.find(selector)},cleanupNestedDivs:function(block){var node,selector="div div";void 0===block&&(block=this),node=block.$editor,node.find(selector).each(function(i,el){var element=$(el);element.replaceWith(element.contents())}),node.find("div:empty").remove()},splitAtReturns:function(){var next,r=this.$el.find("br").first();if(0!==r.length){r.replaceWith('<i id="split-marker"></i>');try{next=this.splitAtSplitMarker()}finally{this.removeSplitMarker()}next.splitAtReturns()}},splitAtSplitMarker:function(){var newBlock,currentPosition,nextBlockPosition,instance=SirTrevor.getInstance(this.instanceID);try{newBlock=instance.createBlock("text",void 0,void 0,!1),currentPosition=instance.getBlockPosition(this.$el),nextBlockPosition=instance.getBlockPosition(newBlock.$el),nextBlockPosition-currentPosition!==1&&instance.changeBlockPosition(newBlock.$el,currentPosition+1,"After");var range=window.getSelection().getRangeAt(0);range.setStartAfter($("#split-marker")[0]),range.setEndAfter(this.$el.find(".st-text-block").children().last()[0]);var remainder=range.cloneContents();range.deleteContents(),newBlock.$editor.append(remainder),newBlock.$editor.find("div:empty").remove()}finally{this.cleanupNestedDivs(newBlock),newBlock.focus(),newBlock.$editor.caretToStart()}return newBlock},onReturn:function(event,target){if(-1!==$.inArray(this.type,["Heading","text"])){SirTrevor.getInstance(this.instanceID);window.getSelection().modify("extend","left","character"),document.execCommand("removeFormat",!1),this.insertSplitMarker();try{this.splitAtSplitMarker()}finally{this.removeSplitMarker()}}},getSelectionForFormatter:function(){_.defer(function(block){var selection=window.getSelection(),selectionStr=selection.toString().trim(),eventType=""===selectionStr?"hide":"position";SirTrevor.EventBus.trigger("formatter:"+eventType,block)},this)},clearInsertedStyles:function(e){var target=e.target;target.removeAttribute("style")},hasTextBlock:function(){return this.getTextBlock().length>0},getTextBlock:function(){return _.isUndefined(this.text_block)&&(this.text_block=this.$(".st-text-block")),this.text_block},isEmpty:function(){var data=jQuery.extend(!0,{},this.saveAndGetData());return delete data.uuid,delete data.note,delete data.style,_.isEmpty(data)}}),Block.extend=extend,Block}(),SirTrevor.DynamicBlocks=function(){return{}}(),SirTrevor.Formatter=function(){var Format=function(options){this.formatId=_.uniqueId("format-"),this._configure(options||{}),this.initialize.apply(this,arguments)},formatOptions=["title","className","cmd","keyCode","param","onClick","toMarkdown","toHTML"];return _.extend(Format.prototype,{title:"",className:"",cmd:null,keyCode:null,param:null,toMarkdown:function(markdown){return markdown},toHTML:function(html){return html},initialize:function(){},_configure:function(options){this.options&&(options=_.extend({},this.options,options));for(var i=0,l=formatOptions.length;l>i;i++){var attr=formatOptions[i];options[attr]&&(this[attr]=options[attr])}this.options=options},isActive:function(){return document.queryCommandState(this.cmd)},_bindToBlock:function(block){var formatter=this,ctrlDown=!1;block.on("keyup",".st-text-block",function(ev){(17==ev.which||224==ev.which||91==ev.which)&&(ctrlDown=!1)}).on("keydown",".st-text-block",{formatter:formatter},function(ev){(17==ev.which||224==ev.which||91==ev.which)&&(ctrlDown=!0),ev.which==ev.data.formatter.keyCode&&ctrlDown===!0&&(document.execCommand(ev.data.formatter.cmd,!1,!0),ev.preventDefault(),ctrlDown=!1)})}}),Format.extend=extend,Format}(),SirTrevor.Blocks.Quote=function(){var template=_.template(['<blockquote class="st-required st-text-block st-block--quote" contenteditable="true"></blockquote>','<label class="st-input-label"> <%= i18n.t("blocks:quote:credit_field") %></label>','<input maxlength="140" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"',' class="st-input-string js-cite-input" type="text" />'].join("\n"));return SirTrevor.Block.extend({type:"quote",title:function(){return i18n.t("blocks:quote:title")},icon_name:"quote",changeable:["Heading","text"],editorHTML:function(){return template(this)},loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type)),this.$(".js-cite-input").val(data.cite)},toMarkdown:function(markdown){return markdown.replace(/^(.+)$/gm,"> $1")}})}(),SirTrevor.Blocks.ExtendedQuote=function(){var template=_.template(['<blockquote class="st-required st-text-block st-block--extended-quote" contenteditable="true"></blockquote>','<label class="st-input-label"> <%= i18n.t("blocks:extended_quote:credit_field") %></label>','<input name="cite" placeholder="<%= i18n.t("blocks:extended_quote:credit_field") %>"',' class="st-input-string js-cite-input" type="text" />'].join("\n"));return SirTrevor.Block.extend({type:"extended_quote",title:function(){return i18n.t("blocks:extended_quote:title")},icon_name:"quote-extended",changeable:["Heading","text"],editorHTML:function(){return template(this)},loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type)),this.$(".js-cite-input").val(data.cite)},toMarkdown:function(markdown){return markdown.replace(/^(.+)$/gm,"> $1")}})}(),SirTrevor.Blocks.Heading=SirTrevor.Block.extend({type:"Heading",title:function(){return i18n.t("blocks:heading:title")},editorHTML:'<div class="st-required st-text-block st-block--heading" contenteditable="true"></div>',icon_name:"heading",changeable:["text","quote"],loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type))}}),SirTrevor.Blocks.Text=SirTrevor.Block.extend({type:"text",title:function(){return i18n.t("blocks:text:title")},editorHTML:'<div class="st-required st-text-block" contenteditable="true"></div>',icon_name:"text",changeable:["Heading","quote"],loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type))}}),SirTrevor.Blocks.List=function(){var template='<div class="st-text-block st-required st-block--list" contenteditable="true"><ul><li></li></ul></div>';return SirTrevor.Block.extend({type:"list",title:function(){return i18n.t("blocks:list:title")},icon_name:"list",editorHTML:function(){return _.template(template,this)},loadData:function(data){this.getTextBlock().html("<ul>"+SirTrevor.toHTML(data.text,this.type)+"</ul>")},onBlockRender:function(){this.checkForList=_.bind(this.checkForList,this),this.getTextBlock().on("click keyup",this.checkForList)},checkForList:function(){0===this.$("ul").length&&document.execCommand("insertUnorderedList",!1,!1)},toMarkdown:function(markdown){return markdown.replace(/<\/li>/gm,"\n").replace(/<\/?[^>]+(>|$)/g,"").replace(/^(.+)$/gm," - $1")},toHTML:function(html){return html=html.replace(/^ - (.+)$/gm,"<li>$1</li>").replace(/\n/gm,"")},onContentPasted:function(event,target){var replace=this.pastedMarkdownToHTML(target[0].innerHTML);this.$("ul").html(replace);this.getTextBlock().caretToEnd()},isEmpty:function(){return _.isEmpty(this.saveAndGetData().text)}})}(),SirTrevor.Blocks.Definition=function(){var template=_.template(['<dl class="st-definition st-block--definition"><dt><label class="st-input-label"> <%= i18n.t("blocks:definition:term") %></label>','<input name="term" placeholder="<%= i18n.t("blocks:definition:term") %>"',' class="st-input-string js-term-input" type="text" /></dt>','<dd class="st-required st-text-block" contenteditable="true" data-placeholder="<%= i18n.t("blocks:definition:description") %>"></dd></dl>'].join("\n"));return SirTrevor.Block.extend({type:"definition",title:function(){return i18n.t("blocks:definition:title")},icon_name:"definition",changeable:["Heading","text"],editorHTML:function(){return template(this)},onBlockRender:function(){var placeholders=this.$el.find("[data-placeholder]");placeholders.on("change keydown keypress input",function(){this.textContent?this.setAttribute("data-hide-placeholder","true"):this.removeAttribute("data-hide-placeholder")})},loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type)),this.$(".js-term-input").val(data.term)},onContentPasted:function(event,target){target.html(this.pastedMarkdownToHTML(target[0].innerHTML)),this.getTextBlock().caretToEnd()}})}(),SirTrevor.Blocks.Divider=function(){var template='<div class="st-divider st-block--divider"><hr></div>';return SirTrevor.Block.extend({type:"divider",title:function(){return i18n.t("blocks:divider:title")},icon_name:"divider",editorHTML:function(){return _.template(template,this)},toMarkdown:function(markdown){return"---------------------------------------"},toHTML:function(html){return template},isEmpty:function(){return!1}})}(),SirTrevor.Blocks.RewardList=function(){var template=['<div class="st-reward-list st-block--reward-list">','<h1><i class="icon--reward"></i>%s</h1>',"</div>"].join("\n");return SirTrevor.Block.extend({type:"reward_list",title:function(){return i18n.t("blocks:reward_list:title")},icon_name:"reward",editorHTML:function(){return _.template(template.replace("%s",this.title()),this)},isEmpty:function(){return!1}})}(),SirTrevor.Blocks.Image=SirTrevor.Block.extend({type:"image",title:function(){return i18n.t("blocks:image:title")},droppable:!0,uploadable:!0,icon_name:"image",loadData:function(data){this.$editor.html($("<img>",{src:data.file.url}))},onBlockRender:function(){this.$inputs.find("button").bind("click",function(ev){ev.preventDefault()}),this.$inputs.find("input").on("change",_.bind(function(ev){this.onDrop(ev.currentTarget)},this))},onUploadSuccess:function(data){this.setData(data),this.ready()},onUploadError:function(jqXHR,status,errorThrown){this.addMessage(i18n.t("blocks:image:upload_error")),this.ready()},onDrop:function(transferData){var file=transferData.files[0],urlAPI="undefined"!=typeof URL?URL:"undefined"!=typeof webkitURL?webkitURL:null;/image/.test(file.type)&&(this.loading(),this.$inputs.hide(),this.$editor.html($("<img>",{src:urlAPI.createObjectURL(file)})).show(),this.uploader(file,this.onUploadSuccess,this.onUploadError))}}),SirTrevor.Blocks.ExtendedImage=SirTrevor.Blocks.Image.extend({type:"extended_image",title:function(){return i18n.t("blocks:extended_image:title")},droppable:!0,uploadable:!0,styleable:!0,styles:[{name:i18n.t("blocks:extended_image:default"),value:"default",className:"default"
12
- },{name:i18n.t("blocks:extended_image:bodywidth"),value:"bodywidth",className:"bodywidth"},{name:i18n.t("blocks:extended_image:fullwidth"),value:"fullwidth",className:"fullwidth"}],icon_name:"image",removeEmpty:!0,loadData:function(data){var payload,editor=this.$editor,figure=$("<figure class='media'></figure>"),picture=$("<picture class='media__img'></picture>"),source=data.file&&data.file.url;payload=void 0!==source?$("<img>",{src:source}):$('<h1><i class="icon--exclamation-triangle"></i></h1>'),figure.append(picture.append(payload));var copyright=($("<figcaption class='media__body'></figcaption>"),$(["<label class='st-input-label'>"+i18n.t("blocks:extended_image:copyright_field")+"</label>","<input type='text' maxlength='140' name='copyright' class='st-input-string js-copyright-input'","placeholder='"+i18n.t("blocks:extended_image:copyright_placeholder")+"'></input>"].join("\n")));figure.append(copyright);var caption=$(["<label class='st-input-label'>"+i18n.t("blocks:extended_image:caption_field")+"</label>","<textarea name='caption' class='st-input-string js-caption-input'","placeholder='"+i18n.t("blocks:extended_image:caption_placeholder")+"'></textarea>"].join("\n"));figure.append(caption);var target_url=$(["<label class='st-input-label'>"+i18n.t("blocks:extended_image:target_url_field")+"</label>","<input type='text' maxlength='140' name='target_url' class='st-input-string js-target_url-input'","placeholder='"+i18n.t("blocks:extended_image:target_url_placeholder")+"'></input>"].join("\n"));figure.append(target_url),editor.html("").show(),editor.append(figure),this.$(".js-target_url-input").val(data.target_url),this.$(".js-copyright-input").val(data.copyright),this.$(".js-caption-input").val(data.caption),void 0!==jQuery.fn.autosize&&figure.find(".js-caption-input").autosize()},onBlockRender:function(){this.$inputs.find("button").bind("click",function(ev){ev.preventDefault()}),this.$inputs.find("input").on("change",_.bind(function(ev){this.onDrop(ev.currentTarget)},this))},onUploadSuccess:function(data){this.setData(data),this.ready()},onUploadError:function(jqXHR,status,errorThrown){this.addMessage(i18n.t("blocks:extended_image:upload_error")),this.ready()},onDrop:function(transferData){var file=transferData.files[0],urlAPI="undefined"!=typeof URL?URL:"undefined"!=typeof webkitURL?webkitURL:null;/image/.test(file.type)&&(this.loading(),this.$inputs.hide(),this.loadData({file:{url:urlAPI.createObjectURL(file)}}),this.uploader(file,this.onUploadSuccess,this.onUploadError))}}),SirTrevor.Blocks.Video=function(){return SirTrevor.Block.extend({providers:{vimeo:{regex:/(?:http[s]?:\/\/)?(?:www.)?vimeo.com\/(.+)/,html:'<iframe src="{{protocol}}//player.vimeo.com/video/{{remote_id}}?title=0&byline=0" width="580" height="320" frameborder="0"></iframe>'},youtube:{regex:/(?:http[s]?:\/\/)?(?:www.)?(?:(?:youtube.com\/watch\?(?:.*)(?:v=))|(?:youtu.be\/))([^&].+)/,html:'<iframe src="{{protocol}}//www.youtube.com/embed/{{remote_id}}" width="580" height="320" frameborder="0" allowfullscreen></iframe>'}},type:"video",title:function(){return i18n.t("blocks:video:title")},droppable:!0,pastable:!0,icon_name:"video",styleable:!0,styles:[{name:"Default",value:"default",className:"default"},{name:"Full-width",value:"fullwidth",className:"default"}],removeEmpty:!0,extractSourceInformation:function(){var url=this.$editor.find("iframe").attr("src");this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string;this.providers.hasOwnProperty(data.source)?(this.providers[data.source].square?this.$editor.addClass("st-block__editor--with-square-media"):this.$editor.addClass("st-block__editor--with-sixteen-by-nine-media"),embed_string=this.providers[data.source].html.replace("{{protocol}}",window.location.protocol).replace("{{remote_id}}",data.remote_id).replace("{{width}}",this.$editor.width())):embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',this.$editor.html(embed_string),this.extractSourceInformation()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Tweet=function(){var tweet_template=_.template(["<blockquote class='twitter-tweet' align='center'>","<p><%= text %></p>","&mdash; <%= user.name %> (@<%= user.screen_name %>)","<a href='<%= status_url %>' data-datetime='<%= created_at %>'><%= created_at %></a>","</blockquote>",'<script src="//platform.twitter.com/widgets.js" charset="utf-8"></script>'].join("\n"));return SirTrevor.Block.extend({type:"tweet",droppable:!0,pastable:!0,fetchable:!0,drop_options:{re_render_on_reorder:!0},title:function(){return i18n.t("blocks:tweet:title")},fetchUrl:function(tweetID){return"/tweets/?tweet_id="+tweetID},icon_name:"twitter",loadData:function(data){_.isUndefined(data.status_url)&&(data.status_url=""),this.$inner.find("iframe").remove(),this.$inner.prepend(tweet_template(data))},onContentPasted:function(event){var input=$(event.target),val=input.val();this.handleTwitterDropPaste(val)},handleTwitterDropPaste:function(url){if(!this.validTweetUrl(url))return void SirTrevor.log("Invalid Tweet URL");var tweetID=url.match(/[^\/]+$/);if(!_.isEmpty(tweetID)){this.loading(),tweetID=tweetID[0];var ajaxOptions={url:this.fetchUrl(tweetID),dataType:"json"};this.fetch(ajaxOptions,this.onTweetSuccess,this.onTweetFail)}},validTweetUrl:function(url){return _.isURI(url)&&-1!==url.indexOf("twitter")&&-1!==url.indexOf("status")},onTweetSuccess:function(data){var obj={user:{profile_image_url:data.user.profile_image_url,profile_image_url_https:data.user.profile_image_url_https,screen_name:data.user.screen_name,name:data.user.name},id:data.id_str,text:data.text,created_at:data.created_at,entities:data.entities,status_url:"https://twitter.com/"+data.user.screen_name+"/status/"+data.id_str};this.setAndLoadData(obj),this.ready()},onTweetFail:function(){this.addMessage(i18n.t("blocks:tweet:fetch_error")),this.ready()},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleTwitterDropPaste(url)}})}(),SirTrevor.Blocks.ExtendedTweet=function(){return SirTrevor.Block.extend({providers:{soundcloud:{regex:/((?:http[s]?:\/\/)?(?:www.)?(:?twitter.com\/.*\/status\/(.*?)))(:?\?.*)?$/,html:function(options,success,error){var fail=window.setTimeout(error,5e3);$.getJSON("https://api.twitter.com/1/statuses/oembed.json?callback=?",{format:"js",url:options.remote_id,align:"center",maxwidth:550,hide_thread:1,iframe:!0}).done(function(data){clearTimeout(fail),success(data.html,options)})}}},type:"extended_tweet",title:function(){return i18n.t("blocks:tweet:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"twitter-outline",extractSourceInformation:function(options){var url=options.remote_id;this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string,self=this,update_editor=function(embed_string,options){self.$editor.html(embed_string),self.extractSourceInformation(options)},display_error=function(){embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',self.$editor.html(embed_string)};if(this.providers.hasOwnProperty(data.source)){var html=this.providers[data.source].html;html instanceof Function?html({protocol:window.location.protocol,remote_id:data.remote_id,width:this.$editor.width()},update_editor,display_error):(embed_string=html.replace("{{protocol}}",window.location.protocol).replace("{{remote_id}}",data.remote_id).replace("{{width}}",this.$editor.width()),update_editor())}else display_error()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.FacebookPost=function(){function initFacebookOnce(){if("undefined"==typeof FB&&!initDone){var facebookInitScript=['<div id="fb-root"></div>',"<script>(function(d, s, id) {"," var js, fjs = d.getElementsByTagName(s)[0];"," if (d.getElementById(id)) return;"," js = d.createElement(s); js.id = id;",' js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";'," fjs.parentNode.insertBefore(js, fjs);",'}(document, "script", "facebook-jssdk"));</script>'].join("\n");jQuery(document.body).append(facebookInitScript),initDone=!0}}var initDone=!1,facebook_post_template=_.template(['<div class="fb-post" data-href="<%= url %>" data-width="<%= width %>"></div>'].join("\n")),facebookPostRegex=/((?:http[s]?:\/\/)?(?:www.)?(:?facebook.com\/(video\.php|photo\.php|(.*\/(posts|photos)\/))(.*?)))(:?\?.*)?$/;return SirTrevor.Block.extend({type:"facebook_post",title:function(){return i18n.t("blocks:facebookpost:title")},droppable:!0,pastable:!0,icon_name:"facebook-outline",extractSourceInformation:function(url){this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){initFacebookOnce(),this.$inner.prepend(facebook_post_template({url:data.url,width:this.$editor.width()||"700"})),this.extractSourceInformation(data.url),"undefined"!=typeof FB&&FB.XFBML.parse()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){if(!this.validPostUrl(url))return void SirTrevor.log("Invalid Facebook Post URL");this.setAndLoadData({url:url}),this.ready()}},validPostUrl:function(url){return url.match(facebookPostRegex)},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Infographic=function(){return SirTrevor.Block.extend({providers:{infoactive:{regex:/(?:http[s]?:\/\/)?(?:www.)?infoactive.co\/plays\/(.+)/,html:["<div data-url='https://infoactive.co/plays/{{remote_id}}' id='infoactive-iframe-container-{{remote_id}}'></div>","<script type='text/javascript'>","jQuery.getScript('https://dqzzm1bt1bnva.cloudfront.net/assets/pym-7afa305c2065e6ace0f4cb837fc78658.js', function() {","var iFrameLoader = new pym.Parent('infoactive-iframe-container-{{remote_id}}','https://infoactive.co/plays/{{remote_id}}', {});","});","</script>"].join("\n")}},type:"infographic",title:function(){return i18n.t("blocks:infographic:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"infographic",extractSourceInformation:function(){var url=this.$editor.find("div[data-url]").attr("data-url");this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string;this.providers.hasOwnProperty(data.source)?(embed_string=this.providers[data.source].html.replace(/{{protocol}}/g,window.location.protocol).replace(/{{remote_id}}/g,data.remote_id).replace(/{{width}}/g,this.$editor.width()),this.$editor.html(embed_string),this.extractSourceInformation()):(embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',this.$editor.html(embed_string))},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Audio=function(){return SirTrevor.Block.extend({providers:{soundcloud:{regex:/((?:http[s]?:\/\/)?(?:www.)?(:?soundcloud.com\/(.*)))/,html:function(options,success,error){var fail=window.setTimeout(error,5e3);$.getJSON("https://soundcloud.com/oembed?callback=?",{format:"js",url:options.remote_id,iframe:!0}).done(function(data){clearTimeout(fail),success(data.html,options)})}}},type:"audio",title:function(){return i18n.t("blocks:audio:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"audio",extractSourceInformation:function(){var url=this.$editor.find("iframe").attr("src");this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string,self=this,update_editor=function(embed_string){self.$editor.html(embed_string),self.extractSourceInformation(),self.providers[data.source].square?self.$editor.addClass("st-block__editor--with-square-media"):self.$editor.addClass("st-block__editor--with-sixteen-by-nine-media")},display_error=function(){embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',self.$editor.html(embed_string)};if(this.providers.hasOwnProperty(data.source)){var html=this.providers[data.source].html;html instanceof Function?html({protocol:window.location.protocol,remote_id:data.remote_id,width:this.$editor.width()},update_editor,display_error):(embed_string=html.replace("{{protocol}}",window.location.protocol).replace("{{remote_id}}",data.remote_id).replace("{{width}}",this.$editor.width()),update_editor())}else display_error()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Html=SirTrevor.Block.extend({type:"html",title:function(){return i18n.t("blocks:html:title")},editorHTML:'<div class="st-required st-html-block" contenteditable="true"></div>',icon_name:"text",changeable:[],getBlock:function(){return this.$(".st-html-block")},toData:function(){SirTrevor.log("toData for "+this.blockID);var uuid=this.getData().uuid||SirTrevor.generateUUID(),dataObj=(this.$el,{uuid:uuid}),content=this.getBlock().text();content.length>0&&(dataObj.text=content),_.isEmpty(dataObj)||this.setData(dataObj)},loadData:function(data){this.getBlock().text(data.text)}}),SirTrevor.Blocks.Instagram=function(){return SirTrevor.Block.extend({providers:{instagram:{regex:/((?:http[s]?:\/\/)?(?:www.)?(:?instagr.*\/p\/(.*?)))(:?\?.*)?$/,html:function(options,success,error){var fail=window.setTimeout(error,5e3);$.ajax({url:"//api.instagram.com/oembed",data:{maxwidth:550,url:options.remote_id},jsonp:"callback",dataType:"jsonp"}).done(function(data){clearTimeout(fail),success(data.html,options)})}}},type:"instagram",title:function(){return i18n.t("blocks:instagram:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"instagram-outline",extractSourceInformation:function(options){var url=options.remote_id;this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string,self=this,update_editor=function(embed_string,options){self.$editor.html(embed_string),self.extractSourceInformation(options)},display_error=function(){embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',self.$editor.html(embed_string)},html=this.providers[data.source].html;html({protocol:window.location.protocol,remote_id:data.remote_id,width:this.$editor.width()},update_editor,display_error)},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.DynamicBlocks.RemoteSelectableList=function(){return function(parameters){return{type:parameters.model_name,fetchable:!0,selectedElements:[],title:function(){return i18n.t("blocks:remote_list:"+parameters.model_name+":title")},icon_name:parameters.icon,editorHTML:function(){return""},onBlockRender:function(){this.getData().selected||(this.loading(),this.setData({selected:[],model_name:parameters.model_name}),parameters.callback(this.onListSuccess.bind(this),this.onGetFail.bind(this)))},loadData:function(data){return _.isArray(data.selected)&&0!==data.selected.length?void this.renderSelected(data.selected):void this.destroy()},renderSelected:function(selected){var data=JSON.stringify({model_name:parameters.model_name,selected:selected});$.get(parameters.render_endpoint,{content:data},this.onGetRenderSuccess.bind(this)).fail(this.onGetFail.bind(this))},onGetRenderSuccess:function(data){this.ready(),this.$el.append(data)},onListSuccess:function(data){this.setAndLoadData({selected:data,model_name:parameters.model_name}),this.ready()},onGetFail:function(){this.addMessage(i18n.t("blocks:remote_list:fetch_error")),this.ready()}}}}(),function(){var Bold=SirTrevor.Formatter.extend({title:"bold",cmd:"bold",keyCode:66,text:"B"}),Italic=SirTrevor.Formatter.extend({title:"italic",cmd:"italic",keyCode:73,text:"i"}),Link=SirTrevor.Formatter.extend({title:"link",iconName:"link",cmd:"CreateLink",text:"link",onClick:function(){var selectionLink="";try{var sel=document.getSelection();sel.rangeCount&&(selectionLink=sel.getRangeAt(0).commonAncestorContainer.parentElement.href||"")}catch(e){}var link=prompt(i18n.t("general:link"),selectionLink),link_regex=/((ftp|http|https):\/\/.)|mailto(?=\:[-\.\w]+@)/;link&&link.length>0&&(link_regex.test(link)||(link="http://"+link),document.execCommand(this.cmd,!1,link))},isActive:function(){var node,selection=window.getSelection();return selection.rangeCount>0&&(node=selection.getRangeAt(0).startContainer.parentNode),node&&"A"==node.nodeName}}),UnLink=SirTrevor.Formatter.extend({title:"unlink",iconName:"link",cmd:"unlink",text:"link"});SirTrevor.Formatters.Bold=new Bold,SirTrevor.Formatters.Italic=new Italic,SirTrevor.Formatters.Link=new Link,SirTrevor.Formatters.Unlink=new UnLink}(),function(){var Heading=SirTrevor.Formatter.extend({title:"heading",iconName:"Heading",text:"H1",prepare:function(){var selection=window.getSelection();if(0===selection.rangeCount)return void SirTrevor.log("Can't get current selection from formatter!");var node=$(selection.getRangeAt(0).startContainer.parentNode).parents(".st-block").first();this._instance=SirTrevor.getInstance(node.attr("data-instance")),this._block=this._instance.getBlocksByIDs([node.attr("id")])[0]},getCurrentBlock:function(){return this._block},getCurrentInstance:function(){return this._instance},onClick:function(){var instance=this.getCurrentInstance(),block=this.getCurrentBlock();instance.changeBlockType(block,"Heading"===block.type?"text":"Heading")},isActive:function(){return this.prepare(),"Heading"===this.getCurrentBlock().type}}),Quote=SirTrevor.Formatter.extend({title:"quote",iconName:"quote",text:"“",prepare:function(){var selection=window.getSelection();if(0===selection.rangeCount)return void SirTrevor.log("Can't get current selection from formatter!");var node=$(selection.getRangeAt(0).startContainer.parentNode).parents(".st-block").first();this._instance=SirTrevor.getInstance(node.attr("data-instance")),this._block=this._instance.getBlocksByIDs([node.attr("id")])[0]},getCurrentBlock:function(){return this._block},getCurrentInstance:function(){return this._instance},onClick:function(){var instance=this.getCurrentInstance(),block=this.getCurrentBlock();instance.changeBlockType(block,"quote"===block.type?"text":"quote")},isActive:function(){return this.prepare(),"quote"===this.getCurrentBlock().type}});SirTrevor.Formatters.Heading=new Heading,SirTrevor.Formatters.Quote=new Quote}(),SirTrevor.BlockControl=function(){var BlockControl=function(type,instance_scope){this.type=type,this.instance_scope=instance_scope,this.block_type=SirTrevor.Blocks[this.type].prototype,this.can_be_rendered=this.block_type.toolbarEnabled,this._ensureElement()};return _.extend(BlockControl.prototype,FunctionBind,Renderable,SirTrevor.Events,{tagName:"a",className:"st-block-control",attributes:function(){return{"data-type":this.block_type.type}},render:function(){return this.$el.html('<span class="st-icon icon--'+_.result(this.block_type,"icon_name")+'" aria-hidden="true"></span>'+_.result(this.block_type,"title")),this}}),BlockControl}(),SirTrevor.BlockControls=function(){var BlockControls=function(available_types,instance_scope){this.instance_scope=instance_scope,this.available_types=available_types||[],this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockControls.prototype,FunctionBind,Renderable,SirTrevor.Events,{bound:["handleControlButtonClick"],block_controls:null,className:"st-block-controls",html:"<a class='st-icon st-icon--close'>"+i18n.t("general:close")+"</a>",initialize:function(){for(var block_type in this.available_types)if(SirTrevor.Blocks.hasOwnProperty(block_type)){var block_control=new SirTrevor.BlockControl(block_type,this.instance_scope);block_control.can_be_rendered&&this.$el.append(block_control.render().$el)}this.$el.delegate(".st-block-control","click",this.handleControlButtonClick)},show:function(){this.$el.addClass("st-block-controls--active"),SirTrevor.EventBus.trigger("block:controls:shown")},hide:function(){this.$el.removeClass("st-block-controls--active"),SirTrevor.EventBus.trigger("block:controls:hidden")},handleControlButtonClick:function(e){e.stopPropagation(),this.trigger("createBlock",$(e.currentTarget).attr("data-type"))}}),BlockControls}(),SirTrevor.FloatingBlockControls=function(){var FloatingBlockControls=function(wrapper,instance_id){this.$wrapper=wrapper,this.instance_id=instance_id,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(FloatingBlockControls.prototype,FunctionBind,Renderable,SirTrevor.Events,{className:"st-block-controls__top",attributes:function(){return{"data-icon":"add"}},bound:["handleBlockMouseOut","handleBlockMouseOver","handleBlockClick","onDrop"],initialize:function(){this.$el.on("click",this.handleBlockClick).dropArea().bind("drop",this.onDrop),this.$wrapper.on("mouseover",".st-block",this.handleBlockMouseOver).on("mouseout",".st-block",this.handleBlockMouseOut).on("click",".st-block--with-plus",this.handleBlockClick)},onDrop:function(ev){ev.preventDefault();var dropped_on=this.$el,item_id=ev.originalEvent.dataTransfer.getData("text/plain"),block=$("#"+item_id);_.isUndefined(item_id)||_.isEmpty(block)||dropped_on.attr("id")==item_id||this.instance_id!=block.attr("data-instance")||dropped_on.after(block),SirTrevor.EventBus.trigger("block:reorder:dropped",item_id)},handleBlockMouseOver:function(e){var block=$(e.currentTarget);block.hasClass("st-block--with-plus")||block.addClass("st-block--with-plus")},handleBlockMouseOut:function(e){var block=$(e.currentTarget);block.hasClass("st-block--with-plus")&&block.removeClass("st-block--with-plus")},handleBlockClick:function(e){e.stopPropagation();var block=$(e.currentTarget);this.trigger("showBlockControls",block)}}),FloatingBlockControls}(),SirTrevor.FormatBar=function(){var FormatBar=function(options){this.options=_.extend({},SirTrevor.DEFAULTS.formatBar,options||{}),this._ensureElement(),this._bindFunctions(),this.initialize.apply(this,arguments)};return _.extend(FormatBar.prototype,FunctionBind,SirTrevor.Events,Renderable,{className:"st-format-bar",bound:["onFormatButtonClick","renderBySelection","hide"],initialize:function(){var formatName,format,btn;SirTrevor.Formatters;this.$btns=[];for(formatName in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(formatName)&&(format=SirTrevor.Formatters[formatName],btn=$("<button>",{"class":"st-format-btn st-format-btn--"+formatName+" "+(format.iconName?"st-icon":""),text:format.text,"data-type":formatName,"data-cmd":format.cmd}),this.$btns.push(btn),btn.appendTo(this.$el));this.$b=$(document),this.$el.bind("click",".st-format-btn",this.onFormatButtonClick)},hide:function(){this.$el.removeClass("st-format-bar--is-ready")},show:function(){this.$el.addClass("st-format-bar--is-ready")},remove:function(){this.$el.remove()},renderBySelection:function(rectangles){var selection=window.getSelection(),range=selection.getRangeAt(0),boundary=range.getBoundingClientRect(),coords={};coords.top=boundary.top+20+window.pageYOffset-this.$el.height()+"px",coords.left=(boundary.left+boundary.right)/2-this.$el.width()/2+"px",this.highlightSelectedButtons(),this.show(),this.$el.css(coords)},highlightSelectedButtons:function(){var formatter;_.each(this.$btns,function($btn){formatter=SirTrevor.Formatters[$btn.attr("data-type")],$btn.toggleClass("st-format-btn--is-active",formatter.isActive())},this)},onFormatButtonClick:function(ev){ev.stopPropagation();var btn=$(ev.target),format=SirTrevor.Formatters[btn.attr("data-type")];return _.isUndefined(format)?!1:(!_.isUndefined(format.onClick)&&_.isFunction(format.onClick)?format.onClick():document.execCommand(btn.attr("data-cmd"),!1,format.param),this.highlightSelectedButtons(),!1)}}),FormatBar}(),SirTrevor.Editor=function(){var SirTrevorEditor=function(options){this.initialize(options)};return _.extend(SirTrevorEditor.prototype,FunctionBind,SirTrevor.Events,{bound:["onFormSubmit","showBlockControls","hideAllTheThings","hideBlockControls","onNewBlockCreated","changeBlockPosition","onBlockDragStart","onBlockDragEnd","removeBlockDragOver","onBlockDropped","createBlock","restoreDefaultType","autosave","_checkEscapeKeyPressed"],events:{"block:reorder:down":"hideBlockControls","block:reorder:dragstart":"onBlockDragStart","block:reorder:dragend":"onBlockDragEnd","block:content:dropped":"removeBlockDragOver","block:reorder:dropped":"onBlockDropped","block:create:new":"onNewBlockCreated"},initialize:function(options){return SirTrevor.log("Init SirTrevor.Editor"),this.blockTypes={},this.blockCounts={},this.blocks=[],this.errors=[],this.options=_.extend({},SirTrevor.DEFAULTS,options||{}),this.ID=_.uniqueId("st-editor-"),this._ensureAndSetElements()?(!_.isUndefined(this.options.onEditorRender)&&_.isFunction(this.options.onEditorRender)&&(this.onEditorRender=this.options.onEditorRender),this._extendLocales(),this._setRequired(),this._createDynamicBlocks(),this._setBlocksTypes(),this._bindFunctions(),this._setupActiveClass(),this.store("create"),SirTrevor.instances.push(this),this.build(),$(window).on("keyup",this._checkEscapeKeyPressed),void SirTrevor.bindFormSubmit(this.$form)):!1},_setupActiveClass:function(){var focus,current,timeout,root=$("#"+this.ID),className="st-active-block",resetActive=function(){window.clearTimeout(timeout),timeout=window.setTimeout(function(){root.find(".st-block").removeClass(className),current.addClass(className)},200)};root.delegate(".st-block","focus",function(e){focus=$(this),current=focus,resetActive()}),root.delegate(".st-block","mouseout",function(e){}),root.delegate(".st-block","mouseover",function(e){return e.stopPropagation(),$(e.target).hasClass("st-block__ui")||$(e.target).parents(".st-block__ui").length>0?!1:(current=$(this),void resetActive())})},build:function(){this.$el.hide(),this.block_controls=new SirTrevor.BlockControls(this.blockTypes,this.ID),this.fl_block_controls=new SirTrevor.FloatingBlockControls(this.$wrapper,this.ID),this.formatBar=new SirTrevor.FormatBar(this.options.formatBar),this.listenTo(this.block_controls,"createBlock",this.createBlock),this.listenTo(this.fl_block_controls,"showBlockControls",this.showBlockControls),SirTrevor.EventBus.on("showBlockControls",this.showBlockControls),this._setEvents(),SirTrevor.EventBus.on(this.ID+":blocks:change_position",this.changeBlockPosition),SirTrevor.EventBus.on("formatter:position",this.formatBar.renderBySelection),SirTrevor.EventBus.on("formatter:hide",this.formatBar.hide),SirTrevor.EventBus.on(this.ID+":blocks:count_update",this.restoreDefaultType),this.$wrapper.prepend(this.fl_block_controls.render().$el),$(document.body).append(this.formatBar.render().$el),this.$outer.append(this.block_controls.render().$el),$(window).bind("click.sirtrevor",this.hideAllTheThings);var store=this.store("read");store.data.length>0?_.each(store.data,function(block){SirTrevor.log("Creating: "+block.type),this.createBlock(block.type,block.data)},this):this.options.defaultType!==!1&&this.restoreDefaultType(),this.$wrapper.addClass("st-ready"),this.options.localStorage===!0&&window.setInterval(this.autosave,2e4),_.isUndefined(this.onEditorRender)||this.onEditorRender()},autosave:function(){this.store("reset");var blockIterator=function(block,index){var _block=_.find(this.blocks,function(b){return b.blockID==$(block).attr("id")});return _.isUndefined(_block)?!1:void this.saveBlockStateToStore(_block)};_.each(this.$wrapper.find(".st-block"),blockIterator,this),this.store("autosave")},restoreDefaultType:function(count){var instance=this;if(void 0===count||0===count){var container=instance.block_controls.current_container;instance.block_controls.current_container=void 0,instance.createBlock(instance.options.defaultType),instance.block_controls.current_container=container}},destroy:function(){this.formatBar.destroy(),this.fl_block_controls.destroy(),this.block_controls.destroy(),_.each(this.blocks,function(block){this.removeBlock(block.blockID)},this),this.stopListening();var el=this.$el.detach();SirTrevor.instances=_.reject(SirTrevor.instances,_.bind(function(instance){return instance.ID==this.ID},this)),this.store("reset"),this.$outer.replaceWith(el)},reinitialize:function(options){this.destroy(),this.initialize(options||this.options)},_setEvents:function(){_.each(this.events,function(callback,type){SirTrevor.EventBus.on(type,this[callback],this)},this)},hideAllTheThings:function(e){this.block_controls.hide(),this.formatBar.hide(),_.isUndefined(this.block_controls.current_container)||this.block_controls.current_container.removeClass("with-st-controls")},showBlockControls:function(container){_.isUndefined(this.block_controls.current_container)||this.block_controls.current_container.removeClass("with-st-controls"),this.block_controls.show(),container.append(this.block_controls.$el.detach()),container.addClass("with-st-controls"),this.block_controls.current_container=container},store:function(method,options){return SirTrevor.editorStore(this,method,options||{})},createBlock:function(type,data,render_at,focus){if(type=_.classify(type),this._blockLimitReached())return SirTrevor.log("Cannot add any more blocks. Limit reached."),!1;if(!this._isBlockTypeAvailable(type))return SirTrevor.log("Block type not available "+type),!1;if(!this._canAddBlockType(type))return SirTrevor.log("Block Limit reached for type "+type),!1;var block=new SirTrevor.Blocks[type](data,this.ID);return this._renderInPosition(block.render().$el),this.listenTo(block,"removeBlock",this.removeBlock),this.blocks.push(block),this._incrementBlockTypeCount(type),focus!==!1&&block.focus(),SirTrevor.EventBus.trigger(data?"block:create:existing":"block:create:new",block),SirTrevor.log("Block created of type "+type),block.trigger("onRender"),this.$wrapper.toggleClass("st--block-limit-reached",this._blockLimitReached()),this.triggerBlockCountUpdate(),block},onNewBlockCreated:function(block){block.instanceID===this.ID&&this.hideBlockControls()},scrollTo:function(element){},blockFocus:function(block){this.block_controls.current_container=null},_checkEscapeKeyPressed:function(e){27==e.keyCode&&this.hideBlockControls()},hideBlockControls:function(){_.isUndefined(this.block_controls.current_container)||this.block_controls.current_container.removeClass("with-st-controls"),this.block_controls.hide()},removeBlockDragOver:function(){
13
- this.$outer.find(".st-drag-over").removeClass("st-drag-over")},triggerBlockCountUpdate:function(){SirTrevor.EventBus.trigger(this.ID+":blocks:count_update",this.blocks.length)},changeBlockType:function(block,type){var replacement=this.createBlock(type),currentPosition=this.getBlockPosition(block.$el);this.changeBlockPosition(replacement.$el,currentPosition+1,"After"),replacement.$editor.append(block.$editor.contents()),this.removeBlock(block.blockID),replacement.focus()},changeBlockPosition:function($block,selectedPosition,where){selectedPosition-=1;var blockPosition=this.getBlockPosition($block),$blockBy=this.$wrapper.find(".st-block").eq(selectedPosition);this.getBlockPosition($blockBy);-1===$.inArray(where,["Before","After"])&&(where=blockPosition>selectedPosition?"Before":"After"),$blockBy&&$blockBy.attr("id")!==$block.attr("id")&&(this.hideAllTheThings(),$block["insert"+where]($blockBy))},onBlockDropped:function(block_id){this.hideAllTheThings();var block=this.findBlockById(block_id);_.isUndefined(block)||_.isEmpty(block.getData())||!block.drop_options.re_render_on_reorder||block.beforeLoadingData()},onBlockDragStart:function(){this.hideBlockControls(),this.$wrapper.addClass("st-outer--is-reordering")},onBlockDragEnd:function(){this.removeBlockDragOver(),this.$wrapper.removeClass("st-outer--is-reordering")},_renderInPosition:function(block){this.block_controls.current_container?this.block_controls.current_container.after(block):this.$wrapper.append(block)},_incrementBlockTypeCount:function(type){this.blockCounts[type]=_.isUndefined(this.blockCounts[type])?1:this.blockCounts[type]+1},_getBlockTypeCount:function(type){return _.isUndefined(this.blockCounts[type])?0:this.blockCounts[type]},_canAddBlockType:function(type){var block_type_limit=this._getBlockTypeLimit(type);return!(0!==block_type_limit&&this._getBlockTypeCount(type)>=block_type_limit)},_blockLimitReached:function(){return 0!==this.options.blockLimit&&this.blocks.length>=this.options.blockLimit},removeBlock:function(block_id){var block=this.findBlockById(block_id),type=_.classify(block.type),controls=block.$el.find(".st-block-controls");controls.length&&(this.block_controls.hide(),this.$wrapper.prepend(controls)),this.blockCounts[type]=this.blockCounts[type]-1,this.blocks=_.reject(this.blocks,function(item){return item.blockID==block.blockID}),this.stopListening(block),block.remove(),SirTrevor.EventBus.trigger("block:remove",block),this.triggerBlockCountUpdate(),this.$wrapper.toggleClass("st--block-limit-reached",this._blockLimitReached())},performValidations:function(block,should_validate){var errors=0;return!SirTrevor.SKIP_VALIDATION&&should_validate&&(block.valid()||(this.errors.push({text:_.result(block,"validationFailMsg")}),SirTrevor.log("Block "+block.blockID+" failed validation"),++errors)),errors},saveBlockStateToStore:function(block){var store=block.saveAndReturnData();store&&!_.isEmpty(store.data)&&(SirTrevor.log("Adding data for block "+block.blockID+" to block store"),this.store("add",{data:store}))},onFormSubmit:function(should_validate){return this.removeEmptyBlocks(),should_validate=should_validate===!1?!1:!0,SirTrevor.log("Handling form submission for Editor "+this.ID),this.removeErrors(),this.store("reset"),this.validateBlocks(should_validate),this.validateBlockTypesExist(should_validate),this.renderErrors(),this.store("save"),this.errors.length},findEmptyTextBlocks:function(){var instance=this;return result=[],this.blocks.forEach(function(block){instance.saveBlockStateToStore(block);var data=block.getData();-1===$.inArray(block.type,["Heading","text"])||void 0!==data.text&&""!==data.text.trim()||result.push(block)}),result},findEmptyRemoveBlocks:function(){var instance=this;return result=[],this.blocks.forEach(function(block){instance.saveBlockStateToStore(block),block.removeEmpty&&block.isEmpty()&&result.push(block)}),result},removeEmptyBlocks:function(){var blocksToDelete=this.findEmptyTextBlocks().concat(this.findEmptyRemoveBlocks()),instance=this;blocksToDelete.forEach(function(block){instance.removeBlock(block.blockID)})},validateBlocks:function(should_validate){if(!this.required&&SirTrevor.SKIP_VALIDATION&&!should_validate)return!1;var blockIterator=function(block,index){var _block=_.find(this.blocks,function(b){return b.blockID==$(block).attr("id")});return _.isUndefined(_block)?!1:(this.performValidations(_block,should_validate),void this.saveBlockStateToStore(_block))};_.each(this.$wrapper.find(".st-block"),blockIterator,this)},validateBlockTypesExist:function(should_validate){if(!this.required&&SirTrevor.SKIP_VALIDATION&&!should_validate)return!1;var blockTypeIterator=function(type,index){if(this._isBlockTypeAvailable(type))if(0===this._getBlockTypeCount(type))SirTrevor.log("Failed validation on required block type "+type),this.errors.push({text:i18n.t("errors:type_missing",{type:type})});else{var blocks=_.filter(this.getBlocksByType(type),function(b){return!b.isEmpty()});if(blocks.length>0)return!1;this.errors.push({text:i18n.t("errors:required_type_empty",{type:type})}),SirTrevor.log("A required block type "+type+" is empty")}};_.isArray(this.required)&&_.each(this.required,blockTypeIterator,this)},renderErrors:function(){if(0===this.errors.length)return!1;_.isUndefined(this.$errors)&&(this.$errors=this._errorsContainer());var str="<ul>";_.each(this.errors,function(error){str+='<li class="st-errors__msg">'+error.text+"</li>"}),str+="</ul>",this.$errors.append(str),this.$errors.show()},_errorsContainer:function(){if(_.isUndefined(this.options.errorsContainer)){var $container=$("<div>",{"class":"st-errors",html:"<p>"+i18n.t("errors:title")+" </p>"});return this.$outer.prepend($container),$container}return $element(this.options.errorsContainer)},removeErrors:function(){return 0===this.errors.length?!1:(this.$errors.hide().find("ul").html(""),void(this.errors=[]))},findBlockById:function(block_id){return _.find(this.blocks,function(b){return b.blockID==block_id})},getBlocksByType:function(block_type){return _.filter(this.blocks,function(b){return _.classify(b.type)==block_type})},getBlocksByIDs:function(block_ids){return _.filter(this.blocks,function(b){return _.contains(block_ids,b.blockID)})},getBlockPosition:function($block){return this.$wrapper.find(".st-block").index($block)},_getBlockTypeLimit:function(t){return this._isBlockTypeAvailable(t)?parseInt(_.isUndefined(this.options.blockTypeLimits[t])?0:this.options.blockTypeLimits[t],10):0},_isBlockTypeAvailable:function(t){return!_.isUndefined(this.blockTypes[t])},_ensureAndSetElements:function(){if(_.isUndefined(this.options.el)||_.isEmpty(this.options.el))return SirTrevor.log("You must provide an el"),!1;this.$el=this.options.el,this.el=this.options.el[0],this.$form=this.$el.parents("form");var $outer=$("<div>").attr({id:this.ID,"class":"st-outer",dropzone:"copy link move"}),$wrapper=$("<div>").attr({"class":"st-blocks"});return this.$el.wrap($outer).wrap($wrapper),this.$outer=this.$form.find("#"+this.ID),this.$wrapper=this.$outer.find(".st-blocks"),!0},_createDynamicBlocks:function(){var options=this.options;_.isUndefined(options.dynamicBlocks)||_.each(options.dynamicBlocks,function(dynamicBlockParams,dynamicBlockName){_.each(dynamicBlockParams,function(dynamicBlockParam){var dynamicBlock=SirTrevor.DynamicBlocks[dynamicBlockName](dynamicBlockParam),type=_.classify("DynamicBlock"+dynamicBlockName+dynamicBlock.type);dynamicBlock.type=type,SirTrevor.Blocks[type]=SirTrevor.Block.extend(dynamicBlock),_.isUndefined(options.blockTypes)||options.blockTypes.push(type)})})},_setBlocksTypes:function(){this.blockTypes=_.flattern(_.isUndefined(this.options.blockTypes)?SirTrevor.Blocks:this.options.blockTypes)},_setRequired:function(){_.isArray(this.options.required)&&!_.isEmpty(this.options.required)?this.required=this.options.required:this.required=!1},_extendLocales:function(){function deepObjectExtend(target,source){return _.each(source,function(value,key){target.hasOwnProperty(key)&&"object"==typeof target?deepObjectExtend(target[key],value):target[key]=value}),target}_.isObject(this.options.locales)&&deepObjectExtend(SirTrevor.Locales,this.options.locales)}}),SirTrevorEditor}(),SirTrevor.setDefaults=function(options){SirTrevor.DEFAULTS=_.extend(SirTrevor.DEFAULTS,options||{})},SirTrevor.bindFormSubmit=function(form){formBound||(new SirTrevor.Submittable(form),form.on("submit.sirtrevor",this.onFormSubmit),formBound=!0)},SirTrevor.onBeforeSubmit=function(should_validate){var errors=0;return _.each(SirTrevor.instances,function(inst,i){errors+=inst.onFormSubmit(should_validate)}),SirTrevor.log("Total errors: "+errors),errors},SirTrevor.onFormSubmit=function(ev){var errors=SirTrevor.onBeforeSubmit();errors>0&&(SirTrevor.EventBus.trigger("onError"),ev.preventDefault())},SirTrevor.getInstance=function(identifier){return _.isUndefined(identifier)?this.instances[0]:_.isString(identifier)?_.find(this.instances,function(editor){return editor.ID===identifier}):this.instances[identifier]},SirTrevor.setBlockOptions=function(type,options){var block=SirTrevor.Blocks[type];_.isUndefined(block)||_.extend(block.prototype,options||{})},SirTrevor.runOnAllInstances=function(method){_.has(SirTrevor.Editor.prototype,method)?([].unshift.call(arguments,SirTrevor.instances),_.invoke.apply(_,arguments)):SirTrevor.log("method doesn't exist")}}(jQuery,_);
10
+ !function($,_){function $element(el){return el instanceof $?el:$(el)}var SirTrevor,root=this;SirTrevor=root.SirTrevor={},SirTrevor.DEBUG=!1,SirTrevor.SKIP_VALIDATION=!1,SirTrevor.version="0.3.0",SirTrevor.LANGUAGE="de",SirTrevor.DEFAULTS={defaultType:!1,spinner:{className:"st-spinner",lines:9,length:8,width:3,radius:6,color:"#000",speed:1.4,trail:57,shadow:!1,left:"50%",top:"50%"},blockLimit:0,blockTypeLimits:{},required:[],uploadUrl:"/attachments",baseImageUrl:"/sir-trevor-uploads/",errorsContainer:void 0,toMarkdown:{aggresiveHTMLStrip:!1}},SirTrevor.BlockMixins={},SirTrevor.Blocks={},SirTrevor.Formatters={},SirTrevor.instances=[],SirTrevor.Events=Eventable;var formBound=!1,FunctionBind={bound:[],_bindFunctions:function(){this.bound.length>0&&_.bindAll.apply(null,_.union([this],this.bound))}},Renderable={tagName:"div",className:"sir-trevor__view",attributes:{},$:function(selector){return this.$el.find(selector)},render:function(){return this},destroy:function(){_.isUndefined(this.stopListening)||this.stopListening(),this.$el.remove()},_ensureElement:function(){if(this.el)this._setElement(this.el);else{var html,attrs=_.extend({},_.result(this,"attributes"));this.id&&(attrs.id=this.id),this.className&&(attrs["class"]=this.className),attrs.html&&(html=attrs.html,delete attrs.html);var $el=$("<"+this.tagName+">").attr(attrs);html&&$el.html(html),this._setElement($el)}},_setElement:function(element){return this.$el=$element(element),this.el=this.$el[0],this}};!function($){function dragEnter(e){e.preventDefault()}function dragOver(e){e.originalEvent.dataTransfer.dropEffect="copy",$(e.currentTarget).addClass("st-drag-over"),e.preventDefault()}function dragLeave(e){$(e.currentTarget).removeClass("st-drag-over"),e.preventDefault()}function setCaret(collapseToStart){return function(){var range,selection;return range=document.createRange(),range.selectNodeContents(this[0]),range.collapse(collapseToStart),selection=window.getSelection(),selection.removeAllRanges(),selection.addRange(range),this}}$.fn.dropArea=function(){return this.bind("dragenter",dragEnter).bind("dragover",dragOver).bind("dragleave",dragLeave),this},$.fn.noDropArea=function(){return this.unbind("dragenter").unbind("dragover").unbind("dragleave"),this},$.fn.caretToEnd=setCaret(!1),$.fn.caretToStart=setCaret(!0)}(jQuery);var extend=function(protoProps,staticProps){var child,parent=this;child=protoProps&&_.has(protoProps,"constructor")?protoProps.constructor:function(){return parent.apply(this,arguments)},_.extend(child,parent,staticProps);var Surrogate=function(){this.constructor=child};return Surrogate.prototype=parent.prototype,child.prototype=new Surrogate,protoProps&&_.extend(child.prototype,protoProps),child.__super__=parent.prototype,child};SirTrevor.log=function(message){!_.isUndefined(console)&&SirTrevor.DEBUG&&console.log(message)},SirTrevor.generateUUID=function(){return"aaaaaaaa-aaaa-4aaa-baaa-aaaaaaaaaaaa".replace(/[ab]/g,function(c){var random=16*Math.random()%16|0;return"b"===c&&(random=7&random|8),random.toString(16)})},SirTrevor.Locales={en:{general:{add:"Add Content",deleteElement:"Delete Element","delete":"Delete?",drop:"Drag __block__ here",paste:"Or paste URL here",upload:"…or choose a file",close:"close",position:"Change position",wait:"Please wait…",link:"Enter a link",note:"Note",style:"Style",source:"Source"},errors:{title:"You have the following errors:",validation_fail:"__type__ block is invalid",block_empty:"__name__ must not be empty",type_missing:"You must have a block of type __type__",required_type_empty:"A required block type __type__ is empty",load_fail:"There was a problem loading the contents of the document"},autosave:{longExplanation:"This article was loaded from your browsers cache. It was changed locally and not saved on the server. You can keep the changes by saving or discard them.",discard:"Discard changes"},blocks:{text:{title:"Text"},list:{title:"List"},quote:{title:"Cite",credit_field:"Credit"},extended_quote:{title:"Extended Cite",credit_field:"Credit"},extended_image:{title:"Image",caption_field:"Caption",caption_placeholder:"Caption",target_url_field:"Link target URL",target_url_placeholder:"Link target URL",copyright_field:"Copyright",copyright_placeholder:"Copyright",upload_error:"There was a problem with your upload",fullwidth:"Page width",bodywidth:"Article width","default":"Small"},image:{title:"Image",upload_error:"There was a problem with your upload"},definition:{title:"Glossary",term:"Term",description:"Description"},divider:{title:"Divider"},reward_list:{title:"Reward List"},audio:{title:"Audio"},infographic:{title:"Infographic"},video:{title:"Video"},facebookpost:{title:"Facebook Post"},tweet:{title:"Tweet",fetch_error:"There was a problem fetching your tweet"},embedly:{title:"Embedly",fetch_error:"There was a problem fetching your embed",key_missing:"An Embedly API key must be present"},heading:{title:"Heading"},remote_list:{fetch_error:"There was a problem fetching the list!",maximumselected:"You can not select any more items!"},html:{title:"Html"},instagram:{title:"Instagram"}}},de:{general:{add:"Absatz hinzufügen",deleteElement:"Absatz löschen","delete":"Löschen?",drop:"__block__ hierher bewegen",paste:"Oder URL hier einfügen",upload:"…oder Datei auswählen",close:"Schließen",position:"Absatz verschieben",wait:"Bitte warten…",link:"Link eingeben",note:"Anmerkung",style:"Darstellung",source:"Quelle"},errors:{title:"Folgende Fehler sind aufgetreten:",validation_fail:"__type__ Block ist nicht gültig",block_empty:"__name__ darf nicht leer sein",type_missing:"Es wird ein Block vom Typ __type__ benötigt",required_type_empty:"Ein benötigter Block vom Typ __type__ ist leer",load_fail:"Es gab ein Problem beim Laden der Daten für dieses Dokument"},autosave:{longExplanation:"Dieser Artikel wurde aus dem Zwischenspeicher dieses Browsers geladen. Er wurde zuvor geändert und nicht auf dem Server gesichert. Du kannst die Änderungen beibehalten indem du speicherst oder die Änderungen verwerfen.",discard:"Verwerfen"},blocks:{text:{title:"Lauftext"},list:{title:"Liste"},quote:{title:"Zitat",credit_field:"Quelle"},extended_quote:{title:"Erweitertes Zitat",credit_field:"Quelle"},extended_image:{title:"Bild",caption_field:"Bildunterzeile",caption_placeholder:"Bildunterzeile",target_url_field:"URL für das Linkziel",target_url_placeholder:"URL für das Linkziel",copyright_field:"Fotograf",copyright_placeholder:"Fotograf",upload_error:"es gab ein problem beim hochladen",fullwidth:"Seitenbreite",bodywidth:"Artikelbreite","default":"Kleine"},image:{title:"Bild",upload_error:"es gab ein problem beim hochladen"},definition:{title:"Glossar",term:"Begriff",description:"Beschreibung"},divider:{title:"Trenner"},reward_list:{title:"Prämienliste"},audio:{title:"Audio"},infographic:{title:"Infografik"},video:{title:"Video"},facebookpost:{title:"Facebook Post"},tweet:{title:"Tweet",fetch_error:"There was a problem fetching your tweet"},embedly:{title:"Embedly",fetch_error:"There was a problem fetching your embed",key_missing:"An Embedly API key must be present"},heading:{title:"Überschrift"},remote_list:{fetch_error:"Liste konnte nicht geladen werden!",maximumselected:"Du kannst nicht mehr Elemente auswählen!"},html:{title:"Html"},instagram:{title:"Instagram"}}}},void 0===window.i18n||void 0===window.i18n.init?(SirTrevor.log("Using i18n stub"),window.i18n={t:function(key,options){var str,obj,part,i,parts=key.split(":");for(obj="undefined"!=typeof SirTrevorUserLanguage?SirTrevor.Locales[SirTrevorUserLanguage]||SirTrevor.Locales[SirTrevor.LANGUAGE]:SirTrevor.Locales[SirTrevor.LANGUAGE],i=0;i<parts.length;i++)part=parts[i],_.isUndefined(obj[part])||(obj=obj[part]);return str=obj,_.isString(str)?(str.indexOf("__")>=0&&_.each(options,function(value,opt){str=str.replace("__"+opt+"__",value)}),str):""}}):(SirTrevor.log("Using i18next"),i18n.init({resStore:SirTrevor.Locales,fallbackLng:SirTrevor.LANGUAGE,ns:{namespaces:["general","blocks"],defaultNs:"general"}})),function(a,b,c){function g(a,c){var e,d=b.createElement(a||"div");for(e in c)d[e]=c[e];return d}function h(a){for(var b=1,c=arguments.length;c>b;b++)a.appendChild(arguments[b]);return a}function j(a,b,c,d){var g=["opacity",b,~~(100*a),c,d].join("-"),h=.01+c/d*100,j=Math.max(1-(1-a)/b*(100-h),a),k=f.substring(0,f.indexOf("Animation")).toLowerCase(),l=k&&"-"+k+"-"||"";return e[g]||(i.insertRule("@"+l+"keyframes "+g+"{0%{opacity:"+j+"}"+h+"%{opacity:"+a+"}"+(h+.01)+"%{opacity:1}"+(h+b)%100+"%{opacity:"+a+"}100%{opacity:"+j+"}}",0),e[g]=1),g}function k(a,b){var f,g,e=a.style;if(e[b]!==c)return b;for(b=b.charAt(0).toUpperCase()+b.slice(1),g=0;g<d.length;g++)if(f=d[g]+b,e[f]!==c)return f}function l(a,b){for(var c in b)a.style[k(a,c)||c]=b[c];return a}function m(a){for(var b=1;b<arguments.length;b++){var d=arguments[b];for(var e in d)a[e]===c&&(a[e]=d[e])}return a}function n(a){for(var b={x:a.offsetLeft,y:a.offsetTop};a=a.offsetParent;)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}var f,d=["webkit","Moz","ms","O"],e={},i=function(){var a=g("style");return h(b.getElementsByTagName("head")[0],a),a.sheet||a.styleSheet}(),o={lines:12,length:7,width:5,radius:10,rotate:0,color:"#000",speed:1,trail:100,opacity:.25,fps:20,zIndex:2e9,className:"spinner",top:"auto",left:"auto"},p=function q(a){return this.spin?void(this.opts=m(a||{},q.defaults,o)):new q(a)};p.defaults={},m(p.prototype,{spin:function(a){this.stop();var h,i,b=this,c=b.opts,d=b.el=l(g(0,{className:c.className}),{position:"relative",zIndex:c.zIndex}),e=c.radius+c.length+c.width;if(a&&(a.insertBefore(d,a.firstChild||null),i=n(a),h=n(d),l(d,{left:("auto"==c.left?i.x-h.x+(a.offsetWidth>>1):c.left+e)+"px",top:("auto"==c.top?i.y-h.y+(a.offsetHeight>>1):c.top+e)+"px"})),d.setAttribute("aria-role","progressbar"),b.lines(d,b.opts),!f){var j=0,k=c.fps,m=k/c.speed,o=(1-c.opacity)/(m*c.trail/100),p=m/c.lines;!function q(){j++;for(var a=c.lines;a;a--){var e=Math.max(1-(j+a*p)%m*o,c.opacity);b.opacity(d,c.lines-a,e,c)}b.timeout=b.el&&setTimeout(q,~~(1e3/k))}()}return b},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=c),this},lines:function(a,b){function e(a,d){return l(g(),{position:"absolute",width:b.length+b.width+"px",height:b.width+"px",background:a,boxShadow:d,transformOrigin:"left",transform:"rotate("+~~(360/b.lines*c+b.rotate)+"deg) translate("+b.radius+"px,0)",borderRadius:(b.width>>1)+"px"})}for(var d,c=0;c<b.lines;c++)d=l(g(),{position:"absolute",top:1+~(b.width/2)+"px",transform:b.hwaccel?"translate3d(0,0,0)":"",opacity:b.opacity,animation:f&&j(b.opacity,b.trail,c,b.lines)+" "+1/b.speed+"s linear infinite"}),b.shadow&&h(d,l(e("#000","0 0 4px #000"),{top:"2px"})),h(a,h(d,e(b.color,"0 0 1px rgba(0,0,0,.1)")));return a},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}}),!function(){function a(a,b){return g("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',b)}var b=l(g("group"),{behavior:"url(#default#VML)"});!k(b,"transform")&&b.adj?(i.addRule(".spin-vml","behavior:url(#default#VML)"),p.prototype.lines=function(b,c){function f(){return l(a("group",{coordsize:e+" "+e,coordorigin:-d+" "+-d}),{width:e,height:e})}function k(b,e,g){h(i,h(l(f(),{rotation:360/c.lines*b+"deg",left:~~e}),h(l(a("roundrect",{arcsize:1}),{width:d,height:c.width,left:c.radius,top:-c.width>>1,filter:g}),a("fill",{color:c.color,opacity:c.opacity}),a("stroke",{opacity:0}))))}var j,d=c.length+c.width,e=2*d,g=2*-(c.width+c.length)+"px",i=l(f(),{position:"absolute",top:g,left:g});if(c.shadow)for(j=1;j<=c.lines;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;j<=c.lines;j++)k(j);return h(b,i)},p.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}):f=k(b,"animation")}(),a.Spinner=p}(window,document),SirTrevor.editorStore=function(editor,method,options){var resp;options=options||{},Version=function(version){var results;try{results=/(\d+)\.(\d+)/.exec(version),this.version=results[0],this.major=results[1],this.minor=results[2]}catch(e){results=/(\d+)/.exec(version),this.version=results[0],this.major=results[1],this.minor="0",this.recreateVersion()}return this},Version.prototype={minorVersion:function(){return parseInt(this.minor,10)},incrementMinorVersion:function(){return this.minor=(this.minorVersion()+1).toString(),this.recreateVersion()},majorVersion:function(){return parseInt(this.major,10)},incrementMajorVersion:function(){return this.major=(this.majorVersion()+1).toString(),this.minor="0",this.recreateVersion()},recreateVersion:function(){return this.version=this.major+"."+this.minor,this},gt:function(version){return this.majorVersion()>version.majorVersion()?!0:this.majorVersion()===version.majorVersion()?this.minorVersion()>version.minorVersion():!1},toString:function(){return this.version}};var newVersion,reset=function(){var oldDataStore=editor.dataStore;editor.dataStore={data:[]},void 0!==oldDataStore&&(editor.dataStore.version=oldDataStore.version,editor.dataStore.uuid=oldDataStore.uuid,editor.dataStore.server_version=oldDataStore.server_version,editor.dataStore.server_uuid=oldDataStore.server_uuid),ensureMetadata()},ensureMetadata=function(){ensureUUID(),ensureVersion(),ensureModelName()},ensureModelName=function(){void 0===editor.dataStore.modelName&&(editor.dataStore.modelName=editor.options.modelName)},ensureUUID=function(){void 0===editor.dataStore.uuid&&(editor.dataStore.uuid=SirTrevor.generateUUID())},ensureVersion=function(){void 0===editor.dataStore.version&&(editor.dataStore.version="0.0")},isNewArticle=function(){var content=_.trim(editor.$el.val());return""===content||void 0===JSON.parse(content).server_uuid},getLatestUnsavedFromUUIDs=function(uuids){var name=editor.options.modelName,urlPrefix=editor.options.baseURL;return _.find(uuids,function(uuid){var result=$.ajax({type:"GET",url:urlPrefix+uuid+"/version",async:!1});return!(result.responseJSON&&result.responseJSON[name]&&result.responseJSON[name].server_version)})},parseKeyData=function(key){try{return JSON.parse(localStorage.getItem(key))}catch(e){return{}}},getAllKeys=function(prefix){return prefix=prefix||"st-",_.filter(Object.keys(localStorage),function(key){var modelName=parseKeyData(key).modelName||editor.options.modelName;return 0===key.lastIndexOf(prefix)&&modelName===editor.options.modelName})},getKeysWithoutServerUUID=function(){return _.filter(getAllKeys(),function(key){return void 0===parseKeyData(key).server_uuid}).map(getUUIDFromKey)},newestDocumentForUUID=function(uuid){if(editor.options.localStorage!==!0)return{};var i,prefix="st-"+uuid,versions=getAllKeys(prefix).map(function(e){return new Version(/version-(\d+(?:\.\d+)?)/.exec(e)[1])}),result=versions[0];for(i=0;i<versions.length;i++)versions[i].gt(result)&&(result=versions[i]);return void 0===result?null:{version:result.toString(),dataStore:localStorage[prefix+"-version-"+result.toString()]}},getUUIDFromKey=function(key){return/st-(.*)-version-(\d+(?:\.\d+)?)/.exec(key)[1]},getAllUUIDs=function(){return _.uniq(getAllKeys().map(getUUIDFromKey))},removeAllForUUID=function(uuid){for(var key,document,stop=!1;!stop&&(document=newestDocumentForUUID(uuid),null!==document);)key="st-"+uuid+"-version-"+document.version,stop=!localStorage.hasOwnProperty(key),localStorage.removeItem(key)},removeOldAutosaves=function(){var uuids=getAllUUIDs(),keysToKeep=uuids.map(function(uuid){return"st-"+uuid+"-version-"+newestDocumentForUUID(uuid).version});_.each(getAllKeys(),function(key){-1===$.inArray(key,keysToKeep)&&localStorage.removeItem(key)})},askUserForConfirmation=function(){return!0},promptRestoration=function(){var warn=$('<div class="st-autoload-info">'+i18n.t("autosave:longExplanation")+"<br></div>"),discard=$('<a href="#" class="st-autoload-discard-button">'+i18n.t("autosave:discard")+"</a>"),close=$('<a href="#" class="st-autoload-close-button"><span class="icon--close" aria-hidden="true"></span><span class="visuallyhidden>close</span></a>');warn.append(discard),warn.append(close),close.on("click",function(e){return e.preventDefault(),warn.remove(),!1}),discard.on("click",function(e){return e.preventDefault(),editor.store("restore"),warn.remove(),!1}),editor.$outer.prepend(warn)};switch(method){case"autosave":newVersion=new Version(editor.dataStore.version).incrementMinorVersion().toString(),editor.dataStore.version=newVersion;var store=editor.dataStore,value=store.data.length>0?JSON.stringify(editor.dataStore):"",key="st-"+store.uuid+"-version-"+store.version;window.localStorage.setItem(key,value),removeOldAutosaves();break;case"restore":removeAllForUUID(editor.dataStore.uuid),editor.reinitialize();break;case"create":var document,str,uuids,unsaved,parsedStore,documentVersion,dataStoreVersion,content=_.trim(editor.$el.val());reset();try{str=JSON.parse(content),_.isUndefined(str.data)||(editor.dataStore=str,ensureMetadata())}catch(e){}if(isNewArticle())uuids=getKeysWithoutServerUUID(),unsaved=getLatestUnsavedFromUUIDs(uuids),void 0!==unsaved&&(document=newestDocumentForUUID(unsaved),null!==document&&(parsedStore=JSON.parse(document.dataStore),documentVersion=new Version(parsedStore.version),dataStoreVersion=new Version(editor.dataStore.version),documentVersion.gt(dataStoreVersion)&&askUserForConfirmation()&&(editor.dataStore=JSON.parse(document.dataStore),promptRestoration())));else try{document=newestDocumentForUUID(editor.dataStore.uuid),null!==document&&(parsedStore=JSON.parse(document.dataStore),documentVersion=new Version(parsedStore.version),dataStoreVersion=new Version(editor.dataStore.version),documentVersion.gt(dataStoreVersion)&&askUserForConfirmation()&&-1===document.dataStore.indexOf(JSON.stringify(editor.dataStore.data))&&(editor.dataStore=JSON.parse(document.dataStore),promptRestoration()))}catch(e){editor.errors.push({text:i18n.t("errors:load_fail")}),editor.renderErrors(),SirTrevor.log("Sorry there has been a problem with parsing the JSON"),SirTrevor.log(e)}break;case"reset":reset();break;case"add":options.data&&(editor.dataStore.data.push(options.data),resp=editor.dataStore);break;case"save":editor.dataStore.version=new Version(editor.dataStore.version).incrementMajorVersion().toString(),editor.$el.val(editor.dataStore.data.length>0?JSON.stringify(editor.dataStore):"");break;case"read":resp=editor.dataStore}return resp?resp:void 0},SirTrevor.Submittable=function($form){this.$form=$form,this.intialize()},_.extend(SirTrevor.Submittable.prototype,{intialize:function(){this.$submitBtn=this.$form.find("input[type='submit']");var btnTitles=[];_.each(this.$submitBtn,function(btn){btnTitles.push($(btn).attr("value"))}),this.submitBtnTitles=btnTitles,this.canSubmit=!0,this.globalUploadCount=0,this._bindEvents()},setSubmitButton:function(e,message){this.$submitBtn.attr("value",message)},resetSubmitButton:function(){_.each(this.$submitBtn,function(item,index){$(item).attr("value",this.submitBtnTitles[index])},this)},onUploadStart:function(e){this.globalUploadCount++,SirTrevor.log("onUploadStart called "+this.globalUploadCount),1===this.globalUploadCount&&this._disableSubmitButton()},onUploadStop:function(e){this.globalUploadCount=this.globalUploadCount<=0?0:this.globalUploadCount-1,SirTrevor.log("onUploadStop called "+this.globalUploadCount),0===this.globalUploadCount&&this._enableSubmitButton()},onError:function(e){SirTrevor.log("onError called"),this.canSubmit=!1},_disableSubmitButton:function(message){this.setSubmitButton(null,message||i18n.t("general:wait")),this.$submitBtn.attr("disabled","disabled").addClass("disabled")},_enableSubmitButton:function(){this.resetSubmitButton(),this.$submitBtn.removeAttr("disabled").removeClass("disabled")},_events:{disableSubmitButton:"_disableSubmitButton",enableSubmitButton:"_enableSubmitButton",setSubmitButton:"setSubmitButton",resetSubmitButton:"resetSubmitButton",onError:"onError",onUploadStart:"onUploadStart",onUploadStop:"onUploadStop"},_bindEvents:function(){_.forEach(this._events,function(callback,type){SirTrevor.EventBus.on(type,this[callback],this)},this)}}),SirTrevor.fileUploader=function(block,file,success,error){var uid=[block.blockID,(new Date).getTime(),"raw"].join("-"),data=new FormData,blockData=block.getData(),instance=SirTrevor.getInstance(block.instanceID);data.append("attachment[name]",file.name),data.append("attachment[file]",file),data.append("attachment[uid]",uid),void 0!==blockData&&data.append("block-uuid",blockData.uuid),void 0!==instance.dataStore&&data.append("article-uuid",instance.dataStore.uuid),void 0!==instance.options&&(data.append("model-name",instance.options.modelName),data.append("column-name",instance.options.columnName)),block.resetMessages();var callbackSuccess=function(){SirTrevor.log("Upload callback called"),!_.isUndefined(success)&&_.isFunction(success)&&success.apply(block,arguments)},callbackError=function(){SirTrevor.log("Upload callback error called"),!_.isUndefined(error)&&_.isFunction(error)&&error.apply(block,arguments)},xhr=$.ajax({url:SirTrevor.DEFAULTS.uploadUrl,data:data,cache:!1,contentType:!1,processData:!1,dataType:"json",type:"POST"});return block.addQueuedItem(uid,xhr),xhr.done(callbackSuccess).fail(callbackError).always(_.bind(block.removeQueuedItem,block,uid)),xhr};var url_regex=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;_.mixin({isURI:function(string){return url_regex.test(string)},titleize:function(str){return null===str?"":(str=String(str).toLowerCase(),str.replace(/(?:^|\s|-)\S/g,function(c){return c.toUpperCase()}))},classify:function(str){return _.titleize(String(str).replace(/[\W_]/g," ")).replace(/\s/g,"")},classifyList:function(a){return _.map(a,function(i){return _.classify(i)})},capitalize:function(string){return string.charAt(0).toUpperCase()+string.substring(1).toLowerCase()},underscored:function(str){return _.trim(str).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},trim:function(string){return string.replace(/^\s\s*/,"").replace(/\s\s*$/,"")},reverse:function(str){return str.split("").reverse().join("")},flattern:function(obj){var x={};return _.each(obj,function(a,b){x[_.isArray(obj)?a:b]=!0}),x},to_slug:function(str){return str.toLowerCase().replace(/[^\w ]+/g,"").replace(/ +/g,"-")}}),SirTrevor.toHTML=function(markdown,type){type=_.classify(type);var html=markdown,shouldWrap="Text"===type;_.isUndefined(shouldWrap)&&(shouldWrap=!1),shouldWrap&&(html="<div>"+html),html=html.replace(/\[([^\]]+)\]\(([^\)]+)\)/gm,function(match,p1,p2){return"<a href='"+p2+"'>"+p1.replace(/\r?\n/g,"")+"</a>"}),html=_.reverse(_.reverse(html).replace(/_(?!\\)((_\\|[^_])*)_(?=$|[^\\])/gm,function(match,p1){return">i/<"+p1.replace(/\r?\n/g,"").replace(/[\s]+$/,"")+">i<"}).replace(/\*\*(?!\\)((\*\*\\|[^\*\*])*)\*\*(?=$|[^\\])/gm,function(match,p1){return">b/<"+p1.replace(/\r?\n/g,"").replace(/[\s]+$/,"")+">b<"})),html=html.replace(/^\> (.+)$/gm,"$1");var formatName,format;for(formatName in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(formatName)&&(format=SirTrevor.Formatters[formatName],!_.isUndefined(format.toHTML)&&_.isFunction(format.toHTML)&&(html=format.toHTML(html)));var block;return SirTrevor.Blocks.hasOwnProperty(type)&&(block=SirTrevor.Blocks[type],!_.isUndefined(block.prototype.toHTML)&&_.isFunction(block.prototype.toHTML)&&(html=block.prototype.toHTML(html))),shouldWrap&&(html=html.replace(/\r?\n\r?\n/gm,"</div><div><br></div><div>"),html=html.replace(/\r?\n/gm,"</div><div>")),html=html.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;").replace(/\r?\n/g,"<br>").replace(/\*\*/,"").replace(/__/,""),html=html.replace(/\\\*/g,"*").replace(/\\\[/g,"[").replace(/\\\]/g,"]").replace(/\\\_/g,"_").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\-/g,"-"),shouldWrap&&(html+="</div>"),html},SirTrevor.toMarkdown=function(content,type){function replaceBolds(match,p1,p2,p3){return _.isUndefined(p3)&&(p3=""),p1+"**"+p2.replace(/<(.)?br(.)?>/g,"")+"**"+p3}function replaceItalics(match,p1,p2,p3){return _.isUndefined(p3)&&(p3=""),p1+"_"+p2.replace(/<(.)?br(.)?>/g,"")+"_"+p3}function replaceHyperlinks(match,p1,p2,p3,p4){return p2+"["+p3.trim().replace(/<(.)?br(.)?>/g,"")+"]("+p1+")"+p4}type=_.classify(type);var markdown=content;markdown=markdown.replace(/&nbsp;/g," "),markdown=markdown.replace(/( class=(")?Mso[a-zA-Z]+(")?)/g,"").replace(/<!--(.*?)-->/g,"").replace(/\/\*(.*?)\*\//g,"").replace(/<(\/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>/gi,"");var tagStripper,i,badTags=["style","script","applet","embed","noframes","noscript"];for(i=0;i<badTags.length;i++)tagStripper=new RegExp("<"+badTags[i]+".*?"+badTags[i]+"(.*?)>","gi"),markdown=markdown.replace(tagStripper,"");markdown=markdown.replace(/\*/g,"\\*").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/\_/g,"\\_").replace(/\(/g,"\\(").replace(/\)/g,"\\)").replace(/\-/g,"\\-");var inlineTags=["em","i","strong","b"];for(i=0;i<inlineTags.length;i++)tagStripper=new RegExp("<"+inlineTags[i]+"><br></"+inlineTags[i]+">","gi"),markdown=markdown.replace(tagStripper,"<br>");markdown=markdown.replace(/<(\w+)(?:\s+\w+="[^"]+(?:"\$[^"]+"[^"]+)?")*>\s*<\/\1>/gim,"").replace(/\n/gm," ").replace(/<a.*?href=[""'](.*?)[""'].*?>(\s*)(.*?)(\s*)<\/a>/gim,replaceHyperlinks).replace(/<strong>(\s*)(.*?)(\s)*?<\/strong>/gim,replaceBolds).replace(/<b>(\s*)(.*?)(\s*)?<\/b>/gim,replaceBolds).replace(/<em>(\s*)(.*?)(\s*)?<\/em>/gim,replaceItalics).replace(/<i>(\s*)(.*?)(\s*)?<\/i>/gim,replaceItalics);var formatName,format;for(formatName in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(formatName)&&(format=SirTrevor.Formatters[formatName],!_.isUndefined(format.toMarkdown)&&_.isFunction(format.toMarkdown)&&(markdown=format.toMarkdown(markdown)));markdown=markdown.replace(/([^<>]+)(<div>)/g,"$1\n$2").replace(/<div><div>/g,"\n<div>").replace(/(?:<div>)([^<>]+)(?:<div>)/g,"$1\n").replace(/(?:<div>)(?:<br>)?([^<>]+)(?:<br>)?(?:<\/div>)/g,"$1\n").replace(/<\/p>/g,"\n\n").replace(/<(.)?br(.)?>/g,"\n").replace(/&lt;/g,"<").replace(/&gt;/g,">");var block;return SirTrevor.Blocks.hasOwnProperty(type)&&(block=SirTrevor.Blocks[type],!_.isUndefined(block.prototype.toMarkdown)&&_.isFunction(block.prototype.toMarkdown)&&(markdown=block.prototype.toMarkdown(markdown))),markdown=SirTrevor.DEFAULTS.toMarkdown.aggresiveHTMLStrip?markdown.replace(/<\/?[^>]+(>|$)/g,""):markdown.replace(/<(?=\S)\/?[^>]+(>|$)/gi,"")},SirTrevor.EventBus=_.extend({},SirTrevor.Events),SirTrevor.BlockMixins.Ajaxable={mixinName:"Ajaxable",ajaxable:!0,initializeAjaxable:function(){this._queued=[]},addQueuedItem:function(name,deferred){SirTrevor.log("Adding queued item for "+this.blockID+" called "+name),SirTrevor.EventBus.trigger("onUploadStart",this.blockID),this._queued.push({name:name,deferred:deferred})},removeQueuedItem:function(name){SirTrevor.log("Removing queued item for "+this.blockID+" called "+name),SirTrevor.EventBus.trigger("onUploadStop",this.blockID),this._queued=_.reject(this._queued,function(queued){return queued.name==name})},hasItemsInQueue:function(){return this._queued.length>0},resolveAllInQueue:function(){_.each(this._queued,function(item){SirTrevor.log("Aborting queued request: "+item.name),item.deferred.abort()},this)}},SirTrevor.BlockMixins.Controllable={mixinName:"Controllable",initializeControllable:function(){SirTrevor.log("Adding controllable to block "+this.blockID),this.$control_ui=$("<div>",{"class":"st-block__control-ui"}),_.each(this.controls,function(handler,cmd){this.addUiControl(cmd,_.bind(handler,this))},this),this.$inner.append(this.$control_ui)},getControlTemplate:function(cmd){return $("<a>",{"data-icon":cmd,"class":"st-icon st-block-control-ui-btn st-block-control-ui-btn--"+cmd})},addUiControl:function(cmd,handler){this.$control_ui.append(this.getControlTemplate(cmd)),this.$control_ui.on("click",".st-block-control-ui-btn--"+cmd,handler)}},SirTrevor.BlockMixins.Droppable={mixinName:"Droppable",valid_drop_file_types:["File","Files","text/plain","text/uri-list"],initializeDroppable:function(){SirTrevor.log("Adding droppable to block "+this.blockID),this.drop_options=_.extend({},SirTrevor.DEFAULTS.Block.drop_options,this.drop_options);var drop_html=$(_.template(this.drop_options.html,{block:this}));this.$editor.hide(),this.$inputs.append(drop_html),this.$dropzone=drop_html,this.$dropzone.dropArea().bind("drop",_.bind(this._handleDrop,this)),this.$inner.addClass("st-block__inner--droppable")},_handleDrop:function(e){e.preventDefault(),e=e.originalEvent;var el=$(e.target),types=e.dataTransfer.types;el.removeClass("st-dropzone--dragover"),!_.isUndefined(types)&&_.some(types,function(type){return _.include(this.valid_drop_file_types,type)},this)&&this.onDrop(e.dataTransfer),SirTrevor.EventBus.trigger("block:content:dropped",this.blockID)}},SirTrevor.BlockMixins.Fetchable={mixinName:"Fetchable",initializeFetchable:function(){this.withMixin(SirTrevor.BlockMixins.Ajaxable)},fetch:function(options,success,failure){var uid=_.uniqueId(this.blockID+"_fetch"),xhr=$.ajax(options);return this.resetMessages(),this.addQueuedItem(uid,xhr),_.isUndefined(success)||xhr.done(_.bind(success,this)),_.isUndefined(failure)||xhr.fail(_.bind(failure,this)),xhr.always(_.bind(this.removeQueuedItem,this,uid)),xhr}},SirTrevor.BlockMixins.Pastable={mixinName:"Pastable",initializePastable:function(){SirTrevor.log("Adding pastable to block "+this.blockID),this.paste_options=_.extend({},SirTrevor.DEFAULTS.Block.paste_options,this.paste_options),this.$inputs.append(_.template(this.paste_options.html,this)),this.$(".st-paste-block").bind("click",function(){$(this).select()}).bind("paste",this._handleContentPaste).bind("submit",this._handleContentPaste)}},SirTrevor.BlockMixins.Uploadable={mixinName:"Uploadable",uploadsCount:0,initializeUploadable:function(){SirTrevor.log("Adding uploadable to block "+this.blockID),this.withMixin(SirTrevor.BlockMixins.Ajaxable),this.upload_options=_.extend({},SirTrevor.DEFAULTS.Block.upload_options,this.upload_options),this.$inputs.append(_.template(this.upload_options.html,this))},uploader:function(file,success,failure){return SirTrevor.fileUploader(this,file,success,failure)}},SirTrevor.BlockNotes=function(){var BlockNotes=function(block_element,instance_id,block){this.$block=block_element,this.instanceID=instance_id,this.block=block,this.changeable=block.changeable,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockNotes.prototype,FunctionBind,Renderable,{bound:["toggle"],notesClassName:"st-block-is-note",className:"btn--editor-panel",visibleClass:"st-block-notes--is-visible",attributes:{html:'<span class="icon--note" aria-hidden="true"></span><span class="btn__label">'+i18n.t("general:note")+"</span>"},OFF_STATE:"no",ON_STATE:"yes",toggle:function(){var val=this.hiddenInput.val();return this.$block.toggleClass(this.notesClassName),this.hiddenInput.val(val===this.ON_STATE?this.OFF_STATE:this.ON_STATE)},instrumentBlock:function(){var data=this.block.getData();this.hiddenInput=$("<input class='st-input-string js-note-input' name='note' type='hidden' value='"+this.OFF_STATE+"'></input>"),this.block.$el.append(this.hiddenInput),data.note===this.ON_STATE&&this.toggle()},initialize:function(){this.instrumentBlock(),this.$el.on("click",this,this.toggle)}}),BlockNotes}(),SirTrevor.BlockReorder=function(){var BlockReorder=function(block_element,instance_id){this.$block=block_element,this.blockID=this.$block.attr("id"),this.instanceID=instance_id,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockReorder.prototype,FunctionBind,Renderable,{bound:["onMouseDown","onClick","onDragStart","onDragEnd","onDrag","onDrop"],className:"btn--editor-panel btn--with-rocker",tagName:"div",attributes:function(){return{html:'<span class="btn--rocker"><button type="button" class="btn--rocker__up"><span class="icon--dropup"></span></button><button type="button" class="btn--rocker__down"><span class="icon--dropdown"></span></button></span><span class="btn__label">'+i18n.t("general:position")+"</span>",
11
+ draggable:"true"}},initialize:function(){this.$el.bind("mousedown touchstart",this.onMouseDown).bind("click",this.onClick).bind("dragstart",this.onDragStart).bind("dragend touchend",this.onDragEnd).bind("drag touchmove",this.onDrag),this.$block.dropArea().bind("drop",this.onDrop)},onMouseDown:function(){SirTrevor.EventBus.trigger("block:reorder:down",this.blockID)},onDrop:function(ev){ev.preventDefault();var dropped_on=this.$block,item_id=ev.originalEvent.dataTransfer.getData("text/plain"),block=$("#"+item_id);_.isUndefined(item_id)||_.isEmpty(block)||dropped_on.attr("id")==item_id||dropped_on.attr("data-instance")!=block.attr("data-instance")||dropped_on.after(block),SirTrevor.EventBus.trigger("block:reorder:dropped",item_id)},onDragStart:function(ev){var btn=$(ev.currentTarget).parent(),self=this,scrollTop=$("body").scrollTop(),position=this.$block.position();ev.originalEvent.dataTransfer.setDragImage(this.$block[0],btn.position().left,btn.position().top),ev.originalEvent.dataTransfer.setData("Text",this.blockID),window.setTimeout(function(){SirTrevor.EventBus.trigger("block:reorder:dragstart",self.blockID),self.$block.addClass("st-block--dragging"),$("body").scrollTop(scrollTop-position.top+self.$block.position().top)},0)},onDragEnd:function(ev){var scrollTop=$("body").scrollTop(),position=this.$block.position();SirTrevor.EventBus.trigger("block:reorder:dragend",this.blockID),this.$block.removeClass("st-block--dragging"),$("body").scrollTop(scrollTop-position.top+this.$block.position().top)},onDrag:function(ev){},onClick:function(event){var $target,idx;event.preventDefault(),$target=$(event.target).closest("button"),idx=this.$block.index(".st-block"),$target.hasClass("btn--rocker__up")?SirTrevor.EventBus.trigger(this.instanceID+":blocks:change_position",this.$block,idx,"before"):$target.hasClass("btn--rocker__down")&&SirTrevor.EventBus.trigger(this.instanceID+":blocks:change_position",this.$block,idx+2,"before")},render:function(){return this}}),BlockReorder}(),SirTrevor.BlockAdd=function(){var BlockAdd=function(block_element){this.$block=block_element,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockAdd.prototype,FunctionBind,Renderable,SirTrevor.Events,{tagName:"a",className:"btn--editor-panel",attributes:{html:'<span class="icon--plus" aria-hidden="true"></span><span class="btn__label">'+i18n.t("general:add")+"</span>"},bound:["create"],create:function(e){SirTrevor.EventBus.trigger("showBlockControls",this.$block)},initialize:function(){this.$el.on("click",this,this.create)}}),BlockAdd}(),SirTrevor.BlockStyles=function(){var BlockStyles=function(block_element,instance_id,block){return block.styleable?(this.$block=block_element,this.instanceID=instance_id,this.block=block,this._ensureElement(),this._bindFunctions(),void this.initialize()):!1};return _.extend(BlockStyles.prototype,FunctionBind,Renderable,SirTrevor.Events,{tagName:"a",className:"btn--editor-panel",attributes:{html:' <span class="btn__label">'+i18n.t("general:style")+"</span>"},bound:["updateValue","onSelectChange"],create:function(e){SirTrevor.EventBus.trigger("showBlockControls",this.$block)},instrumentBlock:function(){var data=this.block.getData();this.hiddenInput=$("<input class='st-input-string js-style-input' name='style' type='hidden' value=''></input>"),this.block.$el.append(this.hiddenInput),this.$el.find("select").val(data.style),this.updateValue(data.style)},availableStyles:function(){return this.block.styles},updateValue:function(val){this.hiddenInput.val(val),this.updateClass(val)},updateClass:function(val){var styles=this.availableStyles(),$el=this.block.$el,classNames=styles.map(function(e){return e.className});$el.removeClass(classNames.join(" "));try{var targetClassName=styles.filter(function(e){return e.value===val}).pop().className;$el.addClass(targetClassName)}catch(e){console.log("Ignoring a style that seems obsolete in current configuration")}},onSelectChange:function(event){var value=event.target.value;this.updateValue(value)},initialize:function(){for(var styles=this.availableStyles(),select="<select>",i=0;i<styles.length;i++)select+='<option value="'+styles[i].value+'">'+styles[i].name+"</option>";select+="</select>",select=$(select),select.on("change",this.onSelectChange),this.$el.prepend(select),this.instrumentBlock()}}),BlockStyles}(),SirTrevor.BlockDeletion=function(){var BlockDeletion=function(){this._ensureElement(),this._bindFunctions()};return _.extend(BlockDeletion.prototype,FunctionBind,Renderable,{tagName:"a",className:"btn--editor-panel btn--editor-panel--delete",attributes:{html:'<span class="icon--bin" aria-hidden="true"></span><span class="btn__label">'+i18n.t("general:deleteElement")+"</span>"}}),BlockDeletion}();var bestNameFromField=function(field){var msg=field.attr("data-st-name")||field.attr("name");return msg||(msg="Field"),_.capitalize(msg)};SirTrevor.BlockValidations={errors:[],valid:function(){return this.performValidations(),0===this.errors.length},performValidations:function(){this.resetErrors();var required_fields=this.$(".st-required");_.each(required_fields,this.validateField,this),_.each(this.validations,this.runValidator,this),this.$el.toggleClass("st-block--with-errors",this.errors.length>0)},validations:[],validateField:function(field){field=$(field);var content=field.attr("contenteditable")?field.text():field.val();0===content.length&&this.setError(field,i18n.t("errors:block_empty",{name:bestNameFromField(field)}))},runValidator:function(validator){_.isUndefined(this[validator])||this[validator].call(this)},setError:function(field,reason){var $msg=this.addMessage(reason,"st-msg--error");field.addClass("st-error"),this.errors.push({field:field,reason:reason,msg:$msg})},resetErrors:function(){_.each(this.errors,function(error){error.field.removeClass("st-error"),error.msg.remove()}),this.$messages.removeClass("st-block__messages--is-visible"),this.errors=[]}},SirTrevor.BlockStore={blockStorage:{},createStore:function(blockData){this.blockStorage={type:_.underscored(this.type),data:blockData||{}}},save:function(){this.toData()},saveAndReturnData:function(){return this.save(),this.blockStorage},saveAndGetData:function(){var store=this.saveAndReturnData();return store.data||store},getData:function(){return this.blockStorage.data},setData:function(blockData){SirTrevor.log("Setting data for block "+this.blockID),_.extend(this.blockStorage.data,blockData||{})},setAndRetrieveData:function(blockData){return this.setData(blockData),this.getData()},setAndLoadData:function(blockData){this.setData(blockData),this.beforeLoadingData()},toData:function(){},loadData:function(){},beforeLoadingData:function(){SirTrevor.log("loadData for "+this.blockID),SirTrevor.EventBus.trigger("block:loadData",this.blockID),this.loadData(this.getData())},_loadData:function(){SirTrevor.log("_loadData is deprecated and will be removed in the future. Please use beforeLoadingData instead."),this.beforeLoadingData()},checkAndLoadData:function(){_.isEmpty(this.getData())||this.beforeLoadingData()}},SirTrevor.SimpleBlock=function(){var SimpleBlock=function(data,instance_id){this.createStore(data),this.blockID=_.uniqueId("st-block-"),this.instanceID=instance_id,this._ensureElement(),this._bindFunctions(),this.initialize.apply(this,arguments)};return _.extend(SimpleBlock.prototype,FunctionBind,SirTrevor.Events,Renderable,SirTrevor.BlockStore,{focus:function(){},valid:function(){return!0},className:"st-block",block_template:_.template("<div class='st-block__inner'><%= editor_html %></div>"),attributes:function(){return{id:this.blockID,"data-type":this.type,"data-instance":this.instanceID}},title:function(){return _.titleize(this.type.replace(/[\W_]/g," "))},blockCSSClass:function(){return this.blockCSSClass=_.to_slug(this.type),this.blockCSSClass},type:"","class":function(){return _.classify(this.type)},editorHTML:"",initialize:function(){},onBlockRender:function(){},beforeBlockRender:function(){},_setBlockInner:function(){var editor_html=_.result(this,"editorHTML");this.$el.append(this.block_template({editor_html:editor_html})),this.$inner=this.$el.find(".st-block__inner"),this.$inner.bind("click",function(e){e.stopPropagation()})},render:function(){return this.beforeBlockRender(),this._setBlockInner(),this._blockPrepare(),this},_blockPrepare:function(){this._initUI(),this._initMessages(),this.checkAndLoadData(),this._initUUID(),this.$el.addClass("st-item-ready"),this.on("onRender",this.onBlockRender),this.save()},_initUUID:function(){var uuid=this.getData().uuid||SirTrevor.generateUUID();this.$el.append($("<input class='st-input-string js-uuid-input' name='uuid' type='hidden' value='"+uuid+"'></input>"))},_withUIComponent:function(component,className,callback){this.$ui.append(component.render().$el),className&&callback&&this.$ui.on("click",className,callback)},_initUI:function(){var ui_element=$("<div>",{"class":"st-block__ui"});this.$inner.append(ui_element),this.$ui=ui_element,this._initUIComponents()},_initMessages:function(){var msgs_element=$("<div>",{"class":"st-block__messages"});this.$inner.prepend(msgs_element),this.$messages=msgs_element},addMessage:function(msg,additionalClass){var $msg=$("<span>",{html:msg,"class":"st-msg "+additionalClass});return this.$messages.append($msg).addClass("st-block__messages--is-visible"),$msg},resetMessages:function(){this.$messages.html("").removeClass("st-block__messages--is-visible")},_initUIComponents:function(){this._withUIComponent(new SirTrevor.BlockReorder(this.$el))}}),SimpleBlock.fn=SimpleBlock.prototype,SimpleBlock.extend=extend,SimpleBlock}(),SirTrevor.Block=function(){var Block=function(data,instance_id){SirTrevor.SimpleBlock.apply(this,arguments)},delete_template=["<div class='st-block__ui-delete-controls'>","<a class='btn--confirm-delete'><span class='icon--tick' aria-hidden='true'></span><span class='visuallyhidden'>Confirm delete</span></a>","<a class='btn--deny-delete'><span class='icon--cross' aria-hidden='true'></span><span class='visuallyhidden'>Do not delete</span></a>","<label class='st-block__delete-label'>","<%= i18n.t('general:delete') %>","</label>","</div>"].join("\n"),drop_options={html:['<div class="st-block__dropzone">','<span class="st-icon"><%= _.result(block, "icon_name") %></span>','<p><%= i18n.t("general:drop", { block: "<span>" + _.result(block, "title") + "</span>" }) %>',"</p></div>"].join("\n"),re_render_on_reorder:!1},paste_options={html:['<input type="text" placeholder="<%= i18n.t("general:paste") %>"',' class="st-block__paste-input st-paste-block">'].join("")},upload_options={html:['<div class="st-block__upload-container">','<input type="file" type="st-file-upload">','<button class="st-upload-btn"><%= i18n.t("general:upload") %></button>',"</div>"].join("\n")};return SirTrevor.DEFAULTS.Block={drop_options:drop_options,paste_options:paste_options,upload_options:upload_options},_.extend(Block.prototype,SirTrevor.SimpleBlock.fn,SirTrevor.BlockValidations,{bound:["_checkArrowKeysUp","_checkArrowKeysDown","_checkReturn","_checkBackspaceAtStartKeyDown","_checkBackspaceAtStartKeyUp","_handleContentPaste","_onFocus","_onBlur","onDrop","onDeleteClick","clearInsertedStyles","getSelectionForFormatter","onBlockRender"],className:"st-block st-icon--add",attributes:function(){return _.extend(SirTrevor.SimpleBlock.fn.attributes.call(this),{"data-icon-after":"add"})},icon_name:"default",validationFailMsg:function(){return i18n.t("errors:validation_fail",{type:this.title()})},editorHTML:'<div class="st-block__editor"></div>',toolbarEnabled:!0,droppable:!1,pastable:!1,uploadable:!1,fetchable:!1,ajaxable:!1,styleable:!1,drop_options:{},paste_options:{},upload_options:{},formattable:!0,removeEmpty:!1,_previousSelection:"",initialize:function(){},toMarkdown:function(markdown){return markdown},toHTML:function(html){return html},withMixin:function(mixin){if(_.isObject(mixin)){var initializeMethod="initialize"+mixin.mixinName;_.isUndefined(this[initializeMethod])&&(_.extend(this,mixin),this[initializeMethod]())}},render:function(){if(this.beforeBlockRender(),this._setBlockInner(),this.$editor=this.$inner.children().first(),this.droppable||this.pastable||this.uploadable){var input_html=$("<div>",{"class":"st-block__inputs"});this.$inner.append(input_html),this.$inputs=input_html}return this.hasTextBlock&&this._initTextBlocks(),this.droppable&&this.withMixin(SirTrevor.BlockMixins.Droppable),this.pastable&&this.withMixin(SirTrevor.BlockMixins.Pastable),this.uploadable&&this.withMixin(SirTrevor.BlockMixins.Uploadable),this.fetchable&&this.withMixin(SirTrevor.BlockMixins.Fetchable),this.controllable&&this.withMixin(SirTrevor.BlockMixins.Controllable),this.formattable&&this._initFormatting(),this.removeEmpty&&this._registerRemoveListener(),this._blockPrepare(),this},_registerRemoveListener:function(){var removeOnOutsideClick=function(){this.isEmpty()&&!this.spinner&&this.trigger("removeBlock",this.blockID)}.bind(this);$(window).on("click",removeOnOutsideClick),this.listenTo(this,"removeBlock",function(){$(window).off("click",removeOnOutsideClick)})},remove:function(){this.ajaxable&&this.resolveAllInQueue(),this.$el.remove()},loading:function(){_.isUndefined(this.spinner)||this.ready(),this.spinner=new Spinner(SirTrevor.DEFAULTS.spinner),this.spinner.spin(this.$el[0]),this.$el.addClass("st--is-loading")},ready:function(){this.$el.removeClass("st--is-loading"),_.isUndefined(this.spinner)||(this.spinner.stop(),delete this.spinner)},toData:function(){SirTrevor.log("toData for "+this.blockID);var dataObj=(this.$el,{});if(this.hasTextBlock()){var content=this.getTextBlock().html();content.length>0&&(dataObj.text=SirTrevor.toMarkdown(content,this.type))}this.$(":input").not(".st-paste-block").length>0&&this.$(":input").each(function(index,input){input.getAttribute("name")&&(dataObj[input.getAttribute("name")]=input.value)}),_.isEmpty(dataObj)||this.setData(dataObj)},focus:function(){this.getTextBlock().focus()},blur:function(){this.getTextBlock().blur()},onFocus:function(){this.getTextBlock().bind("focus",this._onFocus)},onBlur:function(){this.getTextBlock().bind("blur",this._onBlur)},_onFocus:function(){this.trigger("blockFocus",this.$el)},_onBlur:function(){},onDrop:function(dataTransferObj){},onDeleteClick:function(ev){ev.preventDefault();var onDeleteConfirm=function(e){e.preventDefault(),this.trigger("removeBlock",this.blockID)},onDeleteDeny=function(e){e.preventDefault(),this.$el.removeClass("st-block--delete-active"),$delete_el.remove()};if(this.isEmpty())return void onDeleteConfirm.call(this,new Event("click"));this.$inner.find(".btn--editor-panel--delete").append(_.template(delete_template)),this.$el.addClass("st-block--delete-active");var $delete_el=this.$inner.find(".st-block__ui-delete-controls");this.$inner.on("click",".btn--confirm-delete",_.bind(onDeleteConfirm,this)).on("click",".btn--deny-delete",_.bind(onDeleteDeny,this))},pastedMarkdownToHTML:function(content){return SirTrevor.toHTML(SirTrevor.toMarkdown(content,this.type),this.type)},onContentPasted:function(event,target){target.html(this.pastedMarkdownToHTML(target[0].innerHTML)),this.getTextBlock().caretToEnd(),this.splitAtReturns()},beforeLoadingData:function(){this.loading(),(this.droppable||this.uploadable||this.pastable)&&(this.$editor.show(),this.$inputs.hide()),SirTrevor.SimpleBlock.fn.beforeLoadingData.call(this),this.ready()},_handleContentPaste:function(ev){var target=$(ev.currentTarget);_.delay(_.bind(this.onContentPasted,this,ev,target),0)},_getBlockClass:function(){return"st-block--"+this.className},_initUIComponents:function(){this._withUIComponent(new SirTrevor.BlockReorder(this.$el,this.instanceID));var notes=new SirTrevor.BlockNotes(this.$el,this.instanceID,this);this._withUIComponent(notes,".st-block-ui-btn--type-notes"),this._withUIComponent(new SirTrevor.BlockDeletion,".btn--editor-panel--delete",this.onDeleteClick),this._withUIComponent(new SirTrevor.BlockStyles(this.$el,this.instanceID,this)),this._withUIComponent(new SirTrevor.BlockAdd(this.$el)),this.onFocus(),this.onBlur()},_initFormatting:function(){var formatter;for(var name in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(name)&&(formatter=SirTrevor.Formatters[name],_.isUndefined(formatter.keyCode)||formatter._bindToBlock(this.$el))},_initTextBlocks:function(){this.getTextBlock().bind("paste",this._handleContentPaste).bind("keyup",this._checkReturn).bind("keydown",this._checkArrowKeysDown).bind("keyup",this._checkArrowKeysUp).bind("keydown",this._checkBackspaceAtStartKeyDown).bind("keyup",this._checkBackspaceAtStartKeyUp).bind("keyup",this.getSelectionForFormatter).bind("mouseup",this.getSelectionForFormatter).bind("DOMNodeInserted",this.clearInsertedStyles)},_previousCaretOffset:void 0,_checkArrowKeysDown:function(ev){ev.target;if(void 0!==ev&&-1!==[37,38,39,40].indexOf(ev.keyCode)){if(!window.getSelection().isCollapsed)return;try{var marker=this.insertSplitMarker();this._previousCaretOffset=marker.offset()}finally{this.removeSplitMarker()}}},_checkArrowKeysUp:function(ev){ev.target;if(-1===$.inArray(this.type,["Heading","text","Quote","list"]))return!0;if(void 0!==ev&&-1!==$.inArray(ev.keyCode,[37,38,39,40])){if(!window.getSelection().isCollapsed)return;try{var marker=this.insertSplitMarker(),offset=marker.offset();if(offset.top===this._previousCaretOffset.top){if(38===ev.keyCode)return this.focusPreviousBlock(),!1;if(40===ev.keyCode)return this.focusNextBlock(),!1;if(offset.left===this._previousCaretOffset.left){if(37==ev.keyCode)return this.focusPreviousBlock(),!1;if(39==ev.keyCode)return this.focusNextBlock(),!1}}}finally{this.removeSplitMarker()}}return!0},focusPreviousBlock:function(){var instance=SirTrevor.getInstance(this.instanceID),currentPosition=instance.getBlockPosition(this.$el);if(1>currentPosition)return void console.log("Can't focus previous block: no previous block.");var previousBlock=instance.blocks.filter(function(block){return instance.getBlockPosition(block.$el)===currentPosition-1})[0];return void 0===previousBlock?void console.log("Can't merge with previous block: can't find by position"):-1===$.inArray(previousBlock.type,["Heading","text","Quote","list"])?void console.log("Can't focus previous block: not a text block. ("+previousBlock.type+")"):(previousBlock.focus(),void previousBlock.$editor.caretToEnd())},focusNextBlock:function(){var instance=SirTrevor.getInstance(this.instanceID),currentPosition=instance.getBlockPosition(this.$el);if(currentPosition>=instance.blocks.length)return void console.log("Can't focus next block: no next block.");var nextBlock=instance.blocks.filter(function(block){return instance.getBlockPosition(block.$el)===currentPosition+1})[0];return void 0===nextBlock?void console.log("Can't merge with next block: can't find by position"):-1===$.inArray(nextBlock.type,["Heading","text","Quote","list"])?void console.log("Can't focus next block: not a text block. ("+nextBlock.type+")"):(nextBlock.focus(),void nextBlock.$editor.caretToStart())},_checkReturn:function(ev){var target=ev.target;void 0===ev||ev.altKey||13!==ev.keyCode||_.defer(this.onReturn.bind(this,ev,target),0)},_previousContent:null,_checkBackspaceAtStartKeyUp:function(ev){var currentContent,target=ev.target;void 0!==ev&&8===ev.keyCode&&(currentContent=this.$editor[0].innerHTML,currentContent===this._previousContent&&_.defer(this.onBackspaceAtStart.bind(this,ev,target),0))},_checkBackspaceAtStartKeyDown:function(ev){void 0!==ev&&8===ev.keyCode&&(this._previousContent=this.$editor[0].innerHTML)},onBackspaceAtStart:function(event,target){if(-1!==$.inArray(this.type,["Heading","text"])){var instance=SirTrevor.getInstance(this.instanceID),currentPosition=instance.getBlockPosition(this.$el);if(1>currentPosition)return void console.log("Can't merge with previous block: no previous block.");var previousBlock=instance.blocks.filter(function(block){return instance.getBlockPosition(block.$el)===currentPosition-1})[0];if(void 0===previousBlock)return void console.log("Can't merge with previous block: can't find by position");if(-1===$.inArray(previousBlock.type,["Heading","text"]))return void console.log("Can't merge with previous block: not a text block.");previousBlock.focus(),previousBlock.$editor.caretToEnd(),previousBlock.$editor.append(this.$editor.contents()),instance.removeBlock(this.blockID)}},insertSplitMarker:function(html){var selection,range,element,fragment,node,lastNode,marker='<i id="split-marker"></i>';if(window.getSelection){if(selection=window.getSelection(),selection.getRangeAt&&selection.rangeCount){for(range=selection.getRangeAt(0),range.deleteContents(),element=document.createElement("div"),element.innerHTML=marker,fragment=document.createDocumentFragment();node=element.firstChild;)lastNode=fragment.appendChild(node);range.insertNode(fragment)}}else document.selection&&"Control"!=document.selection.type&&document.selection.createRange().pasteHTML(marker);return $("#split-marker")},removeSplitMarker:function(){var marker=$("#split-marker"),parent=marker.parent();marker.remove();var range=window.getSelection().getRangeAt(0);range.startOffset+range.endOffset!==0&&parent[0].normalize()},removeStartingReturns:function(block){var node,returns,selector="> div:first-child > br:first-child, > br:first-child";for(void 0===block&&(block=this),node=block.$editor,returns=node.find(selector);returns.length>0;)returns.remove(),returns=node.find(selector),node.find("div:empty").remove()},removeTrailingReturns:function(block){var node,returns,selector="div:last-child br:last-child, br:last-child";for(void 0===block&&(block=this),node=block.$editor,node.find("div:empty").remove(),returns=node.find(selector);returns.length>0;)returns.remove(),node.find("div:empty").remove(),returns=node.find(selector)},cleanupNestedDivs:function(block){var node,selector="div div";void 0===block&&(block=this),node=block.$editor,node.find(selector).each(function(i,el){var element=$(el);element.replaceWith(element.contents())}),node.find("div:empty").remove()},splitAtReturns:function(){var next,r=this.$el.find("br").first();if(0!==r.length){r.replaceWith('<i id="split-marker"></i>');try{next=this.splitAtSplitMarker()}finally{this.removeSplitMarker()}next.splitAtReturns()}},splitAtSplitMarker:function(){var newBlock,currentPosition,nextBlockPosition,instance=SirTrevor.getInstance(this.instanceID);try{newBlock=instance.createBlock("text",void 0,void 0,!1),currentPosition=instance.getBlockPosition(this.$el),nextBlockPosition=instance.getBlockPosition(newBlock.$el),nextBlockPosition-currentPosition!==1&&instance.changeBlockPosition(newBlock.$el,currentPosition+1,"After");var range=window.getSelection().getRangeAt(0);range.setStartAfter($("#split-marker")[0]),range.setEndAfter(this.$el.find(".st-text-block").children().last()[0]);var remainder=range.cloneContents();range.deleteContents(),newBlock.$editor.append(remainder),newBlock.$editor.find("div:empty").remove()}finally{this.cleanupNestedDivs(newBlock),newBlock.focus(),newBlock.$editor.caretToStart()}return newBlock},onReturn:function(event,target){if(-1!==$.inArray(this.type,["Heading","text"])){SirTrevor.getInstance(this.instanceID);window.getSelection().modify("extend","left","character"),document.execCommand("removeFormat",!1),this.insertSplitMarker();try{this.splitAtSplitMarker()}finally{this.removeSplitMarker()}}},getSelectionForFormatter:function(){_.defer(function(block){var selection=window.getSelection(),selectionStr=selection.toString().trim(),eventType=""===selectionStr?"hide":"position";SirTrevor.EventBus.trigger("formatter:"+eventType,block)},this)},clearInsertedStyles:function(e){var target=e.target;target.removeAttribute("style")},hasTextBlock:function(){return this.getTextBlock().length>0},getTextBlock:function(){return _.isUndefined(this.text_block)&&(this.text_block=this.$(".st-text-block")),this.text_block},isEmpty:function(){var data=jQuery.extend(!0,{},this.saveAndGetData());return delete data.uuid,delete data.note,delete data.style,_.isEmpty(data)}}),Block.extend=extend,Block}(),SirTrevor.DynamicBlocks=function(){return{}}(),SirTrevor.Formatter=function(){var Format=function(options){this.formatId=_.uniqueId("format-"),this._configure(options||{}),this.initialize.apply(this,arguments)},formatOptions=["title","className","cmd","keyCode","param","onClick","toMarkdown","toHTML"];return _.extend(Format.prototype,{title:"",className:"",cmd:null,keyCode:null,param:null,toMarkdown:function(markdown){return markdown},toHTML:function(html){return html},initialize:function(){},_configure:function(options){this.options&&(options=_.extend({},this.options,options));for(var i=0,l=formatOptions.length;l>i;i++){var attr=formatOptions[i];options[attr]&&(this[attr]=options[attr])}this.options=options},isActive:function(){return document.queryCommandState(this.cmd)},_bindToBlock:function(block){var formatter=this,ctrlDown=!1;block.on("keyup",".st-text-block",function(ev){17!=ev.which&&224!=ev.which&&91!=ev.which||(ctrlDown=!1)}).on("keydown",".st-text-block",{formatter:formatter},function(ev){17!=ev.which&&224!=ev.which&&91!=ev.which||(ctrlDown=!0),ev.which==ev.data.formatter.keyCode&&ctrlDown===!0&&(document.execCommand(ev.data.formatter.cmd,!1,!0),ev.preventDefault(),ctrlDown=!1)})}}),Format.extend=extend,Format}(),SirTrevor.Blocks.Quote=function(){var template=_.template(['<blockquote class="st-required st-text-block st-block--quote" contenteditable="true"></blockquote>','<label class="st-input-label"> <%= i18n.t("blocks:quote:credit_field") %></label>','<input maxlength="140" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"',' class="st-input-string js-cite-input" type="text" />'].join("\n"));return SirTrevor.Block.extend({type:"quote",title:function(){return i18n.t("blocks:quote:title")},icon_name:"quote",changeable:["Heading","text"],editorHTML:function(){return template(this)},loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type)),this.$(".js-cite-input").val(data.cite)},toMarkdown:function(markdown){return markdown.replace(/^(.+)$/gm,"> $1")}})}(),SirTrevor.Blocks.ExtendedQuote=function(){var template=_.template(['<blockquote class="st-required st-text-block st-block--extended-quote" contenteditable="true"></blockquote>','<label class="st-input-label"> <%= i18n.t("blocks:extended_quote:credit_field") %></label>','<input name="cite" placeholder="<%= i18n.t("blocks:extended_quote:credit_field") %>"',' class="st-input-string js-cite-input" type="text" />'].join("\n"));return SirTrevor.Block.extend({type:"extended_quote",title:function(){return i18n.t("blocks:extended_quote:title")},icon_name:"quote-extended",changeable:["Heading","text"],editorHTML:function(){return template(this)},loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type)),this.$(".js-cite-input").val(data.cite)},toMarkdown:function(markdown){return markdown.replace(/^(.+)$/gm,"> $1")}})}(),SirTrevor.Blocks.Heading=SirTrevor.Block.extend({type:"Heading",title:function(){return i18n.t("blocks:heading:title")},editorHTML:'<div class="st-required st-text-block st-block--heading" contenteditable="true"></div>',icon_name:"heading",changeable:["text","quote"],loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type))}}),SirTrevor.Blocks.Text=SirTrevor.Block.extend({type:"text",title:function(){return i18n.t("blocks:text:title")},editorHTML:'<div class="st-required st-text-block" contenteditable="true"></div>',icon_name:"text",changeable:["Heading","quote"],loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type))}}),SirTrevor.Blocks.List=function(){var template='<div class="st-text-block st-required st-block--list" contenteditable="true"><ul><li></li></ul></div>';return SirTrevor.Block.extend({type:"list",title:function(){return i18n.t("blocks:list:title")},icon_name:"list",editorHTML:function(){return _.template(template,this)},loadData:function(data){this.getTextBlock().html("<ul>"+SirTrevor.toHTML(data.text,this.type)+"</ul>")},onBlockRender:function(){this.checkForList=_.bind(this.checkForList,this),this.getTextBlock().on("click keyup",this.checkForList)},checkForList:function(){0===this.$("ul").length&&document.execCommand("insertUnorderedList",!1,!1)},toMarkdown:function(markdown){return markdown.replace(/<\/li>/gm,"\n").replace(/<\/?[^>]+(>|$)/g,"").replace(/^(.+)$/gm," - $1")},toHTML:function(html){return html=html.replace(/^ - (.+)$/gm,"<li>$1</li>").replace(/\n/gm,"")},onContentPasted:function(event,target){var replace=this.pastedMarkdownToHTML(target[0].innerHTML);this.$("ul").html(replace);this.getTextBlock().caretToEnd()},isEmpty:function(){return _.isEmpty(this.saveAndGetData().text)}})}(),SirTrevor.Blocks.Definition=function(){var template=_.template(['<dl class="st-definition st-block--definition"><dt><label class="st-input-label"> <%= i18n.t("blocks:definition:term") %></label>','<input name="term" placeholder="<%= i18n.t("blocks:definition:term") %>"',' class="st-input-string js-term-input" type="text" /></dt>','<dd class="st-required st-text-block" contenteditable="true" data-placeholder="<%= i18n.t("blocks:definition:description") %>"></dd></dl>'].join("\n"));return SirTrevor.Block.extend({type:"definition",title:function(){return i18n.t("blocks:definition:title")},icon_name:"definition",changeable:["Heading","text"],editorHTML:function(){return template(this)},onBlockRender:function(){var placeholders=this.$el.find("[data-placeholder]");placeholders.on("change keydown keypress input",function(){this.textContent?this.setAttribute("data-hide-placeholder","true"):this.removeAttribute("data-hide-placeholder")})},loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type)),this.$(".js-term-input").val(data.term)}})}(),SirTrevor.Blocks.Divider=function(){var template='<div class="st-divider st-block--divider"><hr></div>';return SirTrevor.Block.extend({type:"divider",title:function(){return i18n.t("blocks:divider:title")},icon_name:"divider",editorHTML:function(){return _.template(template,this)},toMarkdown:function(markdown){return"---------------------------------------"},toHTML:function(html){return template},isEmpty:function(){return!1}})}(),SirTrevor.Blocks.RewardList=function(){var template=['<div class="st-reward-list st-block--reward-list">','<h1><i class="icon--reward"></i>%s</h1>',"</div>"].join("\n");return SirTrevor.Block.extend({type:"reward_list",title:function(){return i18n.t("blocks:reward_list:title")},icon_name:"reward",editorHTML:function(){return _.template(template.replace("%s",this.title()),this)},isEmpty:function(){return!1}})}(),SirTrevor.Blocks.Image=SirTrevor.Block.extend({type:"image",title:function(){return i18n.t("blocks:image:title")},droppable:!0,uploadable:!0,icon_name:"image",loadData:function(data){this.$editor.html($("<img>",{src:data.file.url}))},onBlockRender:function(){this.$inputs.find("button").bind("click",function(ev){ev.preventDefault()}),this.$inputs.find("input").on("change",_.bind(function(ev){this.onDrop(ev.currentTarget)},this))},onUploadSuccess:function(data){this.setData(data),this.ready()},onUploadError:function(jqXHR,status,errorThrown){this.addMessage(i18n.t("blocks:image:upload_error")),this.ready()},onDrop:function(transferData){var file=transferData.files[0],urlAPI="undefined"!=typeof URL?URL:"undefined"!=typeof webkitURL?webkitURL:null;/image/.test(file.type)&&(this.loading(),this.$inputs.hide(),this.$editor.html($("<img>",{src:urlAPI.createObjectURL(file)})).show(),this.uploader(file,this.onUploadSuccess,this.onUploadError))}}),SirTrevor.Blocks.ExtendedImage=SirTrevor.Blocks.Image.extend({type:"extended_image",title:function(){return i18n.t("blocks:extended_image:title")},droppable:!0,uploadable:!0,styleable:!0,styles:[{name:i18n.t("blocks:extended_image:default"),value:"default",className:"default"},{name:i18n.t("blocks:extended_image:bodywidth"),value:"bodywidth",className:"bodywidth"},{name:i18n.t("blocks:extended_image:fullwidth"),
12
+ value:"fullwidth",className:"fullwidth"}],icon_name:"image",removeEmpty:!0,loadData:function(data){var payload,editor=this.$editor,figure=$("<figure class='media'></figure>"),picture=$("<picture class='media__img'></picture>"),source=data.file&&data.file.url;payload=void 0!==source?$("<img>",{src:source}):$('<h1><i class="icon--exclamation-triangle"></i></h1>'),figure.append(picture.append(payload));var copyright=($("<figcaption class='media__body'></figcaption>"),$(["<label class='st-input-label'>"+i18n.t("blocks:extended_image:copyright_field")+"</label>","<input type='text' maxlength='140' name='copyright' class='st-input-string js-copyright-input'","placeholder='"+i18n.t("blocks:extended_image:copyright_placeholder")+"'></input>"].join("\n")));figure.append(copyright);var caption=$(["<label class='st-input-label'>"+i18n.t("blocks:extended_image:caption_field")+"</label>","<textarea name='caption' class='st-input-string js-caption-input'","placeholder='"+i18n.t("blocks:extended_image:caption_placeholder")+"'></textarea>"].join("\n"));figure.append(caption);var target_url=$(["<label class='st-input-label'>"+i18n.t("blocks:extended_image:target_url_field")+"</label>","<input type='text' maxlength='140' name='target_url' class='st-input-string js-target_url-input'","placeholder='"+i18n.t("blocks:extended_image:target_url_placeholder")+"'></input>"].join("\n"));figure.append(target_url),editor.html("").show(),editor.append(figure),this.$(".js-target_url-input").val(data.target_url),this.$(".js-copyright-input").val(data.copyright),this.$(".js-caption-input").val(data.caption),void 0!==jQuery.fn.autosize&&figure.find(".js-caption-input").autosize()},onBlockRender:function(){this.$inputs.find("button").bind("click",function(ev){ev.preventDefault()}),this.$inputs.find("input").on("change",_.bind(function(ev){this.onDrop(ev.currentTarget)},this))},onUploadSuccess:function(data){this.setData(data),this.ready()},onUploadError:function(jqXHR,status,errorThrown){this.addMessage(i18n.t("blocks:extended_image:upload_error")),this.ready()},onDrop:function(transferData){var file=transferData.files[0],urlAPI="undefined"!=typeof URL?URL:"undefined"!=typeof webkitURL?webkitURL:null;/image/.test(file.type)&&(this.loading(),this.$inputs.hide(),this.loadData({file:{url:urlAPI.createObjectURL(file)}}),this.uploader(file,this.onUploadSuccess,this.onUploadError))}}),SirTrevor.Blocks.Video=function(){return SirTrevor.Block.extend({providers:{vimeo:{regex:/(?:http[s]?:\/\/)?(?:www.)?vimeo.com\/(.+)/,html:'<iframe src="{{protocol}}//player.vimeo.com/video/{{remote_id}}?title=0&byline=0" width="580" height="320" frameborder="0"></iframe>'},youtube:{regex:/(?:http[s]?:\/\/)?(?:www.)?(?:(?:youtube.com\/watch\?(?:.*)(?:v=))|(?:youtu.be\/))([^&].+)/,html:'<iframe src="{{protocol}}//www.youtube.com/embed/{{remote_id}}" width="580" height="320" frameborder="0" allowfullscreen></iframe>'}},type:"video",title:function(){return i18n.t("blocks:video:title")},droppable:!0,pastable:!0,icon_name:"video",styleable:!0,styles:[{name:"Default",value:"default",className:"default"},{name:"Full-width",value:"fullwidth",className:"default"}],removeEmpty:!0,extractSourceInformation:function(){var url=this.$editor.find("iframe").attr("src");this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string;this.providers.hasOwnProperty(data.source)?(this.providers[data.source].square?this.$editor.addClass("st-block__editor--with-square-media"):this.$editor.addClass("st-block__editor--with-sixteen-by-nine-media"),embed_string=this.providers[data.source].html.replace("{{protocol}}",window.location.protocol).replace("{{remote_id}}",data.remote_id).replace("{{width}}",this.$editor.width())):embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',this.$editor.html(embed_string),this.extractSourceInformation()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Tweet=function(){var tweet_template=_.template(["<blockquote class='twitter-tweet' align='center'>","<p><%= text %></p>","&mdash; <%= user.name %> (@<%= user.screen_name %>)","<a href='<%= status_url %>' data-datetime='<%= created_at %>'><%= created_at %></a>","</blockquote>",'<script src="//platform.twitter.com/widgets.js" charset="utf-8"></script>'].join("\n"));return SirTrevor.Block.extend({type:"tweet",droppable:!0,pastable:!0,fetchable:!0,drop_options:{re_render_on_reorder:!0},title:function(){return i18n.t("blocks:tweet:title")},fetchUrl:function(tweetID){return"/tweets/?tweet_id="+tweetID},icon_name:"twitter",loadData:function(data){_.isUndefined(data.status_url)&&(data.status_url=""),this.$inner.find("iframe").remove(),this.$inner.prepend(tweet_template(data))},onContentPasted:function(event){var input=$(event.target),val=input.val();this.handleTwitterDropPaste(val)},handleTwitterDropPaste:function(url){if(!this.validTweetUrl(url))return void SirTrevor.log("Invalid Tweet URL");var tweetID=url.match(/[^\/]+$/);if(!_.isEmpty(tweetID)){this.loading(),tweetID=tweetID[0];var ajaxOptions={url:this.fetchUrl(tweetID),dataType:"json"};this.fetch(ajaxOptions,this.onTweetSuccess,this.onTweetFail)}},validTweetUrl:function(url){return _.isURI(url)&&-1!==url.indexOf("twitter")&&-1!==url.indexOf("status")},onTweetSuccess:function(data){var obj={user:{profile_image_url:data.user.profile_image_url,profile_image_url_https:data.user.profile_image_url_https,screen_name:data.user.screen_name,name:data.user.name},id:data.id_str,text:data.text,created_at:data.created_at,entities:data.entities,status_url:"https://twitter.com/"+data.user.screen_name+"/status/"+data.id_str};this.setAndLoadData(obj),this.ready()},onTweetFail:function(){this.addMessage(i18n.t("blocks:tweet:fetch_error")),this.ready()},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleTwitterDropPaste(url)}})}(),SirTrevor.Blocks.ExtendedTweet=function(){return SirTrevor.Block.extend({providers:{soundcloud:{regex:/((?:http[s]?:\/\/)?(?:www.)?(:?twitter.com\/.*\/status\/(.*?)))(:?\?.*)?$/,html:function(options,success,error){var fail=window.setTimeout(error,5e3);$.getJSON("https://api.twitter.com/1/statuses/oembed.json?callback=?",{format:"js",url:options.remote_id,align:"center",maxwidth:550,hide_thread:1,iframe:!0}).done(function(data){clearTimeout(fail),success(data.html,options)})}}},type:"extended_tweet",title:function(){return i18n.t("blocks:tweet:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"twitter-outline",extractSourceInformation:function(options){var url=options.remote_id;this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string,self=this,update_editor=function(embed_string,options){self.$editor.html(embed_string),self.extractSourceInformation(options)},display_error=function(){embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',self.$editor.html(embed_string)};if(this.providers.hasOwnProperty(data.source)){var html=this.providers[data.source].html;html instanceof Function?html({protocol:window.location.protocol,remote_id:data.remote_id,width:this.$editor.width()},update_editor,display_error):(embed_string=html.replace("{{protocol}}",window.location.protocol).replace("{{remote_id}}",data.remote_id).replace("{{width}}",this.$editor.width()),update_editor())}else display_error()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.FacebookPost=function(){function initFacebookOnce(){if("undefined"==typeof FB&&!initDone){var facebookInitScript=['<div id="fb-root"></div>',"<script>(function(d, s, id) {"," var js, fjs = d.getElementsByTagName(s)[0];"," if (d.getElementById(id)) return;"," js = d.createElement(s); js.id = id;",' js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";'," fjs.parentNode.insertBefore(js, fjs);",'}(document, "script", "facebook-jssdk"));</script>'].join("\n");jQuery(document.body).append(facebookInitScript),initDone=!0}}var initDone=!1,facebook_post_template=_.template(['<div class="fb-post" data-href="<%= url %>" data-width="<%= width %>"></div>'].join("\n")),facebookPostRegex=/((?:http[s]?:\/\/)?(?:www.)?(:?facebook.com\/(video\.php|photo\.php|(.*\/(posts|photos)\/))(.*?)))(:?\?.*)?$/;return SirTrevor.Block.extend({type:"facebook_post",title:function(){return i18n.t("blocks:facebookpost:title")},droppable:!0,pastable:!0,icon_name:"facebook-outline",extractSourceInformation:function(url){this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){initFacebookOnce(),this.$inner.prepend(facebook_post_template({url:data.url,width:this.$editor.width()||"700"})),this.extractSourceInformation(data.url),"undefined"!=typeof FB&&FB.XFBML.parse()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){if(!this.validPostUrl(url))return void SirTrevor.log("Invalid Facebook Post URL");this.setAndLoadData({url:url}),this.ready()}},validPostUrl:function(url){return url.match(facebookPostRegex)},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Infographic=function(){return SirTrevor.Block.extend({providers:{infoactive:{regex:/(?:http[s]?:\/\/)?(?:www.)?infoactive.co\/plays\/(.+)/,html:["<div data-url='https://infoactive.co/plays/{{remote_id}}' id='infoactive-iframe-container-{{remote_id}}'></div>","<script type='text/javascript'>","jQuery.getScript('https://dqzzm1bt1bnva.cloudfront.net/assets/pym-7afa305c2065e6ace0f4cb837fc78658.js', function() {","var iFrameLoader = new pym.Parent('infoactive-iframe-container-{{remote_id}}','https://infoactive.co/plays/{{remote_id}}', {});","});","</script>"].join("\n")}},type:"infographic",title:function(){return i18n.t("blocks:infographic:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"infographic",extractSourceInformation:function(){var url=this.$editor.find("div[data-url]").attr("data-url");this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string;this.providers.hasOwnProperty(data.source)?(embed_string=this.providers[data.source].html.replace(/{{protocol}}/g,window.location.protocol).replace(/{{remote_id}}/g,data.remote_id).replace(/{{width}}/g,this.$editor.width()),this.$editor.html(embed_string),this.extractSourceInformation()):(embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',this.$editor.html(embed_string))},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Audio=function(){return SirTrevor.Block.extend({providers:{soundcloud:{regex:/((?:http[s]?:\/\/)?(?:www.)?(:?soundcloud.com\/(.*)))/,html:function(options,success,error){var fail=window.setTimeout(error,5e3);$.getJSON("https://soundcloud.com/oembed?callback=?",{format:"js",url:options.remote_id,iframe:!0}).done(function(data){clearTimeout(fail),success(data.html,options)})}}},type:"audio",title:function(){return i18n.t("blocks:audio:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"audio",extractSourceInformation:function(){var url=this.$editor.find("iframe").attr("src");this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string,self=this,update_editor=function(embed_string){self.$editor.html(embed_string),self.extractSourceInformation(),self.providers[data.source].square?self.$editor.addClass("st-block__editor--with-square-media"):self.$editor.addClass("st-block__editor--with-sixteen-by-nine-media")},display_error=function(){embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',self.$editor.html(embed_string)};if(this.providers.hasOwnProperty(data.source)){var html=this.providers[data.source].html;html instanceof Function?html({protocol:window.location.protocol,remote_id:data.remote_id,width:this.$editor.width()},update_editor,display_error):(embed_string=html.replace("{{protocol}}",window.location.protocol).replace("{{remote_id}}",data.remote_id).replace("{{width}}",this.$editor.width()),update_editor())}else display_error()},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.Blocks.Html=SirTrevor.Block.extend({type:"html",title:function(){return i18n.t("blocks:html:title")},editorHTML:'<div class="st-required st-html-block" contenteditable="true"></div>',icon_name:"text",changeable:[],getBlock:function(){return this.$(".st-html-block")},toData:function(){SirTrevor.log("toData for "+this.blockID);var uuid=this.getData().uuid||SirTrevor.generateUUID(),dataObj=(this.$el,{uuid:uuid}),content=this.getBlock().text();content.length>0&&(dataObj.text=content),_.isEmpty(dataObj)||this.setData(dataObj)},loadData:function(data){this.getBlock().text(data.text)}}),SirTrevor.Blocks.Instagram=function(){return SirTrevor.Block.extend({providers:{instagram:{regex:/((?:http[s]?:\/\/)?(?:www.)?(:?instagr.*\/p\/(.*?)))(:?\?.*)?$/,html:function(options,success,error){var fail=window.setTimeout(error,5e3);$.ajax({url:"//api.instagram.com/oembed",data:{maxwidth:550,url:options.remote_id},jsonp:"callback",dataType:"jsonp"}).done(function(data){clearTimeout(fail),success(data.html,options)})}}},type:"instagram",title:function(){return i18n.t("blocks:instagram:title")},droppable:!0,pastable:!0,removeEmpty:!0,icon_name:"instagram-outline",extractSourceInformation:function(options){var url=options.remote_id;this.$editor.parents(".st-block").append("<aside>"+i18n.t("general:source")+": "+url+"</aside>")},loadData:function(data){var embed_string,self=this,update_editor=function(embed_string,options){self.$editor.html(embed_string),self.extractSourceInformation(options)},display_error=function(){embed_string='<h1><i class="icon--exclamation-triangle"></i></h1>',self.$editor.html(embed_string)},html=this.providers[data.source].html;html({protocol:window.location.protocol,remote_id:data.remote_id,width:this.$editor.width()},update_editor,display_error)},onContentPasted:function(event){this.handleDropPaste($(event.target).val())},handleDropPaste:function(url){if(_.isURI(url)){var match,data;_.each(this.providers,function(provider,index){match=provider.regex.exec(url),null===match||_.isUndefined(match[1])||(data={source:index,remote_id:match[1]},this.setAndLoadData(data))},this)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),SirTrevor.DynamicBlocks.RemoteSelectableList=function(){return function(parameters){return{type:parameters.model_name,fetchable:!0,selectedElements:[],title:function(){return i18n.t("blocks:remote_list:"+parameters.model_name+":title")},icon_name:parameters.icon,editorHTML:function(){return""},onBlockRender:function(){this.getData().selected||(this.loading(),this.setData({selected:[],model_name:parameters.model_name}),parameters.callback(this.onListSuccess.bind(this),this.onGetFail.bind(this)))},loadData:function(data){return _.isArray(data.selected)&&0!==data.selected.length?void this.renderSelected(data.selected):void this.destroy()},renderSelected:function(selected){var data=JSON.stringify({model_name:parameters.model_name,selected:selected});$.get(parameters.render_endpoint,{content:data},this.onGetRenderSuccess.bind(this)).fail(this.onGetFail.bind(this))},onGetRenderSuccess:function(data){this.ready(),this.$el.append(data)},onListSuccess:function(data){this.setAndLoadData({selected:data,model_name:parameters.model_name}),this.ready()},onGetFail:function(){this.addMessage(i18n.t("blocks:remote_list:fetch_error")),this.ready()}}}}(),function(){var Bold=SirTrevor.Formatter.extend({title:"bold",cmd:"bold",keyCode:66,text:"B"}),Italic=SirTrevor.Formatter.extend({title:"italic",cmd:"italic",keyCode:73,text:"i"}),Link=SirTrevor.Formatter.extend({title:"link",iconName:"link",cmd:"CreateLink",text:"link",onClick:function(){var selectionLink="";try{var sel=document.getSelection();sel.rangeCount&&(selectionLink=sel.getRangeAt(0).commonAncestorContainer.parentElement.href||"")}catch(e){}var link=prompt(i18n.t("general:link"),selectionLink),link_regex=/((ftp|http|https):\/\/.)|mailto(?=\:[-\.\w]+@)/;link&&link.length>0&&(link_regex.test(link)||(link="http://"+link),document.execCommand(this.cmd,!1,link))},isActive:function(){var node,selection=window.getSelection();return selection.rangeCount>0&&(node=selection.getRangeAt(0).startContainer.parentNode),node&&"A"==node.nodeName}}),UnLink=SirTrevor.Formatter.extend({title:"unlink",iconName:"link",cmd:"unlink",text:"link"});SirTrevor.Formatters.Bold=new Bold,SirTrevor.Formatters.Italic=new Italic,SirTrevor.Formatters.Link=new Link,SirTrevor.Formatters.Unlink=new UnLink}(),function(){var Heading=SirTrevor.Formatter.extend({title:"heading",iconName:"Heading",text:"H1",prepare:function(){var selection=window.getSelection();if(0===selection.rangeCount)return void SirTrevor.log("Can't get current selection from formatter!");var node=$(selection.getRangeAt(0).startContainer.parentNode).parents(".st-block").first();this._instance=SirTrevor.getInstance(node.attr("data-instance")),this._block=this._instance.getBlocksByIDs([node.attr("id")])[0]},getCurrentBlock:function(){return this._block},getCurrentInstance:function(){return this._instance},onClick:function(){var instance=this.getCurrentInstance(),block=this.getCurrentBlock();instance.changeBlockType(block,"Heading"===block.type?"text":"Heading")},isActive:function(){return this.prepare(),"Heading"===this.getCurrentBlock().type}}),Quote=SirTrevor.Formatter.extend({title:"quote",iconName:"quote",text:"“",prepare:function(){var selection=window.getSelection();if(0===selection.rangeCount)return void SirTrevor.log("Can't get current selection from formatter!");var node=$(selection.getRangeAt(0).startContainer.parentNode).parents(".st-block").first();this._instance=SirTrevor.getInstance(node.attr("data-instance")),this._block=this._instance.getBlocksByIDs([node.attr("id")])[0]},getCurrentBlock:function(){return this._block},getCurrentInstance:function(){return this._instance},onClick:function(){var instance=this.getCurrentInstance(),block=this.getCurrentBlock();instance.changeBlockType(block,"quote"===block.type?"text":"quote")},isActive:function(){return this.prepare(),"quote"===this.getCurrentBlock().type}});SirTrevor.Formatters.Heading=new Heading,SirTrevor.Formatters.Quote=new Quote}(),SirTrevor.BlockControl=function(){var BlockControl=function(type,instance_scope){this.type=type,this.instance_scope=instance_scope,this.block_type=SirTrevor.Blocks[this.type].prototype,this.can_be_rendered=this.block_type.toolbarEnabled,this._ensureElement()};return _.extend(BlockControl.prototype,FunctionBind,Renderable,SirTrevor.Events,{tagName:"a",className:"st-block-control",attributes:function(){return{"data-type":this.block_type.type}},render:function(){return this.$el.html('<span class="st-icon icon--'+_.result(this.block_type,"icon_name")+'" aria-hidden="true"></span>'+_.result(this.block_type,"title")),this}}),BlockControl}(),SirTrevor.BlockControls=function(){var BlockControls=function(available_types,instance_scope){this.instance_scope=instance_scope,this.available_types=available_types||[],this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockControls.prototype,FunctionBind,Renderable,SirTrevor.Events,{bound:["handleControlButtonClick"],block_controls:null,className:"st-block-controls",html:"<a class='st-icon st-icon--close'>"+i18n.t("general:close")+"</a>",initialize:function(){for(var block_type in this.available_types)if(SirTrevor.Blocks.hasOwnProperty(block_type)){var block_control=new SirTrevor.BlockControl(block_type,this.instance_scope);block_control.can_be_rendered&&this.$el.append(block_control.render().$el)}this.$el.delegate(".st-block-control","click",this.handleControlButtonClick)},show:function(){this.$el.addClass("st-block-controls--active"),SirTrevor.EventBus.trigger("block:controls:shown")},hide:function(){this.$el.removeClass("st-block-controls--active"),SirTrevor.EventBus.trigger("block:controls:hidden")},handleControlButtonClick:function(e){e.stopPropagation(),this.trigger("createBlock",$(e.currentTarget).attr("data-type"))}}),BlockControls}(),SirTrevor.FloatingBlockControls=function(){var FloatingBlockControls=function(wrapper,instance_id){this.$wrapper=wrapper,this.instance_id=instance_id,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(FloatingBlockControls.prototype,FunctionBind,Renderable,SirTrevor.Events,{className:"st-block-controls__top",attributes:function(){return{"data-icon":"add"}},bound:["handleBlockMouseOut","handleBlockMouseOver","handleBlockClick","onDrop"],initialize:function(){this.$el.on("click",this.handleBlockClick).dropArea().bind("drop",this.onDrop),this.$wrapper.on("mouseover",".st-block",this.handleBlockMouseOver).on("mouseout",".st-block",this.handleBlockMouseOut).on("click",".st-block--with-plus",this.handleBlockClick)},onDrop:function(ev){ev.preventDefault();var dropped_on=this.$el,item_id=ev.originalEvent.dataTransfer.getData("text/plain"),block=$("#"+item_id);_.isUndefined(item_id)||_.isEmpty(block)||dropped_on.attr("id")==item_id||this.instance_id!=block.attr("data-instance")||dropped_on.after(block),SirTrevor.EventBus.trigger("block:reorder:dropped",item_id)},handleBlockMouseOver:function(e){var block=$(e.currentTarget);block.hasClass("st-block--with-plus")||block.addClass("st-block--with-plus")},handleBlockMouseOut:function(e){var block=$(e.currentTarget);block.hasClass("st-block--with-plus")&&block.removeClass("st-block--with-plus")},handleBlockClick:function(e){e.stopPropagation();var block=$(e.currentTarget);this.trigger("showBlockControls",block)}}),FloatingBlockControls}(),SirTrevor.FormatBar=function(){var FormatBar=function(options){this.options=_.extend({},SirTrevor.DEFAULTS.formatBar,options||{}),this._ensureElement(),this._bindFunctions(),this.initialize.apply(this,arguments)};return _.extend(FormatBar.prototype,FunctionBind,SirTrevor.Events,Renderable,{className:"st-format-bar",bound:["onFormatButtonClick","renderBySelection","hide"],initialize:function(){var formatName,format,btn;SirTrevor.Formatters;this.$btns=[];for(formatName in SirTrevor.Formatters)SirTrevor.Formatters.hasOwnProperty(formatName)&&(format=SirTrevor.Formatters[formatName],btn=$("<button>",{"class":"st-format-btn st-format-btn--"+formatName+" "+(format.iconName?"st-icon":""),text:format.text,"data-type":formatName,"data-cmd":format.cmd}),this.$btns.push(btn),btn.appendTo(this.$el));this.$b=$(document),this.$el.bind("click",".st-format-btn",this.onFormatButtonClick)},hide:function(){this.$el.removeClass("st-format-bar--is-ready")},show:function(){this.$el.addClass("st-format-bar--is-ready")},remove:function(){this.$el.remove()},renderBySelection:function(rectangles){var selection=window.getSelection(),range=selection.getRangeAt(0),boundary=range.getBoundingClientRect(),coords={};coords.top=boundary.top+20+window.pageYOffset-this.$el.height()+"px",coords.left=(boundary.left+boundary.right)/2-this.$el.width()/2+"px",this.highlightSelectedButtons(),this.show(),this.$el.css(coords)},highlightSelectedButtons:function(){var formatter;_.each(this.$btns,function($btn){formatter=SirTrevor.Formatters[$btn.attr("data-type")],$btn.toggleClass("st-format-btn--is-active",formatter.isActive())},this)},onFormatButtonClick:function(ev){ev.stopPropagation();var btn=$(ev.target),format=SirTrevor.Formatters[btn.attr("data-type")];return _.isUndefined(format)?!1:(!_.isUndefined(format.onClick)&&_.isFunction(format.onClick)?format.onClick():document.execCommand(btn.attr("data-cmd"),!1,format.param),this.highlightSelectedButtons(),!1)}}),FormatBar}(),SirTrevor.Editor=function(){var SirTrevorEditor=function(options){this.initialize(options)};return _.extend(SirTrevorEditor.prototype,FunctionBind,SirTrevor.Events,{bound:["onFormSubmit","showBlockControls","hideAllTheThings","hideBlockControls","onNewBlockCreated","changeBlockPosition","onBlockDragStart","onBlockDragEnd","removeBlockDragOver","onBlockDropped","createBlock","restoreDefaultType","autosave","_checkEscapeKeyPressed"],events:{"block:reorder:down":"hideBlockControls","block:reorder:dragstart":"onBlockDragStart","block:reorder:dragend":"onBlockDragEnd","block:content:dropped":"removeBlockDragOver","block:reorder:dropped":"onBlockDropped","block:create:new":"onNewBlockCreated"},initialize:function(options){return SirTrevor.log("Init SirTrevor.Editor"),this.blockTypes={},this.blockCounts={},this.blocks=[],this.errors=[],this.options=_.extend({},SirTrevor.DEFAULTS,options||{}),this.ID=_.uniqueId("st-editor-"),this._ensureAndSetElements()?(!_.isUndefined(this.options.onEditorRender)&&_.isFunction(this.options.onEditorRender)&&(this.onEditorRender=this.options.onEditorRender),this._extendLocales(),this._setRequired(),this._createDynamicBlocks(),this._setBlocksTypes(),this._bindFunctions(),this._setupActiveClass(),this.store("create"),SirTrevor.instances.push(this),this.build(),$(window).on("keyup",this._checkEscapeKeyPressed),void SirTrevor.bindFormSubmit(this.$form)):!1},_setupActiveClass:function(){var focus,current,timeout,root=$("#"+this.ID),className="st-active-block",resetActive=function(){window.clearTimeout(timeout),timeout=window.setTimeout(function(){root.find(".st-block").removeClass(className),current.addClass(className)},200)};root.delegate(".st-block","focus",function(e){focus=$(this),current=focus,resetActive()}),root.delegate(".st-block","mouseout",function(e){}),root.delegate(".st-block","mouseover",function(e){return e.stopPropagation(),$(e.target).hasClass("st-block__ui")||$(e.target).parents(".st-block__ui").length>0?!1:(current=$(this),void resetActive())})},build:function(){this.$el.hide(),this.block_controls=new SirTrevor.BlockControls(this.blockTypes,this.ID),this.fl_block_controls=new SirTrevor.FloatingBlockControls(this.$wrapper,this.ID),this.formatBar=new SirTrevor.FormatBar(this.options.formatBar),this.listenTo(this.block_controls,"createBlock",this.createBlock),this.listenTo(this.fl_block_controls,"showBlockControls",this.showBlockControls),SirTrevor.EventBus.on("showBlockControls",this.showBlockControls),this._setEvents(),SirTrevor.EventBus.on(this.ID+":blocks:change_position",this.changeBlockPosition),SirTrevor.EventBus.on("formatter:position",this.formatBar.renderBySelection),SirTrevor.EventBus.on("formatter:hide",this.formatBar.hide),SirTrevor.EventBus.on(this.ID+":blocks:count_update",this.restoreDefaultType),this.$wrapper.prepend(this.fl_block_controls.render().$el),$(document.body).append(this.formatBar.render().$el),this.$outer.append(this.block_controls.render().$el),$(window).bind("click.sirtrevor",this.hideAllTheThings);var store=this.store("read");store.data.length>0?_.each(store.data,function(block){SirTrevor.log("Creating: "+block.type),this.createBlock(block.type,block.data)},this):this.options.defaultType!==!1&&this.restoreDefaultType(),this.$wrapper.addClass("st-ready"),this.options.localStorage===!0&&window.setInterval(this.autosave,2e4),_.isUndefined(this.onEditorRender)||this.onEditorRender()},autosave:function(){this.store("reset");var blockIterator=function(block,index){var _block=_.find(this.blocks,function(b){return b.blockID==$(block).attr("id")});return _.isUndefined(_block)?!1:void this.saveBlockStateToStore(_block)};_.each(this.$wrapper.find(".st-block"),blockIterator,this),this.store("autosave")},restoreDefaultType:function(count){var instance=this;if(void 0===count||0===count){var container=instance.block_controls.current_container;instance.block_controls.current_container=void 0,instance.createBlock(instance.options.defaultType),instance.block_controls.current_container=container}},destroy:function(){this.formatBar.destroy(),this.fl_block_controls.destroy(),this.block_controls.destroy(),_.each(this.blocks,function(block){this.removeBlock(block.blockID)},this),this.stopListening();var el=this.$el.detach();SirTrevor.instances=_.reject(SirTrevor.instances,_.bind(function(instance){return instance.ID==this.ID},this)),this.store("reset"),this.$outer.replaceWith(el)},reinitialize:function(options){this.destroy(),this.initialize(options||this.options)},_setEvents:function(){_.each(this.events,function(callback,type){SirTrevor.EventBus.on(type,this[callback],this)},this)},hideAllTheThings:function(e){this.block_controls.hide(),this.formatBar.hide(),_.isUndefined(this.block_controls.current_container)||this.block_controls.current_container.removeClass("with-st-controls")},showBlockControls:function(container){_.isUndefined(this.block_controls.current_container)||this.block_controls.current_container.removeClass("with-st-controls"),this.block_controls.show(),container.append(this.block_controls.$el.detach()),container.addClass("with-st-controls"),this.block_controls.current_container=container},store:function(method,options){return SirTrevor.editorStore(this,method,options||{})},createBlock:function(type,data,render_at,focus){if(type=_.classify(type),this._blockLimitReached())return SirTrevor.log("Cannot add any more blocks. Limit reached."),!1;if(!this._isBlockTypeAvailable(type))return SirTrevor.log("Block type not available "+type),!1;if(!this._canAddBlockType(type))return SirTrevor.log("Block Limit reached for type "+type),!1;var block=new SirTrevor.Blocks[type](data,this.ID);return this._renderInPosition(block.render().$el),this.listenTo(block,"removeBlock",this.removeBlock),this.blocks.push(block),this._incrementBlockTypeCount(type),focus!==!1&&block.focus(),SirTrevor.EventBus.trigger(data?"block:create:existing":"block:create:new",block),SirTrevor.log("Block created of type "+type),block.trigger("onRender"),this.$wrapper.toggleClass("st--block-limit-reached",this._blockLimitReached()),this.triggerBlockCountUpdate(),block},onNewBlockCreated:function(block){block.instanceID===this.ID&&this.hideBlockControls()},scrollTo:function(element){},blockFocus:function(block){this.block_controls.current_container=null},_checkEscapeKeyPressed:function(e){27==e.keyCode&&this.hideBlockControls()},hideBlockControls:function(){_.isUndefined(this.block_controls.current_container)||this.block_controls.current_container.removeClass("with-st-controls"),this.block_controls.hide()},removeBlockDragOver:function(){this.$outer.find(".st-drag-over").removeClass("st-drag-over")},triggerBlockCountUpdate:function(){SirTrevor.EventBus.trigger(this.ID+":blocks:count_update",this.blocks.length);
13
+ },changeBlockType:function(block,type){var replacement=this.createBlock(type),currentPosition=this.getBlockPosition(block.$el);this.changeBlockPosition(replacement.$el,currentPosition+1,"After"),replacement.$editor.append(block.$editor.contents()),this.removeBlock(block.blockID),replacement.focus()},changeBlockPosition:function($block,selectedPosition,where){selectedPosition-=1;var blockPosition=this.getBlockPosition($block),$blockBy=this.$wrapper.find(".st-block").eq(selectedPosition);this.getBlockPosition($blockBy);-1===$.inArray(where,["Before","After"])&&(where=blockPosition>selectedPosition?"Before":"After"),$blockBy&&$blockBy.attr("id")!==$block.attr("id")&&(this.hideAllTheThings(),$block["insert"+where]($blockBy))},onBlockDropped:function(block_id){this.hideAllTheThings();var block=this.findBlockById(block_id);_.isUndefined(block)||_.isEmpty(block.getData())||!block.drop_options.re_render_on_reorder||block.beforeLoadingData()},onBlockDragStart:function(){this.hideBlockControls(),this.$wrapper.addClass("st-outer--is-reordering")},onBlockDragEnd:function(){this.removeBlockDragOver(),this.$wrapper.removeClass("st-outer--is-reordering")},_renderInPosition:function(block){this.block_controls.current_container?this.block_controls.current_container.after(block):this.$wrapper.append(block)},_incrementBlockTypeCount:function(type){this.blockCounts[type]=_.isUndefined(this.blockCounts[type])?1:this.blockCounts[type]+1},_getBlockTypeCount:function(type){return _.isUndefined(this.blockCounts[type])?0:this.blockCounts[type]},_canAddBlockType:function(type){var block_type_limit=this._getBlockTypeLimit(type);return!(0!==block_type_limit&&this._getBlockTypeCount(type)>=block_type_limit)},_blockLimitReached:function(){return 0!==this.options.blockLimit&&this.blocks.length>=this.options.blockLimit},removeBlock:function(block_id){var block=this.findBlockById(block_id),type=_.classify(block.type),controls=block.$el.find(".st-block-controls");controls.length&&(this.block_controls.hide(),this.$wrapper.prepend(controls)),this.blockCounts[type]=this.blockCounts[type]-1,this.blocks=_.reject(this.blocks,function(item){return item.blockID==block.blockID}),this.stopListening(block),block.remove(),SirTrevor.EventBus.trigger("block:remove",block),this.triggerBlockCountUpdate(),this.$wrapper.toggleClass("st--block-limit-reached",this._blockLimitReached())},performValidations:function(block,should_validate){var errors=0;return!SirTrevor.SKIP_VALIDATION&&should_validate&&(block.valid()||(this.errors.push({text:_.result(block,"validationFailMsg")}),SirTrevor.log("Block "+block.blockID+" failed validation"),++errors)),errors},saveBlockStateToStore:function(block){var store=block.saveAndReturnData();store&&!_.isEmpty(store.data)&&(SirTrevor.log("Adding data for block "+block.blockID+" to block store"),this.store("add",{data:store}))},onFormSubmit:function(should_validate){return this.removeEmptyBlocks(),should_validate=should_validate!==!1,SirTrevor.log("Handling form submission for Editor "+this.ID),this.removeErrors(),this.store("reset"),this.validateBlocks(should_validate),this.validateBlockTypesExist(should_validate),this.renderErrors(),this.store("save"),this.errors.length},findEmptyTextBlocks:function(){var instance=this;return result=[],this.blocks.forEach(function(block){instance.saveBlockStateToStore(block);var data=block.getData();-1===$.inArray(block.type,["Heading","text"])||void 0!==data.text&&""!==data.text.trim()||result.push(block)}),result},findEmptyRemoveBlocks:function(){var instance=this;return result=[],this.blocks.forEach(function(block){instance.saveBlockStateToStore(block),block.removeEmpty&&block.isEmpty()&&result.push(block)}),result},removeEmptyBlocks:function(){var blocksToDelete=this.findEmptyTextBlocks().concat(this.findEmptyRemoveBlocks()),instance=this;blocksToDelete.forEach(function(block){instance.removeBlock(block.blockID)})},validateBlocks:function(should_validate){if(!this.required&&SirTrevor.SKIP_VALIDATION&&!should_validate)return!1;var blockIterator=function(block,index){var _block=_.find(this.blocks,function(b){return b.blockID==$(block).attr("id")});return _.isUndefined(_block)?!1:(this.performValidations(_block,should_validate),void this.saveBlockStateToStore(_block))};_.each(this.$wrapper.find(".st-block"),blockIterator,this)},validateBlockTypesExist:function(should_validate){if(!this.required&&SirTrevor.SKIP_VALIDATION&&!should_validate)return!1;var blockTypeIterator=function(type,index){if(this._isBlockTypeAvailable(type))if(0===this._getBlockTypeCount(type))SirTrevor.log("Failed validation on required block type "+type),this.errors.push({text:i18n.t("errors:type_missing",{type:type})});else{var blocks=_.filter(this.getBlocksByType(type),function(b){return!b.isEmpty()});if(blocks.length>0)return!1;this.errors.push({text:i18n.t("errors:required_type_empty",{type:type})}),SirTrevor.log("A required block type "+type+" is empty")}};_.isArray(this.required)&&_.each(this.required,blockTypeIterator,this)},renderErrors:function(){if(0===this.errors.length)return!1;_.isUndefined(this.$errors)&&(this.$errors=this._errorsContainer());var str="<ul>";_.each(this.errors,function(error){str+='<li class="st-errors__msg">'+error.text+"</li>"}),str+="</ul>",this.$errors.append(str),this.$errors.show()},_errorsContainer:function(){if(_.isUndefined(this.options.errorsContainer)){var $container=$("<div>",{"class":"st-errors",html:"<p>"+i18n.t("errors:title")+" </p>"});return this.$outer.prepend($container),$container}return $element(this.options.errorsContainer)},removeErrors:function(){return 0===this.errors.length?!1:(this.$errors.hide().find("ul").html(""),void(this.errors=[]))},findBlockById:function(block_id){return _.find(this.blocks,function(b){return b.blockID==block_id})},getBlocksByType:function(block_type){return _.filter(this.blocks,function(b){return _.classify(b.type)==block_type})},getBlocksByIDs:function(block_ids){return _.filter(this.blocks,function(b){return _.contains(block_ids,b.blockID)})},getBlockPosition:function($block){return this.$wrapper.find(".st-block").index($block)},_getBlockTypeLimit:function(t){return this._isBlockTypeAvailable(t)?parseInt(_.isUndefined(this.options.blockTypeLimits[t])?0:this.options.blockTypeLimits[t],10):0},_isBlockTypeAvailable:function(t){return!_.isUndefined(this.blockTypes[t])},_ensureAndSetElements:function(){if(_.isUndefined(this.options.el)||_.isEmpty(this.options.el))return SirTrevor.log("You must provide an el"),!1;this.$el=this.options.el,this.el=this.options.el[0],this.$form=this.$el.parents("form");var $outer=$("<div>").attr({id:this.ID,"class":"st-outer",dropzone:"copy link move"}),$wrapper=$("<div>").attr({"class":"st-blocks"});return this.$el.wrap($outer).wrap($wrapper),this.$outer=this.$form.find("#"+this.ID),this.$wrapper=this.$outer.find(".st-blocks"),!0},_createDynamicBlocks:function(){var options=this.options;_.isUndefined(options.dynamicBlocks)||_.each(options.dynamicBlocks,function(dynamicBlockParams,dynamicBlockName){_.each(dynamicBlockParams,function(dynamicBlockParam){var dynamicBlock=SirTrevor.DynamicBlocks[dynamicBlockName](dynamicBlockParam),type=_.classify("DynamicBlock"+dynamicBlockName+dynamicBlock.type);dynamicBlock.type=type,SirTrevor.Blocks[type]=SirTrevor.Block.extend(dynamicBlock),_.isUndefined(options.blockTypes)||options.blockTypes.push(type)})})},_setBlocksTypes:function(){this.blockTypes=_.flattern(_.isUndefined(this.options.blockTypes)?SirTrevor.Blocks:this.options.blockTypes)},_setRequired:function(){_.isArray(this.options.required)&&!_.isEmpty(this.options.required)?this.required=this.options.required:this.required=!1},_extendLocales:function(){function deepObjectExtend(target,source){return _.each(source,function(value,key){target.hasOwnProperty(key)&&"object"==typeof target?deepObjectExtend(target[key],value):target[key]=value}),target}_.isObject(this.options.locales)&&deepObjectExtend(SirTrevor.Locales,this.options.locales)}}),SirTrevorEditor}(),SirTrevor.setDefaults=function(options){SirTrevor.DEFAULTS=_.extend(SirTrevor.DEFAULTS,options||{})},SirTrevor.bindFormSubmit=function(form){formBound||(new SirTrevor.Submittable(form),form.on("submit.sirtrevor",this.onFormSubmit),formBound=!0)},SirTrevor.onBeforeSubmit=function(should_validate){var errors=0;return _.each(SirTrevor.instances,function(inst,i){errors+=inst.onFormSubmit(should_validate)}),SirTrevor.log("Total errors: "+errors),errors},SirTrevor.onFormSubmit=function(ev){var errors=SirTrevor.onBeforeSubmit();errors>0&&(SirTrevor.EventBus.trigger("onError"),ev.preventDefault())},SirTrevor.getInstance=function(identifier){return _.isUndefined(identifier)?this.instances[0]:_.isString(identifier)?_.find(this.instances,function(editor){return editor.ID===identifier}):this.instances[identifier]},SirTrevor.setBlockOptions=function(type,options){var block=SirTrevor.Blocks[type];_.isUndefined(block)||_.extend(block.prototype,options||{})},SirTrevor.runOnAllInstances=function(method){_.has(SirTrevor.Editor.prototype,method)?([].unshift.call(arguments,SirTrevor.instances),_.invoke.apply(_,arguments)):SirTrevor.log("method doesn't exist")}}(jQuery,_);
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lady_josephine
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.2
4
+ version: 0.6.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bodo Tasche
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2016-03-23 00:00:00.000000000 Z
12
+ date: 2016-03-24 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: rails