/*!
* Sir Trevor JS v0.3.2
*
* Released under the MIT license
* www.opensource.org/licenses/MIT
*
* 2014-09-08
*/
(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="en",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()}$.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)},SirTrevor.Locales={en:{general:{"delete":"Delete?",drop:"Drag __block__ here",paste:"Or paste URL here",upload:"...or choose a file",close:"close",position:"Position",wait:"Please wait...",link:"Enter a link"},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"},blocks:{text:{title:"Text"},list:{title:"List"},quote:{title:"Quote",credit_field:"Credit"},image:{title:"Image",upload_error:"There was a problem with your upload"},video:{title:"Video"},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"}}}},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=SirTrevor.Locales[SirTrevor.LANGUAGE],i=0;parts.length>i;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+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: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":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},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(){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||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;data.append("attachment[name]",file.name),data.append("attachment[file]",file),data.append("attachment[uid]",uid),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=(str+"").toLowerCase(),str.replace(/(?:^|\s|-)\S/g,function(c){return c.toUpperCase()}))},classify:function(str){return _.titleize((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="
"+html),html=html.replace(/\[([^\]]+)\]\(([^\)]+)\)/gm,function(match,p1,p2){return""+p1.replace(/\r?\n/g,"")+""}),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,"