forked from madebymany/sir-trevor-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sir-trevor.min.js
11 lines (10 loc) · 56.7 KB
/
sir-trevor.min.js
1
2
3
4
5
6
7
8
9
10
11
/*!
* Sir Trevor JS v0.3.0-rc.5
*
* Released under the MIT license
* www.opensource.org/licenses/MIT
*
* 2013-10-17
*/
(function($,_){function $element(el){return el instanceof $?el:$(el)}var SirTrevor,root=this;[].push,[].slice,[].splice,SirTrevor=root.SirTrevor={},SirTrevor.DEBUG=!1,SirTrevor.SKIP_VALIDATION=!1,SirTrevor.version="0.3.0-rc.4",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},SirTrevor.BlockMixins={},SirTrevor.Blocks={},SirTrevor.Formatters={},SirTrevor.instances=[],SirTrevor.Events=Eventable;var formBound=!1,FunctionBind={bound:[],_bindFunctions:function(){_.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},_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()}$.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=function(){var range,selection;return range=document.createRange(),range.selectNodeContents(this[0]),range.collapse(!1),selection=window.getSelection(),selection.removeAllRanges(),selection.addRange(range),this}})(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)},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+100*(c/d),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;d.length>g;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;arguments.length>b;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?(this.opts=m(a||{},q.defaults,o),void 0):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;b.lines>c;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){a.childNodes.length>b&&(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;c.lines>=j;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;c.lines>=j;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&&e.childNodes.length>b+d&&(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;switch(options=options||{},method){case"create":var content=_.trim(editor.$el.val());if(editor.dataStore={data:[]},content.length>0)try{var str=JSON.parse(content);_.isUndefined(str.data)||(editor.dataStore=str)}catch(e){editor.errors.push({text:"There was a problem loading the contents of the document"}),editor.renderErrors(),console.log("Sorry there has been a problem with parsing the JSON"),console.log(e)}break;case"reset":editor.dataStore={data:[]};break;case"add":options.data&&(editor.dataStore.data.push(options.data),resp=editor.dataStore);break;case"save":editor.$el.val(editor.dataStore.data.length>0?JSON.stringify(editor.dataStore):"");break;case"read":resp=editor.dataStore}return resp?resp:void 0};var Submittable=function(){this.intialize()};_.extend(Submittable.prototype,{intialize:function(){this.submitBtn=$("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(){this.globalUploadCount++,SirTrevor.log("onUploadStart called "+this.globalUploadCount),1===this.globalUploadCount&&this._disableSubmitButton()},onUploadStop:function(){this.globalUploadCount=0>=this.globalUploadCount?0:this.globalUploadCount-1,SirTrevor.log("onUploadStop called "+this.globalUploadCount),0===this.globalUploadCount&&this._enableSubmitButton()},onError:function(){SirTrevor.log("onError called"),this.canSubmit=!1},_disableSubmitButton:function(message){this.setSubmitButton(null,message||"Please 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.submittable=function(){new Submittable},SirTrevor.fileUploader=function(block,file,success,error){SirTrevor.EventBus.trigger("onUploadStart");var uid=[block.blockID,(new Date).getTime(),"raw"].join("-"),data=new FormData;data.append("attachment[name]",file.name),data.append("attachment[file]",file),data.append("attachment[uid]",uid),block.resetMessages();var callbackSuccess=function(data){SirTrevor.log("Upload callback called"),SirTrevor.EventBus.trigger("onUploadStop"),!_.isUndefined(success)&&_.isFunction(success)&&_.bind(success,block)(data)},callbackError=function(jqXHR,status){SirTrevor.log("Upload callback error called"),SirTrevor.EventBus.trigger("onUploadStop"),!_.isUndefined(error)&&_.isFunction(error)&&_.bind(error,block)(status)},xhr=$.ajax({url:SirTrevor.DEFAULTS.uploadUrl,data:data,cache:!1,contentType:!1,processData:!1,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)},capitalize:function(string){return string.charAt(0).toUpperCase()+string.substring(1).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){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(/\n/g,"")+"</a>"}),html=_.reverse(_.reverse(html).replace(/_(?!\\)((_\\|[^_])*)_(?=$|[^\\])/gm,function(match,p1){return">i/<"+p1.replace(/\n/g,"").replace(/[\s]+$/,"")+">i<"}).replace(/\*\*(?!\\)((\*\*\\|[^\*\*])*)\*\*(?=$|[^\\])/gm,function(match,p1){return">b/<"+p1.replace(/\n/g,"").replace(/[\s]+$/,"")+">b<"})),html=html.replace(/^\> (.+)$/gm,"$1");var formatName,format;for(formatName in this.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(/\n\n/gm,"</div><div><br></div><div>"),html=html.replace(/\n/gm,"</div><div>")),html=html.replace(/\t/g," ").replace(/\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){return _.isUndefined(p2)&&(p2=""),"**"+p1.replace(/<(.)?br(.)?>/g,"")+"**"+p2}function replaceItalics(match,p1,p2){return _.isUndefined(p2)&&(p2=""),"_"+p1.replace(/<(.)?br(.)?>/g,"")+"_"+p2}var markdown=content;markdown=markdown.replace(/ /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;badTags.length>i;i++)tagStripper=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;inlineTags.length>i;i++)tagStripper=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=[""'](.*?)[""'].*?>(.*?)<\/a>/gim,function(match,p1,p2){return"["+p2.trim().replace(/<(.)?br(.)?>/g,"")+"]("+p1+")"}).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 this.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(/</g,"<").replace(/>/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=markdown.replace(/<\/?[^>]+(>|$)/g,"")},SirTrevor.EventBus=_.extend({},SirTrevor.Events),SirTrevor.BlockMixins.Ajaxable={mixinName:"Ajaxable",ajaxable:!0,initializeAjaxable:function(){this._queued=[]},addQueuedItem:function(name,deffered){SirTrevor.log("Adding queued item for "+this.blockID+" called "+name),this._queued.push({name:name,deffered:deffered})},removeQueuedItem:function(name){SirTrevor.log("Removing queued item for "+this.blockID+" called "+name),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.deffered.abort()},this)}},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")}},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.BlockPositioner=function(){var template=["<div class='st-block-positioner__inner'>","<span class='st-block-positioner__selected-value'></span>","<select class='st-block-positioner__select'></select>","</div>"].join("\n"),BlockPositioner=function(block_element,instance_id){this.$block=block_element,this.instanceID=instance_id,this.total_blocks=0,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockPositioner.prototype,FunctionBind,Renderable,{bound:["onBlockCountChange","onSelectChange","toggle","show","hide"],className:"st-block-positioner",visibleClass:"st-block-positioner--is-visible",initialize:function(){this.$el.append(template),this.$select=this.$(".st-block-positioner__select"),this.$select.on("change",this.onSelectChange),SirTrevor.EventBus.on(this.instanceID+":blocks:count_update",this.onBlockCountChange)},onBlockCountChange:function(new_count){new_count!=this.total_blocks&&(this.total_blocks=new_count,this.renderPositionList())},onSelectChange:function(){var val=this.$select.val();0!==val&&(SirTrevor.EventBus.trigger(this.instanceID+":blocks:change_position",this.$block,val,1==val?"before":"after"),this.toggle())},renderPositionList:function(){for(var inner="<option value='0'>Position</option>",i=1;this.total_blocks>=i;i++)inner+="<option value="+i+">"+i+"</option>";this.$select.html(inner)},toggle:function(){this.$select.val(0),this.$el.toggleClass(this.visibleClass)},show:function(){this.$el.addClass(this.visibleClass)},hide:function(){this.$el.removeClass(this.visibleClass)}}),BlockPositioner}(),SirTrevor.BlockReorder=function(){var BlockReorder=function(block_element){this.$block=block_element,this._ensureElement(),this._bindFunctions(),this.initialize()};return _.extend(BlockReorder.prototype,FunctionBind,Renderable,{bound:["onMouseDown","onClick","onDragStart","onDragEnd","onDrag","onDrop"],className:"st-block-ui-btn st-block-ui-btn--reorder st-icon",tagName:"a",attributes:function(){return{html:"reorder",draggable:"true","data-icon":"move"}},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")},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();ev.originalEvent.dataTransfer.setDragImage(this.$block[0],btn.position().left,btn.position().top),ev.originalEvent.dataTransfer.setData("Text",this.$block.attr("id")),SirTrevor.EventBus.trigger("block:reorder:dragstart"),this.$block.addClass("st-block--dragging")},onDragEnd:function(){SirTrevor.EventBus.trigger("block:reorder:dragend"),this.$block.removeClass("st-block--dragging")},onDrag:function(){},onClick:function(){},render:function(){return this}}),BlockReorder}(),SirTrevor.BlockDeletion=function(){var BlockDeletion=function(){this._ensureElement(),this._bindFunctions()};return _.extend(BlockDeletion.prototype,FunctionBind,Renderable,{tagName:"a",className:"st-block-ui-btn st-block-ui-btn--delete st-icon",attributes:{html:"delete","data-icon":"bin"}}),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,bestNameFromField(field)+" must not be empty")},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:this.type.toLowerCase(),data:blockData||{}}},save:function(){this.toData()},saveAndReturnData:function(){return this.save(),this.blockStorage},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("editor/block/loadData"),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 _.capitalize(this.type)},blockCSSClass:function(){return this.blockCSSClass=_.to_slug(this.type),this.blockCSSClass},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 mouseover",function(e){e.stopPropagation()})},render:function(){return this.beforeBlockRender(),this._setBlockInner(),this._blockPrepare(),this.onBlockRender(),this},_blockPrepare:function(){this._initUI(),this._initMessages(),this.checkAndLoadData(),this.$el.addClass("st-item-ready"),this.save()},_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(){SirTrevor.SimpleBlock.apply(this,arguments)},delete_template=["<div class='st-block__ui-delete-controls'>","<label class='st-block__delete-label'>Delete?</label>","<a class='st-block-ui-btn st-block-ui-btn--confirm-delete st-icon' data-icon='tick'></a>","<a class='st-block-ui-btn st-block-ui-btn--deny-delete st-icon' data-icon='close'></a>","</div>"].join("\n"),drop_options={html:['<div class="st-block__dropzone">','<span class="st-icon"><%= _.result(block, "icon_name") %></span>',"<p>Drag <span><%= block.type %></span> here</p></div>"].join("\n"),re_render_on_reorder:!1},paste_options={html:'<input type="text" placeholder="Or paste URL here" class="st-block__paste-input st-paste-block">'},upload_options={html:['<div class="st-block__upload-container">','<input type="file" type="st-file-upload">','<button class="st-upload-btn">...or choose a file</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:["_handleContentPaste","_onFocus","_onBlur","onDrop","onDeleteClick","clearInsertedStyles","getSelectionForFormatter"],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 this.type+" block is invalid"},editorHTML:'<div class="st-block__editor"></div>',toolbarEnabled:!0,droppable:!1,pastable:!1,uploadable:!1,fetchable:!1,ajaxable:!1,drop_options:{},paste_options:{},upload_options:{},formattable:!0,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.formattable&&this._initFormatting(),this._blockPrepare(),this.onBlockRender(),this},remove:function(){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))}var hasTextAndData=!_.isUndefined(dataObj.text)||!this.hasTextBlock();this.$('input[type="text"]').not(".st-paste-block").length>0&&this.$('input[type="text"]').each(function(index,input){input=$(input),hasTextAndData&&(dataObj[input.attr("name")]=input.val())}),_.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(){},onDeleteClick:function(ev){ev.preventDefault(),this.$inner.append(delete_template),this.$el.addClass("st-block--delete-active");var $delete_el=this.$inner.find(".st-block__ui-delete-controls"),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()};this.$inner.on("click",".st-block-ui-btn--confirm-delete",_.bind(onDeleteConfirm,this)).on("click",".st-block-ui-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()},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(){var positioner=new SirTrevor.BlockPositioner(this.$el,this.instanceID);this._withUIComponent(positioner,".st-block-ui-btn--reorder",positioner.toggle),this._withUIComponent(new SirTrevor.BlockReorder(this.$el)),this._withUIComponent(new SirTrevor.BlockDeletion,".st-block-ui-btn--delete",this.onDeleteClick),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.getSelectionForFormatter).bind("mouseup",this.getSelectionForFormatter).bind("DOMNodeInserted",this.clearInsertedStyles)},getSelectionForFormatter:function(){var selection=window.getSelection();""===(""+selection).trim()?SirTrevor.EventBus.trigger("formatter:hide"):SirTrevor.EventBus.trigger("formatter:positon")},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}}),Block.extend=extend,Block}(),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" contenteditable="true"></blockquote>','<label class="st-input-label">Credit</label>','<input maxlength="140" name="cite" placeholder="Credit" class="st-input-string st-required js-cite-input" type="text" />'].join("\n"));return SirTrevor.Block.extend({type:"Quote",icon_name:"quote",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.Embedly=function(){return SirTrevor.Block.extend({type:"Embedly",key:"",droppable:!0,pastable:!0,fetchable:!0,icon_name:"embed",loadData:function(data){data.html?(this.$editor.addClass("st-block__editor--with-sixteen-by-nine-media"),this.$editor.html(data.html)):"photo"==data.type&&this.$editor.html('<img src="'+data.url+'" />')},onContentPasted:function(event){var input=$(event.target),val=input.val();this.handleDropPaste(val)},handleDropPaste:function(url){if(!_.isURI(url))return SirTrevor.log("Must be a URL"),void 0;this.loading();var embedlyCallbackSuccess=function(data){this.setAndLoadData(data),this.ready()},embedlyCallbackFail=function(){this.ready()},ajaxOptions={url:this.buildAPIUrl(url),dataType:"jsonp"};this.fetch(ajaxOptions,_.bind(embedlyCallbackSuccess,this),_.bind(embedlyCallbackFail,this))},buildAPIUrl:function(url){return"//api.embed.ly/1/oembed?key="+this.key+"&url="+escape(url)},onDrop:function(transferData){this.handleDropPaste(transferData.getData("text/plain"))}})}(),SirTrevor.Blocks.Heading=SirTrevor.Block.extend({type:"Heading",editorHTML:'<div class="st-required st-text-block st-text-block--heading" contenteditable="true"></div>',icon_name:"heading",loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type))}}),SirTrevor.Blocks.Image=SirTrevor.Block.extend({type:"Image",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))},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(),SirTrevor.EventBus.trigger("setSubmitButton",["Please wait..."]),this.uploader(file,function(data){this.setData(data),this.ready()},function(){this.addMessage("There was a problem with your upload"),this.ready()}))}}),SirTrevor.Blocks.Text=SirTrevor.Block.extend({type:"Text",editorHTML:'<div class="st-required st-text-block" contenteditable="true"></div>',icon_name:"text",loadData:function(data){this.getTextBlock().html(SirTrevor.toHTML(data.text,this.type))}}),SirTrevor.Blocks.Tweet=function(){var tweet_template=_.template(["<blockquote class='twitter-tweet' align='center'>","<p><%= text %></p>","— <%= 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},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 SirTrevor.log("Invalid Tweet URL"),void 0;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("There was a problem fetching your tweet"),this.ready()},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleTwitterDropPaste(url)}})}(),SirTrevor.Blocks.List=function(){var template='<div class="st-text-block" contenteditable="true"><ul><li></li></ul></div>';return SirTrevor.Block.extend({type:"List",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()}})}(),SirTrevor.Blocks.Video=function(){var video_regex=/http[s]?:\/\/(?:www.)?(?:(vimeo).com\/(.*))|(?:(youtu(?:be)?).(?:be|com)\/(?:watch\?v=)?([^&]*)(?:&(?:.))?)/;return SirTrevor.Block.extend({type:"Video",droppable:!0,pastable:!0,icon_name:"video",loadData:function(data){this.$editor.addClass("st-block__editor--with-sixteen-by-nine-media"),"youtube"==data.source||"youtu"==data.source?this.$editor.html('<iframe src="'+window.location.protocol+"//www.youtube.com/embed/"+data.remote_id+'" width="580" height="320" frameborder="0" allowfullscreen></iframe>'):"vimeo"==data.source&&this.$editor.html('<iframe src="'+window.location.protocol+"//player.vimeo.com/video/"+data.remote_id+'?title=0&byline=0" width="580" height="320" frameborder="0"></iframe>')},onContentPasted:function(event){var input=$(event.target),val=input.val();this.handleDropPaste(val)},handleDropPaste:function(url){if(_.isURI(url)&&(-1!=url.indexOf("youtu")||-1!=url.indexOf("vimeo"))){var data={},videos=url.match(video_regex);void 0!==videos[3]?(data.source=videos[3],data.remote_id=videos[4]):void 0!==videos[1]&&(data.source=videos[1],data.remote_id=videos[2]),"youtu"==data.source&&(data.source="youtube"),this.setAndLoadData(data)}},onDrop:function(transferData){var url=transferData.getData("text/plain");this.handleDropPaste(url)}})}(),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 link=prompt("Enter a link"),link_regex=/(ftp|http|https):\/\/./;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}(),SirTrevor.BlockControl=function(){var BlockControl=function(type,instance_scope){this.type=type,this.instance_scope=instance_scope,this._ensureElement(),this.initialize()};return _.extend(BlockControl.prototype,FunctionBind,Renderable,SirTrevor.Events,{tagName:"a",className:"st-block-control",attributes:function(){return{"data-type":this.type}},initialize:function(){this.block_type=SirTrevor.Blocks[this.type].prototype,this.can_be_rendered=this.block_type.toolbarEnabled},render:function(){return this.$el.html('<span class="st-icon">'+_.result(this.block_type,"icon_name")+"</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'>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")},hide:function(){this.$el.removeClass("st-block-controls--active")},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;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(){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){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._setRequired(),this._setBlocksTypes(),this._bindFunctions(),this.store("create"),this.build(),SirTrevor.instances.push(this),SirTrevor.bindFormSubmit(this.$form),void 0):!1};return _.extend(SirTrevorEditor.prototype,FunctionBind,SirTrevor.Events,{bound:["onFormSubmit","showBlockControls","hideAllTheThings","hideBlockControls","onNewBlockCreated","changeBlockPosition","onBlockDragStart","onBlockDragEnd","removeBlockDragOver","onBlockDropped","createBlock"],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(){},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),this._setEvents(),SirTrevor.EventBus.on(this.ID+":blocks:change_position",this.changeBlockPosition),SirTrevor.EventBus.on("formatter:positon",this.formatBar.renderBySelection),SirTrevor.EventBus.on("formatter:hide",this.formatBar.hide),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",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.createBlock(this.options.defaultType,{}),this.$wrapper.addClass("st-ready"),_.isUndefined(this.onEditorRender)||this.onEditorRender()},_setEvents:function(){_.each(this.events,function(callback,type){SirTrevor.EventBus.on(type,this[callback],this)},this)},hideAllTheThings:function(){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){if(type=_.capitalize(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);this._renderInPosition(block.render().$el),this.listenTo(block,"removeBlock",this.removeBlock),this.blocks.push(block),this._incrementBlockTypeCount(type),block.focus(),SirTrevor.EventBus.trigger(data?"block:create:existing":"block:create:new",block),SirTrevor.log("Block created of type "+type),this.$wrapper.toggleClass("st--block-limit-reached",this._blockLimitReached()),this.triggerBlockCountUpdate()},onNewBlockCreated:function(block){this.hideBlockControls(),this.scrollTo(block.$el)},scrollTo:function(element){$("html, body").animate({scrollTop:element.position().top},300,"linear")},blockFocus:function(){this.block_controls.current_container=null},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)},changeBlockPosition:function($block,selectedPosition){selectedPosition-=1;var blockPosition=this.getBlockPosition($block),$blockBy=this.$wrapper.find(".st-block").eq(selectedPosition);this.getBlockPosition($blockBy);var where=blockPosition>selectedPosition?"Before":"After";$blockBy&&$blockBy.attr("id")!==$block.attr("id")&&(this.hideAllTheThings(),$block["insert"+where]($blockBy),this.scrollTo($block))},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),controls=block.$el.find(".st-block-controls");controls.length&&(this.block_controls.hide(),this.$wrapper.prepend(controls)),this.blockCounts[block.type]=this.blockCounts[block.type]-1,this.blocks=_.reject(this.blocks,function(item){return item.blockID==block.blockID}),this.stopListening(block),block.ajaxable&&block.resolveAllInQueue(),block.remove(),SirTrevor.EventBus.trigger("block:remove"),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 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},validateBlocks:function(should_validate){if(!this.required&&SirTrevor.SKIP_VALIDATION&&!should_validate)return!1;var blockIterator=function(block){var _block=_.find(this.blocks,function(b){return b.blockID==$(block).attr("id")});return _.isUndefined(_block)?!1:(this.performValidations(_block,should_validate),this.saveBlockStateToStore(_block),void 0)};_.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){if(this._isBlockTypeAvailable(type))if(0===this._getBlockTypeCount(type))SirTrevor.log("Failed validation on required block type "+type),this.errors.push({text:"You must have a block of type "+type});else{var blocks=_.filter(this.blocks,function(b){return b.type==type&&!_.isEmpty(b.getData())});if(blocks.length>0)return!1;this.errors.push({text:"A required block type "+type+" is empty"}),SirTrevor.log("A required block type "+type+" is empty")}};_.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>You have the following errors: </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(""),this.errors=[],void 0)},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 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},_setBlocksTypes:function(){this.blockTypes=_.flattern(_.isUndefined(this.options.blockTypes)?SirTrevor.Blocks:this.options.blockTypes)},_setRequired:function(){this.required=_.isArray(this.options.required)&&!_.isEmpty(this.options.required)?this.options.required:!1}}),SirTrevorEditor}(),SirTrevor.setDefaults=function(options){SirTrevor.DEFAULTS=_.extend(SirTrevor.DEFAULTS,options||{})},SirTrevor.bindFormSubmit=function(form){formBound||(SirTrevor.submittable(),form.bind("submit",this.onFormSubmit),formBound=!0)},SirTrevor.onBeforeSubmit=function(should_validate){var errors=0;return _.each(SirTrevor.instances,function(inst){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.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,_);