diff --git a/public/cache.manifest b/public/cache.manifest index cfabe26c..8eb56c89 100644 --- a/public/cache.manifest +++ b/public/cache.manifest @@ -1,5 +1,5 @@ CACHE MANIFEST -#Date Mon Apr 21 2014 17:31:32 +#Date Mon Apr 21 2014 18:45:42 CACHE: res/worker.js diff --git a/public/res-min/main.js b/public/res-min/main.js index af209d68..ca65e609 100644 --- a/public/res-min/main.js +++ b/public/res-min/main.js @@ -649,12 +649,12 @@ if(0===t.usedFootnotes.length)return e;e+='\n\n
\n
\n\n \n
\n
\n \n
\n'}),define("extensions/dialogManageSharing",["jquery","underscore","classes/Extension","text!html/dialogManageSharingLocation.html"],function(e,t,n,i){var r,o=new n("dialogManageSharing",'Button "Share"',!1,!0);o.onEventMgrCreated=function(e){r=e};var a,s,l,c,u=function(e){if(void 0===e||e===a){var n=t.reduce(a.publishLocations,function(e,n){return n.sharingLink&&(e+=t.template(i,{link:n.sharingLink,title:a.title})),e},"");s.innerHTML=n,r.onTweet(),l.toggleClass("hide",0===n.length),c.toggleClass("hide",0!==n.length)}};return o.onFileSelected=function(e){a=e,u(e)},o.onNewPublishSuccess=function(t,n){u(t),n.sharingLink&&(e(".modal").modal("hide"),e(".modal-manage-sharing").modal("show"))},o.onPublishRemoved=u,o.onReady=function(){var t=document.querySelector(".modal-manage-sharing");s=t.querySelector(".share-list"),l=e(t.querySelectorAll(".msg-share-list")),c=e(t.querySelectorAll(".msg-no-share"))},o}),function(){var e=this,t={},n=!1;"undefined"!=typeof module&&module.exports?(module.exports=t,e.toMarkdown=t,n=!0):e.toMarkdown=t,t.converter=function(e){e&&e.elements&&$.isArray(e.elements)&&(c=c.concat(e.elements)),this.makeMd=function(e,t){var r;if(n){var o=require("jsdom");o.env({html:e,scripts:["http://code.jquery.com/jquery-1.6.4.min.js"],done:function(n,r){"function"==typeof t&&t(i(e,r.$))}})}else r=i(e,$);return r}};var i=function(e,t){e=e.replace(/(\d+)\. /g,"$1\\. ");var n=t("
"),i=n.html(e);i.find("*:not(pre, code)").contents().filter(function(){return 3===this.nodeType&&/^\s+$/.test(this.nodeValue)}).remove();for(var r=[],o=0,s=c.length;s>o;o++)r.push(c[o].selector);for(r=r.join(",");i.find(r).length;)for(var o=0,s=c.length;s>o;o++)$matches=i.find(c[o].selector+':not(:has("'+r+'"))'),$matches.each(function(e,n){var i=t(n);i.before(c[o].replacement(i.html(),i)).remove()});return a(i.html())},r=function(e){return e.replace(/^[\n\r\f]+|[\n\r\f]+$/g,"")},o=function(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"')},a=function(e){return e=e.replace(/^[\t\r\n]+|[\t\r\n]+$/g,""),e=e.replace(/\n\s+\n/g,"\n\n"),e=e.replace(/\n{3,}/g,"\n\n"),e=o(e)},s=function(e){return e=r(e),e?"**"+e+"**":""},l=function(e){return e=r(e),e?"_"+e+"_":""},c=[{selector:"p",replacement:function(e){return e=$.trim(e),e?"\n\n"+e+"\n\n":""}},{selector:"br",replacement:function(){return"\n"}},{selector:"h1,h2,h3,h4,h5,h6",replacement:function(e,t){e=$.trim(e);for(var n=t.prop("nodeName").charAt(1),i="",r=0;n>r;r++)i+="#";return e?"\n\n"+i+" "+e+"\n\n":""}},{selector:"hr",replacement:function(){return"\n\n* * *\n\n"}},{selector:"a[href]",replacement:function(e,t){if(e){e=r(e);var n=t.attr("href"),i=t.attr("title")||"";return"["+e+"]("+n+(i?' "'+i+'"':"")+")"}return!1}},{selector:"b",replacement:s},{selector:"strong",replacement:s},{selector:"i",replacement:l},{selector:"em",replacement:l},{selector:"code",replacement:function(e){return e=r(e),e?"`"+e+"`":""}},{selector:"img",replacement:function(e,t){var n=t.attr("alt")||"",i=t.attr("src")||"",r=t.attr("title")||"";return"!["+n+"]("+i+(r?' "'+r+'"':"")+")"}},{selector:"pre",replacement:function(e){return/^\s*\`/.test(e)?(e=e.replace(/\`/g,"")," "+e.replace(/\n/g,"\n ")):""}},{selector:"li",replacement:function(e,t){e=e.replace(/^\s+|\s+$/,"").replace(/\n/gm,"\n ");var n="* ",i="",r=t.parent(),o=r.contents().filter(function(){return 1===this.nodeType&&"LI"===this.nodeName||3===this.nodeType}),a=o.index(t)+1;return n=r.is("ol")?a+". ":"* ",a==o.length&&(t.parents("li").length||(i="\n"),e=e.replace(/\s+$/,""),t.unwrap()),n+e+i+"\n"}},{selector:"blockquote",replacement:function(e){return e=e=$.trim(e).replace(/\n{3,}/g,"\n\n"),e=e.replace(/\n/g,"\n> "),"> "+e}}]}(),define("toMarkdown",["jquery"],function(e){return function(){var t;return t||e.toMarkdown}}(this)),define("extensions/dialogOpenHarddrive",["jquery","underscore","constants","utils","classes/Extension","toMarkdown"],function(e,t,n,i,r,o){function a(i){i.stopPropagation(),i.preventDefault();var r=(i.dataTransfer||i.target).files;e(".modal-import-harddrive-markdown, .modal-import-harddrive-html").modal("hide"),t.each(r,function(t){if(!e(i.target).is("#wmd-input *")||!t.name.match(/.(jpe?g|png|gif)$/i)){var r=new FileReader;r.onload=function(e){return function(t){var n=t.target.result;if(n.match(/\uFFFD/))return void p.onError(e.name+" is a binary file.");if(n=f?f(n):n,void 0===n)return void p.onError(e.name+" is not a valid HTML file.");var i=e.name,r=i.lastIndexOf(".");i=-1!==r?i.substring(0,r):i;var o=u.createFile(i,n);u.selectFile(o)}}(t);var o=t.slice(0,n.IMPORT_FILE_MAX_CONTENT_SIZE);r.readAsText(o)}})}function s(e){f=void 0,a(e)}function l(e){f=m,a(e)}function c(e){e.stopPropagation(),e.preventDefault(),e.dataTransfer.dropEffect="copy"}var u,d=new r("dialogOpenHarddrive",'Dialog "Open from"');d.onFileMgrCreated=function(e){u=e};var p;d.onEventMgrCreated=function(e){p=e};var f,h,m=function(e){return h.makeMd(e)};return d.onReady=function(){h=new o.converter,e("#input-file-import-harddrive-markdown").change(s),e("#dropzone-import-harddrive-markdown, #wmd-input").each(function(){this.addEventListener("dragover",c,!1),this.addEventListener("drop",s,!1)}),e("#input-file-import-harddrive-html").change(l),e("#dropzone-import-harddrive-html").each(function(){this.addEventListener("dragover",c,!1),this.addEventListener("drop",l,!1)}),e(".action-convert-html").click(function(e){var t=i.getInputTextValue("#input-convert-html",e);if(void 0!==t){if(t=h.makeMd(t),void 0===t)return void p.onError("Invalid HTML code.");var n=u.createFile(void 0,t);u.selectFile(n)}})},d}),define("extensions/documentTitle",["jquery","underscore","classes/Extension"],function(e,t,n){var i,r,o=new n("documentTitle","Document Title"),a=t.debounce(function(t){if(t===i){var n=i.title;document.title="StackEdit – "+n,r.html(i.composeTitle()),e(".file-title").text(n),e(".input-file-title").val(n)}},50);return o.onFileSelected=function(e){i=e,a(e)},o.onTitleChanged=a,o.onSyncExportSuccess=a,o.onSyncRemoved=a,o.onNewPublishSuccess=a,o.onPublishRemoved=a,o.onReady=a,o.onReady=function(){r=e(".file-title-navbar"),r.hover(function(){var e=r[0].scrollWidth-r.outerWidth();r.stop(!0,!0).animate({scrollLeft:e},15*e,"linear")},function(){r.stop(!0,!0).scrollLeft(0)}).click(function(){r.stop(!0,!0).scrollLeft(0)})},o}),function(e,t){function n(e,t,n){return e.addEventListener?void e.addEventListener(t,n,!1):void e.attachEvent("on"+t,n)}function i(e){if("keypress"==e.type){var t=String.fromCharCode(e.which);return e.shiftKey||(t=t.toLowerCase()),t}return E[e.which]?E[e.which]:T[e.which]?T[e.which]:String.fromCharCode(e.which).toLowerCase()}function r(e,t){return e.sort().join(",")===t.sort().join(",")}function o(e){e=e||{};var t,n=!1;for(t in N)e[t]?n=!0:N[t]=0;n||(A=!1)}function a(e,t,n,i,o,a){var s,l,c=[],u=n.type;if(!I[e])return[];for("keyup"==u&&f(e)&&(t=[e]),s=0;s95&&112>e||E.hasOwnProperty(e)&&(S[E[e]]=e)}return S}function g(e,t,n){return n||(n=m()[e]?"keydown":"keypress"),"keypress"==n&&t.length&&(n="keydown"),n}function v(e,t,n,r){function a(t){return function(){A=t,++N[e],h()}}function s(t){u(n,t,e),"keyup"!==r&&(L=i(t)),setTimeout(o,10)}N[e]=0;for(var l=0;l1?void v(e,s,t,n):(o=y(e,n),I[o.key]=I[o.key]||[],a(o.key,o.modifiers,{type:o.action},i,e,r),void I[o.key][i?"unshift":"push"]({callback:t,modifiers:o.modifiers,action:o.action,seq:i,level:r,combo:e}))}function w(e,t,n){for(var i=0;i":".","?":"/","|":"\\"},_={option:"alt",command:"meta","return":"enter",escape:"esc",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},I={},D={},N={},L=!1,M=!1,A=!1,R=1;20>R;++R)E[111+R]="f"+R;for(R=0;9>=R;++R)E[R+96]=R;n(t,"keypress",p),n(t,"keydown",p),n(t,"keyup",p);var P={bind:function(e,t,n){return e=e instanceof Array?e:[e],w(e,t,n),this},unbind:function(e,t){return P.bind(e,function(){},t)},trigger:function(e,t){return D[e+":"+t]&&D[e+":"+t]({},e),this},reset:function(){return I={},D={},this},stopCallback:function(e,t){return(" "+t.className+" ").indexOf(" mousetrap ")>-1?!1:"INPUT"==t.tagName||"SELECT"==t.tagName||"TEXTAREA"==t.tagName||t.isContentEditable},handleKey:d};e.Mousetrap=P,"function"==typeof define&&define.amd&&define("mousetrap",P)}(window,document),define("classes/FileDescriptor",["underscore","utils","storage"],function(e,t,n){function i(e,t,i,r){this.fileIndex=e,this._title=t||n[e+".title"],this._editorScrollTop=parseInt(n[e+".editorScrollTop"])||0,this._editorStart=parseInt(n[e+".editorEnd"])||0,this._editorEnd=parseInt(n[e+".editorEnd"])||0,this._previewScrollTop=parseInt(n[e+".previewScrollTop"])||0,this._selectTime=parseInt(n[e+".selectTime"])||0,this._discussionList=JSON.parse(n[e+".discussionList"]||"{}"),this.syncLocations=i||{},this.publishLocations=r||{},Object.defineProperty(this,"title",{get:function(){return this._title},set:function(e){this._title=e,n[this.fileIndex+".title"]=e}}),Object.defineProperty(this,"content",{get:function(){return n[this.fileIndex+".content"]},set:function(e){n[this.fileIndex+".content"]=e}}),Object.defineProperty(this,"editorScrollTop",{get:function(){return this._editorScrollTop},set:function(e){this._editorScrollTop=e,n[this.fileIndex+".editorScrollTop"]=e}}),Object.defineProperty(this,"editorStart",{get:function(){return this._editorStart},set:function(e){this._editorStart=e,n[this.fileIndex+".editorStart"]=e}}),Object.defineProperty(this,"editorEnd",{get:function(){return this._editorEnd},set:function(e){this._editorEnd=e,n[this.fileIndex+".editorEnd"]=e}}),Object.defineProperty(this,"previewScrollTop",{get:function(){return this._previewScrollTop},set:function(e){this._previewScrollTop=e,n[this.fileIndex+".previewScrollTop"]=e}}),Object.defineProperty(this,"selectTime",{get:function(){return this._selectTime},set:function(e){this._selectTime=e,n[this.fileIndex+".selectTime"]=e}}),Object.defineProperty(this,"discussionList",{get:function(){return this._discussionList},set:function(e){this._discussionList=e,n[this.fileIndex+".discussionList"]=JSON.stringify(e)}}),Object.defineProperty(this,"discussionListJSON",{get:function(){return n[this.fileIndex+".discussionList"]||"{}"},set:function(e){this._discussionList=JSON.parse(e),n[this.fileIndex+".discussionList"]=e}})}return i.prototype.addSyncLocation=function(e){t.storeAttributes(e),t.appendIndexToArray(this.fileIndex+".sync",e.syncIndex),this.syncLocations[e.syncIndex]=e},i.prototype.removeSyncLocation=function(e){t.removeIndexFromArray(this.fileIndex+".sync",e.syncIndex),delete this.syncLocations[e.syncIndex]},i.prototype.addPublishLocation=function(e){t.storeAttributes(e),t.appendIndexToArray(this.fileIndex+".publish",e.publishIndex),this.publishLocations[e.publishIndex]=e},i.prototype.removePublishLocation=function(e){t.removeIndexFromArray(this.fileIndex+".publish",e.publishIndex),delete this.publishLocations[e.publishIndex]},i.prototype.composeTitle=function(){var t=[];return e.chain(this.syncLocations).sortBy(function(e){return e.provider.providerId}).each(function(e){t.push('')}),0!==e.size(this.syncLocations)&&t.push(''),e.chain(this.publishLocations).sortBy(function(e){return e.provider.providerId}).each(function(e){t.push('')}),0!==e.size(this.publishLocations)&&t.push(''),t.push(e.escape(this.title)),t.join("")},i}),define("fileSystem",["underscore","utils","classes/FileDescriptor","storage"],function(e,t,n,i){var r={};return t.retrieveIndexArray("file.list").forEach(function(e){r[e]=new n(e)}),Object.keys(i).forEach(function(e){var t=e.match(/(file\.\S+?)\.\S+/);t&&!r.hasOwnProperty(t[1])&&i.removeItem(e)}),r}),define("text!html/documentSelectorSettingsBlock.html",[],function(){return'

Allows toggling document with keyboard shortcuts.

\n
\n
\n \n
\n \n
\n
\n
\n \n
\n \n
\n
\n
\n \n
\n \n
\n
\n
'}),define("extensions/documentSelector",["jquery","underscore","crel","utils","classes/Extension","mousetrap","fileSystem","text!html/documentSelectorSettingsBlock.html"],function(e,t,n,i,r,o,a,s){var l=new r("documentSelector","Document Selector",!0);l.settingsBlock=s,l.defaultConfig={orderBy:"mru",shortcutPrevious:"Ctrl+[",shortcutNext:"Ctrl+]"},l.onLoadSettings=function(){i.setInputValue("#select-document-selector-orderby",l.config.orderBy),i.setInputValue("#input-document-selector-shortcut-previous",l.config.shortcutPrevious),i.setInputValue("#input-document-selector-shortcut-next",l.config.shortcutNext)},l.onSaveSettings=function(e,t){e.orderBy=i.getInputValue("#select-document-selector-orderby"),e.shortcutPrevious=i.getInputTextValue("#input-document-selector-shortcut-previous",t),e.shortcutNext=i.getInputTextValue("#input-document-selector-shortcut-next",t)};var c;l.onFileMgrCreated=function(e){c=e};var u,d,p,f,h,m,g,v=['
  • " data-file-index="<%= fileDesc.fileIndex %>">',' '," <%= fileDesc.composeTitle() %>"," ","
  • "].join(""),b=t.debounce(function(){var n=t.chain(a).sortBy(f).reduce(function(e,n){return e+t.template(v,{fileDesc:n,isCurrent:n===h})},"").value();u.innerHTML=n,p=[],d={},t.each(u.querySelectorAll("li"),function(t){var n=e(t);p.push(n);var i=a[n.data("fileIndex")];d[i.fileIndex]=n,n.find("a").click(function(){m=void 0,n.hasClass("disabled")?g.focus():c.selectFile(i)})})},50);return l.onFileSelected=function(e){h=e,b()},l.onFileCreated=b,l.onFileDeleted=b,l.onTitleChanged=b,l.onSyncExportSuccess=b,l.onSyncRemoved=b,l.onNewPublishSuccess=b,l.onPublishRemoved=b,l.onReady=function(){g=e("#wmd-input"),"title"==l.config.orderBy?f=function(e){return e.title.toLowerCase()}:"mru"==l.config.orderBy&&(f=function(e){return-e.selectTime}),u=n("ul",{"class":"dropdown-menu dropdown-file-selector"}),document.querySelector(".navbar").appendChild(n("div",n("div",{"data-toggle":"dropdown"}),u));var i=e(u).dropdown(),r=e(".document-panel .collapse-button");r.prop("title",t.template("<%= title %> <%= shortcutPrevious %> <%= shortcutNext %>",{title:r.prop("title"),shortcutPrevious:l.config.shortcutPrevious,shortcutNext:l.config.shortcutNext}));var a=l.config.shortcutPrevious.toLowerCase();o.bind(a,function(){void 0===m&&(i.dropdown("toggle"),m=d[h.fileIndex]);var e=t.indexOf(p,m)-1;return-2===e&&(e=-1),m=p[(e+p.length)%p.length],setTimeout(function(){m.find("a").focus()},10),!1});var s=l.config.shortcutNext.toLowerCase();o.bind(l.config.shortcutNext.toLowerCase(),function(){void 0===m&&(i.dropdown("toggle"),m=d[h.fileIndex]);var e=t.indexOf(p,m)+1;return m=p[e%p.length],setTimeout(function(){m.find("a").focus()},10),!1});var c=a.indexOf("+"),v=-1===c?a:a.substring(0,c),b=s.indexOf("+"),y=-1===b?s:s.substring(0,b);o.bind([v,y],function(){void 0!==m&&m.find("a").click()},"keyup")},l}),define("classes/FolderDescriptor",["underscore","utils","storage","fileSystem"],function(e,t,n,i){function r(r,o){this.folderIndex=r,this._name=o||n[r+".name"],this.fileList={},e.each(t.retrieveIndexArray(r+".files"),function(e){try{var n=i[e];n.folder=this,this.fileList[e]=n}catch(o){t.removeIndexFromArray(r+".files",e)}},this),Object.defineProperty(this,"name",{get:function(){return this._name},set:function(e){this._name=e,n[this.folderIndex+".name"]=e}})}return r.prototype.addFile=function(e){e.folder=this,t.appendIndexToArray(this.folderIndex+".files",e.fileIndex),this.fileList[e.fileIndex]=e},r.prototype.removeFile=function(e){e.folder=void 0,t.removeIndexFromArray(this.folderIndex+".files",e.fileIndex),delete this.fileList[e.fileIndex]},r}),define("folderList",["underscore","utils","storage","classes/FolderDescriptor","storage"],function(e,t,n,i){var r={};return t.retrieveIndexArray("folder.list").forEach(function(e){r[e]=new i(e)}),Object.keys(n).forEach(function(e){var t=e.match(/(folder\.\S+?)\.\S+/);t&&!r.hasOwnProperty(t[1])&&n.removeItem(e)}),r}),define("extensions/documentPanel",["jquery","underscore","utils","classes/Extension","folderList","fileSystem"],function(e,t,n,i,r,o){function a(n){if(n!=y){if(y=n,b.scrollTop=0,!n)return f.addClass("hide"),void d.removeClass("hide");var i=n.toLowerCase().split(/\s+/);t.each(p.querySelectorAll(".file"),function(n){var r=e(n),o=r.text().toLowerCase();r.toggle(!t.some(i,function(e){return-1===o.indexOf(e)}))}),f.removeClass("hide"),d.addClass("hide")}}var s,l=new i("documentPanel","Document Panel");l.onFileMgrCreated=function(e){s=e};var c,u,d,p,f,h,m=['','
    '," <%= _.size(folderDesc.fileList) %>","
    ",' <%= folderDesc.name %>',"
    ",'
    '," <%= fileListHtml %>","
    "].join(""),g=['"',' data-file-index="<%= fileDesc.fileIndex %>">'," <%= fileDesc.composeTitle() %>",""].join(""),v=t.debounce(function(){var n=t.filter(o,function(e){return void 0===e.folder}),i=t.chain(n).sortBy(function(e){return e.title.toLowerCase()}).reduce(function(e,n){return e+"
  • "+t.template(g,{fileDesc:n,selectedFileDesc:h})+"
  • "},"").value();i=i&&'",t.chain(r).sortBy(function(e){return e.name.toLowerCase()}).each(function(e){var n=t.chain(e.fileList).sortBy(function(e){return e.title.toLowerCase()}).reduce(function(e,n){return e+"
  • "+t.template(g,{fileDesc:n,selectedFileDesc:h})+"
  • "},"").value();n=n&&'",i+=t.template(m,{folderDesc:e,fileListHtml:n,id:e.folderIndex.replace(".","")})}),u.innerHTML=i;var a=t.chain(o).sortBy(function(e){return e.title.toLowerCase()}).reduce(function(e,n){return e+"
  • "+t.template(g,{fileDesc:n,selectedFileDesc:h})+"
  • "},"").value();a='",p.innerHTML=a,t.each(c.querySelectorAll(".file"),function(t){var n=e(t);n.click(function(){var e=o[n.data("fileIndex")];e&&e!==h&&s.selectFile(e)})})},50);l.onFileSelected=function(e){h=e,v()},l.onFileCreated=v,l.onFileDeleted=v,l.onTitleChanged=v,l.onSyncExportSuccess=v,l.onSyncRemoved=v,l.onNewPublishSuccess=v,l.onPublishRemoved=v,l.onFoldersChanged=v;var b,y="";return l.onReady=function(){c=document.querySelector(".document-panel"),b=c.querySelector(".panel-content"),u=c.querySelector(".document-list"),d=e(u),p=c.querySelector(".document-list-filtered"),f=e(p),e(c).on("show.layout.toggle",function(){var t=h.folder;void 0!==t&&e(c.querySelector(".file-list."+t.folderIndex.replace(".",""))).collapse("show")}).on("shown.layout.toggle",function(){var e=u.querySelector(".file.active");e&&(b.scrollTop+=e.getBoundingClientRect().top-240)}).on("hidden.layout.toggle",function(){t.val(""),a("")});var t=e(c.querySelector(".search-bar .form-control"));t.bind("propertychange keyup input paste",function(){a(t.val())})},l}),define("extensions/documentManager",["jquery","underscore","constants","utils","storage","classes/Extension","classes/FolderDescriptor","folderList","fileSystem"],function(e,t,n,i,r,o,a,s,l){function c(){N=[],D=[],t.each(b.querySelectorAll('input[type="checkbox"]:checked'),function(t){var n=e(t.parentNode.parentNode),i=s[n.data("folderIndex")],r=l[n.data("fileIndex")];void 0!==i?N.push(i):void 0!==r&&D.push(r)})}function u(){if(0===t.size(D))return void d();var n=t.chain(D).sortBy(function(e){return e.title.toLowerCase()}).reduce(function(e,n){return e+t.template(I,{fileDesc:n})},"").value();y.innerHTML='",e(v.querySelectorAll(".document-list")).addClass("hide"),e(v.querySelectorAll(".confirm-delete, .selected-document-list")).removeClass("hide")}function d(){t.each(D,function(e){e.folder&&e.folder.removeFile(e),f.deleteFile(e)}),t.each(N,function(e){i.removeIndexFromArray("folder.list",e.folderIndex),delete s[e.folderIndex]}),m.onFoldersChanged()}function p(){c(),x.toggleClass("disabled",0===t.size(s)||0===t.size(D)),w.toggleClass("disabled",0===t.size(N)&&0===t.size(D))}var f,h=new o("documentManager","Document Manager",!1,!0);h.onFileMgrCreated=function(e){f=e};var m;h.onEventMgrCreated=function(e){m=e};var g,v,b,y,x,w,S,C,E,T=['','','','','
    <%= _.size(folderDesc.fileList) %>
    ','
    ',"<%= folderDesc.name %>
    ",'
    ','
    <%= fileListHtml %>
    '].join(""),k=['
  • ','','','','
    <%= fileDesc.composeTitle() %>
    ','
  • '].join(""),_=['','
    <%= _.size(folderDesc.fileList) %>
    ','
    ',"<%= folderDesc.name %>
    "].join(""),I=['
  • ','
    <%= fileDesc.composeTitle() %>
  • '].join(""),D=[],N=[],L=t.debounce(function(){if(g!==!1){p(),C.text(t.size(l)),E.text(t.size(s)+1),S=t.filter(l,function(e){return void 0===e.folder});var n=['','','
    ',t.size(S),"
    ",'
    ',"ROOT folder
    "].join(""),i=t.chain(S).sortBy(function(e){return e.title.toLowerCase()}).reduce(function(e,n){return e+t.template(k,{fileDesc:n})},"").value();i=i&&'",n+='
    '+i+"
    ",t.chain(s).sortBy(function(e){return e.name.toLowerCase()}).each(function(e){var i=t.chain(e.fileList).sortBy(function(e){return e.title.toLowerCase()}).reduce(function(e,n){return e+t.template(k,{fileDesc:n})},"").value();i=i&&'",n+=t.template(T,{folderDesc:e,fileListHtml:i,id:e.folderIndex.replace(".","")})}),b.innerHTML=n,t.each(b.querySelectorAll(".button-delete"),function(t){var n=e(t);n.click(function(e){e.stopPropagation();var t=n.parent(),i=s[t.data("folderIndex")],r=l[t.data("fileIndex")];D=[],N=[],i?(N.push(i),D=i.fileList):r&&D.push(r),u()})}),t.each(b.querySelectorAll(".button-rename"),function(t){var n=e(t);n.click(function(e){e.stopPropagation();var t,i=n.parent(),r=s[i.data("folderIndex")],o=l[i.data("fileIndex")];r?t=r.name:o&&(t=o.title),i.find(".name").addClass("hide"),i.find(".input-rename").removeClass("hide").val(t)[0].select()})}),t.each(b.querySelectorAll(".input-rename"),function(t){function n(){var t=i.parent(),n=e.trim(i.val()),r=s[t.data("folderIndex")],o=l[t.data("fileIndex")];n&&r&&n!=r.name?(r.name=n,m.onFoldersChanged()):n&&o&&n!=o.title?(o.title=n,m.onTitleChanged(o)):(i.addClass("hide"),t.find(".name").removeClass("hide"))}var i=e(t);i.blur(function(){n()}).keyup(function(e){13==e.keyCode&&(n(),e.stopPropagation()),27==e.keyCode&&(i.val(""),n(),e.stopPropagation())})}),t.each(b.querySelectorAll(".file .checkbox"),function(t){var n=e(t);n.click(function(e){e.stopPropagation()}).find("[type=checkbox]").change(function(){n.parents(".list-group").find(".folder [type=checkbox]").prop("checked",!1)})}),t.each(b.querySelectorAll(".folder .checkbox"),function(t){var n=e(t);n.click(function(e){e.stopPropagation()}).find("[type=checkbox]").change(function(){n.parent().next().find("[type=checkbox]").prop("checked",this.checked)})}),e(b.querySelectorAll("[type=checkbox]")).change(p)}},50);return h.onFileCreated=L,h.onFileDeleted=L,h.onSyncExportSuccess=L,h.onSyncRemoved=L,h.onNewPublishSuccess=L,h.onPublishRemoved=L,h.onFoldersChanged=L,h.onTitleChanged=function(t){g!==!1&&(e(b).find('[data-file-index="'+t.fileIndex+'"] .name').html(t.composeTitle()).removeClass("hide"),e(b.querySelectorAll(".input-rename")).addClass("hide"))},h.onReady=function(){v=document.querySelector(".modal-document-manager"),b=v.querySelector(".list-group.document-list"),C=e(v.querySelectorAll(".document-count")),E=e(v.querySelectorAll(".folder-count")),y=v.querySelector(".list-group.selected-document-list");var o=v.querySelector(".list-group.select-folder-list");e(v).on("show.bs.modal",function(){g=!0,L(),setTimeout(function(){e(b.querySelectorAll(".root-folder")).click()},250)}).on("hide.bs.modal",function(){g=!1,b.innerHTML=""}),e(v.querySelectorAll(".action-create-folder")).click(function(){var o;do o="folder."+i.randomString();while(t.has(s,o));r[o+".name"]=n.DEFAULT_FOLDER_NAME;var l=new a(o,n.DEFAULT_FOLDER_NAME);i.appendIndexToArray("folder.list",o),s[o]=l,m.onFoldersChanged(),setTimeout(function(){var t=e(v.querySelector('[data-folder-index="'+o+'"] .button-rename')).click();v.scrollTop+=t.offset().top-50},60)}),e(v.querySelectorAll(".action-select-all")).click(function(){e(b.querySelectorAll('input[type="checkbox"]')).prop("checked",!0).change()}),e(v.querySelectorAll(".action-unselect-all")).click(function(){e(b.querySelectorAll('input[type="checkbox"]')).prop("checked",!1).change()});var l=e(v.querySelectorAll(".action-delete-items")).click(function(){w.hasClass("disabled")||(c(),u())});w=l.parent(),e(v.querySelectorAll(".action-delete-items-confirm")).click(function(){d(),e(v.querySelectorAll(".document-list")).removeClass("hide"),e(v.querySelectorAll(".confirm-delete, .selected-document-list")).addClass("hide")});var p=e(v.querySelectorAll(".action-move-items")).click(function(){if(!x.hasClass("disabled")){c();var n=['','
    ',t.size(S),"
    ",'
    ',"ROOT folder
    "].join("");n+=t.chain(s).sortBy(function(e){return e.name.toLowerCase()}).reduce(function(e,n){return e+t.template(_,{folderDesc:n})},"").value(),o.innerHTML=n,t.each(o.querySelectorAll(".folder"),function(n){n=e(n),n.click(function(){var i=s[n.data("folderIndex")];t.each(D,function(e){e.folder&&e.folder.removeFile(e),i&&i.addFile(e)}),m.onFoldersChanged(),e(v.querySelectorAll(".document-list")).removeClass("hide"),e(v.querySelectorAll(".choose-folder, .select-folder-list")).addClass("hide") })}),e(v.querySelectorAll(".document-list")).addClass("hide"),e(v.querySelectorAll(".choose-folder, .select-folder-list")).removeClass("hide")}});x=p.parent(),e(v.querySelectorAll(".action-cancel")).click(function(){e(v.querySelectorAll(".document-list")).removeClass("hide"),e(v.querySelectorAll(".confirm-delete, .choose-folder, .selected-document-list, .select-folder-list")).addClass("hide")})},h}),define("extensions/workingIndicator",["jquery","underscore","crel","classes/Extension"],function(e,t,n,i){var r,o,a=new i("workingIndicator","Working Indicator"),s=["@<%= prefix %>keyframes <%= name %> {"," 0% { opacity:<%= z %>; }"," <%= start %>.01% { opacity:<%= alpha %>; }"," <%= start %>.02% { opacity:1; }"," <%= ((start + trail) % 100) %>.01% { opacity:<%= alpha %>; }"," 100% { opacity:<%= z %>; }","}"].join("\n");return a.onAsyncRunning=function(e){r.toggleClass("working",e),o.toggleClass("hide",!e)},a.onReady=function(){function i(e){e.z=Math.max(1-(1-e.alpha)/e.trail*(100-e.start),e.alpha),a+=t.template(s,t.extend({prefix:""},e)),a+=t.template(s,t.extend({prefix:"-webkit-"},e))}var a="";r=e(document.body),o=e('
    '),e(".working-indicator").append(o);for(var l=0;3>l;l++){var c="working-indicator-bar"+l;i({name:c,alpha:.25,start:20*l,trail:50});var u=c+" 0.7s linear infinite";o.append(e('
    ').css({animation:u,"-webkit-animation":u}))}var d=n("style",{type:"text/css"});document.head.appendChild(d),d.innerHTML=a},a}),function(e){var t=function(){return!1===e.support.boxModel&&e.support.objectAll&&$support.leadingWhitespace}();e.jGrowl=function(t,n){0==e("#jGrowl").size()&&e('
    ').addClass(n&&n.position?n.position:e.jGrowl.defaults.position).appendTo("body"),e("#jGrowl").jGrowl(t,n)},e.fn.jGrowl=function(t,n){if(e.isFunction(this.each)){var i=arguments;return this.each(function(){void 0==e(this).data("jGrowl.instance")&&(e(this).data("jGrowl.instance",e.extend(new e.fn.jGrowl,{notifications:[],element:null,interval:null})),e(this).data("jGrowl.instance").startup(this)),e.isFunction(e(this).data("jGrowl.instance")[t])?e(this).data("jGrowl.instance")[t].apply(e(this).data("jGrowl.instance"),e.makeArray(i).slice(1)):e(this).data("jGrowl.instance").create(t,n)})}},e.extend(e.fn.jGrowl.prototype,{defaults:{pool:0,header:"",group:"",sticky:!1,position:"top-right",glue:"after",theme:"default",themeState:"highlight",corners:"10px",check:250,life:3e3,closeDuration:"normal",openDuration:"normal",easing:"swing",closer:!0,closeTemplate:"×",closerTemplate:"
    [ close all ]
    ",log:function(){},beforeOpen:function(){},afterOpen:function(){},open:function(){},beforeClose:function(){},close:function(){},animateOpen:{opacity:"show"},animateClose:{opacity:"hide"}},notifications:[],element:null,interval:null,create:function(t,n){var n=e.extend({},this.defaults,n);"undefined"!=typeof n.speed&&(n.openDuration=n.speed,n.closeDuration=n.speed),this.notifications.push({message:t,options:n}),n.log.apply(this.element,[this.element,t,n])},render:function(t){var n=this,i=t.message,r=t.options;r.themeState=""==r.themeState?"":"ui-state-"+r.themeState;var t=e('
    '+r.closeTemplate+'
    '+r.header+'
    '+i+"
    ").data("jGrowl",r).addClass(r.theme).children("div.jGrowl-close").bind("click.jGrowl",function(){e(this).parent().trigger("jGrowl.beforeClose")}).parent();e(t).bind("mouseover.jGrowl",function(){e("div.jGrowl-notification",n.element).data("jGrowl.pause",!0)}).bind("mouseout.jGrowl",function(){e("div.jGrowl-notification",n.element).data("jGrowl.pause",!1)}).bind("jGrowl.beforeOpen",function(){0!=r.beforeOpen.apply(t,[t,i,r,n.element])&&e(this).trigger("jGrowl.open")}).bind("jGrowl.open",function(){0!=r.open.apply(t,[t,i,r,n.element])&&("after"==r.glue?e("div.jGrowl-notification:last",n.element).after(t):e("div.jGrowl-notification:first",n.element).before(t),e(this).animate(r.animateOpen,r.openDuration,r.easing,function(){e.support.opacity===!1&&this.style.removeAttribute("filter"),null!=e(this).data("jGrowl")&&(e(this).data("jGrowl").created=new Date),e(this).trigger("jGrowl.afterOpen")}))}).bind("jGrowl.afterOpen",function(){r.afterOpen.apply(t,[t,i,r,n.element])}).bind("jGrowl.beforeClose",function(){0!=r.beforeClose.apply(t,[t,i,r,n.element])&&e(this).trigger("jGrowl.close")}).bind("jGrowl.close",function(){e(this).data("jGrowl.pause",!0),e(this).animate(r.animateClose,r.closeDuration,r.easing,function(){e.isFunction(r.close)?r.close.apply(t,[t,i,r,n.element])!==!1&&e(this).remove():e(this).remove()})}).trigger("jGrowl.beforeOpen"),""!=r.corners&&void 0!=e.fn.corner&&e(t).corner(r.corners),e("div.jGrowl-notification:parent",n.element).size()>1&&0==e("div.jGrowl-closer",n.element).size()&&0!=this.defaults.closer&&e(this.defaults.closerTemplate).addClass("jGrowl-closer "+this.defaults.themeState+" ui-corner-all").addClass(this.defaults.theme).appendTo(n.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function(){e(this).siblings().trigger("jGrowl.beforeClose"),e.isFunction(n.defaults.closer)&&n.defaults.closer.apply(e(this).parent()[0],[e(this).parent()[0]])})},update:function(){e(this.element).find("div.jGrowl-notification:parent").each(function(){void 0!=e(this).data("jGrowl")&&void 0!=e(this).data("jGrowl").created&&e(this).data("jGrowl").created.getTime()+parseInt(e(this).data("jGrowl").life)<(new Date).getTime()&&1!=e(this).data("jGrowl").sticky&&(void 0==e(this).data("jGrowl.pause")||1!=e(this).data("jGrowl.pause"))&&e(this).trigger("jGrowl.beforeClose")}),this.notifications.length>0&&(0==this.defaults.pool||e(this.element).find("div.jGrowl-notification:parent").size()
    '),this.interval=setInterval(function(){e(n).data("jGrowl.instance").update()},parseInt(this.defaults.check)),t&&e(this.element).addClass("ie6")},shutdown:function(){e(this.element).removeClass("jGrowl").find("div.jGrowl-notification").remove(),clearInterval(this.interval)},close:function(){e(this.element).find("div.jGrowl-notification").each(function(){e(this).trigger("jGrowl.beforeClose")})}}),e.jGrowl.defaults=e.fn.jGrowl.prototype.defaults}(jQuery),define("jgrowl",["jquery"],function(e){return function(){var t;return t||e.jQuery.jGrowl}}(this)),define("text!html/notificationsSettingsBlock.html",[],function(){return'

    Shows notification messages in the bottom-right corner of the\n screen.

    \n
    \n
    \n \n
    \n ms\n
    \n
    \n
    '}),define("extensions/notifications",["jquery","underscore","utils","logger","classes/Extension","jgrowl","text!html/notificationsSettingsBlock.html"],function(e,t,n,i,r,o,a){function s(){f===!1&&(o.defaults.life=u.config.timeout,o.defaults.closer=!1,o.defaults.closeTemplate="",o.defaults.position="bottom-right",f=!0)}function l(e,n,r){if(i.info(e),s(),e){var a=e.indexOf("|");(-1===a||(e=e.substring(0,a)))&&(r=r||{},n=n||"icon-info-circled",o(" "+t.escape(e).replace(/\n/g,"
    "),r))}}function c(){h!==!1&&(d.toggleClass("hide",!m),p.toggleClass("hide",m))}var u=new r("notifications","Notifications");u.settingsBlock=a,u.defaultConfig={timeout:8e3},u.onLoadSettings=function(){n.setInputValue("#input-notifications-timeout",u.config.timeout)},u.onSaveSettings=function(e,t){e.timeout=n.getInputIntValue("#input-notifications-timeout",t,1,6e4)};var d,p,f=!1,h=!1;u.onReady=function(){h=!0,d=e(".navbar .offline-status"),p=e(".navbar .extension-buttons"),c()},u.onMessage=function(e){l(e)},u.onError=function(e){i.error(e),t.isString(e)?l(e,"icon-attention"):t.isObject(e)&&l(e.message,"icon-attention")};var m=!1;return u.onOfflineChanged=function(e){m=e,c(),m===!0?l("You are offline.","icon-attention-circled msg-offline"):l("You are back online!","icon-signal")},u.onSyncImportSuccess=function(e,n){var i=t.map(e,function(e){return e.title}).join(", ");l(i+" imported successfully from "+n.providerName+".")},u.onSyncExportSuccess=function(e,t){l('"'+e.title+'" will now be synchronized on '+t.provider.providerName+".")},u.onSyncRemoved=function(e,t){l(t.provider.providerName+" synchronized location has been removed.")},u.onPublishSuccess=function(e){l('"'+e.title+'" successfully published.')},u.onNewPublishSuccess=function(e,t){l('"'+e.title+'" is now published on '+t.provider.providerName+".")},u.onPublishRemoved=function(e,t){l(t.provider.providerName+" publish location has been removed.")},u}),define("text!html/buttonToc.html",[],function(){return'\n\n'}),define("text!html/tocSettingsBlock.html",[],function(){return'

    Generates a table of contents when a [TOC] marker is found.

    \n
    \n
    \n \n
    \n \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n \n
    '}),define("extensions/toc",["jquery","underscore","utils","classes/Extension","text!html/buttonToc.html","text!html/tocSettingsBlock.html"],function(e,t,n,i,r,o){function a(e,t,n){this.tagName=e,this.anchor=t,this.text=n,this.children=[]}function s(e,n){function i(){void 0!==r&&(r.children.length>0&&(r.children=s(r.children,n+1)),l.push(r))}n=n||1;var r,o="H"+n,l=[];return t.each(e,function(e){e.tagName!=o?n!==c.config.maxDepth&&(void 0===r&&(r=new a),r.children.push(e)):(i(),r=e)}),i(),l}function l(){function e(e){for(var r=e.id||n.slugify(e.textContent)||"title",o=r,a=0;t.has(i,o);)o=r+"-"+ ++a;return i[o]=!0,e.id=o,o}var i={},r=[];return t.each(u.querySelectorAll("h1, h2, h3, h4, h5, h6"),function(t){r.push(new a(t.tagName,e(t),t.textContent))}),r=s(r),'
    \n
      \n'+r.join("")+"
    \n
    \n"}var c=new i("toc","Table of Contents",!0);c.settingsBlock=o,c.defaultConfig={marker:"\\[(TOC|toc)\\]",maxDepth:6,button:!0},c.onLoadSettings=function(){n.setInputValue("#input-toc-marker",c.config.marker),n.setInputValue("#input-toc-maxdepth",c.config.maxDepth),n.setInputChecked("#input-toc-button",c.config.button)},c.onSaveSettings=function(e,t){e.marker=n.getInputRegExpValue("#input-toc-marker",t),e.maxDepth=n.getInputIntValue("#input-toc-maxdepth"),e.button=n.getInputChecked("#input-toc-button")},c.onCreatePreviewButton=function(){return c.config.button?r:void 0},a.prototype.childrenToString=function(){if(0===this.children.length)return"";var e="
      \n";return t.each(this.children,function(t){e+=t.toString()}),e+="
    \n"},a.prototype.toString=function(){var e="
  • ";return this.anchor&&this.text&&(e+=''+this.text+""),e+=this.childrenToString()+"
  • \n"};var u;return c.onPagedownConfigure=function(e){u=document.getElementById("preview-contents");var n=new RegExp("^\\s*"+c.config.marker+"\\s*$");e.hooks.chain("onPreviewRefresh",function(){var e=document.querySelectorAll(".table-of-contents, .toc"),i=l();t.each(u.getElementsByTagName("p"),function(e){n.test(e.innerHTML)&&(e.innerHTML=i)}),t.each(e,function(e){e.innerHTML=i})})},c}),define("extensions/emailConverter",["classes/Extension"],function(e){var t=new e("emailConverter","Markdown Email",!0);return t.settingsBlock="

    Converts email adresses in the form <email@example.com> into clickable links.

    ",t.onPagedownConfigure=function(e){e.getConverter().hooks.chain("postConversion",function(e){return e.replace(/<(mailto\:)?([^\s>]+@[^\s>]+\.\S+?)>/g,function(e,t,n){return''+n+""})})},t}),define("text!html/scrollSyncSettingsBlock.html",[],function(){return"

    Binds together editor and preview scrollbars.

    \n
    \n Note: The mapping between Markdown and HTML is based on the\n position of the title elements (h1, h2...) in the page. Therefore if\n your document does not contain any title, the mapping will be linear and\n consequently less accurate.\n
    "}),define("extensions/scrollSync",["jquery","underscore","classes/Extension","text!html/scrollSyncSettingsBlock.html"],function(e,t,n,i){var r=new n("scrollSync","Scroll Sync",!0,!0);r.settingsBlock=i,e.easing.easeOutSine=function(e){return Math.cos((1-e)*Math.PI/2)};var o;r.onSectionsCreated=function(e){o=e};var a,s,l,c,u=!0,d=[],p=[],f=t.debounce(function(){if(u){d=[];var t,n,i=a.scrollTop();a.find(".wmd-input-section").each(function(){if(void 0===t)return void(t=0);var n=e(this.firstChild),r=n.position().top+i;d.push({startOffset:t,endOffset:r,height:r-t}),t=r}),n=a.prop("scrollHeight"),d.push({startOffset:t,endOffset:n,height:n-t}),p=[];var r,o=s.scrollTop();s.find(".wmd-preview-section").each(function(){if(void 0===r)return void(r=0);var t=e(this),n=t.position().top+o;p.push({startOffset:r,endOffset:n,height:n-r}),r=n}),n=s.prop("scrollHeight"),p.push({startOffset:r,endOffset:n,height:n-r}),l=-10,c=-10,y()}},500),h=!1,m=!1,g=!1,v=!1,b=e("
    "),y=t.throttle(function(){function e(e,n,i){var r,o=t.find(n,function(t,n){return r=n,en&&(n=0);var i,r=s.scrollTop();if(h===!0){if(Math.abs(n-l)<=9)return;if(h=!1,l=n,i=e(n,d,p),i=t.min([i,s.prop("scrollHeight")-s.outerHeight()]),Math.abs(i-r)<=9)return void(c=r);b.stop("scrollSyncFx",!0).css("value",0).animate({value:i-r},{easing:"easeOutSine",duration:200,queue:"scrollSyncFx",step:function(e){v=!0,c=r+e,s.scrollTop(c)},done:function(){setTimeout(function(){v=!1},10)}}).dequeue("scrollSyncFx")}else if(m===!0){if(Math.abs(r-c)<=9)return;if(m=!1,c=r,i=e(r,p,d),i=t.min([i,a.prop("scrollHeight")-a.outerHeight()]),Math.abs(i-n)<=9)return void(l=n);b.stop("scrollSyncFx",!0).css("value",0).animate({value:i-n},{easing:"easeOutSine",duration:200,queue:"scrollSyncFx",step:function(e){g=!0,l=n+e,a.scrollTop(l)},done:function(){setTimeout(function(){g=!1},10)}}).dequeue("scrollSyncFx")}}},100);r.onLayoutResize=function(){h=!0,f()},r.onFileClosed=function(){d=[]};var x=!1;r.onReady=function(){s=e(".preview-container"),a=e("#wmd-input"),s.scroll(function(){v===!1&&x===!1&&(m=!0,h=!1,y()),x=!1}),a.scroll(function(){g===!1&&(h=!0,m=!1,y())}),s.on("hide.layout.toggle",function(){u=!1}),s.on("shown.layout.toggle",function(){u=!0})};var w;return r.onPagedownConfigure=function(t){w=e("#preview-contents"),t.getConverter().hooks.chain("postConversion",function(e){return w.height(w.height()),e})},r.onPreviewFinished=function(){var e=w.height();w.height("auto");var t=w.height();h=!0,e>t&&(x=!0),f()},r}),define("text!html/buttonSyncSettingsBlock.html",[],function(){return'

    Adds a "Synchronize documents" button in the navigation bar.

    \n
    \n
    \n \n
    \n ms\n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    '}),define("extensions/buttonSync",["jquery","underscore","crel","utils","classes/Extension","mousetrap","text!html/buttonSyncSettingsBlock.html"],function(e,t,n,i,r,o,a){var s=new r("buttonSync",'Button "Synchronize"',!1,!0);s.settingsBlock=a,s.defaultConfig={syncPeriod:18e4,syncShortcut:"mod+s"},s.onLoadSettings=function(){i.setInputValue("#input-sync-period",s.config.syncPeriod),i.setInputValue("#input-sync-shortcut",s.config.syncShortcut)},s.onSaveSettings=function(e,t){e.syncPeriod=i.getInputIntValue("#input-sync-period",t,0),e.syncShortcut=i.getInputTextValue("#input-sync-shortcut",t)};var l;s.onSynchronizerCreated=function(e){l=e};var c,u=!1,d=!1,p=function(){void 0!==c&&(u===!0||l.hasSync()===!1||d?c.addClass("disabled"):c.removeClass("disabled"))},f=0;return s.onPeriodicRun=function(){!s.config.syncPeriod||f+s.config.syncPeriod>i.currentTime||l.sync()&&(f=i.currentTime)},s.onCreateButton=function(){var t=n("a",{"class":"btn btn-success button-synchronize",title:"Force synchronization Ctrl/Cmd+S"},n("i",{"class":"icon-refresh"}));return c=e(t),c.click(function(){c.hasClass("disabled")||l.sync()&&(f=i.currentTime)}),t},s.onReady=p,s.onFileCreated=p,s.onFileDeleted=p,s.onSyncImportSuccess=p,s.onSyncExportSuccess=p,s.onSyncRemoved=p,s.onSyncRunning=function(e){u=e,p()},s.onOfflineChanged=function(e){d=e,p()},s.onReady=function(){o.bind(s.config.syncShortcut,function(e){l.sync()&&(f=i.currentTime),e.preventDefault()}),e(".action-force-synchronization").click(function(){l.sync()&&(f=i.currentTime)})},s}),define("extensions/buttonPublish",["jquery","underscore","crel","classes/Extension"],function(e,t,n,i){function r(){void 0!==o&&(c===!0||u===!1||d===!0?o.addClass("disabled"):o.removeClass("disabled"))}var o,a,s,l=new i("buttonPublish",'Button "Publish"'),c=!1,u=!1,d=!1;l.onPublisherCreated=function(e){s=e},l.onCreateButton=function(){var t=n("a",{"class":"btn btn-success button-publish",title:"Update document publication"},n("i",{"class":"icon-upload"}));return o=e(t).click(function(){o.hasClass("disabled")||s.publish()}),t},l.onPublishRunning=function(e){c=e,r()},l.onOfflineChanged=function(e){d=e,r()};var p=function(){u=0===t.size(a.publishLocations)?!1:!0,r()};return l.onFileSelected=function(e){a=e,p()},l.onReady=function(){e(".action-update-publication").click(s.publish)},l.onPublishRemoved=p,l.onNewPublishSuccess=p,l}),define("text!html/buttonStat.html",[],function(){return'\n\n'}),define("text!html/buttonStatSettingsBlock.html",[],function(){return'

    Adds a "Document statistics" button over the preview.

    \n
    \n
    \n RegExp \n
    \n
    \n RegExp \n
    \n
    \n RegExp \n
    \n
    \n'}),define("extensions/buttonStat",["jquery","underscore","utils","classes/Extension","text!html/buttonStat.html","text!html/buttonStatSettingsBlock.html"],function(e,t,n,i,r,o){var a=new i("buttonStat",'Button "Statistics"',!0,!0);a.settingsBlock=o,a.defaultConfig={name1:"Characters",value1:"\\S",name2:"Words",value2:"\\S+",name3:"Paragraphs",value3:"\\S.*"},a.onLoadSettings=function(){t.each([1,2,3],function(e){n.setInputValue("#input-stat-name"+e,a.config["name"+e]),n.setInputValue("#input-stat-value"+e,a.config["value"+e])})},a.onSaveSettings=function(e,i){t.each([1,2,3],function(t){e["name"+t]=n.getInputTextValue("#input-stat-name"+t,i),e["value"+t]=n.getInputRegExpValue("#input-stat-value"+t,i)})},a.onCreatePreviewButton=function(){return t.template(r,a.config)};var s,l,c,u;return a.onReady=function(){s=document.getElementById("preview-contents"),l=document.getElementById("span-stat-value1"),c=document.getElementById("span-stat-value2"),u=document.getElementById("span-stat-value3")},a.onPreviewFinished=function(){for(var e=s.cloneNode(!0),t=e.getElementsByTagName("script"),n=t.length-1;n>=0;n--){var i=t[n];i.parentNode.removeChild(i)}var r=e.textContent;l.textContent=(r.match(new RegExp(a.config.value1,"g"))||[]).length,c.textContent=(r.match(new RegExp(a.config.value2,"g"))||[]).length,u.textContent=(r.match(new RegExp(a.config.value3,"g"))||[]).length},a}),define("text!html/buttonHtmlCode.html",[],function(){return'\n\n'}),define("text!html/buttonHtmlCodeSettingsBlock.html",[],function(){return'

    Adds a "HTML code" button over the preview.

    \n
    \n
    \n \n
    \n \n
    \n
    \n
    '}),define("extensions/buttonHtmlCode",["jquery","underscore","utils","classes/Extension","text!html/buttonHtmlCode.html","text!html/buttonHtmlCodeSettingsBlock.html"],function(e,t,n,i,r,o){var a=new i("buttonHtmlCode",'Button "HTML code"',!0,!0);a.settingsBlock=o,a.defaultConfig={template:"<%= documentHTML %>"},a.onLoadSettings=function(){n.setInputValue("#textarea-html-code-template",a.config.template)},a.onSaveSettings=function(e){e.template=n.getInputValue("#textarea-html-code-template")};var s;a.onEventMgrCreated=function(e){s=e},a.onCreatePreviewButton=function(){return r};var l;a.onFileSelected=function(e){l=e};var c,u;return a.onPreviewFinished=function(e,t){c=e,u=t},a.onReady=function(){var n=document.getElementById("input-html-code");e(".action-html-code").click(function(){setTimeout(function(){e("#input-html-code").each(function(){e(this).is(":hidden")||this.select()})},10)}).parent().on("show.bs.dropdown",function(){try{var e=t.template(a.config.template,{documentTitle:l.title,documentMarkdown:l.content,strippedDocumentMarkdown:l.content.substring(l.frontMatter?l.frontMatter._frontMatter.length:0),documentHTML:u,documentHTMLWithComments:c,frontMatter:l.frontMatter,publishAttributes:void 0});n.value=e}catch(i){s.onError(i)}})},a}),define("text!html/buttonViewer.html",[],function(){return'\n \n\n'}),define("extensions/buttonViewer",["jquery","classes/Extension","text!html/buttonViewer.html"],function(e,t,n){var i=new t("buttonViewer",'Button "Viewer"',!0,!0);return i.settingsBlock='

    Adds a "Viewer" button over the preview.

    ',i.onCreatePreviewButton=function(){return n},i}),"undefined"==typeof jQuery)throw new Error("Bootstrap requires jQuery");+function(e){function t(){var e=document.createElement("bootstrap"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var n in t)if(void 0!==e.style[n])return{end:t[n]}}e.fn.emulateTransitionEnd=function(t){var n=!1,i=this;e(this).one(e.support.transition.end,function(){n=!0});var r=function(){n||e(i).trigger(e.support.transition.end)};return setTimeout(r,t),this},e(function(){e.support.transition=t()})}(jQuery),+function(e){var t='[data-dismiss="alert"]',n=function(n){e(n).on("click",t,this.close)};n.prototype.close=function(t){function n(){o.trigger("closed.bs.alert").remove()}var i=e(this),r=i.attr("data-target");r||(r=i.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,""));var o=e(r);t&&t.preventDefault(),o.length||(o=i.hasClass("alert")?i:i.parent()),o.trigger(t=e.Event("close.bs.alert")),t.isDefaultPrevented()||(o.removeClass("in"),e.support.transition&&o.hasClass("fade")?o.one(e.support.transition.end,n).emulateTransitionEnd(150):n())};var i=e.fn.alert;e.fn.alert=function(t){return this.each(function(){var i=e(this),r=i.data("bs.alert");r||i.data("bs.alert",r=new n(this)),"string"==typeof t&&r[t].call(i)})},e.fn.alert.Constructor=n,e.fn.alert.noConflict=function(){return e.fn.alert=i,this},e(document).on("click.bs.alert.data-api",t,n.prototype.close)}(jQuery),+function(e){var t=function(n,i){this.$element=e(n),this.options=e.extend({},t.DEFAULTS,i)};t.DEFAULTS={loadingText:"loading..."},t.prototype.setState=function(e){var t="disabled",n=this.$element,i=n.is("input")?"val":"html",r=n.data();e+="Text",r.resetText||n.data("resetText",n[i]()),n[i](r[e]||this.options[e]),setTimeout(function(){"loadingText"==e?n.addClass(t).attr(t,t):n.removeClass(t).removeAttr(t)},0)},t.prototype.toggle=function(){var e=this.$element.closest('[data-toggle="buttons"]'),t=!0;if(e.length){var n=this.$element.find("input");"radio"===n.prop("type")&&(n.prop("checked")&&this.$element.hasClass("active")?t=!1:e.find(".active").removeClass("active")),t&&n.prop("checked",!this.$element.hasClass("active")).trigger("change")}t&&this.$element.toggleClass("active")};var n=e.fn.button;e.fn.button=function(n){return this.each(function(){var i=e(this),r=i.data("bs.button"),o="object"==typeof n&&n;r||i.data("bs.button",r=new t(this,o)),"toggle"==n?r.toggle():n&&r.setState(n)})},e.fn.button.Constructor=t,e.fn.button.noConflict=function(){return e.fn.button=n,this},e(document).on("click.bs.button.data-api","[data-toggle^=button]",function(t){var n=e(t.target);n.hasClass("btn")||(n=n.closest(".btn")),n.button("toggle"),t.preventDefault()})}(jQuery),+function(e){var t=function(t,n){this.$element=e(t),this.$indicators=this.$element.find(".carousel-indicators"),this.options=n,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",e.proxy(this.pause,this)).on("mouseleave",e.proxy(this.cycle,this))};t.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},t.prototype.cycle=function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(e.proxy(this.next,this),this.options.interval)),this},t.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},t.prototype.to=function(t){var n=this,i=this.getActiveIndex();return t>this.$items.length-1||0>t?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){n.to(t)}):i==t?this.pause().cycle():this.slide(t>i?"next":"prev",e(this.$items[t]))},t.prototype.pause=function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&e.support.transition.end&&(this.$element.trigger(e.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},t.prototype.next=function(){return this.sliding?void 0:this.slide("next")},t.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},t.prototype.slide=function(t,n){var i=this.$element.find(".item.active"),r=n||i[t](),o=this.interval,a="next"==t?"left":"right",s="next"==t?"first":"last",l=this;if(!r.length){if(!this.options.wrap)return;r=this.$element.find(".item")[s]()}this.sliding=!0,o&&this.pause();var c=e.Event("slide.bs.carousel",{relatedTarget:r[0],direction:a});if(!r.hasClass("active")){if(this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid.bs.carousel",function(){var t=e(l.$indicators.children()[l.getActiveIndex()]);t&&t.addClass("active")})),e.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(c),c.isDefaultPrevented())return;r.addClass(t),r[0].offsetWidth,i.addClass(a),r.addClass(a),i.one(e.support.transition.end,function(){r.removeClass([t,a].join(" ")).addClass("active"),i.removeClass(["active",a].join(" ")),l.sliding=!1,setTimeout(function(){l.$element.trigger("slid.bs.carousel")},0)}).emulateTransitionEnd(600)}else{if(this.$element.trigger(c),c.isDefaultPrevented())return;i.removeClass("active"),r.addClass("active"),this.sliding=!1,this.$element.trigger("slid.bs.carousel")}return o&&this.cycle(),this}};var n=e.fn.carousel;e.fn.carousel=function(n){return this.each(function(){var i=e(this),r=i.data("bs.carousel"),o=e.extend({},t.DEFAULTS,i.data(),"object"==typeof n&&n),a="string"==typeof n?n:o.slide;r||i.data("bs.carousel",r=new t(this,o)),"number"==typeof n?r.to(n):a?r[a]():o.interval&&r.pause().cycle()})},e.fn.carousel.Constructor=t,e.fn.carousel.noConflict=function(){return e.fn.carousel=n,this},e(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(t){var n,i=e(this),r=e(i.attr("data-target")||(n=i.attr("href"))&&n.replace(/.*(?=#[^\s]+$)/,"")),o=e.extend({},r.data(),i.data()),a=i.attr("data-slide-to");a&&(o.interval=!1),r.carousel(o),(a=i.attr("data-slide-to"))&&r.data("bs.carousel").to(a),t.preventDefault()}),e(window).on("load",function(){e('[data-ride="carousel"]').each(function(){var t=e(this);t.carousel(t.data())})})}(jQuery),+function(e){var t=function(n,i){this.$element=e(n),this.options=e.extend({},t.DEFAULTS,i),this.transitioning=null,this.options.parent&&(this.$parent=e(this.options.parent)),this.options.toggle&&this.toggle()};t.DEFAULTS={toggle:!0},t.prototype.dimension=function(){var e=this.$element.hasClass("width");return e?"width":"height"},t.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var t=e.Event("show.bs.collapse");if(this.$element.trigger(t),!t.isDefaultPrevented()){var n=this.$parent&&this.$parent.find("> .panel > .in");if(n&&n.length){var i=n.data("bs.collapse");if(i&&i.transitioning)return;n.collapse("hide"),i||n.data("bs.collapse",null)}var r=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[r](0),this.transitioning=1;var o=function(){this.$element.removeClass("collapsing").addClass("in")[r]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse") };if(!e.support.transition)return o.call(this);var a=e.camelCase(["scroll",r].join("-"));this.$element.one(e.support.transition.end,e.proxy(o,this)).emulateTransitionEnd(350)[r](this.$element[0][a])}}},t.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var t=e.Event("hide.bs.collapse");if(this.$element.trigger(t),!t.isDefaultPrevented()){var n=this.dimension();this.$element[n](this.$element[n]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var i=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return e.support.transition?void this.$element[n](0).one(e.support.transition.end,e.proxy(i,this)).emulateTransitionEnd(350):i.call(this)}}},t.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var n=e.fn.collapse;e.fn.collapse=function(n){return this.each(function(){var i=e(this),r=i.data("bs.collapse"),o=e.extend({},t.DEFAULTS,i.data(),"object"==typeof n&&n);r||i.data("bs.collapse",r=new t(this,o)),"string"==typeof n&&r[n]()})},e.fn.collapse.Constructor=t,e.fn.collapse.noConflict=function(){return e.fn.collapse=n,this},e(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(t){var n,i=e(this),r=i.attr("data-target")||t.preventDefault()||(n=i.attr("href"))&&n.replace(/.*(?=#[^\s]+$)/,""),o=e(r),a=o.data("bs.collapse"),s=a?"toggle":i.data(),l=i.attr("data-parent"),c=l&&e(l);a&&a.transitioning||(c&&c.find('[data-toggle=collapse][data-parent="'+l+'"]').not(i).addClass("collapsed"),i[o.hasClass("in")?"addClass":"removeClass"]("collapsed")),o.collapse(s)})}(jQuery),+function(e){function t(){e(i).remove(),e(r).each(function(t){var i=n(e(this));i.hasClass("open")&&(i.trigger(t=e.Event("hide.bs.dropdown")),t.isDefaultPrevented()||i.removeClass("open").trigger("hidden.bs.dropdown"))})}function n(t){var n=t.attr("data-target");n||(n=t.attr("href"),n=n&&/#/.test(n)&&n.replace(/.*(?=#[^\s]*$)/,""));var i=n&&e(n);return i&&i.length?i:t.parent()}var i=".dropdown-backdrop",r="[data-toggle=dropdown]",o=function(t){e(t).on("click.bs.dropdown",this.toggle)};o.prototype.toggle=function(i){var r=e(this);if(!r.is(".disabled, :disabled")){var o=n(r),a=o.hasClass("open");if(t(),!a){if("ontouchstart"in document.documentElement&&!o.closest(".navbar-nav").length&&e(''}),t.prototype=e.extend({},e.fn.tooltip.Constructor.prototype),t.prototype.constructor=t,t.prototype.getDefaults=function(){return t.DEFAULTS},t.prototype.setContent=function(){var e=this.tip(),t=this.getTitle(),n=this.getContent();e.find(".popover-title")[this.options.html?"html":"text"](t),e.find(".popover-content")[this.options.html?"html":"text"](n),e.removeClass("fade top bottom left right in"),e.find(".popover-title").html()||e.find(".popover-title").hide()},t.prototype.hasContent=function(){return this.getTitle()||this.getContent()},t.prototype.getContent=function(){var e=this.$element,t=this.options;return e.attr("data-content")||("function"==typeof t.content?t.content.call(e[0]):t.content)},t.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},t.prototype.tip=function(){return this.$tip||(this.$tip=e(this.options.template)),this.$tip};var n=e.fn.popover;e.fn.popover=function(n){return this.each(function(){var i=e(this),r=i.data("bs.popover"),o="object"==typeof n&&n;r||i.data("bs.popover",r=new t(this,o)),"string"==typeof n&&r[n]()})},e.fn.popover.Constructor=t,e.fn.popover.noConflict=function(){return e.fn.popover=n,this}}(jQuery),+function(e){function t(n,i){var r,o=e.proxy(this.process,this);this.$element=e(e(n).is("body")?window:n),this.$body=e("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",o),this.options=e.extend({},t.DEFAULTS,i),this.selector=(this.options.target||(r=e(n).attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=e([]),this.targets=e([]),this.activeTarget=null,this.refresh(),this.process()}t.DEFAULTS={offset:10},t.prototype.refresh=function(){var t=this.$element[0]==window?"offset":"position";this.offsets=e([]),this.targets=e([]);{var n=this;this.$body.find(this.selector).map(function(){var i=e(this),r=i.data("target")||i.attr("href"),o=/^#\w/.test(r)&&e(r);return o&&o.length&&[[o[t]().top+(!e.isWindow(n.$scrollElement.get(0))&&n.$scrollElement.scrollTop()),r]]||null}).sort(function(e,t){return e[0]-t[0]}).each(function(){n.offsets.push(this[0]),n.targets.push(this[1])})}},t.prototype.process=function(){var e,t=this.$scrollElement.scrollTop()+this.options.offset,n=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,i=n-this.$scrollElement.height(),r=this.offsets,o=this.targets,a=this.activeTarget;if(t>=i)return a!=(e=o.last()[0])&&this.activate(e);for(e=r.length;e--;)a!=o[e]&&t>=r[e]&&(!r[e+1]||t<=r[e+1])&&this.activate(o[e])},t.prototype.activate=function(t){this.activeTarget=t,e(this.selector).parents(".active").removeClass("active");var n=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',i=e(n).parents("li").addClass("active");i.parent(".dropdown-menu").length&&(i=i.closest("li.dropdown").addClass("active")),i.trigger("activate.bs.scrollspy")};var n=e.fn.scrollspy;e.fn.scrollspy=function(n){return this.each(function(){var i=e(this),r=i.data("bs.scrollspy"),o="object"==typeof n&&n;r||i.data("bs.scrollspy",r=new t(this,o)),"string"==typeof n&&r[n]()})},e.fn.scrollspy.Constructor=t,e.fn.scrollspy.noConflict=function(){return e.fn.scrollspy=n,this},e(window).on("load",function(){e('[data-spy="scroll"]').each(function(){var t=e(this);t.scrollspy(t.data())})})}(jQuery),+function(e){var t=function(t){this.element=e(t)};t.prototype.show=function(){var t=this.element,n=t.closest("ul:not(.dropdown-menu)"),i=t.data("target");if(i||(i=t.attr("href"),i=i&&i.replace(/.*(?=#[^\s]*$)/,"")),!t.parent("li").hasClass("active")){var r=n.find(".active:last a")[0],o=e.Event("show.bs.tab",{relatedTarget:r});if(t.trigger(o),!o.isDefaultPrevented()){var a=e(i);this.activate(t.parent("li"),n),this.activate(a,a.parent(),function(){t.trigger({type:"shown.bs.tab",relatedTarget:r})})}}},t.prototype.activate=function(t,n,i){function r(){o.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),t.addClass("active"),a?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu")&&t.closest("li.dropdown").addClass("active"),i&&i()}var o=n.find("> .active"),a=i&&e.support.transition&&o.hasClass("fade");a?o.one(e.support.transition.end,r).emulateTransitionEnd(150):r(),o.removeClass("in")};var n=e.fn.tab;e.fn.tab=function(n){return this.each(function(){var i=e(this),r=i.data("bs.tab");r||i.data("bs.tab",r=new t(this)),"string"==typeof n&&r[n]()})},e.fn.tab.Constructor=t,e.fn.tab.noConflict=function(){return e.fn.tab=n,this},e(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(t){t.preventDefault(),e(this).tab("show")})}(jQuery),+function(e){var t=function(n,i){this.options=e.extend({},t.DEFAULTS,i),this.$window=e(window).on("scroll.bs.affix.data-api",e.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",e.proxy(this.checkPositionWithEventLoop,this)),this.$element=e(n),this.affixed=this.unpin=null,this.checkPosition()};t.RESET="affix affix-top affix-bottom",t.DEFAULTS={offset:0},t.prototype.checkPositionWithEventLoop=function(){setTimeout(e.proxy(this.checkPosition,this),1)},t.prototype.checkPosition=function(){if(this.$element.is(":visible")){var n=e(document).height(),i=this.$window.scrollTop(),r=this.$element.offset(),o=this.options.offset,a=o.top,s=o.bottom;"object"!=typeof o&&(s=a=o),"function"==typeof a&&(a=o.top()),"function"==typeof s&&(s=o.bottom());var l=null!=this.unpin&&i+this.unpin<=r.top?!1:null!=s&&r.top+this.$element.height()>=n-s?"bottom":null!=a&&a>=i?"top":!1;this.affixed!==l&&(this.unpin&&this.$element.css("top",""),this.affixed=l,this.unpin="bottom"==l?r.top-i:null,this.$element.removeClass(t.RESET).addClass("affix"+(l?"-"+l:"")),"bottom"==l&&this.$element.offset({top:document.body.offsetHeight-s-this.$element.height()}))}};var n=e.fn.affix;e.fn.affix=function(n){return this.each(function(){var i=e(this),r=i.data("bs.affix"),o="object"==typeof n&&n;r||i.data("bs.affix",r=new t(this,o)),"string"==typeof n&&r[n]()})},e.fn.affix.Constructor=t,e.fn.affix.noConflict=function(){return e.fn.affix=n,this},e(window).on("load",function(){e('[data-spy="affix"]').each(function(){var t=e(this),n=t.data();n.offset=n.offset||{},n.offsetBottom&&(n.offset.bottom=n.offsetBottom),n.offsetTop&&(n.offset.top=n.offsetTop),t.affix(n)})})}(jQuery),define("bootstrap",function(){}),function(e,t){var n,i;return i=t.document,n=function(){function n(n){this._options=e.extend({name:"tour",container:"body",keyboard:!0,storage:t.localStorage,debug:!1,backdrop:!1,redirect:!0,orphan:!1,duration:!1,basePath:"",template:"

    ",afterSetState:function(){},afterGetState:function(){},afterRemoveState:function(){},onStart:function(){},onEnd:function(){},onShow:function(){},onShown:function(){},onHide:function(){},onHidden:function(){},onNext:function(){},onPrev:function(){},onPause:function(){},onResume:function(){}},n),this._force=!1,this._inited=!1,this._steps=[],this.backdrop={overlay:null,$element:null,$background:null,backgroundShown:!1,overlayElementShown:!1}}return n.prototype.setState=function(e,t){var n,i;if(this._options.storage){i=""+this._options.name+"_"+e;try{this._options.storage.setItem(i,t)}catch(r){n=r,n.code===DOMException.QUOTA_EXCEEDED_ERR&&this.debug("LocalStorage quota exceeded. setState failed.")}return this._options.afterSetState(i,t)}return null==this._state&&(this._state={}),this._state[e]=t},n.prototype.removeState=function(e){var t;return this._options.storage?(t=""+this._options.name+"_"+e,this._options.storage.removeItem(t),this._options.afterRemoveState(t)):null!=this._state?delete this._state[e]:void 0},n.prototype.getState=function(e){var t,n;return this._options.storage?(t=""+this._options.name+"_"+e,n=this._options.storage.getItem(t)):null!=this._state&&(n=this._state[e]),(void 0===n||"null"===n)&&(n=null),this._options.afterGetState(e,n),n},n.prototype.addSteps=function(e){var t,n,i,r;for(r=[],n=0,i=e.length;i>n;n++)t=e[n],r.push(this.addStep(t));return r},n.prototype.addStep=function(e){return this._steps.push(e)},n.prototype.getStep=function(t){return null!=this._steps[t]?e.extend({id:"step-"+t,path:"",placement:"right",title:"",content:"

    ",next:t===this._steps.length-1?-1:t+1,prev:t-1,animation:!0,container:this._options.container,backdrop:this._options.backdrop,redirect:this._options.redirect,orphan:this._options.orphan,duration:this._options.duration,template:this._options.template,onShow:this._options.onShow,onShown:this._options.onShown,onHide:this._options.onHide,onHidden:this._options.onHidden,onNext:this._options.onNext,onPrev:this._options.onPrev,onPause:this._options.onPause,onResume:this._options.onResume},this._steps[t]):void 0},n.prototype.init=function(e){var t=this;return this._force=e,this.ended()?this._debug("Tour ended, init prevented."):(this.setCurrentStep(),this._setupMouseNavigation(),this._setupKeyboardNavigation(),this._onResize(function(){return t.showStep(t._current)}),null!==this._current&&this.showStep(this._current),this._inited=!0,this)},n.prototype.start=function(e){var t;return null==e&&(e=!1),this._inited||this.init(e),null===this._current?(t=this._makePromise(null!=this._options.onStart?this._options.onStart(this):void 0),this._callOnPromiseDone(t,this.showStep,0)):void 0},n.prototype.next=function(){var e;return this.ended()?this._debug("Tour ended, next prevented."):(e=this.hideStep(this._current),this._callOnPromiseDone(e,this._showNextStep))},n.prototype.prev=function(){var e;return this.ended()?this._debug("Tour ended, prev prevented."):(e=this.hideStep(this._current),this._callOnPromiseDone(e,this._showPrevStep))},n.prototype.goTo=function(e){var t;return this.ended()?this._debug("Tour ended, goTo prevented."):(t=this.hideStep(this._current),this._callOnPromiseDone(t,this.showStep,e))},n.prototype.end=function(){var n,r,o=this;return n=function(){return e(i).off("click.tour-"+o._options.name),e(i).off("keyup.tour-"+o._options.name),e(t).off("resize.tour-"+o._options.name),o.setState("end","yes"),o._inited=!1,o._force=!1,o._clearTimer(),null!=o._options.onEnd?o._options.onEnd(o):void 0},r=this.hideStep(this._current),this._callOnPromiseDone(r,n)},n.prototype.ended=function(){return!this.force&&!!this.getState("end")},n.prototype.restart=function(){return this.removeState("current_step"),this.removeState("end"),this.setCurrentStep(0),this.start()},n.prototype.pause=function(){var e;return e=this.getStep(this._current),e&&e.duration?(this._paused=!0,this._duration-=(new Date).getTime()-this._start,t.clearTimeout(this._timer),this._debug("Paused/Stopped step "+(this._current+1)+" timer ("+this._duration+" remaining)."),null!=e.onPause?e.onPause(this,this._duration):void 0):void 0},n.prototype.resume=function(){var e,n=this;return e=this.getStep(this._current),e&&e.duration?(this._paused=!1,this._start=(new Date).getTime(),this._duration=this._duration||e.duration,this._timer=t.setTimeout(function(){return n._isLast()?n.next():n.end()},this._duration),this._debug("Started step "+(this._current+1)+" timer with duration "+this._duration),null!=e.onResume&&this._duration!==e.duration?e.onResume(this,this._duration):void 0):void 0},n.prototype.hideStep=function(t){var n,i,r,o=this;return(r=this.getStep(t))?(this._clearTimer(),i=this._makePromise(null!=r.onHide?r.onHide(this,t):void 0),n=function(){var t;return t=e(r.element),t.data("bs.popover")||t.data("popover")||(t=e("body")),t.popover("destroy"),r.reflex&&t.css("cursor","").off("click.tour-"+o._options.name),r.backdrop&&o._hideBackdrop(),null!=r.onHidden?r.onHidden(o):void 0},this._callOnPromiseDone(i,n),i):void 0},n.prototype.showStep=function(t){var n,r,o,a,s=this;return(a=this.getStep(t))?(o=t").parent().html(),i.popover({placement:t.placement,trigger:"manual",title:t.title,content:t.content,html:!0,animation:t.animation,container:t.container,template:t.template,selector:t.element}).popover("show"),a=i.data("bs.popover")?i.data("bs.popover").tip():i.data("popover").tip(),a.attr("id",t.id),this._reposition(a,t),s?this._center(a):void 0},n.prototype._reposition=function(t,n){var r,o,a,s,l,c,u;if(s=t[0].offsetWidth,o=t[0].offsetHeight,u=t.offset(),l=u.left,c=u.top,r=e(i).outerHeight()-u.top-t.outerHeight(),0>r&&(u.top=u.top+r),a=e("html").outerWidth()-u.left-t.outerWidth(),0>a&&(u.left=u.left+a),u.top<0&&(u.top=0),u.left<0&&(u.left=0),t.offset(u),"bottom"===n.placement||"top"===n.placement){if(l!==u.left)return this._replaceArrow(t,2*(u.left-l),s,"left")}else if(c!==u.top)return this._replaceArrow(t,2*(u.top-c),o,"top")},n.prototype._center=function(n){return n.css("top",e(t).outerHeight()/2-n.outerHeight()/2)},n.prototype._replaceArrow=function(e,t,n,i){return e.find(".arrow").css(i,t?50*(1-t/n)+"%":"")},n.prototype._scrollIntoView=function(n,i){var r,o,a,s,l,c=this;return n?(r=e(n),o=e(t),a=r.offset().top,l=o.height(),s=Math.max(0,a-l/2),this._debug("Scroll into view. ScrollTop: "+s+". Element offset: "+a+". Window height: "+l+"."),e("body").stop().animate({scrollTop:Math.ceil(s)},function(){return i(),c._debug("Scroll into view. Animation end element offset: "+r.offset().top+". Window height: "+o.height()+".")})):i()},n.prototype._onResize=function(n,i){return e(t).on("resize.tour-"+this._options.name,function(){return clearTimeout(i),i=setTimeout(n,100)})},n.prototype._setupMouseNavigation=function(){var t=this;return t=this,e(i).off("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=next]:not(.disabled)").on("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=next]:not(.disabled)",function(e){return e.preventDefault(),t.next()}),e(i).off("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=prev]:not(.disabled)").on("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=prev]:not(.disabled)",function(e){return e.preventDefault(),t.prev()}),e(i).off("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=end]").on("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=end]",function(e){return e.preventDefault(),t.end()}),e(i).off("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=pause-resume]").on("click.tour-"+this._options.name,".popover.tour-"+this._options.name+" *[data-role=pause-resume]",function(n){var i; -return n.preventDefault(),i=e(this),i.text(i.data(t._paused?"pause-text":"resume-text")),t._paused?t.resume():t.pause()})},n.prototype._setupKeyboardNavigation=function(){var t=this;if(this._options.keyboard)return e(i).on("keyup.tour-"+this._options.name,function(e){if(e.which)switch(e.which){case 39:return e.preventDefault(),t._isLast()?t.next():t.end();case 37:if(e.preventDefault(),t._current>0)return t.prev();break;case 27:return e.preventDefault(),t.end()}})},n.prototype._makePromise=function(t){return t&&e.isFunction(t.then)?t:null},n.prototype._callOnPromiseDone=function(e,t,n){var i=this;return e?e.then(function(){return t.call(i,n)}):t.call(this,n)},n.prototype._showBackdrop=function(){return this.backdrop.backgroundShown?void 0:(this.backdrop=e("
    ",{"class":"tour-backdrop"}),this.backdrop.backgroundShown=!0,e("body").append(this.backdrop))},n.prototype._hideBackdrop=function(){return this._hideOverlayElement(),this._hideBackground()},n.prototype._hideBackground=function(){return this.backdrop.remove(),this.backdrop.overlay=null,this.backdrop.backgroundShown=!1},n.prototype._showOverlayElement=function(t){var n,i,r;if(!this.backdrop.overlayElementShown)return this.backdrop.overlayElementShown=!0,i=e(t),n=e("
    "),r=i.offset(),r.top=r.top,r.left=r.left,n.width(i.innerWidth()).height(i.innerHeight()).addClass("tour-step-background").offset(r),i.addClass("tour-step-backdrop"),e("body").append(n),this.backdrop.$element=i,this.backdrop.$background=n},n.prototype._hideOverlayElement=function(){return this.backdrop.overlayElementShown?(this.backdrop.$element.removeClass("tour-step-backdrop"),this.backdrop.$background.remove(),this.backdrop.$element=null,this.backdrop.$background=null,this.backdrop.overlayElementShown=!1):void 0},n.prototype._clearTimer=function(){return t.clearTimeout(this._timer),this._timer=null,this._duration=null},n}(),t.Tour=n}(jQuery,window),define("bootstrap-tour",["bootstrap"],function(e){return function(){var t;return t||e.Tour}}(this)),define("extensions/welcomeTour",["underscore","jquery","storage","classes/Extension","bootstrap-tour"],function(e,t,n,i,r){var o,a=new i("welcomeTour","Welcome tour",!1,!0);return a.onEventMgrCreated=function(e){o=e},a.onReady=function(){function i(e,n,i){var r=t(e).tooltip({html:!0,placement:i,trigger:"manual",title:n}).tooltip("show").addClass("info-tooltip");r.one("click",function(){r.tooltip("hide").removeClass("info-tooltip")}),setTimeout(function(){r.tooltip("hide").removeClass("info-tooltip")},2e4)}var a=new r({keyboard:!1,storage:{getItem:function(){},setItem:function(){},removeItem:function(){}},onEnd:function(){n.welcomeTour="done",i(".menu-panel .toggle-button *","Synchronize, publish and more...","right"),i(".document-panel .toggle-button *","Create and manage documents","left"),i(".extension-preview-buttons .btn-group:first","Need help with Markdown syntax?","left"),i(".layout-toggler-preview","Toggle preview","right")},template:['
    ','
    ','

    ','
    ',' ","
    "].join("")});a.addSteps([{element:".navbar-inner",title:"StackEdit 4 beta preview!",content:["

    What's new?

    ","
      ","
    • New contenteditable based editor (credit to Dabblet, Editorially...)
    • ","
    • New layout with CSS3 transitions (lighter supposedly)
    • ","
    • Comments/discussions support (see the new icon in the navigation bar)
    • ","
    • Auto-merge and conflict detection using standard synchronization
    • ","
    • Dropped real time sync support :( since you can collaborate simultaneously using standard synchronization
    • ","
    ",'

    Please provide your feedback here and declare issues on GitHub... Thanks!

    ',''].join(""),placement:"bottom",onShown:function(){o.onTweet()}}]),e.has(n,"welcomeTour")||a.start(),t(".action-welcome-tour").click(function(){a.restart()})},a}),define("text!extensions/shortcutsDefaultMapping.settings",[],function(){return"{\n 'mod+b': bindPagedownButton('bold'),\n 'mod+i': bindPagedownButton('italic'),\n 'mod+l': bindPagedownButton('link'),\n 'mod+q': bindPagedownButton('quote'),\n 'mod+k': bindPagedownButton('code'),\n 'mod+g': bindPagedownButton('image'),\n 'mod+o': bindPagedownButton('olist'),\n 'mod+u': bindPagedownButton('ulist'),\n 'mod+h': bindPagedownButton('heading'),\n 'mod+r': bindPagedownButton('hr'),\n 'mod+z': bindPagedownButton('undo'),\n 'mod+y': bindPagedownButton('redo'),\n 'mod+shift+z': bindPagedownButton('redo'),\n 'mod+m': function(evt) {\n $('.button-open-discussion').click();\n evt.preventDefault();\n },\n '= = > space': function() {\n expand('==> ', '⇒ ');\n },\n '< = = space': function() {\n expand('<== ', '⇐ ');\n },\n 'S t a c k E d i t': function() {\n eventMgr.onMessage(\"You are stunned!!! Aren't you?\");\n }\n}\n"}),define("text!html/shortcutsSettingsBlock.html",[],function(){return'

    Maps keyboard shortcuts to JavaScript functions.

    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n'}),define("extensions/shortcuts",["jquery","underscore","utils","mousetrap","classes/Extension","text!extensions/shortcutsDefaultMapping.settings","text!html/shortcutsSettingsBlock.html"],function($,_,utils,mousetrap,Extension,shortcutsDefaultMapping,shortcutsSettingsBlockHTML){function bindPagedownButton(e){return function(t){pagedownEditor.uiManager.doClick(pagedownEditor.uiManager.buttons[e]),t.preventDefault()}}function expand(e,t){utils.defer(function(){require("editor").replacePreviousText(e,t)})}var shortcuts=new Extension("shortcuts","Shortcuts",!0,!0);shortcuts.settingsBlock=shortcutsSettingsBlockHTML,shortcuts.defaultConfig={mapping:shortcutsDefaultMapping};var eventMgr,pagedownEditor;return shortcuts.onEventMgrCreated=function(e){eventMgr=e,eventMgr.addListener("onPagedownConfigure",function(e){pagedownEditor=e})},shortcuts.onLoadSettings=function(){utils.setInputValue("#textarea-shortcuts-mapping",shortcuts.config.mapping)},shortcuts.onSaveSettings=function(newConfig,event){newConfig.code=utils.getInputValue("#textarea-shortcuts-mapping");try{eval("var test = "+newConfig.code)}catch(e){eventMgr.onError(e),utils.getInputTextValue("#textarea-shortcuts-mapping",event,/^$/)}},shortcuts.onInit=function(){try{var shortcutMap;eval("shortcutMap = "+shortcuts.config.mapping),_.each(shortcutMap,function(e,t){mousetrap.bind(t,e)})}catch(e){console.error(e)}},shortcuts}),define("text!html/userCustomSettingsBlock.html",[],function(){return'

    Allows users to implement their own extension.

    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \nMore info'}),define("extensions/userCustom",["jquery","underscore","utils","classes/Extension","fileSystem","settings","text!html/userCustomSettingsBlock.html"],function($,_,utils,Extension,fileSystem,settings,userCustomSettingsBlockHTML){var userCustom=new Extension("userCustom","UserCustom extension",!0);userCustom.settingsBlock=userCustomSettingsBlockHTML,userCustom.defaultConfig={code:""};var fileMgr;userCustom.onFileMgrCreated=function(e){fileMgr=e};var synchronizer;userCustom.onSynchronizerCreated=function(e){synchronizer=e};var publisher;userCustom.onPublisherCreated=function(e){publisher=e};var eventMgr;return userCustom.onEventMgrCreated=function(e){eventMgr=e},userCustom.onLoadSettings=function(){utils.setInputValue("#textarea-usercustom-code",userCustom.config.code)},userCustom.onSaveSettings=function(newConfig,event){newConfig.code=utils.getInputValue("#textarea-usercustom-code");try{eval(newConfig.code)}catch(e){eventMgr.onError(e),utils.getInputTextValue("#textarea-usercustom-code",event,/^$/)}},userCustom.onInit=function(){try{eval(userCustom.config.code)}catch(e){console.error(e)}},userCustom}),define("text!html/commentsPopoverContent.html",[],function(){return'
    \n
    <%= commentList %>
    \n
    \n
    \n \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n'}),define("extensions/comments",["jquery","underscore","utils","storage","crel","rangy","classes/Extension","text!html/commentsPopoverContent.html","bootstrap"],function(e,t,n,i,r,o,a,s){function l(e,t,n){t=Math.round(t);for(var i=t-21;t+22>i;)w[i]&&(t=i+22),i++;!n&&(w[t]=1);var r=-8;-1!==e.className.indexOf(" icon-split")&&(r=-12);var o=t+r;e.style.top=o+"px",e.style.right="12px"}function c(t,n){this.commentElt=t,this.$commentElt=e(t).addClass("active"),this.fileDesc=n,this.discussionIndex=t.discussionIndex}function u(e){var t=C.getPopoverElt(),n=0;t.offsetWidthi&&(t.style.top=parseInt(t.style.top)+i+"px")}function d(){C&&C.$commentElt.popover("toggle").popover("destroy")}function p(){var e=C.getDiscussion(),n=i["author.name"],r=[];return e.commentList&&(r=e.commentList.map(function(e){var i=e.author||"Anonymous";return t.template(m,{author:i,content:e.content,reply:e.author!=n})})),"conflict"==e.type&&r.unshift(t.template(m,{author:"StackEdit",content:"Multiple users have made conflicting modifications.",reply:!0})),r.join("")}var f,h=new a("comments","Comments",!1,!0),m=["
    \">",'
    <%= author %>
    ','
    <%= content %>
    ',"
    "].join(""),g=['',' ',' '," "," “<%- title %>”",""].join("");h.onEventMgrCreated=function(e){f=e};var v,b;h.onEditorCreated=function(e){v=e,b=v.selectionMgr};var y,x,w=[],S=r("a",{"class":"discussion icon-comment new"});c.prototype.getDiscussion=function(){return this.discussionIndex?this.fileDesc.discussionList[this.discussionIndex]:this.fileDesc.newDiscussion},c.prototype.getPopoverElt=function(){return document.querySelector(".comments-popover .popover:last-child")};var C,E,T,k,_,I,D={},N=[],L=!1,M=t.debounce(function(){function e(){var i;if(0===o.length)return t.filter(D,function(e,n){return!t.has(T.discussionList,n)}).forEach(function(e){x.removeChild(e),delete D[e.discussionIndex]}),C&&!C.discussionIndex&&(i=b.getCoordinates(C.getDiscussion().selectionEnd),l(S,i.y,!0),y.scrollTop+=parseInt(S.style.top)-y.scrollTop-3*y.offsetHeight/4,u(S)),N=t.sortBy(D,function(e){return e.selectionEnd}),_.toggleClass("some",0!==N.length),_.toggleClass("replied",L),void I.toggleClass("icon-chat",0!==N.length);var a=o.shift(),s=D[a.discussionIndex];s||(s=r("a"));var c="discussion",d=!a.commentList||!n||t.last(a.commentList).author!=n;d&&(L=!0),c+="conflict"==a.type?" icon-split":" icon-comment",c+=d?" replied":" added",s.className=c,s.discussionIndex=a.discussionIndex,s.selectionEnd=a.selectionEnd,i=b.getCoordinates(a.selectionEnd),l(s,i.y),x.appendChild(s),D[a.discussionIndex]=s,C&&C.getDiscussion()===a&&(y.scrollTop+=parseInt(s.style.top)-y.scrollTop-3*y.offsetHeight/4,u(s)),k=setTimeout(e,5)}if(void 0!==T){L=!1,N=[];var n=i["author.name"];w=[];var o=t.sortBy(T.discussionList,function(e){return e.selectionEnd});clearTimeout(k),k=setTimeout(e,5)}},50);return h.onLayoutResize=M,h.onFileOpen=function(e){T=e,M()},h.onContentChanged=function(e){T===e&&M()},h.onCommentsChanged=function(e){if(T===e){if(void 0!==C){var t=C;t.discussionIndex&&(t.getPopoverElt().querySelector(".discussion-comment-list").innerHTML=p());try{E.undoToRange(t.rangyRange)}catch(n){}var i=t.getDiscussion();t.selectionRange=b.createRange(i.selectionStart,i.selectionEnd),t.rangyRange=o.createRange(),t.rangyRange.setStart(t.selectionRange.startContainer,t.selectionRange.startOffset),t.rangyRange.setEnd(t.selectionRange.endContainer,t.selectionRange.endOffset),setTimeout(function(){C===t&&E.applyToRange(t.rangyRange)},50)}M()}},h.onDiscussionCreated=function(e){T===e&&M()},h.onDiscussionRemoved=function(e,t){T===e&&(void 0!==C&&C.discussionIndex==t.discussionIndex&&d(),M())},h.onReady=function(){E=o.createCssClassApplier("comment-highlight",{normalize:!1});var a="";y=document.getElementById("wmd-input"),x=document.querySelector("#wmd-input > .editor-margin"),x.appendChild(S);var h=e(r("div",{"class":"comments-popover"}));e(document.body).append(h).on("click",function(e){C&&C.$commentElt[0]!==e.target&&d()}).popover({placement:"auto top",container:".comments-popover",html:!0,title:function(){if(!C)return!0;var e=C.getDiscussion(),n=e.selectionEnd-e.selectionStart,i=v.getValue().substr(e.selectionStart,n>20?20:n);return n>20&&(i+="..."),t.template(g,{title:i})},content:function(){var e=t.template(s,{commentList:p()});return e},selector:"#wmd-input > .editor-margin > .discussion"}),e(x).on("show.bs.popover",function(e){d();var t=new c(e.target,T);C=t;var n=t.getDiscussion();if(!n){var i=Math.min(b.selectionStart,b.selectionEnd),r=Math.max(b.selectionStart,b.selectionEnd);if(i===r){var o=b.getClosestWordOffset(i);i=o.start,r=o.end}n={selectionStart:i,selectionEnd:r,commentList:[]},T.newDiscussion=n;var a=b.getCoordinates(i);l(S,a.y,!0)}t.selectionRange=b.createRange(n.selectionStart,n.selectionEnd),y.scrollTop+=parseInt(e.target.style.top)-y.scrollTop-3*y.offsetHeight/4}).on("shown.bs.popover",function(r){var s=C,l=s.getPopoverElt();s.$authorInputElt=e(l.querySelector(".input-comment-author")).val(i["author.name"]),s.$contentInputElt=e(l.querySelector(".input-comment-content")),s.hr=l.querySelector("hr"),u(s.commentElt),l.querySelector(".scrollport").scrollTop=9999999;var c=e(l.querySelector(".action-add-comment"));e().add(s.$contentInputElt).add(s.$authorInputElt).keydown(function(e){switch(e.which){case 13:return e.preventDefault(),void c.click();case 27:return e.preventDefault(),d(),v.focus(),void v.adjustCursorPosition()}}),c.click(function(e){var i=n.getInputTextValue(s.$authorInputElt),r=n.getInputTextValue(s.$contentInputElt,e);if(!e.isPropagationStopped()){var o=s.getDiscussion();s.$contentInputElt.val(""),d(),o.commentList=o.commentList||[],o.commentList.push({author:i,content:r});var a=s.fileDesc.discussionList||{};if(o.discussionIndex)s.fileDesc.discussionList=a,f.onCommentsChanged(s.fileDesc);else{var l;do l=n.randomString();while(t.has(a,l));o.discussionIndex=l,a[l]=o,s.fileDesc.discussionList=a,f.onDiscussionCreated(s.fileDesc,o)}y.focus()}});var p=e(l.querySelector(".action-remove-discussion"));r.target.discussionIndex?p.click(function(){d();var e=s.getDiscussion();delete s.fileDesc.discussionList[e.discussionIndex],s.fileDesc.discussionList=s.fileDesc.discussionList,f.onDiscussionRemoved(s.fileDesc,e),y.focus()}):p.hide(),s.rangyRange=o.createRange(),s.rangyRange.setStart(s.selectionRange.startContainer,s.selectionRange.startOffset),s.rangyRange.setEnd(s.selectionRange.endContainer,s.selectionRange.endOffset),setTimeout(function(){C===s&&E.applyToRange(s.rangyRange)},50),s.$contentInputElt.focus().val(a)}).on("hide.bs.popover",function(){C&&(C.$commentElt.removeClass("active"),a=C.$contentInputElt.val(),i["author.name"]=C.$authorInputElt.val(),E.undoToRange(C.rangyRange),C=void 0,delete T.newDiscussion)}),h.on("click",".popover",function(e){e.stopPropagation()});var m=e(S);_=e(".button-open-discussion").click(function(n){var i=m;if(C)if(C.discussionIndex){var r=-1;N.some(function(e,t){return e===C.commentElt?(r=t,!0):void 0}),i=e(N[r+1])}else i=e(t.first(N));0===i.length?(d(),v.focus(),v.adjustCursorPosition()):i.click(),n.stopPropagation()}),I=_.find("i")},h}),function(e){var t="waitForImages";e.waitForImages={hasImageProperties:["backgroundImage","listStyleImage","borderImage","borderCornerImage"]},e.expr[":"].uncached=function(t){if(!e(t).is('img[src!=""]'))return!1;var n=new Image;return n.src=t.src,!n.complete},e.fn.waitForImages=function(n,i,r){var o=0,a=0;if(e.isPlainObject(arguments[0])&&(r=arguments[0].waitForAll,i=arguments[0].each,n=arguments[0].finished),n=n||e.noop,i=i||e.noop,r=!!r,!e.isFunction(n)||!e.isFunction(i))throw new TypeError("An invalid callback was supplied.");return this.each(function(){var s=e(this),l=[],c=e.waitForImages.hasImageProperties||[],u=/url\(\s*(['"]?)(.*?)\1\s*\)/g;r?s.find("*").andSelf().each(function(){var t=e(this);t.is("img:uncached")&&l.push({src:t.attr("src"),element:t[0]}),e.each(c,function(e,n){var i,r=t.css(n);if(!r)return!0;for(;i=u.exec(r);)l.push({src:i[2],element:t[0]})})}):s.find("img:uncached").each(function(){l.push({src:this.src,element:this})}),o=l.length,a=0,0===o&&n.call(s[0]),e.each(l,function(r,l){var c=new Image;e(c).bind("load."+t+" error."+t,function(e){return a++,i.call(l.element,a,o,"load"==e.type),a==o?(n.call(s[0]),!1):void 0}),c.src=l.src})})}}(jQuery),define("jquery-waitforimages",function(){}),define("eventMgr",["jquery","underscore","crel","utils","logger","classes/Extension","settings","text!html/settingsExtensionsAccordion.html","extensions/yamlFrontMatterParser","extensions/markdownSectionParser","extensions/partialRendering","extensions/buttonMarkdownSyntax","extensions/googleAnalytics","extensions/twitter","extensions/dialogAbout","extensions/dialogManagePublication","extensions/dialogManageSynchronization","extensions/dialogManageSharing","extensions/dialogOpenHarddrive","extensions/documentTitle","extensions/documentSelector","extensions/documentPanel","extensions/documentManager","extensions/workingIndicator","extensions/notifications","extensions/markdownExtra","extensions/toc","extensions/mathJax","extensions/emailConverter","extensions/scrollSync","extensions/buttonSync","extensions/buttonPublish","extensions/buttonStat","extensions/buttonHtmlCode","extensions/buttonViewer","extensions/welcomeTour","extensions/shortcuts","extensions/userCustom","extensions/comments","bootstrap","jquery-waitforimages"],function(e,t,n,i,r,o,a,s){function l(e){return t.chain(p).map(function(t){return t.enabled&&t[e]}).compact().value()}function c(e){return h[e]=l(e),function(){r.log(e,arguments);var n=arguments;t.each(h[e],function(e){try{e.apply(null,n)}catch(i){console.error(t.isObject(i)?i.stack:i)}})}}function u(e){d[e]=c(e)}var d={},p=t.chain(arguments).map(function(e){return e instanceof o&&e}).compact().value(),f=a.extensionSettings||{};t.each(p,function(e){e.config=t.extend({},e.defaultConfig,f[e.extensionId]),e.enabled=window.viewerMode===!0&&e.disableInViewer===!0?!1:!e.isOptional||void 0===e.config.enabled||e.config.enabled===!0});var h={};d.addListener=function(e,t){try{h[e].push(t)}catch(n){console.error("No event listener called "+e)}},c("onInit")(),d.onLoadSettings=function(){r.log("onLoadSettings"),t.each(p,function(e){var t=!e.isOptional||void 0===e.config.enabled||e.config.enabled===!0;i.setInputChecked("#input-enable-extension-"+e.extensionId,t),"markdownExtra"==e.extensionId?i.setInputChecked("#input-settings-markdown-extra",t):"mathJax"==e.extensionId&&i.setInputChecked("#input-settings-mathjax",t);var n=e.onLoadSettings;n&&n()})},d.onSaveSettings=function(e,n){r.log("onSaveSettings"),t.each(p,function(r){var o=t.extend({},r.defaultConfig);o.enabled=i.getInputChecked("#input-enable-extension-"+r.extensionId);var a;"markdownExtra"==r.extensionId?(a=i.getInputChecked("#input-settings-markdown-extra"),a!=r.enabled&&(o.enabled=a)):"mathJax"==r.extensionId&&(a=i.getInputChecked("#input-settings-mathjax"),a!=r.enabled&&(o.enabled=a));var s=r.onSaveSettings;s&&s(o,n),e[r.extensionId]=o})},u("onMessage"),u("onError"),u("onOfflineChanged"),u("onUserActive"),u("onAsyncRunning"),u("onPeriodicRun"),u("onEditorCreated"),u("onFileMgrCreated"),u("onSynchronizerCreated"),u("onPublisherCreated"),u("onEventMgrCreated"),u("onFileCreated"),u("onFileDeleted"),u("onFileSelected"),u("onFileOpen"),u("onFileClosed"),u("onContentChanged"),u("onTitleChanged"),u("onFoldersChanged"),u("onSyncRunning"),u("onSyncSuccess"),u("onSyncImportSuccess"),u("onSyncExportSuccess"),u("onSyncRemoved"),u("onPublishRunning"),u("onPublishSuccess"),u("onNewPublishSuccess"),u("onPublishRemoved"),u("onLayoutCreated"),u("onLayoutResize"),u("onPagedownConfigure"),u("onSectionsCreated"),u("onCursorCoordinates"),u("onDiscussionCreated"),u("onDiscussionRemoved"),u("onCommentsChanged"),u("onTweet");var m,g,v=c("onPreviewFinished"),b=l("onAsyncPreview");d.onAsyncPreview=function(){function e(n){var r=n.length?n.shift():function(){setTimeout(function(){var e="";t.each(m.children,function(t){e+=t.innerHTML});var n=i.trim(e),r=n.replace(/ .*?<\/span> /g,"");v(n,r)},10)};r(function(){e(n)})}r.log("onAsyncPreview"),e(b.concat([function(e){g.waitForImages(e)}]))};var y=c("onReady");return d.onReady=function(){m=document.getElementById("preview-contents"),g=e(m);var i=function(e){var i=n("div",{"class":"btn-group"}),r=e();return t.isString(r)?i.innerHTML=r:t.isElement(r)&&i.appendChild(r),i};if(window.viewerMode===!1){var o=t.chain(p).sortBy(function(e){return e.extensionName.toLowerCase()}).reduce(function(e,n){return e+(n.settingsBlock?t.template(s,{extensionId:n.extensionId,extensionName:n.extensionName,isOptional:n.isOptional,settingsBlock:n.settingsBlock}):"")},"").value();document.querySelector(".accordion-extensions").innerHTML=o,r.log("onCreateButton");var a=l("onCreateButton"),c=document.createDocumentFragment();t.each(a,function(e){c.appendChild(i(e))}),document.querySelector(".extension-buttons").appendChild(c)}r.log("onCreatePreviewButton");var u=l("onCreatePreviewButton"),d=document.createDocumentFragment();t.each(u,function(e){d.appendChild(i(e))});var f=document.querySelector(".extension-preview-buttons");f.appendChild(d),y()},d.onEventMgrCreated(d),d}),function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=t.util.clone(e[r]));return i;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var i=t.util.clone(t.languages[e]);for(var r in n)i[r]=n[r];return i},insertBefore:function(e,n,i,r){r=r||t.languages;var o=r[e],a={};for(var s in o)if(o.hasOwnProperty(s)){if(s==n)for(var l in i)i.hasOwnProperty(l)&&(a[l]=i[l]);a[s]=o[s]}return r[e]=a},DFS:function(e,n){for(var i in e)n.call(e,i,e[i]),"Object"===t.util.type(e)&&t.languages.DFS(e[i],n)}},highlightAll:function(e,n){for(var i,r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'),o=0;i=r[o++];)t.highlightElement(i,e===!0,n)},highlightElement:function(i,r,o){for(var a,s,l=i;l&&!e.test(l.className);)l=l.parentNode;if(l&&(a=(l.className.match(e)||[,""])[1],s=t.languages[a]),s){i.className=i.className.replace(e,"").replace(/\s+/g," ")+" language-"+a,l=i.parentNode,/pre/i.test(l.nodeName)&&(l.className=l.className.replace(e,"").replace(/\s+/g," ")+" language-"+a);var c=i.textContent;if(c){c=c.replace(/&/g,"&").replace(/e.length)break e;if(!(p instanceof i)){s.lastIndex=0;var f=s.exec(p);if(f){c&&(u=f[1].length);var h=f.index-1+u,f=f[0].slice(u),m=f.length,g=h+m,v=p.slice(0,h+1),b=p.slice(g+1),y=[d,1];v&&y.push(v);var x=new i(a,l?t.tokenize(f,l):f);y.push(x),b&&y.push(b),Array.prototype.splice.apply(r,y)}}}}return r},hooks:{all:{},add:function(e,n){var i=t.hooks.all;i[e]=i[e]||[],i[e].push(n)},run:function(e,n){var i=t.hooks.all[e];if(i&&i.length)for(var r,o=0;r=i[o++];)r(n)}}},n=t.Token=function(e,t){this.type=e,this.content=t};if(n.stringify=function(e,i,r){if("string"==typeof e)return e;if("[object Array]"==Object.prototype.toString.call(e))return e.map(function(t){return n.stringify(t,i,e)}).join("");var o={type:e.type,content:n.stringify(e.content,i,r),tag:"span",classes:["token",e.type],attributes:{},language:i,parent:r};"comment"==o.type&&(o.attributes.spellcheck="true"),t.hooks.run("wrap",o);var a="";for(var s in o.attributes)a+=s+'="'+(o.attributes[s]||"")+'"';return"<"+o.tag+' class="'+o.classes.join(" ")+'" '+a+">"+o.content+""},!self.document)return void self.addEventListener("message",function(e){var n=JSON.parse(e.data),i=n.language,r=n.code;self.postMessage(JSON.stringify(t.tokenize(r,t.languages[i]))),self.close()},!1);var i=document.getElementsByTagName("script");i=i[i.length-1],i&&(t.filename=i.src,document.addEventListener&&!i.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll))}(),define("prism-core",function(e){return function(){var t;return t||e.Prism}}(this));var DIFF_DELETE=-1,DIFF_INSERT=1,DIFF_EQUAL=0;diff_match_patch.Diff,diff_match_patch.prototype.diff_main=function(e,t,n,i){"undefined"==typeof i&&(i=this.Diff_Timeout<=0?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout);var r=i;if(null==e||null==t)throw new Error("Null input. (diff_main)");if(e==t)return e?[[DIFF_EQUAL,e]]:[];"undefined"==typeof n&&(n=!0);var o=n,a=this.diff_commonPrefix(e,t),s=e.substring(0,a);e=e.substring(a),t=t.substring(a),a=this.diff_commonSuffix(e,t);var l=e.substring(e.length-a);e=e.substring(0,e.length-a),t=t.substring(0,t.length-a);var c=this.diff_compute_(e,t,o,r);return s&&c.unshift([DIFF_EQUAL,s]),l&&c.push([DIFF_EQUAL,l]),this.diff_cleanupMerge(c),c},diff_match_patch.prototype.diff_compute_=function(e,t,n,i){var r;if(!e)return[[DIFF_INSERT,t]];if(!t)return[[DIFF_DELETE,e]];var o=e.length>t.length?e:t,a=e.length>t.length?t:e,s=o.indexOf(a);if(-1!=s)return r=[[DIFF_INSERT,o.substring(0,s)],[DIFF_EQUAL,a],[DIFF_INSERT,o.substring(s+a.length)]],e.length>t.length&&(r[0][0]=r[2][0]=DIFF_DELETE),r;if(1==a.length)return[[DIFF_DELETE,e],[DIFF_INSERT,t]];var l=this.diff_halfMatch_(e,t);if(l){var c=l[0],u=l[1],d=l[2],p=l[3],f=l[4],h=this.diff_main(c,d,n,i),m=this.diff_main(u,p,n,i);return h.concat([[DIFF_EQUAL,f]],m)}return n&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,i):this.diff_bisect_(e,t,i)},diff_match_patch.prototype.diff_lineMode_=function(e,t,n){var i=this.diff_linesToChars_(e,t);e=i.chars1,t=i.chars2;var r=i.lineArray,o=this.diff_main(e,t,!1,n);this.diff_charsToLines_(o,r),this.diff_cleanupSemantic(o),o.push([DIFF_EQUAL,""]);for(var a=0,s=0,l=0,c="",u="";a=1&&l>=1){o.splice(a-s-l,s+l),a=a-s-l;for(var i=this.diff_main(c,u,!1,n),d=i.length-1;d>=0;d--)o.splice(a,0,i[d]);a+=i.length}l=0,s=0,c="",u=""}a++}return o.pop(),o},diff_match_patch.prototype.diff_bisect_=function(e,t,n){for(var i=e.length,r=t.length,o=Math.ceil((i+r)/2),a=o,s=2*o,l=new Array(s),c=new Array(s),u=0;s>u;u++)l[u]=-1,c[u]=-1;l[a+1]=0,c[a+1]=0;for(var d=i-r,p=d%2!=0,f=0,h=0,m=0,g=0,v=0;o>v&&!((new Date).getTime()>n);v++){for(var b=-v+f;v-h>=b;b+=2){var y,x=a+b;y=b==-v||b!=v&&l[x-1]y&&r>w&&e.charAt(y)==t.charAt(w);)y++,w++;if(l[x]=y,y>i)h+=2;else if(w>r)f+=2;else if(p){var S=a+d-b;if(S>=0&&s>S&&-1!=c[S]){var C=i-c[S];if(y>=C)return this.diff_bisectSplit_(e,t,y,w,n)}}}for(var E=-v+m;v-g>=E;E+=2){var C,S=a+E;C=E==-v||E!=v&&c[S-1]C&&r>T&&e.charAt(i-C-1)==t.charAt(r-T-1);)C++,T++;if(c[S]=C,C>i)g+=2;else if(T>r)m+=2;else if(!p){var x=a+d-E;if(x>=0&&s>x&&-1!=l[x]){var y=l[x],w=a+y-x;if(C=i-C,y>=C)return this.diff_bisectSplit_(e,t,y,w,n)}}}}return[[DIFF_DELETE,e],[DIFF_INSERT,t]]},diff_match_patch.prototype.diff_bisectSplit_=function(e,t,n,i,r){var o=e.substring(0,n),a=t.substring(0,i),s=e.substring(n),l=t.substring(i),c=this.diff_main(o,a,!1,r),u=this.diff_main(s,l,!1,r);return c.concat(u)},diff_match_patch.prototype.diff_linesToChars_=function(e,t){function n(e){for(var t="",n=0,o=-1,a=i.length;on;)e.substring(o,r)==t.substring(o,r)?(n=r,o=n):i=r,r=Math.floor((i-n)/2+n);return r},diff_match_patch.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var n=0,i=Math.min(e.length,t.length),r=i,o=0;r>n;)e.substring(e.length-r,e.length-o)==t.substring(t.length-r,t.length-o)?(n=r,o=n):i=r,r=Math.floor((i-n)/2+n);return r},diff_match_patch.prototype.diff_commonOverlap_=function(e,t){var n=e.length,i=t.length;if(0==n||0==i)return 0;n>i?e=e.substring(n-i):i>n&&(t=t.substring(0,n));var r=Math.min(n,i);if(e==t)return r;for(var o=0,a=1;;){var s=e.substring(r-a),l=t.indexOf(s);if(-1==l)return o;a+=l,(0==l||e.substring(r-a)==t.substring(0,a))&&(o=a,a++)}},diff_match_patch.prototype.diff_halfMatch_=function(e,t){function n(e,t,n){for(var i,r,o,s,l=e.substring(n,n+Math.floor(e.length/4)),c=-1,u="";-1!=(c=t.indexOf(l,c+1));){var d=a.diff_commonPrefix(e.substring(n),t.substring(c)),p=a.diff_commonSuffix(e.substring(0,n),t.substring(0,c));u.length0)return t.prev();break;case 27:return e.preventDefault(),t.end()}})},n.prototype._makePromise=function(t){return t&&e.isFunction(t.then)?t:null},n.prototype._callOnPromiseDone=function(e,t,n){var i=this;return e?e.then(function(){return t.call(i,n)}):t.call(this,n)},n.prototype._showBackdrop=function(){return this.backdrop.backgroundShown?void 0:(this.backdrop=e("
    ",{"class":"tour-backdrop"}),this.backdrop.backgroundShown=!0,e("body").append(this.backdrop))},n.prototype._hideBackdrop=function(){return this._hideOverlayElement(),this._hideBackground()},n.prototype._hideBackground=function(){return this.backdrop.remove(),this.backdrop.overlay=null,this.backdrop.backgroundShown=!1},n.prototype._showOverlayElement=function(t){var n,i,r;if(!this.backdrop.overlayElementShown)return this.backdrop.overlayElementShown=!0,i=e(t),n=e("
    "),r=i.offset(),r.top=r.top,r.left=r.left,n.width(i.innerWidth()).height(i.innerHeight()).addClass("tour-step-background").offset(r),i.addClass("tour-step-backdrop"),e("body").append(n),this.backdrop.$element=i,this.backdrop.$background=n},n.prototype._hideOverlayElement=function(){return this.backdrop.overlayElementShown?(this.backdrop.$element.removeClass("tour-step-backdrop"),this.backdrop.$background.remove(),this.backdrop.$element=null,this.backdrop.$background=null,this.backdrop.overlayElementShown=!1):void 0},n.prototype._clearTimer=function(){return t.clearTimeout(this._timer),this._timer=null,this._duration=null},n}(),t.Tour=n}(jQuery,window),define("bootstrap-tour",["bootstrap"],function(e){return function(){var t;return t||e.Tour}}(this)),define("extensions/welcomeTour",["underscore","jquery","storage","classes/Extension","bootstrap-tour"],function(e,t,n,i,r){var o,a=new i("welcomeTour","Welcome tour",!1,!0);return a.onEventMgrCreated=function(e){o=e},a.onReady=function(){function i(e,n,i){var r=t(e).tooltip({html:!0,placement:i,trigger:"manual",title:n}).tooltip("show").addClass("info-tooltip");r.one("click",function(){r.tooltip("hide").removeClass("info-tooltip")}),setTimeout(function(){r.tooltip("hide").removeClass("info-tooltip")},2e4)}var a=new r({keyboard:!1,storage:{getItem:function(){},setItem:function(){},removeItem:function(){}},onEnd:function(){n.welcomeTour="done",i(".menu-panel .toggle-button *","Synchronize, publish and more...","right"),i(".document-panel .toggle-button *","Create and manage documents","left"),i(".extension-preview-buttons .btn-group:first","Need help with Markdown syntax?","left"),i(".layout-toggler-preview","Toggle preview","right")},template:['
    ','
    ','

    ','
    ',' ","
    "].join("")});a.addSteps([{element:".navbar-inner",title:"StackEdit 4 beta preview!",content:["

    What's new?

    ","
      ","
    • New contenteditable based editor (credit to Dabblet, Editorially...)
    • ","
    • New layout with CSS3 transitions (lighter supposedly)
    • ","
    • Comments/discussions support (see the new icon in the navigation bar)
    • ","
    • Auto-merge and conflict detection using standard synchronization
    • ","
    • Dropped real time sync support :( since you can collaborate simultaneously using standard synchronization
    • ","
    ",'

    Please provide your feedback here and declare issues on GitHub... Thanks!

    ',''].join(""),placement:"bottom",onShown:function(){o.onTweet()}}]),e.has(n,"welcomeTour")||a.start(),t(".action-welcome-tour").click(function(){a.restart()})},a}),define("text!extensions/shortcutsDefaultMapping.settings",[],function(){return"{\n 'mod+b': bindPagedownButton('bold'),\n 'mod+i': bindPagedownButton('italic'),\n 'mod+l': bindPagedownButton('link'),\n 'mod+q': bindPagedownButton('quote'),\n 'mod+k': bindPagedownButton('code'),\n 'mod+g': bindPagedownButton('image'),\n 'mod+o': bindPagedownButton('olist'),\n 'mod+u': bindPagedownButton('ulist'),\n 'mod+h': bindPagedownButton('heading'),\n 'mod+r': bindPagedownButton('hr'),\n 'mod+z': bindPagedownButton('undo'),\n 'mod+y': bindPagedownButton('redo'),\n 'mod+shift+z': bindPagedownButton('redo'),\n 'mod+m': function(evt) {\n $('.button-open-discussion').click();\n evt.preventDefault();\n },\n '= = > space': function() {\n expand('==> ', '⇒ ');\n },\n '< = = space': function() {\n expand('<== ', '⇐ ');\n },\n 'S t a c k E d i t': function() {\n eventMgr.onMessage(\"You are stunned!!! Aren't you?\");\n }\n}\n"}),define("text!html/shortcutsSettingsBlock.html",[],function(){return'

    Maps keyboard shortcuts to JavaScript functions.

    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n'}),define("extensions/shortcuts",["jquery","underscore","utils","mousetrap","classes/Extension","text!extensions/shortcutsDefaultMapping.settings","text!html/shortcutsSettingsBlock.html"],function($,_,utils,mousetrap,Extension,shortcutsDefaultMapping,shortcutsSettingsBlockHTML){function bindPagedownButton(e){return function(t){pagedownEditor.uiManager.doClick(pagedownEditor.uiManager.buttons[e]),t.preventDefault()}}function expand(e,t){utils.defer(function(){require("editor").replacePreviousText(e,t)})}var shortcuts=new Extension("shortcuts","Shortcuts",!0,!0);shortcuts.settingsBlock=shortcutsSettingsBlockHTML,shortcuts.defaultConfig={mapping:shortcutsDefaultMapping};var eventMgr,pagedownEditor;return shortcuts.onEventMgrCreated=function(e){eventMgr=e,eventMgr.addListener("onPagedownConfigure",function(e){pagedownEditor=e})},shortcuts.onLoadSettings=function(){utils.setInputValue("#textarea-shortcuts-mapping",shortcuts.config.mapping)},shortcuts.onSaveSettings=function(newConfig,event){newConfig.code=utils.getInputValue("#textarea-shortcuts-mapping");try{eval("var test = "+newConfig.code)}catch(e){eventMgr.onError(e),utils.getInputTextValue("#textarea-shortcuts-mapping",event,/^$/)}},shortcuts.onInit=function(){try{var shortcutMap;eval("shortcutMap = "+shortcuts.config.mapping),_.each(shortcutMap,function(e,t){mousetrap.bind(t,e)})}catch(e){console.error(e)}},shortcuts}),define("text!html/userCustomSettingsBlock.html",[],function(){return'

    Allows users to implement their own extension.

    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \nMore info'}),define("extensions/userCustom",["jquery","underscore","utils","classes/Extension","fileSystem","settings","text!html/userCustomSettingsBlock.html"],function($,_,utils,Extension,fileSystem,settings,userCustomSettingsBlockHTML){var userCustom=new Extension("userCustom","UserCustom extension",!0);userCustom.settingsBlock=userCustomSettingsBlockHTML,userCustom.defaultConfig={code:""};var fileMgr;userCustom.onFileMgrCreated=function(e){fileMgr=e};var synchronizer;userCustom.onSynchronizerCreated=function(e){synchronizer=e};var publisher;userCustom.onPublisherCreated=function(e){publisher=e};var eventMgr;return userCustom.onEventMgrCreated=function(e){eventMgr=e},userCustom.onLoadSettings=function(){utils.setInputValue("#textarea-usercustom-code",userCustom.config.code)},userCustom.onSaveSettings=function(newConfig,event){newConfig.code=utils.getInputValue("#textarea-usercustom-code");try{eval(newConfig.code)}catch(e){eventMgr.onError(e),utils.getInputTextValue("#textarea-usercustom-code",event,/^$/)}},userCustom.onInit=function(){try{eval(userCustom.config.code)}catch(e){console.error(e)}},userCustom}),define("text!html/commentsPopoverContent.html",[],function(){return'
    \n
    <%= commentList %>
    \n
    \n
    \n \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n'}),define("extensions/comments",["jquery","underscore","utils","storage","crel","rangy","classes/Extension","text!html/commentsPopoverContent.html","bootstrap"],function(e,t,n,i,r,o,a,s){function l(e,t,n){t=Math.round(t);for(var i=t-21;t+22>i;)w[i]&&(t=i+22),i++;!n&&(w[t]=1);var r=-8;-1!==e.className.indexOf(" icon-split")&&(r=-12);var o=t+r;e.style.top=o+"px",e.style.right="12px"}function c(t,n){this.commentElt=t,this.$commentElt=e(t).addClass("active"),this.fileDesc=n,this.discussionIndex=t.discussionIndex}function u(e){var t=C.getPopoverElt(),n=0;t.offsetWidthi&&(t.style.top=parseInt(t.style.top)+i+"px")}function d(){C&&C.$commentElt.popover("toggle").popover("destroy")}function p(){var e=C.getDiscussion(),n=i["author.name"],r=[];return e.commentList&&(r=e.commentList.map(function(e){var i=e.author||"Anonymous";return t.template(m,{author:i,content:e.content,reply:e.author!=n})})),"conflict"==e.type&&r.unshift(t.template(m,{author:"StackEdit",content:"Multiple users have made conflicting modifications.",reply:!0})),r.join("")}var f,h=new a("comments","Comments",!1,!0),m=["
    \">",'
    <%= author %>
    ','
    <%= content %>
    ',"
    "].join(""),g=['',' ',' '," "," “<%- title %>”",""].join("");h.onEventMgrCreated=function(e){f=e};var v,b;h.onEditorCreated=function(e){v=e,b=v.selectionMgr};var y,x,w=[],S=r("a",{"class":"discussion icon-comment new"});c.prototype.getDiscussion=function(){return this.discussionIndex?this.fileDesc.discussionList[this.discussionIndex]:this.fileDesc.newDiscussion},c.prototype.getPopoverElt=function(){return document.querySelector(".comments-popover .popover:last-child")};var C,E,T,k,_,I,D={},N=[],L=!1,M=t.debounce(function(){function e(){var i;if(0===o.length)return t.filter(D,function(e,n){return!t.has(T.discussionList,n)}).forEach(function(e){x.removeChild(e),delete D[e.discussionIndex]}),C&&!C.discussionIndex&&(i=b.getCoordinates(C.getDiscussion().selectionEnd),l(S,i.y,!0),y.scrollTop+=parseInt(S.style.top)-y.scrollTop-3*y.offsetHeight/4,u(S)),N=t.sortBy(D,function(e){return e.selectionEnd}),_.toggleClass("some",0!==N.length),_.toggleClass("replied",L),void I.toggleClass("icon-chat",0!==N.length);var a=o.shift(),s=D[a.discussionIndex];s||(s=r("a"));var c="discussion",d=!a.commentList||!n||t.last(a.commentList).author!=n;d&&(L=!0),c+="conflict"==a.type?" icon-split":" icon-comment",c+=d?" replied":" added",s.className=c,s.discussionIndex=a.discussionIndex,s.selectionEnd=a.selectionEnd,i=b.getCoordinates(a.selectionEnd),l(s,i.y),x.appendChild(s),D[a.discussionIndex]=s,C&&C.getDiscussion()===a&&(y.scrollTop+=parseInt(s.style.top)-y.scrollTop-3*y.offsetHeight/4,u(s)),k=setTimeout(e,5)}if(void 0!==T){L=!1,N=[];var n=i["author.name"];w=[];var o=t.sortBy(T.discussionList,function(e){return e.selectionEnd});clearTimeout(k),k=setTimeout(e,5)}},50);return h.onLayoutResize=M,h.onFileOpen=function(e){T=e,M()},h.onContentChanged=function(e){T===e&&M()},h.onCommentsChanged=function(e){if(T===e){if(void 0!==C){var t=C;t.discussionIndex&&(t.getPopoverElt().querySelector(".discussion-comment-list").innerHTML=p());try{E.undoToRange(t.rangyRange)}catch(n){}var i=t.getDiscussion();t.selectionRange=b.createRange(i.selectionStart,i.selectionEnd),t.rangyRange=o.createRange(),t.rangyRange.setStart(t.selectionRange.startContainer,t.selectionRange.startOffset),t.rangyRange.setEnd(t.selectionRange.endContainer,t.selectionRange.endOffset),setTimeout(function(){C===t&&E.applyToRange(t.rangyRange)},50)}M()}},h.onDiscussionCreated=function(e){T===e&&M()},h.onDiscussionRemoved=function(e,t){T===e&&(void 0!==C&&C.discussionIndex==t.discussionIndex&&d(),M())},h.onReady=function(){E=o.createCssClassApplier("comment-highlight",{normalize:!1});var a="";y=document.getElementById("wmd-input"),x=document.querySelector("#wmd-input > .editor-margin"),x.appendChild(S);var h=e(r("div",{"class":"comments-popover"}));e(document.body).append(h).on("click",function(e){C&&C.$commentElt[0]!==e.target&&d()}).popover({placement:"auto top",container:".comments-popover",html:!0,title:function(){if(!C)return!0;var e=C.getDiscussion(),n=e.selectionEnd-e.selectionStart,i=v.getValue().substr(e.selectionStart,n>20?20:n);return n>20&&(i+="..."),t.template(g,{title:i})},content:function(){var e=t.template(s,{commentList:p()});return e},selector:"#wmd-input > .editor-margin > .discussion"}),e(x).on("show.bs.popover",function(e){d();var t=new c(e.target,T);C=t;var n=t.getDiscussion();if(!n){var i=Math.min(b.selectionStart,b.selectionEnd),r=Math.max(b.selectionStart,b.selectionEnd);if(i===r){var o=b.getClosestWordOffset(i);i=o.start,r=o.end}n={selectionStart:i,selectionEnd:r,commentList:[]},T.newDiscussion=n;var a=b.getCoordinates(i);l(S,a.y,!0)}t.selectionRange=b.createRange(n.selectionStart,n.selectionEnd),y.scrollTop+=parseInt(e.target.style.top)-y.scrollTop-3*y.offsetHeight/4}).on("shown.bs.popover",function(r){var s=C,l=s.getPopoverElt();s.$authorInputElt=e(l.querySelector(".input-comment-author")).val(i["author.name"]),s.$contentInputElt=e(l.querySelector(".input-comment-content")),s.hr=l.querySelector("hr"),u(s.commentElt),l.querySelector(".scrollport").scrollTop=9999999;var c=e(l.querySelector(".action-add-comment"));e().add(s.$contentInputElt).add(s.$authorInputElt).keydown(function(e){switch(e.which){case 13:return e.preventDefault(),void c.click();case 27:return e.preventDefault(),d(),v.focus(),void v.adjustCursorPosition()}}),c.click(function(e){var i=n.getInputTextValue(s.$authorInputElt),r=n.getInputTextValue(s.$contentInputElt,e);if(!e.isPropagationStopped()){var o=s.getDiscussion();s.$contentInputElt.val(""),d(),o.commentList=o.commentList||[],o.commentList.push({author:i,content:r});var a=s.fileDesc.discussionList||{};if(o.discussionIndex)s.fileDesc.discussionList=a,f.onCommentsChanged(s.fileDesc);else{var l;do l=n.randomString();while(t.has(a,l));o.discussionIndex=l,a[l]=o,s.fileDesc.discussionList=a,f.onDiscussionCreated(s.fileDesc,o)}y.focus()}});var p=e(l.querySelector(".action-remove-discussion"));r.target.discussionIndex?p.click(function(){d();var e=s.getDiscussion();delete s.fileDesc.discussionList[e.discussionIndex],s.fileDesc.discussionList=s.fileDesc.discussionList,f.onDiscussionRemoved(s.fileDesc,e),y.focus()}):p.hide(),s.rangyRange=o.createRange(),s.rangyRange.setStart(s.selectionRange.startContainer,s.selectionRange.startOffset),s.rangyRange.setEnd(s.selectionRange.endContainer,s.selectionRange.endOffset),setTimeout(function(){C===s&&E.applyToRange(s.rangyRange)},50),s.$contentInputElt.focus().val(a)}).on("hide.bs.popover",function(){C&&(C.$commentElt.removeClass("active"),a=C.$contentInputElt.val(),i["author.name"]=C.$authorInputElt.val(),E.undoToRange(C.rangyRange),C=void 0,delete T.newDiscussion)}),h.on("click",".popover",function(e){e.stopPropagation()});var m=e(S);_=e(".button-open-discussion").click(function(n){var i=m;if(C)if(C.discussionIndex){var r=-1;N.some(function(e,t){return e===C.commentElt?(r=t,!0):void 0}),i=e(N[r+1])}else i=e(t.first(N));0===i.length?(d(),v.focus(),v.adjustCursorPosition()):i.click(),n.stopPropagation()}),I=_.find("i")},h}),function(e){var t="waitForImages";e.waitForImages={hasImageProperties:["backgroundImage","listStyleImage","borderImage","borderCornerImage"]},e.expr[":"].uncached=function(t){if(!e(t).is('img[src!=""]'))return!1;var n=new Image;return n.src=t.src,!n.complete},e.fn.waitForImages=function(n,i,r){var o=0,a=0;if(e.isPlainObject(arguments[0])&&(r=arguments[0].waitForAll,i=arguments[0].each,n=arguments[0].finished),n=n||e.noop,i=i||e.noop,r=!!r,!e.isFunction(n)||!e.isFunction(i))throw new TypeError("An invalid callback was supplied.");return this.each(function(){var s=e(this),l=[],c=e.waitForImages.hasImageProperties||[],u=/url\(\s*(['"]?)(.*?)\1\s*\)/g;r?s.find("*").andSelf().each(function(){var t=e(this);t.is("img:uncached")&&l.push({src:t.attr("src"),element:t[0]}),e.each(c,function(e,n){var i,r=t.css(n);if(!r)return!0;for(;i=u.exec(r);)l.push({src:i[2],element:t[0]})})}):s.find("img:uncached").each(function(){l.push({src:this.src,element:this})}),o=l.length,a=0,0===o&&n.call(s[0]),e.each(l,function(r,l){var c=new Image;e(c).bind("load."+t+" error."+t,function(e){return a++,i.call(l.element,a,o,"load"==e.type),a==o?(n.call(s[0]),!1):void 0}),c.src=l.src})})}}(jQuery),define("jquery-waitforimages",function(){}),define("eventMgr",["jquery","underscore","crel","utils","logger","classes/Extension","settings","text!html/settingsExtensionsAccordion.html","extensions/yamlFrontMatterParser","extensions/markdownSectionParser","extensions/partialRendering","extensions/buttonMarkdownSyntax","extensions/googleAnalytics","extensions/twitter","extensions/dialogAbout","extensions/dialogManagePublication","extensions/dialogManageSynchronization","extensions/dialogManageSharing","extensions/dialogOpenHarddrive","extensions/documentTitle","extensions/documentSelector","extensions/documentPanel","extensions/documentManager","extensions/workingIndicator","extensions/notifications","extensions/markdownExtra","extensions/toc","extensions/mathJax","extensions/emailConverter","extensions/scrollSync","extensions/buttonSync","extensions/buttonPublish","extensions/buttonStat","extensions/buttonHtmlCode","extensions/buttonViewer","extensions/welcomeTour","extensions/shortcuts","extensions/userCustom","extensions/comments","bootstrap","jquery-waitforimages"],function(e,t,n,i,r,o,a,s){function l(e){return t.chain(p).map(function(t){return t.enabled&&t[e]}).compact().value()}function c(e){return h[e]=l(e),function(){r.log(e,arguments);var n=arguments;t.each(h[e],function(e){try{e.apply(null,n)}catch(i){console.error(t.isObject(i)?i.stack:i)}})}}function u(e){d[e]=c(e)}var d={},p=t.chain(arguments).map(function(e){return e instanceof o&&e}).compact().value(),f=a.extensionSettings||{};t.each(p,function(e){e.config=t.extend({},e.defaultConfig,f[e.extensionId]),e.enabled=window.viewerMode===!0&&e.disableInViewer===!0?!1:!e.isOptional||void 0===e.config.enabled||e.config.enabled===!0});var h={};d.addListener=function(e,t){try{h[e].push(t)}catch(n){console.error("No event listener called "+e)}},c("onInit")(),d.onLoadSettings=function(){r.log("onLoadSettings"),t.each(p,function(e){var t=!e.isOptional||void 0===e.config.enabled||e.config.enabled===!0;i.setInputChecked("#input-enable-extension-"+e.extensionId,t),"markdownExtra"==e.extensionId?i.setInputChecked("#input-settings-markdown-extra",t):"mathJax"==e.extensionId&&i.setInputChecked("#input-settings-mathjax",t);var n=e.onLoadSettings;n&&n()})},d.onSaveSettings=function(e,n){r.log("onSaveSettings"),t.each(p,function(r){var o=t.extend({},r.defaultConfig);o.enabled=i.getInputChecked("#input-enable-extension-"+r.extensionId);var a;"markdownExtra"==r.extensionId?(a=i.getInputChecked("#input-settings-markdown-extra"),a!=r.enabled&&(o.enabled=a)):"mathJax"==r.extensionId&&(a=i.getInputChecked("#input-settings-mathjax"),a!=r.enabled&&(o.enabled=a));var s=r.onSaveSettings;s&&s(o,n),e[r.extensionId]=o})},u("onMessage"),u("onError"),u("onOfflineChanged"),u("onUserActive"),u("onAsyncRunning"),u("onPeriodicRun"),u("onEditorCreated"),u("onFileMgrCreated"),u("onSynchronizerCreated"),u("onPublisherCreated"),u("onEventMgrCreated"),u("onFileCreated"),u("onFileDeleted"),u("onFileSelected"),u("onFileOpen"),u("onFileClosed"),u("onContentChanged"),u("onTitleChanged"),u("onFoldersChanged"),u("onSyncRunning"),u("onSyncSuccess"),u("onSyncImportSuccess"),u("onSyncExportSuccess"),u("onSyncRemoved"),u("onPublishRunning"),u("onPublishSuccess"),u("onNewPublishSuccess"),u("onPublishRemoved"),u("onLayoutCreated"),u("onLayoutResize"),u("onPagedownConfigure"),u("onSectionsCreated"),u("onCursorCoordinates"),u("onDiscussionCreated"),u("onDiscussionRemoved"),u("onCommentsChanged"),u("onTweet");var m,g,v=c("onPreviewFinished"),b=l("onAsyncPreview");d.onAsyncPreview=function(){function e(n){var r=n.length?n.shift():function(){setTimeout(function(){var e="";t.each(m.children,function(t){e+=t.innerHTML});var n=i.trim(e),r=n.replace(/ .*?<\/span> /g,"");v(n,r)},10)};r(function(){e(n)})}r.log("onAsyncPreview"),e(b.concat([function(e){g.waitForImages(e)}]))};var y=c("onReady");return d.onReady=function(){m=document.getElementById("preview-contents"),g=e(m);var i=function(e){var i=n("div",{"class":"btn-group"}),r=e();return t.isString(r)?i.innerHTML=r:t.isElement(r)&&i.appendChild(r),i};if(window.viewerMode===!1){var o=t.chain(p).sortBy(function(e){return e.extensionName.toLowerCase()}).reduce(function(e,n){return e+(n.settingsBlock?t.template(s,{extensionId:n.extensionId,extensionName:n.extensionName,isOptional:n.isOptional,settingsBlock:n.settingsBlock}):"")},"").value();document.querySelector(".accordion-extensions").innerHTML=o,r.log("onCreateButton");var a=l("onCreateButton"),c=document.createDocumentFragment();t.each(a,function(e){c.appendChild(i(e))}),document.querySelector(".extension-buttons").appendChild(c)}r.log("onCreatePreviewButton");var u=l("onCreatePreviewButton"),d=document.createDocumentFragment();t.each(u,function(e){d.appendChild(i(e))});var f=document.querySelector(".extension-preview-buttons");f.appendChild(d),y()},d.onEventMgrCreated(d),d}),function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var i={};for(var r in e)e.hasOwnProperty(r)&&(i[r]=t.util.clone(e[r]));return i;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var i=t.util.clone(t.languages[e]);for(var r in n)i[r]=n[r];return i},insertBefore:function(e,n,i,r){r=r||t.languages;var o=r[e],a={};for(var s in o)if(o.hasOwnProperty(s)){if(s==n)for(var l in i)i.hasOwnProperty(l)&&(a[l]=i[l]);a[s]=o[s]}return r[e]=a},DFS:function(e,n){for(var i in e)n.call(e,i,e[i]),"Object"===t.util.type(e)&&t.languages.DFS(e[i],n)}},highlightAll:function(e,n){for(var i,r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'),o=0;i=r[o++];)t.highlightElement(i,e===!0,n)},highlightElement:function(i,r,o){for(var a,s,l=i;l&&!e.test(l.className);)l=l.parentNode;if(l&&(a=(l.className.match(e)||[,""])[1],s=t.languages[a]),s){i.className=i.className.replace(e,"").replace(/\s+/g," ")+" language-"+a,l=i.parentNode,/pre/i.test(l.nodeName)&&(l.className=l.className.replace(e,"").replace(/\s+/g," ")+" language-"+a);var c=i.textContent;if(c){c=c.replace(/&/g,"&").replace(/e.length)break e;if(!(p instanceof i)){s.lastIndex=0;var f=s.exec(p);if(f){c&&(u=f[1].length);var h=f.index-1+u,f=f[0].slice(u),m=f.length,g=h+m,v=p.slice(0,h+1),b=p.slice(g+1),y=[d,1];v&&y.push(v);var x=new i(a,l?t.tokenize(f,l):f);y.push(x),b&&y.push(b),Array.prototype.splice.apply(r,y)}}}}return r},hooks:{all:{},add:function(e,n){var i=t.hooks.all;i[e]=i[e]||[],i[e].push(n)},run:function(e,n){var i=t.hooks.all[e];if(i&&i.length)for(var r,o=0;r=i[o++];)r(n)}}},n=t.Token=function(e,t){this.type=e,this.content=t};if(n.stringify=function(e,i,r){if("string"==typeof e)return e;if("[object Array]"==Object.prototype.toString.call(e))return e.map(function(t){return n.stringify(t,i,e)}).join("");var o={type:e.type,content:n.stringify(e.content,i,r),tag:"span",classes:["token",e.type],attributes:{},language:i,parent:r};"comment"==o.type&&(o.attributes.spellcheck="true"),t.hooks.run("wrap",o);var a="";for(var s in o.attributes)a+=s+'="'+(o.attributes[s]||"")+'"';return"<"+o.tag+' class="'+o.classes.join(" ")+'" '+a+">"+o.content+""},!self.document)return void self.addEventListener("message",function(e){var n=JSON.parse(e.data),i=n.language,r=n.code;self.postMessage(JSON.stringify(t.tokenize(r,t.languages[i]))),self.close()},!1);var i=document.getElementsByTagName("script");i=i[i.length-1],i&&(t.filename=i.src,document.addEventListener&&!i.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll))}(),define("prism-core",function(e){return function(){var t;return t||e.Prism}}(this));var DIFF_DELETE=-1,DIFF_INSERT=1,DIFF_EQUAL=0;diff_match_patch.Diff,diff_match_patch.prototype.diff_main=function(e,t,n,i){"undefined"==typeof i&&(i=this.Diff_Timeout<=0?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout);var r=i;if(null==e||null==t)throw new Error("Null input. (diff_main)");if(e==t)return e?[[DIFF_EQUAL,e]]:[];"undefined"==typeof n&&(n=!0);var o=n,a=this.diff_commonPrefix(e,t),s=e.substring(0,a);e=e.substring(a),t=t.substring(a),a=this.diff_commonSuffix(e,t);var l=e.substring(e.length-a);e=e.substring(0,e.length-a),t=t.substring(0,t.length-a);var c=this.diff_compute_(e,t,o,r);return s&&c.unshift([DIFF_EQUAL,s]),l&&c.push([DIFF_EQUAL,l]),this.diff_cleanupMerge(c),c},diff_match_patch.prototype.diff_compute_=function(e,t,n,i){var r;if(!e)return[[DIFF_INSERT,t]];if(!t)return[[DIFF_DELETE,e]];var o=e.length>t.length?e:t,a=e.length>t.length?t:e,s=o.indexOf(a);if(-1!=s)return r=[[DIFF_INSERT,o.substring(0,s)],[DIFF_EQUAL,a],[DIFF_INSERT,o.substring(s+a.length)]],e.length>t.length&&(r[0][0]=r[2][0]=DIFF_DELETE),r;if(1==a.length)return[[DIFF_DELETE,e],[DIFF_INSERT,t]];var l=this.diff_halfMatch_(e,t);if(l){var c=l[0],u=l[1],d=l[2],p=l[3],f=l[4],h=this.diff_main(c,d,n,i),m=this.diff_main(u,p,n,i);return h.concat([[DIFF_EQUAL,f]],m)}return n&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,i):this.diff_bisect_(e,t,i)},diff_match_patch.prototype.diff_lineMode_=function(e,t,n){var i=this.diff_linesToChars_(e,t);e=i.chars1,t=i.chars2;var r=i.lineArray,o=this.diff_main(e,t,!1,n);this.diff_charsToLines_(o,r),this.diff_cleanupSemantic(o),o.push([DIFF_EQUAL,""]);for(var a=0,s=0,l=0,c="",u="";a=1&&l>=1){o.splice(a-s-l,s+l),a=a-s-l;for(var i=this.diff_main(c,u,!1,n),d=i.length-1;d>=0;d--)o.splice(a,0,i[d]);a+=i.length}l=0,s=0,c="",u=""}a++}return o.pop(),o},diff_match_patch.prototype.diff_bisect_=function(e,t,n){for(var i=e.length,r=t.length,o=Math.ceil((i+r)/2),a=o,s=2*o,l=new Array(s),c=new Array(s),u=0;s>u;u++)l[u]=-1,c[u]=-1;l[a+1]=0,c[a+1]=0;for(var d=i-r,p=d%2!=0,f=0,h=0,m=0,g=0,v=0;o>v&&!((new Date).getTime()>n);v++){for(var b=-v+f;v-h>=b;b+=2){var y,x=a+b;y=b==-v||b!=v&&l[x-1]y&&r>w&&e.charAt(y)==t.charAt(w);)y++,w++;if(l[x]=y,y>i)h+=2;else if(w>r)f+=2;else if(p){var S=a+d-b;if(S>=0&&s>S&&-1!=c[S]){var C=i-c[S];if(y>=C)return this.diff_bisectSplit_(e,t,y,w,n)}}}for(var E=-v+m;v-g>=E;E+=2){var C,S=a+E;C=E==-v||E!=v&&c[S-1]C&&r>T&&e.charAt(i-C-1)==t.charAt(r-T-1);)C++,T++;if(c[S]=C,C>i)g+=2;else if(T>r)m+=2;else if(!p){var x=a+d-E;if(x>=0&&s>x&&-1!=l[x]){var y=l[x],w=a+y-x;if(C=i-C,y>=C)return this.diff_bisectSplit_(e,t,y,w,n)}}}}return[[DIFF_DELETE,e],[DIFF_INSERT,t]]},diff_match_patch.prototype.diff_bisectSplit_=function(e,t,n,i,r){var o=e.substring(0,n),a=t.substring(0,i),s=e.substring(n),l=t.substring(i),c=this.diff_main(o,a,!1,r),u=this.diff_main(s,l,!1,r);return c.concat(u)},diff_match_patch.prototype.diff_linesToChars_=function(e,t){function n(e){for(var t="",n=0,o=-1,a=i.length;on;)e.substring(o,r)==t.substring(o,r)?(n=r,o=n):i=r,r=Math.floor((i-n)/2+n);return r},diff_match_patch.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var n=0,i=Math.min(e.length,t.length),r=i,o=0;r>n;)e.substring(e.length-r,e.length-o)==t.substring(t.length-r,t.length-o)?(n=r,o=n):i=r,r=Math.floor((i-n)/2+n);return r},diff_match_patch.prototype.diff_commonOverlap_=function(e,t){var n=e.length,i=t.length;if(0==n||0==i)return 0;n>i?e=e.substring(n-i):i>n&&(t=t.substring(0,n));var r=Math.min(n,i);if(e==t)return r;for(var o=0,a=1;;){var s=e.substring(r-a),l=t.indexOf(s);if(-1==l)return o;a+=l,(0==l||e.substring(r-a)==t.substring(0,a))&&(o=a,a++)}},diff_match_patch.prototype.diff_halfMatch_=function(e,t){function n(e,t,n){for(var i,r,o,s,l=e.substring(n,n+Math.floor(e.length/4)),c=-1,u="";-1!=(c=t.indexOf(l,c+1));){var d=a.diff_commonPrefix(e.substring(n),t.substring(c)),p=a.diff_commonSuffix(e.substring(0,n),t.substring(0,c));u.length=e.length?[i,r,o,s,u]:null}if(this.Diff_Timeout<=0)return null;var i=e.length>t.length?e:t,r=e.length>t.length?t:e;if(i.length<4||2*r.lengthl[4].length?s:l:l:s;var c,u,d,p;e.length>t.length?(c=o[0],u=o[1],d=o[2],p=o[3]):(d=o[0],p=o[1],c=o[2],u=o[3]);var f=o[4];return[c,u,d,p,f]},diff_match_patch.prototype.diff_cleanupSemantic=function(e){for(var t=!1,n=[],i=0,r=null,o=0,a=0,s=0,l=0,c=0;o0?n[i-1]:-1,a=0,s=0,l=0,c=0,r=null,t=!0)),o++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),o=1;o=f?(p>=u.length/2||p>=d.length/2)&&(e.splice(o,0,[DIFF_EQUAL,d.substring(0,p)]),e[o-1][1]=u.substring(0,u.length-p),e[o+1][1]=d.substring(p),o++):(f>=u.length/2||f>=d.length/2)&&(e.splice(o,0,[DIFF_EQUAL,u.substring(0,f)]),e[o-1][0]=DIFF_INSERT,e[o-1][1]=d.substring(0,d.length-f),e[o+1][0]=DIFF_DELETE,e[o+1][1]=u.substring(f),o++),o++}o++}},diff_match_patch.prototype.diff_cleanupSemanticLossless=function(e){function t(e,t){if(!e||!t)return 6;var n=e.charAt(e.length-1),i=t.charAt(0),r=n.match(diff_match_patch.nonAlphaNumericRegex_),o=i.match(diff_match_patch.nonAlphaNumericRegex_),a=r&&n.match(diff_match_patch.whitespaceRegex_),s=o&&i.match(diff_match_patch.whitespaceRegex_),l=a&&n.match(diff_match_patch.linebreakRegex_),c=s&&i.match(diff_match_patch.linebreakRegex_),u=l&&e.match(diff_match_patch.blanklineEndRegex_),d=c&&t.match(diff_match_patch.blanklineStartRegex_);return u||d?5:l||c?4:r&&!a&&s?3:a||s?2:r||o?1:0}for(var n=1;n=d&&(d=p,l=i,c=r,u=o)}e[n-1][1]!=l&&(l?e[n-1][1]=l:(e.splice(n-1,1),n--),e[n][1]=c,u?e[n+1][1]=u:(e.splice(n+1,1),n--))}n++}},diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/,diff_match_patch.whitespaceRegex_=/\s/,diff_match_patch.linebreakRegex_=/[\r\n]/,diff_match_patch.blanklineEndRegex_=/\n\r?\n$/,diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/,diff_match_patch.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,n=[],i=0,r=null,o=0,a=!1,s=!1,l=!1,c=!1;o0?n[i-1]:-1,l=c=!1),t=!0)),o++;t&&this.diff_cleanupMerge(e)},diff_match_patch.prototype.diff_cleanupMerge=function(e){e.push([DIFF_EQUAL,""]);for(var t,n=0,i=0,r=0,o="",a="";n1?(0!==i&&0!==r&&(t=this.diff_commonPrefix(a,o),0!==t&&(n-i-r>0&&e[n-i-r-1][0]==DIFF_EQUAL?e[n-i-r-1][1]+=a.substring(0,t):(e.splice(0,0,[DIFF_EQUAL,a.substring(0,t)]),n++),a=a.substring(t),o=o.substring(t)),t=this.diff_commonSuffix(a,o),0!==t&&(e[n][1]=a.substring(a.length-t)+e[n][1],a=a.substring(0,a.length-t),o=o.substring(0,o.length-t))),0===i?e.splice(n-r,i+r,[DIFF_INSERT,a]):0===r?e.splice(n-i,i+r,[DIFF_DELETE,o]):e.splice(n-i-r,i+r,[DIFF_DELETE,o],[DIFF_INSERT,a]),n=n-i-r+(i?1:0)+(r?1:0)+1):0!==n&&e[n-1][0]==DIFF_EQUAL?(e[n-1][1]+=e[n][1],e.splice(n,1)):n++,r=0,i=0,o="",a=""}""===e[e.length-1][1]&&e.pop();var s=!1;for(n=1;nt));n++)o=i,a=r;return e.length!=n&&e[n][0]===DIFF_DELETE?a:a+(t-o)},diff_match_patch.prototype.diff_prettyHtml=function(e){for(var t=[],n=/&/g,i=//g,o=/\n/g,a=0;a");switch(s){case DIFF_INSERT:t[a]=''+c+"";break;case DIFF_DELETE:t[a]=''+c+"";break;case DIFF_EQUAL:t[a]=""+c+""}}return t.join("")},diff_match_patch.prototype.diff_text1=function(e){for(var t=[],n=0;nthis.Match_MaxBits)throw new Error("Pattern too long for this browser.");var r=this.match_alphabet_(t),o=this,a=this.Match_Threshold,s=e.indexOf(t,n);-1!=s&&(a=Math.min(i(0,s),a),s=e.lastIndexOf(t,n+t.length),-1!=s&&(a=Math.min(i(0,s),a)));var l=1<c;)i(f,n+u)<=a?c=u:p=u,u=Math.floor((p-c)/2+c);p=u;var h=Math.max(1,n-u+1),m=Math.min(n+u,e.length)+t.length,g=Array(m+2);g[m+1]=(1<=h;v--){var b=r[e.charAt(v-1)];if(g[v]=0===f?(g[v+1]<<1|1)&b:(g[v+1]<<1|1)&b|((d[v+1]|d[v])<<1|1)|d[v+1],g[v]&l){var y=i(f,v-1);if(a>=y){if(a=y,s=v-1,!(s>n))break;h=Math.max(1,2*n-s)}}}if(i(f+1,n)>a)break;d=g}return s},diff_match_patch.prototype.match_alphabet_=function(e){for(var t={},n=0;n2&&(this.diff_cleanupSemantic(r),this.diff_cleanupEfficiency(r));else if(e&&"object"==typeof e&&"undefined"==typeof t&&"undefined"==typeof n)r=e,i=this.diff_text1(r);else if("string"==typeof e&&t&&"object"==typeof t&&"undefined"==typeof n)i=e,r=t;else{if("string"!=typeof e||"string"!=typeof t||!n||"object"!=typeof n)throw new Error("Unknown call format to patch_make.");i=e,r=n}if(0===r.length)return[];for(var o=[],a=new diff_match_patch.patch_obj,s=0,l=0,c=0,u=i,d=i,p=0;p=2*this.Patch_Margin&&s&&(this.patch_addContext_(a,u),o.push(a),a=new diff_match_patch.patch_obj,s=0,u=d,l=c)}f!==DIFF_INSERT&&(l+=h.length),f!==DIFF_DELETE&&(c+=h.length)}return s&&(this.patch_addContext_(a,u),o.push(a)),o},diff_match_patch.prototype.patch_deepCopy=function(e){for(var t=[],n=0;nthis.Match_MaxBits?(a=this.match_main(t,l.substring(0,this.Match_MaxBits),s),-1!=a&&(c=this.match_main(t,l.substring(l.length-this.Match_MaxBits),s+l.length-this.Match_MaxBits),(-1==c||a>=c)&&(a=-1))):a=this.match_main(t,l,s),-1==a)r[o]=!1,i-=e[o].length2-e[o].length1;else{r[o]=!0,i=a-s;var u;if(u=-1==c?t.substring(a,a+l.length):t.substring(a,c+this.Match_MaxBits),l==u)t=t.substring(0,a)+this.diff_text2(e[o].diffs)+t.substring(a+l.length);else{var d=this.diff_main(l,u,!1);if(l.length>this.Match_MaxBits&&this.diff_levenshtein(d)/l.length>this.Patch_DeleteThreshold)r[o]=!1;else{this.diff_cleanupSemanticLossless(d);for(var p,f=0,h=0;h=i;i++)n+=String.fromCharCode(i);for(var i=0;io[0][1].length){var a=t-o[0][1].length;o[0][1]=n.substring(o[0][1].length)+o[0][1],r.start1-=a,r.start2-=a,r.length1+=a,r.length2+=a}if(r=e[e.length-1],o=r.diffs,0==o.length||o[o.length-1][0]!=DIFF_EQUAL)o.push([DIFF_EQUAL,n]),r.length1+=t,r.length2+=t;else if(t>o[o.length-1][1].length){var a=t-o[o.length-1][1].length;o[o.length-1][1]+=n.substring(0,a),r.length1+=a,r.length2+=a}return n},diff_match_patch.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,n=0;n2*t?(s.length1+=u.length,r+=u.length,l=!1,s.diffs.push([c,u]),i.diffs.shift()):(u=u.substring(0,t-s.length1-this.Patch_Margin),s.length1+=u.length,r+=u.length,c===DIFF_EQUAL?(s.length2+=u.length,o+=u.length):l=!1,s.diffs.push([c,u]),u==i.diffs[0][1]?i.diffs.shift():i.diffs[0][1]=i.diffs[0][1].substring(u.length))}a=this.diff_text2(s.diffs),a=a.substring(a.length-this.Patch_Margin);var d=this.diff_text1(i.diffs).substring(0,this.Patch_Margin);""!==d&&(s.length1+=d.length,s.length2+=d.length,0!==s.diffs.length&&s.diffs[s.diffs.length-1][0]===DIFF_EQUAL?s.diffs[s.diffs.length-1][1]+=d:s.diffs.push([DIFF_EQUAL,d])),l||e.splice(++n,0,s)}}},diff_match_patch.prototype.patch_toText=function(e){for(var t=[],n=0;n0)){var i=n.shift();i()}},!0),function(e){n.push(e),window.postMessage("process-tick","*")}}return function(e){setTimeout(e,0)}}(),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.binding=function(){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(){throw new Error("process.chdir is not supported")}},{}],2:[function(e,t,n){var i=e("../pipe").Pipe,r=function(){};r.prototype.setResult=function(e){return this.result=e,this.hasResult=!0,this},r.prototype.exit=function(){return this.exiting=!0,this},r.prototype.switchTo=function(e,t){return"string"==typeof e||e instanceof i?this.nextPipe=e:(this.next=e,t&&(this.nextPipe=t)),this},r.prototype.push=function(e,t){return e.parent=this,"undefined"!=typeof t&&(e.childName=t),e.root=this.root||this,e.options=e.options||this.options,this.children?(this.children[this.children.length-1].next=e,this.children.push(e)):(this.children=[e],this.nextAfterChildren=this.next||null,this.next=e),e.next=this,this},n.Context=r},{"../pipe":15}],3:[function(e,t,n){var i=e("./context").Context,r=function(e,t){this.left=e,this.right=t,this.pipe="diff"};r.prototype=new i,n.DiffContext=r},{"./context":2}],4:[function(e,t,n){var i=e("./context").Context,r=function(e,t){this.left=e,this.delta=t,this.pipe="patch"};r.prototype=new i,n.PatchContext=r},{"./context":2}],5:[function(e,t,n){var i=e("./context").Context,r=function(e){this.delta=e,this.pipe="reverse"};r.prototype=new i,n.ReverseContext=r},{"./context":2}],6:[function(e,t){t.exports=function(e,t){var n;return"string"==typeof t&&(n=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/.exec(t))?new Date(Date.UTC(+n[1],+n[2]-1,+n[3],+n[4],+n[5],+n[6])):t}},{}],7:[function(e,t,n){var i=e("./processor").Processor,r=e("./pipe").Pipe,o=e("./contexts/diff").DiffContext,a=e("./contexts/patch").PatchContext,s=e("./contexts/reverse").ReverseContext,l=e("./filters/trivial"),c=e("./filters/nested"),u=e("./filters/arrays"),d=e("./filters/dates"),p=e("./filters/texts"),f=function(e){this.processor=new i(e),this.processor.pipe(new r("diff").append(c.collectChildrenDiffFilter,l.diffFilter,d.diffFilter,p.diffFilter,c.objectsDiffFilter,u.diffFilter).shouldHaveResult()),this.processor.pipe(new r("patch").append(c.collectChildrenPatchFilter,u.collectChildrenPatchFilter,l.patchFilter,p.patchFilter,c.patchFilter,u.patchFilter).shouldHaveResult()),this.processor.pipe(new r("reverse").append(c.collectChildrenReverseFilter,u.collectChildrenReverseFilter,l.reverseFilter,p.reverseFilter,c.reverseFilter,u.reverseFilter).shouldHaveResult())};f.prototype.options=function(){return this.processor.options.apply(this.processor,arguments)},f.prototype.diff=function(e,t){return this.processor.process(new o(e,t))},f.prototype.patch=function(e,t){return this.processor.process(new a(e,t))},f.prototype.reverse=function(e){return this.processor.process(new s(e))},f.prototype.unpatch=function(e,t){return this.patch(e,this.reverse(t))},n.DiffPatcher=f},{"./contexts/diff":3,"./contexts/patch":4,"./contexts/reverse":5,"./filters/arrays":9,"./filters/dates":10,"./filters/nested":12,"./filters/texts":13,"./filters/trivial":14,"./pipe":15,"./processor":16}],8:[function(e,t,n){(function(t){var i=e("./diffpatcher").DiffPatcher;n.DiffPatcher=i,n.create=function(e){return new i(e)},n.dateReviver=e("./date-reviver");var r;n.diff=function(){return r||(r=new i),r.diff.apply(r,arguments)},n.patch=function(){return r||(r=new i),r.patch.apply(r,arguments)},n.unpatch=function(){return r||(r=new i),r.unpatch.apply(r,arguments)},n.reverse=function(){return r||(r=new i),r.reverse.apply(r,arguments)};var o="undefined"!=typeof t&&"string"==typeof t.execPath;if(o){var a=e("./formatters/index");n.formatters=a,n.console=a.console}else n.homepage="https://github.com/benjamine/jsondiffpatch",n.version="0.1.5"}).call(this,e("/home/sheila/proj/JsonDiffPatch/node_modules/gulp-browserify/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"))},{"./date-reviver":6,"./diffpatcher":7,"/home/sheila/proj/JsonDiffPatch/node_modules/gulp-browserify/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":1}],9:[function(e,t,n){var i=e("../contexts/diff").DiffContext,r=e("../contexts/patch").PatchContext,o=e("../contexts/reverse").ReverseContext,a=e("./lcs"),s=3,l="function"==typeof Array.isArray?Array.isArray:function(e){return e instanceof Array},c="function"==typeof Array.prototype.indexOf?function(e,t){return e.indexOf(t)}:function(e,t){for(var n=e.length,i=0;n>i;i++)if(e[i]===t)return i;return-1},u=function(e){if(e.leftIsArray){for(var t,n,r,o,l=e.options&&e.options.objectHash,u=function(e,t,n,i,r){var o=e[n],a=t[i];if(o===a)return!0;if("object"!=typeof o||"object"!=typeof a)return!1;if(!l)return!1;var s,c;return"number"==typeof n?(r.hashCache1=r.hashCache1||[],s=r.hashCache1[n],"undefined"==typeof s&&(r.hashCache1[n]=s=l(o,n))):s=l(o),"undefined"==typeof s?!1:("number"==typeof i?(r.hashCache2=r.hashCache2||[],c=r.hashCache2[i],"undefined"==typeof c&&(r.hashCache2[i]=c=l(a,i))):c=l(a),"undefined"==typeof c?!1:s===c)},d={},p=0,f=0,h=e.left,m=e.right,g=h.length,v=m.length;g>p&&v>p&&u(h,m,p,p,d);)t=p,o=new i(e.left[t],e.right[t]),e.push(o,t),p++;for(;g>f+p&&v>f+p&&u(h,m,g-1-f,v-1-f,d);)n=g-1-f,r=v-1-f,o=new i(e.left[n],e.right[r]),e.push(o,r),f++;var b;if(p+f===g){if(g===v)return void e.setResult(void 0).exit();for(b=b||{_t:"a"},t=p;v-f>t;t++)b[t]=[m[t]];return void e.setResult(b).exit()}if(p+f===v){for(b=b||{_t:"a"},t=p;g-f>t;t++)b["_"+t]=[h[t],0,0];return void e.setResult(b).exit()}d={};var y=h.slice(p,g-f),x=m.slice(p,v-f),w=a.get(y,x,u,d),S=[];for(b=b||{_t:"a"},t=p;g-f>t;t++)c(w.indices1,t-p)<0&&(b["_"+t]=[h[t],0,0],S.push(t));var C=!0;e.options&&e.options.arrays&&e.options.arrays.detectMove===!1&&(C=!1);var E=!1;e.options&&e.options.arrays&&e.options.arrays.includeValueOnMove&&(E=!0);var T=S.length;for(t=p;v-f>t;t++){var k=c(w.indices2,t-p);if(0>k){var _=!1;if(C&&T>0)for(n=0;T>n;n++)if(u(y,x,S[n]-p,t-p,d)){b["_"+S[n]].splice(1,2,t,s),E||(b["_"+S[n]][0]=""),n=S[n],r=t,o=new i(e.left[n],e.right[r]),e.push(o,r),S.splice(n,1),_=!0;break}_||(b[t]=[m[t]])}else n=w.indices1[k]+p,r=w.indices2[k]+p,o=new i(e.left[n],e.right[r]),e.push(o,r)}e.setResult(b).exit()}};u.filterName="arrays";var d={numerically:function(e,t){return e-t},numericallyBy:function(e){return function(t,n){return t[e]-n[e]}}},p=function(e){if(e.nested&&"a"===e.delta._t){var t,n,i=e.delta,o=e.left,a=[],l=[],c=[];for(t in i)if("_t"!==t)if("_"===t[0]){if(0!==i[t][2]&&i[t][2]!==s)throw new Error("only removal or move can be applied at original array indices, invalid diff type: "+i[t][2]);a.push(parseInt(t.slice(1),10))}else 1===i[t].length?l.push({index:parseInt(t,10),value:i[t][0]}):c.push({index:parseInt(t,10),delta:i[t]});for(a=a.sort(d.numerically),t=a.length-1;t>=0;t--){n=a[t];var u=i["_"+n],p=o.splice(n,1)[0];u[2]===s&&l.push({index:u[1],value:p})}l=l.sort(d.numericallyBy("index"));var f=l.length;for(t=0;f>t;t++){var h=l[t];o.splice(h.index,0,h.value)}var m,g=c.length;if(g>0)for(t=0;g>t;t++){var v=c[t];m=new r(e.left[v.index],v.delta),e.push(m,v.index)}return e.children?void e.exit():void e.setResult(e.left).exit()}};p.filterName="arrays";var f=function(e){if(e&&e.children&&"a"===e.delta._t){for(var t,n=e.children.length,i=0;n>i;i++)t=e.children[i],e.left[t.childName]=t.result;e.setResult(e.left).exit()}};f.filterName="arraysCollectChildren";var h=function(e){if(!e.nested)return void(e.delta[2]===s&&(e.newName="_"+e.delta[1],e.setResult([e.delta[0],parseInt(e.childName.substr(1),10),s]).exit()));if("a"===e.delta._t){var t,n;for(t in e.delta)"_t"!==t&&(n=new o(e.delta[t]),e.push(n,t));e.exit()}};h.filterName="arrays";var m=function(e,t,n){var i=t;if("string"==typeof t&&"_"===t[0])i=parseInt(t.substr(1),10);else{var r="_"+t;if(l(n)&&0===n[2])i=r;else for(var o in e){var a=e[o];l(a)&&a[2]===s&&a[1].toString()===t&&(i=o.substr(1))}}return i},g=function(e){if(e&&e.children&&"a"===e.delta._t){for(var t,n=e.children.length,i={_t:"a"},r=0;n>r;r++){t=e.children[r];var o=t.newName;"undefined"==typeof o&&(o=m(e.delta,t.childName,t.result)),i[o]!==t.result&&(i[o]=t.result)}e.setResult(i).exit()}};g.filterName="arraysCollectChildren",n.diffFilter=u,n.patchFilter=p,n.collectChildrenPatchFilter=f,n.reverseFilter=h,n.collectChildrenReverseFilter=g},{"../contexts/diff":3,"../contexts/patch":4,"../contexts/reverse":5,"./lcs":11}],10:[function(e,t,n){var i=function(e){e.left instanceof Date?(e.setResult(e.right instanceof Date?e.left.getTime()!==e.right.getTime()?[e.left,e.right]:void 0:[e.left,e.right]),e.exit()):e.right instanceof Date&&e.setResult([e.left,e.right]).exit()};i.filterName="dates",n.diffFilter=i},{}],11:[function(e,t,n){var i=function(e,t,n,i){return e[n]===t[i]},r=function(e,t,n,i){var r,o,a=e.length,s=t.length,l=[a+1];for(r=0;a+1>r;r++)for(l[r]=[s+1],o=0;s+1>o;o++)l[r][o]=0;for(l.match=n,r=1;a+1>r;r++)for(o=1;s+1>o;o++)l[r][o]=n(e,t,r-1,o-1,i)?l[r-1][o-1]+1:Math.max(l[r-1][o],l[r][o-1]);return l},o=function(e,t,n,i,r,a){if(0===i||0===r)return{sequence:[],indices1:[],indices2:[]};if(e.match(t,n,i-1,r-1,a)){var s=o(e,t,n,i-1,r-1,a);return s.sequence.push(t[i-1]),s.indices1.push(i-1),s.indices2.push(r-1),s}return e[i][r-1]>e[i-1][r]?o(e,t,n,i,r-1,a):o(e,t,n,i-1,r,a)},a=function(e,t,n,a){a=a||{};var s=r(e,t,n||i,a),l=o(s,e,t,e.length,t.length,a);return"string"==typeof e&&"string"==typeof t&&(l.sequence=l.sequence.join("")),l};n.get=a},{}],12:[function(e,t,n){var i=e("../contexts/diff").DiffContext,r=e("../contexts/patch").PatchContext,o=e("../contexts/reverse").ReverseContext,a=function(e){if(e&&e.children){for(var t,n=e.children.length,i=e.result,r=0;n>r;r++)t=e.children[r],"undefined"!=typeof t.result&&(i=i||{},i[t.childName]=t.result);i&&e.leftIsArray&&(i._t="a"),e.setResult(i).exit()}};a.filterName="collectChildren";var s=function(e){if(!e.leftIsArray&&"object"===e.leftType){var t,n;for(t in e.left)n=new i(e.left[t],e.right[t]),e.push(n,t);for(t in e.right)"undefined"==typeof e.left[t]&&(n=new i(void 0,e.right[t]),e.push(n,t));return e.children&&0!==e.children.length?void e.exit():void e.setResult(void 0).exit()}};s.filterName="objects";var l=function(e){if(e.nested&&!e.delta._t){var t,n;for(t in e.delta)n=new r(e.left[t],e.delta[t]),e.push(n,t);e.exit()}};l.filterName="objects";var c=function(e){if(e&&e.children&&!e.delta._t){for(var t,n=e.children.length,i=0;n>i;i++)t=e.children[i],e.left[t.childName]!==t.result&&(e.left[t.childName]=t.result);e.setResult(e.left).exit()}};c.filterName="collectChildren";var u=function(e){if(e.nested&&!e.delta._t){var t,n;for(t in e.delta)n=new o(e.delta[t]),e.push(n,t);e.exit()}};u.filterName="objects";var d=function(e){if(e&&e.children&&!e.delta._t){for(var t,n=e.children.length,i={},r=0;n>r;r++)t=e.children[r],i[t.childName]!==t.result&&(i[t.childName]=t.result);e.setResult(i).exit()}};d.filterName="collectChildren",n.collectChildrenDiffFilter=a,n.objectsDiffFilter=s,n.patchFilter=l,n.collectChildrenPatchFilter=c,n.reverseFilter=u,n.collectChildrenReverseFilter=d},{"../contexts/diff":3,"../contexts/patch":4,"../contexts/reverse":5}],13:[function(e,t,n){var i=2,r=60,o=null,a=function(){if(!o){var t;if("undefined"!=typeof diff_match_patch)t=new diff_match_patch;else if("function"==typeof e){var n=e("../../external/diff_match_patch_uncompressed");t=new n.diff_match_patch}if(!t){var i=new Error("text diff_match_patch library not found");throw i.diff_match_patch_not_found=!0,i}o={diff:function(e,n){return t.patch_toText(t.patch_make(e,n))},patch:function(e,n){for(var i=t.patch_apply(t.patch_fromText(n),e),r=0;rt;t++){r=i[t];var d=r.slice(0,1);"@"===d?(c=u.exec(r),a=t,s=null,l=null,i[a]="@@ -"+c[3]+","+c[4]+" +"+c[1]+","+c[2]+" @@"):"+"===d?(s=t,i[t]="-"+i[t].slice(1),"+"===i[t-1].slice(0,1)&&(o=i[t],i[t]=i[t-1],i[t-1]=o)):"-"===d&&(l=t,i[t]="+"+i[t].slice(1))}return i.join("\n")},u=function(e){e.nested||e.delta[2]===i&&e.setResult([c(e.delta[0]),0,i]).exit()};u.filterName="texts",n.diffFilter=s,n.patchFilter=l,n.reverseFilter=u},{}],14:[function(e,t,n){var i="function"==typeof Array.isArray?Array.isArray:function(e){return e instanceof Array},r=function(e){if(e.left===e.right)return void e.setResult(void 0).exit();if("undefined"==typeof e.left){if("function"==typeof e.right)throw new Error("functions are not supported");return void e.setResult([e.right]).exit()}if("undefined"==typeof e.right)return void e.setResult([e.left,0,0]).exit();if("function"==typeof e.left||"function"==typeof e.right)throw new Error("functions are not supported");return e.leftType=null===e.left?"null":typeof e.left,e.rightType=null===e.right?"null":typeof e.right,e.leftType!==e.rightType?void e.setResult([e.left,e.right]).exit():"boolean"===e.leftType||"number"===e.leftType?void e.setResult([e.left,e.right]).exit():("object"===e.leftType&&(e.leftIsArray=i(e.left)),"object"===e.rightType&&(e.rightIsArray=i(e.right)),e.leftIsArray!==e.rightIsArray?void e.setResult([e.left,e.right]).exit():void 0)};r.filterName="trivial";var o=function(e){return"undefined"==typeof e.delta?void e.setResult(e.left).exit():(e.nested=!i(e.delta),e.nested?void 0:1===e.delta.length?void e.setResult(e.delta[0]).exit():2===e.delta.length?void e.setResult(e.delta[1]).exit():3===e.delta.length&&0===e.delta[2]?void e.setResult(void 0).exit():void 0)};o.filterName="trivial";var a=function(e){return"undefined"==typeof e.delta?void e.setResult(e.delta).exit():(e.nested=!i(e.delta),e.nested?void 0:1===e.delta.length?void e.setResult([e.delta[0],0,0]).exit():2===e.delta.length?void e.setResult([e.delta[1],e.delta[0]]).exit():3===e.delta.length&&0===e.delta[2]?void e.setResult([e.delta[0]]).exit():void 0)};a.filterName="trivial",n.diffFilter=r,n.patchFilter=o,n.reverseFilter=a},{}],15:[function(e,t,n){var i=function(e){this.name=e,this.filters=[]};i.prototype.process=function(e){if(!this.processor)throw new Error("add this pipe to a processor before using it");for(var t=this.debug,n=this.filters.length,i=e,r=0;n>r;r++){var o=this.filters[r];if(t&&this.log("filter: "+o.filterName),o(i),"object"==typeof i&&i.exiting){i.exiting=!1;break}}!i.next&&this.resultCheck&&this.resultCheck(i)},i.prototype.log=function(e){console.log("[jsondiffpatch] "+this.name+" pipe, "+e)},i.prototype.append=function(){return this.filters.push.apply(this.filters,arguments),this},i.prototype.prepend=function(){return this.filters.unshift.apply(this.filters,arguments),this},i.prototype.indexOf=function(e){if(!e)throw new Error("a filter name is required");for(var t=0;t>>0)+(t++ +"__")};n.prototype={set:function(t,n){var i=t[this.name];i&&i[0]===t?i[1]=n:e(t,this.name,{value:[t,n],writable:!0})},get:function(e){var t;return(t=e[this.name])&&t[0]===e?t[1]:void 0},"delete":function(e){this.set(e,void 0)}},window.WeakMap=n}(),define("WeakMap",function(){}),function(e){function t(e){x.push(e),y||(y=!0,g(i))}function n(e){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(e)||e}function i(){y=!1;var e=x;x=[],e.sort(function(e,t){return e.uid_-t.uid_});var t=!1;e.forEach(function(e){var n=e.takeRecords();r(e),n.length&&(e.callback_(n,e),t=!0)}),t&&i()}function r(e){e.nodes_.forEach(function(t){var n=m.get(t);n&&n.forEach(function(t){t.observer===e&&t.removeTransientObservers()})})}function o(e,t){for(var n=e;n;n=n.parentNode){var i=m.get(n);if(i)for(var r=0;r0){var r=n[i-1],o=f(r,e);if(o)return void(n[i-1]=o)}else t(this.observer);n[i]=e},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(e){var t=this.options;t.attributes&&e.addEventListener("DOMAttrModified",this,!0),t.characterData&&e.addEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.addEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(e){var t=this.options;t.attributes&&e.removeEventListener("DOMAttrModified",this,!0),t.characterData&&e.removeEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.removeEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(e){if(e!==this.target){this.addListeners_(e),this.transientObservedNodes.push(e);var t=m.get(e);t||m.set(e,t=[]),t.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[],e.forEach(function(e){this.removeListeners_(e);for(var t=m.get(e),n=0;n/g,prolog:/<\?.+?\?>/,doctype:/<!DOCTYPE.+?>/,cdata:/<!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/&#?[\da-z]{1,8};/gi},Prism.hooks.add("wrap",function(e){"entity"===e.type&&(e.attributes.title=e.content.replace(/&/,"&"))}),define("bower-libs/prism/components/prism-markup",function(){}),Prism.languages.latex={keyword:/\\(?:[^a-zA-Z]|[a-zA-Z]+)/g,lparen:/[[({]/g,rparen:/[\])}]/g,comment:/%.*/g},define("libs/prism-latex",function(){}),Prism.languages.md=function(){var e=/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>\[\]'"]+|\([^\s()<>\[\]'"]*\))+(?:\([^\s()<>\[\]'"]*\)|[^\s`!()\[\]{}:'".,<>?«»“”‘’]))/gi,t=/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b/gi,n=Prism.languages.latex,i={};i.pre={pattern:/(^|(?:^|(?:^|\n)(?![ \t]*([*+\-]|\d+\.)[ \t]).*\n)\s*?\n)(\s*(?: {4}|\t).*(?:\n|$))+/g,lookbehind:!0,inside:{}},i["pre gfm"]={pattern:/^ {0,3}`{3}.*?\n(.*?\n)*? {0,3}`{3} *$/gm,inside:{"md md-pre":/`{3}/}},i["h1 alt"]={pattern:/^(.+)[ \t]*\n=+[ \t]*$/gm,inside:{}},i["h2 alt"]={pattern:/^(.+)[ \t]*\n-+[ \t]*$/gm,inside:{}},i.hr={pattern:/^([*\-_] *){3,}$/gm},i.li={pattern:/^[ \t]*([*+\-]|\d+\.)[ \t].+$/gm,inside:{"md md-li":/^ ?([*+\-]|\d+\.)[ \t]/m,"md md-li2":/^ ?(?: {2}|\t{1})([*+\-]|\d+\.)[ \t]/m,"md md-li3":/^ ?(?: {4}|\t{2})([*+\-]|\d+\.)[ \t]/m,"md md-li4":/^ ?(?: {6}|\t{3})([*+\-]|\d+\.)[ \t]/m,"md md-li5":/^ ?(?: {8}|\t{4})([*+\-]|\d+\.)[ \t]/m,"md md-li6":/^ ?(?: {10}|\t{5})([*+\-]|\d+\.)[ \t]/m,"md md-li7":/^ ?(?: {12}|\t{6})([*+\-]|\d+\.)[ \t]/m,"md md-li8":/^ ?(?: {14}|\t{7})([*+\-]|\d+\.)[ \t]/m,"md md-li9":/^ ?(?: {16}|\t{8})([*+\-]|\d+\.)[ \t]/m,"md md-li10":/^ ?(?: {18}|\t{9})([*+\-]|\d+\.)[ \t]/m,"md md-li11":/^ ?(?: {20}|\t{10})([*+\-]|\d+\.)[ \t]/m}};for(var r=6;r>=1;r--)i["h"+r]={pattern:new RegExp("^#{"+r+"}.+$","gm"),inside:{"md md-hash":new RegExp("^#{"+r+"} ")}};i.blockquote={pattern:/^ {0,3}> *[^\n]+$/gm,inside:{"md md-gt":/^ {0,3}> */,li:i.li}},i["math block"]={pattern:/(\$\$|\\\\\[|\\\\\\\\\()[\s\S]*?(\$\$|\\\\\]|\\\\\\\\\))/g,inside:{"md md-bracket-start":/^(\$\$|\\\\\[|\\\\\\\\\()/,"md md-bracket-end":/(\$\$|\\\\\]|\\\\\\\\\))/,lf:/\n/gm,rest:n}},i["latex block"]={pattern:/\\?\\begin\{[a-z]*\*?\}[\s\S]*?\\?\\end\{[a-z]*\*?\}/g,inside:{keyword:/\\?\\(begin|end)/,lf:/\n/gm,rest:n}},i.fndef={pattern:/^ {0,3}\[\^.*?\]:[ \t]+.*$/gm,inside:{"ref-id":{pattern:/\[\^.*?\]/,inside:{"md md-bracket-start":/\[/,"md md-bracket-end":/\]/}}}},i.linkdef={pattern:/^ {0,3}\[.*?\]:[ \t]+.*$/gm,inside:{"link-id":{pattern:/\[.*?\]/,inside:{"md md-bracket-start":/\[/,"md md-bracket-end":/\]/}},url:e,linktitle:/['\"\(][^\'\"\)]*['\"\)]/}},i.p={pattern:/.+/g,inside:{"md md-toc":/^\s*\[(toc|TOC)\]\s*$/g}},i.lf=/^\n$/gm,i.img={pattern:/!\[[^\]]*\]\([^\)]+\)/g,inside:{"md md-bang":/^!/,"md md-bracket-start":/\[/,"md md-alt":/[^\[]+(?=\])/,"md md-bracket-end":/\](?=\()/,"md img-parens":{pattern:/\([^\)]+\)/,inside:{"md md-paren-start":/^\(/,"md md-title":/(['‘][^'’]*['’]|["“][^"”]*["”])(?=\)$)/,"md md-src":/[^\('" \t]+(?=[\)'" \t])/,"md md-paren-end":/\)$/}}}},i.link={pattern:/\[(?:(\\.)|[^\[\]])*\]\([^\(\)\s]+(\(\S*?\))??[^\(\)\s]*?(\s(['‘][^'’]*['’]|["“][^"”]*["”]))?\)/gm,inside:{"md md-bracket-start":{pattern:/(^|[^\\])\[/,lookbehind:!0},"md md-underlined-text":{pattern:/(?:(\\.)|[^\[\]])+(?=\])/},"md md-bracket-end":/\]\s?\(/,"md md-paren-end":/\)$/,"md md-href":/.*/}},i.fn={pattern:/\[\^(.*?)\]/g,inside:{ref:{pattern:/^\[[^\[\]]+\] ?/,inside:{"md md-bracket-start":/\[/,"md md-ref":/^[^\[\]]+/,"md md-bracket-end":/\]/}}}},i.imgref={pattern:/!\[(.*?)\] ?\[(.*?)\]/g,inside:{"md md-bang":/^!/,"ref-end":{pattern:/\[[^\[\]]+\]$/,inside:{"md md-bracket-start":/\[/,"md md-href":/[^\[\]]+(?=]$)/,"md md-bracket-end":/\]/}},"ref-start":{pattern:/^\[[^\[\]]+\] ?/,inside:{"md md-bracket-start":/\[/,"md md-alt":/^[^\[\]]+/,"md md-bracket-end":/\]/}}}},i.linkref={pattern:/\[(.*?)\] ?\[(.*?)\]/g,inside:{"ref-end":{pattern:/\[[^\[\]]+\]$/,inside:{"md md-bracket-start":/\[/,"md md-href":/[^\[\]]+(?=]$)/,"md md-bracket-end":/\]/}},"ref-start":{pattern:/^\[[^\[\]]+\] ?/,inside:{"md md-bracket-start":/\[/,"md md-underlined-text":/^[^\[\]]+/,"md md-bracket-end":/\]/}}}},i.email={pattern:t},i.code={pattern:/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/g,lookbehind:!0,inside:{"md md-code":/`/}},i.math={pattern:/\$.*?\$/g,inside:{"md md-bracket-start":/^\$/,"md md-bracket-end":/\$$/,rest:n}},i.strong={pattern:/([_\*])\1((?!\1{2}).)*\1{2}/g,inside:{"md md-strong":/([_\*])\1/g}},i.em={pattern:/(^|[^\\])(\*|_)(\S[^\2]*?)??[^\s\\]+?\2/g,lookbehind:!0,inside:{"md md-em md-start":/^(\*|_)/,"md md-em md-close":/(\*|_)$/}},i.strike={pattern:/(^|\n|\W)(~~)(?=\S)([^\r]*?\S)\2/gm,lookbehind:!0,inside:{"md md-s":/(~~)/,"md-strike-text":/[^~]+/}};for(var o={code:i.code,math:i.math,fn:i.fn,img:i.img,link:i.link,imgref:i.imgref,linkref:i.linkref,url:i.url,email:i.email,strong:i.strong,em:i.em,strike:i.strike,conflict:/⧸⧸/g,comment:Prism.languages.markup.comment,tag:Prism.languages.markup.tag,entity:Prism.languages.markup.entity},a=6;a>=1;a--)i["h"+a].inside.rest=o;i["h1 alt"].inside.rest=o,i["h2 alt"].inside.rest=o,i.p.inside.rest=o,i.blockquote.inside.rest=o,i.li.inside.rest=o,i.fndef.inside.rest=o,o={code:i.code,fn:i.fn,link:i.link,linkref:i.linkref,conflict:/⧸⧸/g},i.strong.inside.rest=o,i.em.inside.rest=o,i.strike.inside.rest=o;var s={code:i.code,strong:i.strong,em:i.em,strike:i.strike,conflict:/⧸⧸/g,comment:Prism.languages.markup.comment,tag:Prism.languages.markup.tag,entity:Prism.languages.markup.entity};return i.link.inside["md md-underlined-text"].inside=s,i.linkref.inside["ref-start"].inside["md md-underlined-text"].inside=s,i}(),define("libs/prism-markdown",function(){}),define("editor",["jquery","underscore","utils","settings","eventMgr","prism-core","diff_match_patch_uncompressed","jsondiffpatch","crel","rangy","MutationObservers","libs/prism-markdown"],function(e,t,n,i,r,o,a,s,l,c){function u(){this.isWatching=!1;var e;this.startWatching=function(){this.isWatching=!0,e=e||new MutationObserver(y),e.observe(_,{childList:!0,subtree:!0,characterData:!0})},this.stopWatching=function(){e.disconnect(),this.isWatching=!1},this.noWatch=function(e){this.isWatching===!0?(this.stopWatching(),e(),this.startWatching()):e()}}function d(){var e=this;this.selectionStart=0,this.selectionEnd=0,this.cursorY=0,this.findOffset=function(e){for(var t=document.createTreeWalker(_,4),n="";t.nextNode();){if(n=t.currentNode.nodeValue||"",n.length>e)return{container:t.currentNode,offset:e};e-=n.length}return{container:t.currentNode,offset:n.length}},this.createRange=function(e,n){e=0>e?0:e,n=0>n?0:n;var i=document.createRange(),r=t.isObject(e)?e:this.findOffset(e);return i.setStart(r.container,r.offset),n&&n!=e&&(r=t.isObject(n)?n:this.findOffset(n)),i.setEnd(r.container,r.offset),i},this.setSelectionStartEnd=function(e,t,n,i){void 0===e&&(e=this.selectionStart),void 0===t&&(t=this.selectionEnd),this.selectionStart=e,this.selectionEnd=t;var o=Math.min(e,t),a=Math.max(e,t);if(n=n||this.createRange(o,a),!i){var s=c.getSelection();s.removeAllRanges(),s.addRange(n,e>t)}F.editorStart=this.selectionStart,F.editorEnd=this.selectionEnd,k.toggleClass("has-selection",this.selectionStart!==this.selectionEnd);var l=this.getCoordinates(this.selectionEnd,this.selectionEndContainer,this.selectionEndOffset);return this.cursorY!==l.y&&(this.cursorY=l.y,r.onCursorCoordinates(l.x,l.y)),n},this.saveSelectionState=function(){function t(){if(O===!1){var t,n=e.selectionStart,i=e.selectionEnd,r=c.getSelection();if(r.rangeCount>0){var o=r.getRangeAt(0),a=o.startContainer;if(16&_.compareDocumentPosition(a)){t=o;var s=a,l=t.startOffset;do{for(;a=a.previousSibling;)a.textContent&&(l+=a.textContent.length);a=s=s.parentNode}while(a&&a!=T);r.isBackwards()?(n=l+(t+"").length,i=l):(n=l,i=l+(t+"").length)}}e.setSelectionStartEnd(n,i,t,!0)}U.saveSelectionState()}var i=n.debounce(t);return function(e){e?i():t()}}(),this.getCoordinates=function(e,t,n){t||(n=this.findOffset(e),t=n.container,n=n.offset);var i=0,r=0;if("\n"==t.textContent)r=t.parentNode.offsetTop+t.parentNode.offsetHeight/2;else{var o=H[e],a={container:t,offset:n},s={container:t,offset:n};e>0&&(void 0===o||"\n"==o)?0===a.offset?a=e-1:a.offset-=1:s.offset===t.textContent.length?s=e+1:s.offset+=1;var l=this.createRange(a,s),c=l.getBoundingClientRect();r=c.top+c.height/2-T.getBoundingClientRect().top+T.scrollTop,l.detach()}return{x:i,y:r}},this.getClosestWordOffset=function(e){var t=0,n=0,i=0;return H.split(/\s/).some(function(r){return r&&(t=i,n=i+r.length,n>e)?!0:void(i+=r.length+1)}),{start:t,end:n}}}function p(e){var t=j.diff_commonPrefix(H,e);t===H.length&&t--;var n=Math.min(j.diff_commonSuffix(H,e),H.length-t,e.length-t),i=e.substring(t,e.length-n),r=G.createRange(t,H.length-n);r.deleteContents(),r.insertNode(document.createTextNode(i))}function f(e,t){var n=G.selectionStart;if(n!==G.selectionEnd)return!1;var i=G.createRange(n-e.length,n);return""+i!=e?!1:(i.deleteContents(),i.insertNode(document.createTextNode(t)),n=n-e.length+t.length,G.setSelectionStartEnd(n,n),!0)}function h(e){p(e),H=e}function m(){return H}function g(){I.focus(),G.setSelectionStartEnd(),T.scrollTop=R}function v(){function e(e,n,i){B.noWatch(function(){H!=e.content&&(h(e.content),F.content=e.content,r.onContentChanged(F,e.content)),G.setSelectionStartEnd(n,i);var o=F.discussionListJSON;if(o!=e.discussionListJSON){var a=F.discussionList;F.discussionListJSON=e.discussionListJSON;var s=F.discussionList,l=$.diff(a,s),c=!1;t.each(l,function(e,n){t.isArray(e)?1===e.length?r.onDiscussionCreated(F,s[n]):r.onDiscussionRemoved(F,a[n]):c=!0}),c&&r.onCommentsChanged(F)}}),s=n,l=i,a=e,this.currentMode=void 0,o=void 0,this.onButtonStateChange(),q()}var i,o,a,s,l,c=[],u=[];this.setCommandMode=function(){this.currentMode="command"},this.setMode=function(){},this.onButtonStateChange=function(){},this.saveState=n.debounce(function(){u=[];var e=Date.now();"comment"==this.currentMode||this.currentMode!=o&&"newlines"!=o||e-i>1e3?(c.push(a),100===c.length&&c.shift()):(s=a.selectionStartBefore,l=a.selectionEndBefore),a={selectionStartBefore:s,selectionEndBefore:l,selectionStartAfter:G.selectionStart,selectionEndAfter:G.selectionEnd,content:H,discussionListJSON:F.discussionListJSON},i=e,o=this.currentMode,this.currentMode=void 0,this.onButtonStateChange()},this),this.saveSelectionState=t.debounce(function(){void 0===this.currentMode&&(s=G.selectionStart,l=G.selectionEnd)},10),this.canUndo=function(){return c.length},this.canRedo=function(){return u.length},this.undo=function(){var t=c.pop();t&&(u.push(a),e.call(this,t,a.selectionStartBefore,a.selectionEndBefore))},this.redo=function(){var t=u.pop();t&&(c.push(a),e.call(this,t,t.selectionStartAfter,t.selectionEndAfter))},this.init=function(){var e=F.content;c=[],u=[],i=0,a={selectionStartAfter:F.selectionStart,selectionEndAfter:F.selectionEnd,content:e,discussionListJSON:F.discussionListJSON},this.currentMode=void 0,o=void 0,_.textContent=e,y()}}function b(){B.isWatching===!0&&(U.currentMode=U.currentMode||"comment",U.saveState())}function y(){var e=T.textContent;if(_.lastChild===z&&"\n"==z.textContent.slice(-1)&&(e=e.slice(0,-1)),e=e.replace(/\r\n/g,"\n"),e=e.replace(/\r/g,"\n"),O===!1){if(e==H)return void(0===_.children.length&&(_.innerHTML="",W.forEach(function(e){_.appendChild(e.elt)}),C()));U.currentMode=U.currentMode||"typing";var n=t.values(F.discussionList);F.newDiscussion&&n.push(F.newDiscussion);var i=x(H,e,n);H=e,i===!0&&(F.discussionList=F.discussionList),F.content=H,G.saveSelectionState(),r.onContentChanged(F,H),i&&r.onCommentsChanged(F),U.saveState()}else H=e,F.content=H,G.setSelectionStartEnd(F.editorStart,F.editorEnd),G.saveSelectionState(),r.onFileOpen(F,H),L.scrollTop=F.previewScrollTop,R=F.editorScrollTop,T.scrollTop=R,O=!1}function x(e,t,n){if(n.length){var i=j.diff_main(e,t),r=!1,o=0;return i.forEach(function(e){var t=e[0],i=e[1];if(0===t)return void(o+=i.length);var a=o,s=i.length;-1===t&&(a+=s,s=-s),n.forEach(function(e){e.selectionEnd>a?(e.selectionEnd+=s,e.discussionIndex&&(r=!0)):e.selectionEnd>o&&(e.selectionEnd=o,e.discussionIndex&&(r=!0)),e.selectionStart>=a?(e.selectionStart+=s,e.discussionIndex&&(r=!0)):e.selectionStart>o&&(e.selectionStart=o,e.discussionIndex&&(r=!0))}),1===t&&(o+=i.length)}),r}}function w(e){if(X=[],Q=[],V=void 0,O===!0)return Q=W,W=e,void(X=e);var n=W.length;t.some(W,function(t,i){var r=e[i];return i>=e.length||t.textWithFrontMatter!=r.textWithFrontMatter||t.elt.parentNode!==_||t.elt.textContent!=r.textWithFrontMatter?(n=i,!0):void 0});var i=-W.length;t.some(W.slice().reverse(),function(t,n){var r=e[e.length-n-1];return n>=e.length||t.textWithFrontMatter!=r.textWithFrontMatter||t.elt.parentNode!==_||t.elt.textContent!=r.textWithFrontMatter?(i=-n,!0):void 0}),n-i>W.length&&(i=n-W.length);var r=W.slice(0,n);X=e.slice(n,e.length+i);var o=W.slice(W.length+i,W.length);V=t.first(o),Q=W.slice(n,W.length+i),W=r.concat(X).concat(o)}function S(){var e=document.createDocumentFragment();X.forEach(function(t){E(t),e.appendChild(t.elt)}),B.noWatch(function(){if(O===!0)_.innerHTML="",_.appendChild(e);else{Q.forEach(function(e){e.elt.parentNode===_&&_.removeChild(e.elt)}),void 0!==V?_.insertBefore(e,V.elt):_.appendChild(e);for(var t=_.firstChild;t;){var n=t.nextSibling;t.generated||_.removeChild(t),t=n}}C(),G.setSelectionStartEnd()})}function C(){z=l("span",{"class":"token lf"}),z.textContent="\n",_.appendChild(z)}function E(e){var t=K(e.text);window.viewerMode||(t=o.highlight(t,o.languages.md));var n=e.textWithFrontMatter.substring(0,e.textWithFrontMatter.length-e.text.length);n.length&&(n=K(n),n=n.replace(/\n/g,'\n'),t=''+n+""+t);var i=l("span",{id:"wmd-input-section-"+e.id,"class":"wmd-input-section"});i.generated=!0,i.innerHTML=t,e.elt=i}var T,k,_,I,D,N,L,M,A={},R=0,P=function(){var e=0,n=function(){var t=Date.now();M.refreshPreview(),e=Date.now()-t};return i.lazyRendering===!0?t.debounce(n,500):function(){setTimeout(n,2e3>e?e:2e3)}}();r.addListener("onPagedownConfigure",function(e){M=e}),r.addListener("onSectionsCreated",function(e){w(e),S(),O===!0?M.refreshPreview():P()});var F,O=!0;r.addListener("onFileSelected",function(e){O=!0,F=e});var B=new u;A.watcher=B;var j=new a,$=s.create({objectHash:function(e){return JSON.stringify(e)},arrays:{detectMove:!1},textDiff:{minLength:9999999}}),G=new d;A.selectionMgr=G,e(document).on("selectionchange",".editor-content",t.bind(G.saveSelectionState,G,!0));var q=function(){var e=n.debounce(function(){var e=T.offsetHeight/2;e>130&&(e=130);var t=T.scrollTop+e,n=T.scrollTop+T.offsetHeight-e;G.cursorYn&&(T.scrollTop+=G.cursorY-n)});return function(){void 0!==T&&(G.saveSelectionState(!0),e())}}();A.adjustCursorPosition=q;var H;A.setValue=p,A.replacePreviousText=f,A.setValueNoWatch=h,A.getValue=m,A.focus=g;var U=new v;A.undoMgr=U,r.addListener("onDiscussionCreated",b),r.addListener("onDiscussionRemoved",b),r.addListener("onCommentsChanged",b);var z;A.adjustCommentOffsets=x,A.init=function(){if(T=document.getElementById("wmd-input"),k=e(T),_=T.querySelector(".editor-content"),I=e(_),D=T.querySelector(".editor-margin"),N=e(D),L=document.querySelector(".preview-container"),k.addClass(i.editorFontClass),B.startWatching(),e(T).scroll(function(){R=T.scrollTop,O===!1&&(F.editorScrollTop=R)}),e(L).scroll(function(){O===!1&&(F.previewScrollTop=L.scrollTop)}),/AppleWebKit\/([\d.]+)/.exec(navigator.userAgent)){var n=e('').appendTo("html");I.blur(function(){n[0].setSelectionRange(0,0),n.blur()})}T.focus=g,Object.defineProperty(T,"value",{get:function(){return H},set:p}),Object.defineProperty(T,"selectionStart",{get:function(){return Math.min(G.selectionStart,G.selectionEnd)},set:function(e){G.setSelectionStartEnd(e)},enumerable:!0,configurable:!0}),Object.defineProperty(T,"selectionEnd",{get:function(){return Math.max(G.selectionStart,G.selectionEnd)},set:function(e){G.setSelectionStartEnd(void 0,e)},enumerable:!0,configurable:!0});var r=!1;I.on("keydown",function(e){if(17!==e.which&&91!==e.which&&18!==e.which&&16!==e.which){G.saveSelectionState();var t=e.metaKey||e.ctrlKey;switch(t||q(),e.which){case 9:t||(o("indent",{inverse:e.shiftKey}),e.preventDefault());break;case 13:o("newline"),e.preventDefault()}13!==e.which&&(r=!1)}}).on("mouseup",t.bind(G.saveSelectionState,G,!0)).on("paste",function(){U.currentMode="paste",q()}).on("cut",function(){U.currentMode="cut",q()});var o=function(e,t){t=t||{};var n=m(),i=t.start||G.selectionStart,r=t.end||G.selectionEnd,o={selectionStart:i,selectionEnd:r,before:n.slice(0,i),after:n.slice(r),selection:n.slice(i,r)};a[e](o,t),p(o.before+o.selection+o.after),G.setSelectionStartEnd(o.selectionStart,o.selectionEnd)},a={indent:function(e,t){function n(e,t,n,i){return n=+n||0,i=i||"",e.slice(0,t)+i+e.slice(t+n)}var i=e.before.lastIndexOf("\n")+1;if(t.inverse)/\s/.test(e.before.charAt(i))&&(e.before=n(e.before,i,1),e.selectionStart--,e.selectionEnd--),e.selection=e.selection.replace(/^[ \t]/gm,"");else{if(!e.selection)return e.before+=" ",e.selectionStart++,void e.selectionEnd++;e.before=n(e.before,i,0," "),e.selection=e.selection.replace(/\r?\n(?=[\s\S])/g,"\n "),e.selectionStart++,e.selectionEnd++}e.selectionEnd=e.selectionStart+e.selection.length},newline:function(e){var t=e.before.lastIndexOf("\n")+1;if(r)return e.before=e.before.substring(0,t),e.selection="",e.selectionStart=t,e.selectionEnd=t,void(r=!1);r=!1;var n=e.before.slice(t),i=n.match(/^ {0,3}>[ ]*|^[ \t]*(?:[*+\-]|(\d+)\.)[ \t]|^\s+/),o=(i||[""])[0];if(i&&i[1]){var a=parseInt(i[1],10);o=o.replace(/\d+/,a+1)}o.length&&(r=!0),U.currentMode="newlines",e.before+="\n"+o,e.selection="",e.selectionStart+=o.length+1,e.selectionEnd=e.selectionStart}}};var V,W=[],Q=[],X=[],K=function(){var e={"&":"&","<":"<"," ":" "};return function(t){return t.replace(/[&<\u00a0]/g,function(t){return e[t]})}}();return r.onEditorCreated(A),A}),function(e,t){function n(){i.READY||(b.determineEventTypes(),h.each(i.gestures,function(e){x.register(e)}),b.onTouch(i.DOCUMENT,p,x.detect),b.onTouch(i.DOCUMENT,f,x.detect),i.READY=!0)}var i=function(e,t){return new i.Instance(e,t||{})};i.VERSION="1.0.10",i.defaults={stop_browser_behavior:{userSelect:"none",touchAction:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},i.HAS_POINTEREVENTS=e.navigator.pointerEnabled||e.navigator.msPointerEnabled,i.HAS_TOUCHEVENTS="ontouchstart"in e,i.MOBILE_REGEX=/mobile|tablet|ip(ad|hone|od)|android|silk/i,i.NO_MOUSEEVENTS=i.HAS_TOUCHEVENTS&&e.navigator.userAgent.match(i.MOBILE_REGEX),i.EVENT_TYPES={},i.UPDATE_VELOCITY_INTERVAL=16,i.DOCUMENT=e.document;var r=i.DIRECTION_DOWN="down",o=i.DIRECTION_LEFT="left",a=i.DIRECTION_UP="up",s=i.DIRECTION_RIGHT="right",l=i.POINTER_MOUSE="mouse",c=i.POINTER_TOUCH="touch",u=i.POINTER_PEN="pen",d=i.EVENT_START="start",p=i.EVENT_MOVE="move",f=i.EVENT_END="end";i.plugins=i.plugins||{},i.gestures=i.gestures||{},i.READY=!1;var h=i.utils={extend:function(e,n,i){for(var r in n)e[r]!==t&&i||(e[r]=n[r]);return e},each:function(e,n,i){var r,o;if("forEach"in e)e.forEach(n,i);else if(e.length!==t){for(r=-1;o=e[++r];)if(n.call(i,o,r,e)===!1)return}else for(r in e)if(e.hasOwnProperty(r)&&n.call(i,e[r],r,e)===!1)return},inStr:function(e,t){return e.indexOf(t)>-1},hasParent:function(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1},getCenter:function(e){var t=[],n=[],i=[],r=[],o=Math.min,a=Math.max;return 1===e.length?{pageX:e[0].pageX,pageY:e[0].pageY,clientX:e[0].clientX,clientY:e[0].clientY}:(h.each(e,function(e){t.push(e.pageX),n.push(e.pageY),i.push(e.clientX),r.push(e.clientY)}),{pageX:(o.apply(Math,t)+a.apply(Math,t))/2,pageY:(o.apply(Math,n)+a.apply(Math,n))/2,clientX:(o.apply(Math,i)+a.apply(Math,i))/2,clientY:(o.apply(Math,r)+a.apply(Math,r))/2})},getVelocity:function(e,t,n){return{x:Math.abs(t/e)||0,y:Math.abs(n/e)||0}},getAngle:function(e,t){var n=t.clientX-e.clientX,i=t.clientY-e.clientY;return 180*Math.atan2(i,n)/Math.PI},getDirection:function(e,t){var n=Math.abs(e.clientX-t.clientX),i=Math.abs(e.clientY-t.clientY);return n>=i?e.clientX-t.clientX>0?o:s:e.clientY-t.clientY>0?a:r},getDistance:function(e,t){var n=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.sqrt(n*n+i*i)},getScale:function(e,t){return e.length>=2&&t.length>=2?this.getDistance(t[0],t[1])/this.getDistance(e[0],e[1]):1},getRotation:function(e,t){return e.length>=2&&t.length>=2?this.getAngle(t[1],t[0])-this.getAngle(e[1],e[0]):0},isVertical:function(e){return e==a||e==r},toggleDefaultBehavior:function(e,t,n){if(t&&e&&e.style){h.each(["webkit","moz","Moz","ms","o",""],function(i){h.each(t,function(t,r){i&&(r=i+r.substring(0,1).toUpperCase()+r.substring(1)),r in e.style&&(e.style[r]=!n&&t)})});var i=function(){return!1};"none"==t.userSelect&&(e.onselectstart=!n&&i),"none"==t.userDrag&&(e.ondragstart=!n&&i)}}};i.Instance=function(e,t){var r=this;return n(),this.element=e,this.enabled=!0,this.options=h.extend(h.extend({},i.defaults),t||{}),this.options.stop_browser_behavior&&h.toggleDefaultBehavior(this.element,this.options.stop_browser_behavior,!1),this.eventStartHandler=b.onTouch(e,d,function(e){r.enabled&&x.startDetect(r,e)}),this.eventHandlers=[],this},i.Instance.prototype={on:function(e,t){var n=e.split(" ");return h.each(n,function(e){this.element.addEventListener(e,t,!1),this.eventHandlers.push({gesture:e,handler:t})},this),this},off:function(e,t){var n,i,r=e.split(" ");return h.each(r,function(e){for(this.element.removeEventListener(e,t,!1),n=-1;i=this.eventHandlers[++n];)i.gesture===e&&i.handler===t&&this.eventHandlers.splice(n,1)},this),this},trigger:function(e,t){t||(t={});var n=i.DOCUMENT.createEvent("Event");n.initEvent(e,!0,!0),n.gesture=t;var r=this.element;return h.hasParent(t.target,r)&&(r=t.target),r.dispatchEvent(n),this},enable:function(e){return this.enabled=e,this},dispose:function(){var e,t;for(this.options.stop_browser_behavior&&h.toggleDefaultBehavior(this.element,this.options.stop_browser_behavior,!0),e=-1;t=this.eventHandlers[++e];)this.element.removeEventListener(t.gesture,t.handler,!1);return this.eventHandlers=[],b.unbindDom(this.element,i.EVENT_TYPES[d],this.eventStartHandler),null}};var m=null,g=!1,v=!1,b=i.event={bindDom:function(e,t,n){var i=t.split(" ");h.each(i,function(t){e.addEventListener(t,n,!1)})},unbindDom:function(e,t,n){var i=t.split(" ");h.each(i,function(t){e.removeEventListener(t,n,!1)})},onTouch:function(e,t,n){var r=this,o=function(o){var a=o.type.toLowerCase();if(!h.inStr(a,"mouse")||!v){h.inStr(a,"touch")||h.inStr(a,"pointerdown")||h.inStr(a,"mouse")&&1===o.which?g=!0:h.inStr(a,"mouse")&&!o.which&&(g=!1),(h.inStr(a,"touch")||h.inStr(a,"pointer"))&&(v=!0);var s=0;g&&(i.HAS_POINTEREVENTS&&t!=f?s=y.updatePointer(t,o):h.inStr(a,"touch")?s=o.touches.length:v||(s=h.inStr(a,"up")?0:1),s>0&&t==f?t=p:s||(t=f),(s||null===m)&&(m=o),n.call(x,r.collectEventData(e,t,r.getTouchList(m,t),o)),i.HAS_POINTEREVENTS&&t==f&&(s=y.updatePointer(t,o))),s||(m=null,g=!1,v=!1,y.reset())}};return this.bindDom(e,i.EVENT_TYPES[t],o),o},determineEventTypes:function(){var e;e=i.HAS_POINTEREVENTS?y.getEvents():i.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],i.EVENT_TYPES[d]=e[0],i.EVENT_TYPES[p]=e[1],i.EVENT_TYPES[f]=e[2]},getTouchList:function(e){return i.HAS_POINTEREVENTS?y.getTouchList():e.touches?e.touches:(e.identifier=1,[e])},collectEventData:function(e,t,n,i){var r=c;return(h.inStr(i.type,"mouse")||y.matchType(l,i))&&(r=l),{center:h.getCenter(n),timeStamp:Date.now(),target:i.target,touches:n,eventType:t,pointerType:r,srcEvent:i,preventDefault:function(){var e=this.srcEvent;e.preventManipulation&&e.preventManipulation(),e.preventDefault&&e.preventDefault()},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return x.stopDetect()}}}},y=i.PointerEvent={pointers:{},getTouchList:function(){var e=[];return h.each(this.pointers,function(t){e.push(t)}),e},updatePointer:function(e,t){return e==f?delete this.pointers[t.pointerId]:(t.identifier=t.pointerId,this.pointers[t.pointerId]=t),Object.keys(this.pointers).length},matchType:function(e,t){if(!t.pointerType)return!1;var n=t.pointerType,i={};return i[l]=n===l,i[c]=n===c,i[u]=n===u,i[e]},getEvents:function(){return["pointerdown MSPointerDown","pointermove MSPointerMove","pointerup pointercancel MSPointerUp MSPointerCancel"]},reset:function(){this.pointers={}}},x=i.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(e,t){this.current||(this.stopped=!1,this.current={inst:e,startEvent:h.extend({},t),lastEvent:!1,lastVelocityEvent:!1,velocity:!1,name:""},this.detect(t)) },detect:function(e){if(this.current&&!this.stopped){e=this.extendEventData(e);var t=this.current.inst,n=t.options;return h.each(this.gestures,function(i){return this.stopped||n[i.name]===!1||t.enabled===!1||i.handler.call(i,e,t)!==!1?void 0:(this.stopDetect(),!1)},this),this.current&&(this.current.lastEvent=e),e.eventType==f&&!e.touches.length-1&&this.stopDetect(),e}},stopDetect:function(){this.previous=h.extend({},this.current),this.current=null,this.stopped=!0},getVelocityData:function(e,t,n,r){var o=this.current,a=o.lastVelocityEvent,s=o.velocity;a&&e.timeStamp-a.timeStamp>i.UPDATE_VELOCITY_INTERVAL?(s=h.getVelocity(e.timeStamp-a.timeStamp,e.center.clientX-a.center.clientX,e.center.clientY-a.center.clientY),o.lastVelocityEvent=e):o.velocity||(s=h.getVelocity(t,n,r),o.lastVelocityEvent=e),o.velocity=s,e.velocityX=s.x,e.velocityY=s.y},getInterimData:function(e){var t,n,i=this.current.lastEvent;e.eventType==f?(t=i&&i.interimAngle,n=i&&i.interimDirection):(t=i&&h.getAngle(i.center,e.center),n=i&&h.getDirection(i.center,e.center)),e.interimAngle=t,e.interimDirection=n},extendEventData:function(e){var t=this.current,n=t.startEvent;(e.touches.length!=n.touches.length||e.touches===n.touches)&&(n.touches=[],h.each(e.touches,function(e){n.touches.push(h.extend({},e))}));var i=e.timeStamp-n.timeStamp,r=e.center.clientX-n.center.clientX,o=e.center.clientY-n.center.clientY;return this.getVelocityData(e,i,r,o),this.getInterimData(e),h.extend(e,{startEvent:n,deltaTime:i,deltaX:r,deltaY:o,distance:h.getDistance(n.center,e.center),angle:h.getAngle(n.center,e.center),direction:h.getDirection(n.center,e.center),scale:h.getScale(n.touches,e.touches),rotation:h.getRotation(n.touches,e.touches)}),e},register:function(e){var n=e.defaults||{};return n[e.name]===t&&(n[e.name]=!0),h.extend(i.defaults,n,!0),e.index=e.index||1e3,this.gestures.push(e),this.gestures.sort(function(e,t){return e.indext.index?1:0}),this.gestures}};i.gestures.Drag={name:"drag",index:50,defaults:{drag_min_distance:10,correct_for_drag_min_distance:!0,drag_max_touches:1,drag_block_horizontal:!1,drag_block_vertical:!1,drag_lock_to_axis:!1,drag_lock_min_distance:25},triggered:!1,handler:function(e,t){var n=x.current;if(n.name!=this.name&&this.triggered)return t.trigger(this.name+"end",e),void(this.triggered=!1);if(!(t.options.drag_max_touches>0&&e.touches.length>t.options.drag_max_touches))switch(e.eventType){case d:this.triggered=!1;break;case p:if(e.distance0)){var l=Math.abs(t.options.drag_min_distance/e.distance);i.pageX+=e.deltaX*l,i.pageY+=e.deltaY*l,i.clientX+=e.deltaX*l,i.clientY+=e.deltaY*l,e=x.extendEventData(e)}(n.lastEvent.drag_locked_to_axis||t.options.drag_lock_to_axis&&t.options.drag_lock_min_distance<=e.distance)&&(e.drag_locked_to_axis=!0);var c=n.lastEvent.direction;e.drag_locked_to_axis&&c!==e.direction&&(e.direction=h.isVertical(c)?e.deltaY<0?a:r:e.deltaX<0?o:s),this.triggered||(t.trigger(this.name+"start",e),this.triggered=!0),t.trigger(this.name,e),t.trigger(this.name+e.direction,e);var u=h.isVertical(e.direction);(t.options.drag_block_vertical&&u||t.options.drag_block_horizontal&&!u)&&e.preventDefault();break;case f:this.triggered&&t.trigger(this.name+"end",e),this.triggered=!1}}},i.gestures.Hold={name:"hold",index:10,defaults:{hold_timeout:500,hold_threshold:2},timer:null,handler:function(e,t){switch(e.eventType){case d:clearTimeout(this.timer),x.current.name=this.name,this.timer=setTimeout(function(){"hold"==x.current.name&&t.trigger("hold",e)},t.options.hold_timeout);break;case p:e.distance>t.options.hold_threshold&&clearTimeout(this.timer);break;case f:clearTimeout(this.timer)}}},i.gestures.Release={name:"release",index:1/0,handler:function(e,t){e.eventType==f&&t.trigger(this.name,e)}},i.gestures.Swipe={name:"swipe",index:40,defaults:{swipe_min_touches:1,swipe_max_touches:1,swipe_velocity:.7},handler:function(e,t){if(e.eventType==f){if(e.touches.lengtht.options.swipe_max_touches)return;(e.velocityX>t.options.swipe_velocity||e.velocityY>t.options.swipe_velocity)&&(t.trigger(this.name,e),t.trigger(this.name+e.direction,e))}}},i.gestures.Tap={name:"tap",index:100,defaults:{tap_max_touchtime:250,tap_max_distance:10,tap_always:!0,doubletap_distance:20,doubletap_interval:300},has_moved:!1,handler:function(e,t){var n,i,r;e.eventType==d?this.has_moved=!1:e.eventType!=p||this.moved?e.eventType==f&&"touchcancel"!=e.srcEvent.type&&e.deltaTimet.options.tap_max_distance}},i.gestures.Touch={name:"touch",index:-1/0,defaults:{prevent_default:!1,prevent_mouseevents:!1},handler:function(e,t){return t.options.prevent_mouseevents&&e.pointerType==l?void e.stopDetect():(t.options.prevent_default&&e.preventDefault(),void(e.eventType==d&&t.trigger(this.name,e)))}},i.gestures.Transform={name:"transform",index:45,defaults:{transform_min_scale:.01,transform_min_rotation:1,transform_always_block:!1,transform_within_instance:!1},triggered:!1,handler:function(e,t){if(x.current.name!=this.name&&this.triggered)return t.trigger(this.name+"end",e),void(this.triggered=!1);if(!(e.touches.length<2)){if(t.options.transform_always_block&&e.preventDefault(),t.options.transform_within_instance)for(var n=-1;e.touches[++n];)if(!h.hasParent(e.touches[n].target,t.element))return;switch(e.eventType){case d:this.triggered=!1;break;case p:var i=Math.abs(1-e.scale),r=Math.abs(e.rotation);if(it.options.transform_min_rotation&&t.trigger("rotate",e),i>t.options.transform_min_scale&&(t.trigger("pinch",e),t.trigger("pinch"+(e.scale<1?"in":"out"),e));break;case f:this.triggered&&t.trigger(this.name+"end",e),this.triggered=!1}}}},"function"==typeof define&&define.amd?define("hammerjs",[],function(){return i}):"object"==typeof module&&module.exports?module.exports=i:e.Hammer=i}(window),define("layout",["jquery","underscore","utils","constants","settings","eventMgr","crel","mousetrap","hammerjs"],function(e,t,n,i,r,o,a,s,l){function c(){$=!0,v.$elt.addClass("layout-animate")}function u(){$=!1,v.$elt.removeClass("layout-animate")}function d(t){this.selector=t,this.elt=document.querySelector(t),this.$elt=e(this.elt)}function p(e){e&&e.target!==v.elt&&e.target!==b.elt&&e.target!==E.elt||(G.forEach(function(e){e()}),u(),0!==G.length&&h(),G=[])}function f(){return t.find(J,function(e){return g.width>e.screenWidth}).maxWidth}function h(){var e=y.height-60,t=(C.elt.offsetWidth-f())/2;t\n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n\n \n\n\n
    \n \n \n
    \n
    \n
    \n
    \n
    \n
    \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    \n
    \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    \n' }),define("text!html/bodyViewer.html",[],function(){return'
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n\n \n\n\n
    \n \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n\n\n'}),define("text!html/settingsTemplateTooltip.html",[],function(){return'Available variables:\n
    \n
      \n
    • \n documentTitle: document title
    • \n
    • \n documentMarkdown: document in Markdown format
    • \n
    • \n strippedDocumentMarkdown: document without front matter
    • \n
    • \n documentHTML: document in HTML format
    • \n
    • \n frontMatter: YAML front matter object (undefined if not present)
    • \n
    • \n publishAttributes: attributes of the publish location (undefined if\n not publishing)
    • \n
    \nExamples:\n
    <title><%= documentTitle %></title>\n
    <div><%- documentHTML %></div>\n
    <%\n
    if(publishAttributes.provider.providerId == "github") print(documentMarkdown);\n%>\n
    \n
    \nMore\n info\n
    \n
    \n\n Careful! Template is subject to malicious code. Don\'t copy/paste untrusted\n content.\n'}),define("text!html/settingsShortcutsExtensionTooltip.html",[],function(){return'You can create expanding macros like this:\n
    \n
    \n\'- - > space\': function() {\n
    \n expand(\'--> \', \'→ \');\n
    \n}\n
    \n
    \nMore\n info\n
    \n
    \n Careful! This is subject to malicious code. Don\'t copy/paste untrusted content.\n'}),define("text!html/settingsUserCustomExtensionTooltip.html",[],function(){return'Extension variable name:\nuserCustom\n
    \n
    \nExample:\n
    \nuserCustom.onPreviewFinished = function() {\n
    \n  eventMgr.onMessage("Finished!");\n
    \n};\n
    \n
    \nMore\n info\n
    \n
    \n Careful! This is subject to malicious code. Don\'t copy/paste untrusted content.'}),function(){function e(){}function t(e){this.buttonBar=d.getElementById("wmd-button-bar"+e),this.preview=d.getElementById("wmd-preview"+e),this.input=d.getElementById("wmd-input"+e)}function n(e,t){var n,r,o,a=this,s=[],c=0,u="none",d=function(e,t){u!=e&&(u=e,t||f()),m.isIE&&"moving"==u?o=null:r=setTimeout(p,1)},p=function(e){o=new i(t,e),r=void 0};this.setCommandMode=function(){u="command",f(),r=setTimeout(p,0)},this.canUndo=function(){return c>1},this.canRedo=function(){return s[c+1]?!0:!1},this.undo=function(){a.canUndo()&&(n?(n.restore(),n=null):(s[c]=new i(t),s[--c].restore(),e&&e())),u="none",t.input.focus(),p()},this.redo=function(){a.canRedo()&&(s[++c].restore(),e&&e()),u="none",t.input.focus(),p()};var f=function(){var r=o||new i(t);return r?"moving"==u?void(n||(n=r)):(n&&(s[c-1].text!=n.text&&(s[c++]=n),n=null),s[c++]=r,s[c+1]=null,void(e&&e())):!1},h=function(e){if(!e.ctrlKey&&!e.metaKey){var t=e.keyCode;t>=33&&40>=t||t>=63232&&63235>=t?d("moving"):8==t||46==t||127==t?d("deleting"):13==t?d("newlines"):27==t?d("escape"):(16>t||t>20)&&91!=t&&d("typing")}},g=function(){l.addEvent(t.input,"keypress",function(e){!e.ctrlKey&&!e.metaKey||e.altKey||89!=e.keyCode&&90!=e.keyCode||e.preventDefault()});var e=function(){(m.isIE||o&&o.text!=t.input.value)&&void 0==r&&(u="paste",f(),p())};l.addEvent(t.input,"keydown",h),l.addEvent(t.input,"mousedown",function(){d("moving")}),t.input.onpaste=e,t.input.ondrop=e},v=function(){g(),p(!0)};this.reinit=function(e,t,i,a){s=[],c=0,u="none",n=void 0,r=void 0,p(),o.text=e,o.start=t,o.end=i,o.scrollTop=a,o.setInputAreaSelection(),f()},this.setMode=d,v()}function i(t){var n=this,i=t.input;this.init=function(){l.isVisible(i)&&(this.setInputAreaSelectionStartEnd(),this.scrollTop=i.scrollTop,(!this.text&&i.selectionStart||0===i.selectionStart)&&(this.text=i.value))},this.setInputAreaSelection=function(){if(l.isVisible(i))if(void 0===i.selectionStart||m.isOpera){if(d.selection){i.focus();var e=i.createTextRange();e.moveStart("character",-i.value.length),e.moveEnd("character",-i.value.length),e.moveEnd("character",n.end),e.moveStart("character",n.start),e.select()}}else i.focus(),i.selectionStart=n.start,i.selectionEnd=n.end,i.scrollTop=n.scrollTop},this.setInputAreaSelectionStartEnd=function(){if(t.ieCachedRange||!i.selectionStart&&0!==i.selectionStart){if(d.selection){n.text=l.fixEolChars(i.value);var e=t.ieCachedRange||d.selection.createRange(),r=l.fixEolChars(e.text),o="",a=o+r+o;e.text=a;var s=l.fixEolChars(i.value);e.moveStart("character",-a.length),e.text=r,n.start=s.indexOf(o),n.end=s.lastIndexOf(o)-o.length;var c=n.text.length-l.fixEolChars(i.value).length;if(c){for(e.moveStart("character",-r.length);c--;)r+="\n",n.end+=1;e.text=r}t.ieCachedRange&&(n.scrollTop=t.ieCachedScrollTop),t.ieCachedRange=null,this.setInputAreaSelection()}}else n.start=i.selectionStart,n.end=i.selectionEnd},this.restore=function(){void 0!=n.text&&n.text!=i.value&&(i.value=n.text),this.setInputAreaSelection(),setTimeout(function(){i.scrollTop=n.scrollTop},0)},this.getChunks=function(){var t=new e;return t.before=l.fixEolChars(n.text.substring(0,n.start)),t.startTag="",t.selection=l.fixEolChars(n.text.substring(n.start,n.end)),t.endTag="",t.after=l.fixEolChars(n.text.substring(n.end)),t.scrollTop=n.scrollTop,t},this.setChunks=function(e){e.before=e.before+e.startTag,e.after=e.endTag+e.after,this.start=e.before.length,this.end=e.before.length+e.selection.length,this.text=e.before+e.selection+e.after,this.scrollTop=e.scrollTop},this.init()}function r(e,t,n){var i,r,o,a=3e3,s="manual",c=function(e,t){l.addEvent(e,"input",t),e.onpaste=t,e.ondrop=t,l.addEvent(e,"keypress",t),l.addEvent(e,"keydown",t)},u=function(){if(t.preview){var n=t.input.value;if(!n||n!=o){o=n;var i=(new Date).getTime();n=e.makeHtml(n);var a=(new Date).getTime();r=a-i,g(n)}}},d=function(){if(i&&(clearTimeout(i),i=void 0),"manual"!==s){var e=0;"delayed"===s&&(e=r),e>a&&(e=a),i=setTimeout(u,e)}};this.refresh=function(e){e?(o="",u()):d()},this.processingTime=function(){return r};var p,f=function(e){var n=t.preview,i=n.parentNode,r=n.nextSibling;i.removeChild(n),n.innerHTML=e,r?i.insertBefore(n,r):i.appendChild(n)},h=function(e){t.preview.innerHTML=e},m=function(e){if(p)return p(e);try{h(e),p=h}catch(t){p=f,p(e)}},g=function(e){t.preview&&(m(e),n())},v=function(){c(t.input,d),t.preview&&(t.preview.scrollTop=0)};v()}function o(e,t,n,r,o,a,s){function l(e){f.focus();var o="wmd-link-button"==e.id||"wmd-image-button"==e.id;if(e.textOp){n&&!o&&n.setCommandMode();var a=new i(t);if(!a)return;var s=a.getChunks(),l=function(){f.focus(),s&&a.setChunks(s),a.restore(),r.refresh()},c=e.textOp(s,l);c||(l(),o||f.dispatchEvent(new Event("keydown")))}e.execute&&e.execute(n)}function c(e,n){var i="0px",r="-20px",o="-40px",a=e.getElementsByTagName("span")[0];n?(a.style.backgroundPosition=e.XShift+" "+i,e.onmouseover=function(){a.style.backgroundPosition=this.XShift+" "+o},e.onmouseout=function(){a.style.backgroundPosition=this.XShift+" "+i},m.isIE&&(e.onmousedown=function(){t.ieCachedRange=document.selection.createRange(),t.ieCachedScrollTop=t.input.scrollTop}),e.isHelp||(e.onclick=function(){return this.onmouseout&&this.onmouseout(),l(this),!1}),e.className=e.className.replace(/ disabled/g,"")):(a.style.backgroundPosition=e.XShift+" "+r,e.onmouseover=e.onmouseout=e.onclick=function(){},e.className+=" disabled")}function u(e){return"string"==typeof e&&(e=o[e]),function(){e.apply(o,arguments)}}function d(){var n=t.buttonBar,i=document.createElement("ul");i.id="wmd-button-row"+e,i.className="wmd-button-row",i=n.appendChild(i);var r=0,o=function(t,n,o,a){var s=document.createElement("li");s.className="wmd-button",s.style.left=r+"px",r+=25;var l=document.createElement("span");return s.id=t+e,s.appendChild(l),s.title=n,s.XShift=o,a&&(s.textOp=a),c(s,!0),i.appendChild(s),s},l=function(t){var n=document.createElement("li");n.className="wmd-spacer wmd-spacer"+t,n.id="wmd-spacer"+t+e,i.appendChild(n),r+=25};if(h.bold=o("wmd-bold-button",s("bold"),"0px",u("doBold")),h.italic=o("wmd-italic-button",s("italic"),"-20px",u("doItalic")),l(1),h.link=o("wmd-link-button",s("link"),"-40px",u(function(e,t){return this.doLinkOrImage(e,t,!1)})),h.quote=o("wmd-quote-button",s("quote"),"-60px",u("doBlockquote")),h.code=o("wmd-code-button",s("code"),"-80px",u("doCode")),h.image=o("wmd-image-button",s("image"),"-100px",u(function(e,t){return this.doLinkOrImage(e,t,!0)})),l(2),h.olist=o("wmd-olist-button",s("olist"),"-120px",u(function(e,t){this.doList(e,t,!0)})),h.ulist=o("wmd-ulist-button",s("ulist"),"-140px",u(function(e,t){this.doList(e,t,!1)})),h.heading=o("wmd-heading-button",s("heading"),"-160px",u("doHeading")),h.hr=o("wmd-hr-button",s("hr"),"-180px",u("doHorizontalRule")),l(3),h.undo=o("wmd-undo-button",s("undo"),"-200px",null),h.undo.execute=function(e){e&&e.undo()},h.redo=o("wmd-redo-button",s("redo"),"-220px",null),h.redo.execute=function(e){e&&e.redo()},a){var d=document.createElement("li"),f=document.createElement("span");d.appendChild(f),d.className="wmd-button wmd-help-button",d.id="wmd-help-button"+e,d.XShift="-240px",d.isHelp=!0,d.style.right="0px",d.title=s("help"),d.onclick=a.handler,c(d,!0),i.appendChild(d),h.help=d}p()}function p(){n&&(c(h.undo,n.canUndo()),c(h.redo,n.canRedo()))}var f=t.input,h={};d();var g="keydown";m.isOpera&&(g="keypress"),this.setUndoRedoButtonStates=p,this.buttons=h,this.doClick=l}function a(e,t){this.hooks=e,this.getString=t}function s(e){return e.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/,function(e,t,n){return t=t.replace(/\?.*$/,function(e){return e.replace(/\+/g," ")}),t=decodeURIComponent(t),t=encodeURI(t).replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29"),t=t.replace(/\?.*$/,function(e){return e.replace(/\+/g,"%2b")}),n&&(n=n.trim?n.trim():n.replace(/^\s*/,"").replace(/\s*$/,""),n=n.replace(/"/g,"quot;").replace(/\(/g,"(").replace(/\)/g,")").replace(//g,">")),n?t+' "'+n+'"':t})}var l={},c={},u={},d=window.document,p=window.RegExp,f=window.navigator,h={lineLength:72},m={isIE:/msie/.test(f.userAgent.toLowerCase()),isIE_5or6:/msie 6/.test(f.userAgent.toLowerCase())||/msie 5/.test(f.userAgent.toLowerCase()),isOpera:/opera/.test(f.userAgent.toLowerCase())},g={bold:"Strong Ctrl/Cmd+B",boldexample:"strong text",italic:"Emphasis Ctrl/Cmd+I",italicexample:"emphasized text",link:"Hyperlink Ctrl/Cmd+L",linkdescription:"enter link description here",linkdialog:'

    Insert Hyperlink

    http://example.com/ "optional title"

    ',quote:"Blockquote
    Ctrl/Cmd+Q",quoteexample:"Blockquote",code:"Code Sample
     Ctrl/Cmd+K",codeexample:"enter code here",image:"Image  Ctrl/Cmd+G",imagedescription:"enter image description here",imagedialog:"

    Insert Image

    http://example.com/images/diagram.jpg \"optional title\"

    Need
    free image hosting?

    ",olist:"Numbered List
      Ctrl/Cmd+O",ulist:"Bulleted List
        Ctrl/Cmd+U",litem:"List item",heading:"Heading

        /

        Ctrl/Cmd+H",headingexample:"Heading",hr:"Horizontal Rule
        Ctrl/Cmd+R",undo:"Undo - Ctrl/Cmd+Z",redo:"Redo - Ctrl/Cmd+Y",help:"Markdown Editing Help"},v="http://",b="http://";Markdown.Editor=function(e,i,s){s=s||{},"function"==typeof s.handler&&(s={helpButton:s}),s.strings=s.strings||{},s.helpButton&&(s.strings.help=s.strings.help||s.helpButton.title);var l=function(e){return s.strings[e]||g[e]};i=i||"";var c=this.hooks=new Markdown.HookCollection;c.addNoop("onPreviewRefresh"),c.addNoop("postBlockquoteCreation"),c.addFalse("insertImageDialog"),c.addFalse("insertLinkDialog"),this.getConverter=function(){return e};var u,p,f=this;this.run=function(){if(!u){u=new t(i);var h,m=new a(c,l),g=new r(e,u,function(){c.onPreviewRefresh()});s.undoManager?(p=s.undoManager,p.onButtonStateChange=function(){h.setUndoRedoButtonStates()},h&&h.setUndoRedoButtonStates()):/\?noundo/.test(d.location.href)||(p=new n(function(){g.refresh(),h&&h.setUndoRedoButtonStates()},u),this.textOperation=function(e){p.setCommandMode(),e(),f.refreshPreview()}),h=new o(i,u,p,g,m,s.helpButton,l),h.setUndoRedoButtonStates();{f.refreshPreview=function(){g.refresh(!0)}}f.undoManager=p,f.uiManager=h}}},e.prototype.findTags=function(e,t){var n,i=this;e&&(n=l.extendRegExp(e,"","$"),this.before=this.before.replace(n,function(e){return i.startTag=i.startTag+e,""}),n=l.extendRegExp(e,"^",""),this.selection=this.selection.replace(n,function(e){return i.startTag=i.startTag+e,""})),t&&(n=l.extendRegExp(t,"","$"),this.selection=this.selection.replace(n,function(e){return i.endTag=e+i.endTag,""}),n=l.extendRegExp(t,"^",""),this.after=this.after.replace(n,function(e){return i.endTag=e+i.endTag,""}))},e.prototype.trimWhitespace=function(e){var t,n,i=this;e?t=n="":(t=function(e){return i.before+=e,""},n=function(e){return i.after=e+i.after,""}),this.selection=this.selection.replace(/^(\s*)/,t).replace(/(\s*)$/,n)},e.prototype.skipLines=function(e,t,n){void 0===e&&(e=1),void 0===t&&(t=1),e++,t++;var i,r;if(navigator.userAgent.match(/Chrome/)&&"X".match(/()./),this.selection=this.selection.replace(/(^\n*)/,""),this.startTag=this.startTag+p.$1,this.selection=this.selection.replace(/(\n*$)/,""),this.endTag=this.endTag+p.$1,this.startTag=this.startTag.replace(/(^\n*)/,""),this.before=this.before+p.$1,this.endTag=this.endTag.replace(/(\n*$)/,""),this.after=this.after+p.$1,this.before){for(i=r="";e--;)i+="\\n?",r+="\n";n&&(i="\\n*"),this.before=this.before.replace(new p(i+"$",""),r)}if(this.after){for(i=r="";t--;)i+="\\n?",r+="\n";n&&(i="\\n*"),this.after=this.after.replace(new p(i,""),r)}},l.isVisible=function(e){return window.getComputedStyle?"none"!==window.getComputedStyle(e,null).getPropertyValue("display"):e.currentStyle?"none"!==e.currentStyle.display:void 0},l.addEvent=function(e,t,n){e.attachEvent?e.attachEvent("on"+t,n):e.addEventListener(t,n,!1)},l.removeEvent=function(e,t,n){e.detachEvent?e.detachEvent("on"+t,n):e.removeEventListener(t,n,!1)},l.fixEolChars=function(e){return e=e.replace(/\r\n/g,"\n"),e=e.replace(/\r/g,"\n")},l.extendRegExp=function(e,t,n){(null===t||void 0===t)&&(t=""),(null===n||void 0===n)&&(n="");var i,r=e.toString();return r=r.replace(/\/([gim]*)$/,function(e,t){return i=t,""}),r=r.replace(/(^\/|\/$)/g,""),r=t+r+n,new p(r,i)},c.getTop=function(e,t){var n=e.offsetTop;if(!t)for(;e=e.offsetParent;)n+=e.offsetTop;return n},c.getHeight=function(e){return e.offsetHeight||e.scrollHeight},c.getWidth=function(e){return e.offsetWidth||e.scrollWidth},c.getPageSize=function(){var e,t,n,i;self.innerHeight&&self.scrollMaxY?(e=d.body.scrollWidth,t=self.innerHeight+self.scrollMaxY):d.body.scrollHeight>d.body.offsetHeight?(e=d.body.scrollWidth,t=d.body.scrollHeight):(e=d.body.offsetWidth,t=d.body.offsetHeight),self.innerHeight?(n=self.innerWidth,i=self.innerHeight):d.documentElement&&d.documentElement.clientHeight?(n=d.documentElement.clientWidth,i=d.documentElement.clientHeight):d.body&&(n=d.body.clientWidth,i=d.body.clientHeight);var r=Math.max(e,n),o=Math.max(t,i);return[r,o,n,i]},u.createBackground=function(){var e=d.createElement("div"),t=e.style;e.className="wmd-prompt-background",t.position="absolute",t.top="0",t.zIndex="1000",m.isIE?t.filter="alpha(opacity=50)":t.opacity="0.5";var n=c.getPageSize();return t.height=n[1]+"px",m.isIE?(t.left=d.documentElement.scrollLeft,t.width=d.documentElement.clientWidth):(t.left="0",t.width="100%"),d.body.appendChild(e),e},u.prompt=function(e,t,n){var i,r;void 0===t&&(t="");var o=function(e){var t=e.charCode||e.keyCode;27===t&&a(!0)},a=function(e){l.removeEvent(d.body,"keydown",o);var t=r.value;return e?t=null:(t=t.replace(/^http:\/\/(https?|ftp):\/\//,"$1://"),/^(?:https?|ftp):\/\//.test(t)||(t="http://"+t)),i.parentNode.removeChild(i),n(t),!1},s=function(){i=d.createElement("div"),i.className="wmd-prompt-dialog",i.style.padding="10px;",i.style.position="fixed",i.style.width="400px",i.style.zIndex="1001";var n=d.createElement("div");n.innerHTML=e,n.style.padding="5px",i.appendChild(n);var s=d.createElement("form"),u=s.style;s.onsubmit=function(){return a(!1)},u.padding="0",u.margin="0",u.cssFloat="left",u.width="100%",u.textAlign="center",u.position="relative",i.appendChild(s),r=d.createElement("input"),r.type="text",r.value=t,u=r.style,u.display="block",u.width="80%",u.marginLeft=u.marginRight="auto",s.appendChild(r);var p=d.createElement("input");p.type="button",p.onclick=function(){return a(!1)},p.value="OK",u=p.style,u.margin="10px",u.display="inline",u.width="7em";var f=d.createElement("input");f.type="button",f.onclick=function(){return a(!0)},f.value="Cancel",u=f.style,u.margin="10px",u.display="inline",u.width="7em",s.appendChild(p),s.appendChild(f),l.addEvent(d.body,"keydown",o),i.style.top="50%",i.style.left="50%",i.style.display="block",m.isIE_5or6&&(i.style.position="absolute",i.style.top=d.documentElement.scrollTop+200+"px",i.style.left="50%"),d.body.appendChild(i),i.style.marginTop=-(c.getHeight(i)/2)+"px",i.style.marginLeft=-(c.getWidth(i)/2)+"px"};setTimeout(function(){s();var e=t.length;if(void 0!==r.selectionStart)r.selectionStart=0,r.selectionEnd=e;else if(r.createTextRange){var n=r.createTextRange();n.collapse(!1),n.moveStart("character",-e),n.moveEnd("character",e),n.select()}r.focus()},0)};var y=a.prototype;y.prefixes="(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)",y.unwrap=function(e){var t=new p("([^\\n])\\n(?!(\\n|"+this.prefixes+"))","g");e.selection=e.selection.replace(t,"$1 $2")},y.wrap=function(e,t){this.unwrap(e);var n=new p("(.{1,"+t+"})( +|$\\n?)","gm"),i=this;e.selection=e.selection.replace(n,function(e,t){return new p("^"+i.prefixes,"").test(e)?e:t+"\n"}),e.selection=e.selection.replace(/\s+$/,"")},y.doBold=function(e,t){return this.doBorI(e,t,2,this.getString("boldexample"))},y.doItalic=function(e,t){return this.doBorI(e,t,1,this.getString("italicexample"))},y.doBorI=function(e,t,n,i){e.trimWhitespace(),e.selection=e.selection.replace(/\n{2,}/g,"\n");var r=/(\**$)/.exec(e.before)[0],o=/(^\**)/.exec(e.after)[0],a=Math.min(r.length,o.length);if(a>=n&&(2!=a||1!=n))e.before=e.before.replace(p("[*]{"+n+"}$",""),""),e.after=e.after.replace(p("^[*]{"+n+"}",""),"");else if(!e.selection&&o){e.after=e.after.replace(/^([*_]*)/,""),e.before=e.before.replace(/(\s?)$/,"");var s=p.$1;e.before=e.before+o+s}else{e.selection||o||(e.selection=i);var l=1>=n?"*":"**";e.before=e.before+l,e.after=l+e.after}},y.stripLinkDefs=function(e,t){return e=e.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,function(e,n,i,r,o){return t[n]=e.replace(/\s*$/,""),r?(t[n]=e.replace(/["(](.+?)[")]$/,""),r+o):""})},y.addLinkDef=function(e,t){var n=0,i={};e.before=this.stripLinkDefs(e.before,i),e.selection=this.stripLinkDefs(e.selection,i),e.after=this.stripLinkDefs(e.after,i);var r="",o=/(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g,a=function(e){n++,e=e.replace(/^[ ]{0,3}\[(\d+)\]:/," ["+n+"]:"),r+="\n"+e},s=function(e,t,r,l,c,u){return r=r.replace(o,s),i[c]?(a(i[c]),t+r+l+n+u):e};e.before=e.before.replace(o,s),t?a(t):e.selection=e.selection.replace(o,s);var l=n;return e.after=e.after.replace(o,s),e.after&&(e.after=e.after.replace(/\n*$/,"")),e.after||(e.selection=e.selection.replace(/\n*$/,"")),e.after+="\n\n"+r,l},y.doLinkOrImage=function(e,t,n){e.trimWhitespace(),e.findTags(/\s*!?\[/,/\][ ]?(?:\n[ ]*)?(\(.*?\))?/);var i;if(!(e.endTag.length>1&&e.startTag.length>0)){if(e.selection=e.startTag+e.selection+e.endTag,e.startTag=e.endTag="",/\n\n/.test(e.selection))return void this.addLinkDef(e,null);var r=this,o=function(o){i.parentNode.removeChild(i),null!==o&&(e.selection=(" "+e.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g,"$1\\").substr(1),e.startTag=n?"![":"[",e.endTag="]("+s(o)+")",e.selection||(e.selection=r.getString(n?"imagedescription":"linkdescription"))),t()};return i=u.createBackground(),n?this.hooks.insertImageDialog(o)||u.prompt(this.getString("imagedialog"),v,o):this.hooks.insertLinkDialog(o)||u.prompt(this.getString("linkdialog"),b,o),!0}e.startTag=e.startTag.replace(/!?\[/,""),e.endTag="",this.addLinkDef(e,null)},y.doAutoindent=function(e){var t=this,n=!1;e.before=e.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/,"\n\n"),e.before=e.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/,"\n\n"),e.before=e.before.replace(/(\n|^)[ \t]+\n$/,"\n\n"),e.selection||/^[ \t]*(?:\n|$)/.test(e.after)||(e.after=e.after.replace(/^[^\n]*/,function(t){return e.selection=t,""}),n=!0),/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(e.before)&&t.doList&&t.doList(e),/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(e.before)&&t.doBlockquote&&t.doBlockquote(e),/(\n|^)(\t|[ ]{4,}).*\n$/.test(e.before)&&t.doCode&&t.doCode(e),n&&(e.after=e.selection+e.after,e.selection="")},y.doBlockquote=function(e){e.selection=e.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,function(t,n,i,r){return e.before+=n,e.after=r+e.after,i}),e.before=e.before.replace(/(>[ \t]*)$/,function(t,n){return e.selection=n+e.selection,""}),e.selection=e.selection.replace(/^(\s|>)+$/,""),e.selection=e.selection||this.getString("quoteexample");var t,n="",i="";if(e.before){for(var r=e.before.replace(/\n$/,"").split("\n"),o=!1,a=0;a0,/^>/.test(t)?(s=!0,!o&&t.length>1&&(o=!0)):s=/^[ \t]*$/.test(t)?!0:o,s?n+=t+"\n":(i+=n+t,n="\n")}/(^|\n)>/.test(n)||(i+=n,n="")}e.startTag=n,e.before=i,e.after&&(e.after=e.after.replace(/^\n?/,"\n")),e.after=e.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,function(t){return e.endTag=t,""});var l=function(t){var n=t?"> ":"";e.startTag&&(e.startTag=e.startTag.replace(/\n((>|\s)*)\n$/,function(e,t){return"\n"+t.replace(/^[ ]{0,3}>?[ \t]*$/gm,n)+"\n"})),e.endTag&&(e.endTag=e.endTag.replace(/^\n((>|\s)*)\n/,function(e,t){return"\n"+t.replace(/^[ ]{0,3}>?[ \t]*$/gm,n)+"\n"}))};/^(?![ ]{0,3}>)/m.test(e.selection)?(this.wrap(e,h.lineLength-2),e.selection=e.selection.replace(/^/gm,"> "),l(!0),e.skipLines()):(e.selection=e.selection.replace(/^[ ]{0,3}> ?/gm,""),this.unwrap(e),l(!1),!/^(\n|^)[ ]{0,3}>/.test(e.selection)&&e.startTag&&(e.startTag=e.startTag.replace(/\n{0,2}$/,"\n\n")),!/(\n|^)[ ]{0,3}>.*$/.test(e.selection)&&e.endTag&&(e.endTag=e.endTag.replace(/^\n{0,2}/,"\n\n"))),e.selection=this.hooks.postBlockquoteCreation(e.selection),/\n/.test(e.selection)||(e.selection=e.selection.replace(/^(> *)/,function(t,n){return e.startTag+=n,""}))},y.doCode=function(e){var t=/\S[ ]*$/.test(e.before),n=/^[ ]*\S/.test(e.after);if(!n&&!t||/\n/.test(e.selection)){e.before=e.before.replace(/[ ]{4}$/,function(t){return e.selection=t+e.selection,""});var i=1,r=1;/(\n|^)(\t|[ ]{4,}).*\n$/.test(e.before)&&(i=0),/^\n(\t|[ ]{4,})/.test(e.after)&&(r=0),e.skipLines(i,r),e.selection?/^[ ]{0,3}\S/m.test(e.selection)?/\n/.test(e.selection)?e.selection=e.selection.replace(/^/gm," "):e.before+=" ":e.selection=e.selection.replace(/^(?:[ ]{4}|[ ]{0,3}\t)/gm,""):(e.startTag=" ",e.selection=this.getString("codeexample"))}else e.trimWhitespace(),e.findTags(/`/,/`/),e.startTag||e.endTag?e.endTag&&!e.startTag?(e.before+=e.endTag,e.endTag=""):e.startTag=e.endTag="":(e.startTag=e.endTag="`",e.selection||(e.selection=this.getString("codeexample")))},y.doList=function(e,t,n){var i=/(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/,r=/^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/,o="-",a=1,s=function(){var e;return n?(e=" "+a+". ",a++):e=" "+o+" ",e},l=function(e){return void 0===n&&(n=/^\s*\d/.test(e)),e=e.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,function(){return s()})};if(e.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/,null),!e.before||/\n$/.test(e.before)||/^\n/.test(e.startTag)||(e.before+=e.startTag,e.startTag=""),e.startTag){var c=/\d+[.]/.test(e.startTag);if(e.startTag="",e.selection=e.selection.replace(/\n[ ]{4}/g,"\n"),this.unwrap(e),e.skipLines(),c&&(e.after=e.after.replace(r,l)),n==c)return}var u=1;e.before=e.before.replace(i,function(e){return/^\s*([*+-])/.test(e)&&(o=p.$1),u=/[^\n]\n\n[^\n]/.test(e)?1:0,l(e)}),e.selection||(e.selection=this.getString("litem"));var d=s(),f=1;e.after=e.after.replace(r,function(e){return f=/[^\n]\n\n[^\n]/.test(e)?1:0,l(e)}),e.trimWhitespace(!0),e.skipLines(u,f,!0),e.startTag=d;var m=d.replace(/./g," ");this.wrap(e,h.lineLength-m.length),e.selection=e.selection.replace(/\n/g,"\n"+m)},y.doHeading=function(e){if(e.selection=e.selection.replace(/\s+/g," "),e.selection=e.selection.replace(/(^\s+|\s+$)/g,""),!e.selection)return e.startTag="## ",e.selection=this.getString("headingexample"),void(e.endTag=" ##");var t=0;e.findTags(/#+[ ]*/,/[ ]*#+/),/#+/.test(e.startTag)&&(t=p.lastMatch.length),e.startTag=e.endTag="",e.findTags(null,/\s?(-+|=+)/),/=+/.test(e.endTag)&&(t=1),/-+/.test(e.endTag)&&(t=2),e.startTag=e.endTag="",e.skipLines(1,1);var n=0==t?2:t-1;if(n>0){var i=n>=2?"-":"=",r=e.selection.length;for(r>h.lineLength&&(r=h.lineLength),e.endTag="\n";r--;)e.endTag+=i}},y.doHorizontalRule=function(e){e.startTag="----------\n",e.selection="",e.skipLines(2,1,!0)}}(),define("pagedown",function(){}),define("core",["jquery","underscore","crel","editor","layout","constants","utils","storage","settings","eventMgr","text!html/bodyIndex.html","text!html/bodyViewer.html","text!html/settingsTemplateTooltip.html","text!html/settingsShortcutsExtensionTooltip.html","text!html/settingsUserCustomExtensionTooltip.html","storage","pagedown"],function(e,t,n,i,r,o,a,s,l,c,u,d,p,f,h){function m(){T=!0,k=!0;var e=a.currentTime;e>I+1e3&&(I=e,c.onUserActive())}function g(){return a.currentTime-I>o.USER_IDLE_THRESHOLD&&(k=!1),k&&_}function v(){if(T!==!1&&_!==!1){void 0===C&&(C=a.randomString(),s.frontWindowId=C);var t=s.frontWindowId;t!=C&&(_=!1,void 0!==S&&clearInterval(S),e(".modal").modal("hide"),e(".modal-non-unique").modal("show"),window.close())}}function b(){D===!0&&(D=!1,c.onOfflineChanged(!1))}function y(){D===!0&&navigator.onLine===!0&&N+o.CHECK_ONLINE_PERIOD$2
        "),e=e.replace(/(\*|_)(?=\S)(.+?)(?=\S)\1/g,"$2")}};n.setOptions(r),M=new Markdown.Editor(n,void 0,{undoManager:i.undoMgr}),M.hooks.set("insertLinkDialog",function(t){return E.insertLinkCallback=t,a.resetModalInputs(),e(".modal-insert-link").modal(),!0}),M.hooks.set("insertImageDialog",function(t){return E.insertLinkCallback=t,E.catchModal?!0:(a.resetModalInputs(),e(".modal-insert-image").modal(),!0)}),c.onPagedownConfigure(M),M.hooks.chain("onPreviewRefresh",c.onAsyncPreview),M.run(),i.undoMgr.init(),e(".wmd-button-row li").addClass("btn btn-success").css("left",0).find("span").hide();var o=e(".wmd-button-group1");e("#wmd-bold-button").append(e('')).appendTo(o),e("#wmd-italic-button").append(e('')).appendTo(o),o=e(".wmd-button-group2"),e("#wmd-link-button").append(e('')).appendTo(o),e("#wmd-quote-button").append(e('')).appendTo(o),e("#wmd-code-button").append(e('')).appendTo(o),e("#wmd-image-button").append(e('')).appendTo(o),o=e(".wmd-button-group3"),e("#wmd-olist-button").append(e('')).appendTo(o),e("#wmd-ulist-button").append(e('')).appendTo(o),e("#wmd-heading-button").append(e('')).appendTo(o),e("#wmd-hr-button").append(e('')).appendTo(o),o=e(".wmd-button-group5"),e("#wmd-undo-button").append(e('')).appendTo(o),e("#wmd-redo-button").append(e('')).appendTo(o)},E.onReady=function(){document.body.className+=" "+l.editMode,document.body.innerHTML=window.viewerMode===!0?d:u,a.init(),e(window).on("offline",E.setOffline),e(window).on("online",b),navigator.onLine===!1&&E.setOffline(),e(document).mousemove(m).keypress(m),r.init(),i.init(),S=window.setInterval(function(){a.updateCurrentTime(),v(),(g()===!0||window.viewerMode===!0)&&(c.onPeriodicRun(),y())},1e3),c.onReady()},c.addListener("onReady",function(){function n(e){if(e=e||"default",u!=e){var t="less!themes/"+e;-1!==window.baseDir.indexOf("-min")&&(t="css!themes/"+e),requirejs.undef(t),require([t]),u=e}}function r(n,i){t.each(document.querySelectorAll(n),function(t){var n=e(t);n.tooltip({html:!0,container:n.parents(".modal-content"),placement:"right",trigger:"manual",title:i}).click(function(){var t=this;m&&m[0]===t||a.defer(function(){e(document).on("click.close-tooltip",function(){m&&m.tooltip("hide"),m=void 0,e(document).off("click.close-tooltip")}),m=e(t).tooltip("show")})})})}e(".modal").on("shown.bs.modal",function(){var t=e(this);setTimeout(function(){t.find(".btn:first").focus(),t.find("button:first").focus(),t.find("input:enabled:visible:first").focus()},50)}).on("hidden.bs.modal",function(){i.focus(),n(window.theme)}).keyup(function(t){13!=t.which||e(t.target).is("textarea")||e(this).find(".modal-footer a:last").click()}),e(".action-insert-link").click(function(t){var n=a.getInputTextValue(e("#input-insert-link"),t);void 0!==n&&(E.insertLinkCallback(n),E.insertLinkCallback=void 0)}),e(".action-insert-image").click(function(t){var n=a.getInputTextValue(e("#input-insert-image"),t);void 0!==n&&(E.insertLinkCallback(n),E.insertLinkCallback=void 0)}),e(".modal-insert-link, .modal-insert-image").on("hidden.bs.modal",function(){void 0!==E.insertLinkCallback&&(E.insertLinkCallback(null),E.insertLinkCallback=void 0)}),e(".action-load-settings").click(function(){x()}),e(".action-apply-settings").click(function(e){w(e),e.isPropagationStopped()||window.location.reload()}),e(".action-add-google-drive-account").click(function(){3!==l.gdriveMultiAccount&&(l.gdriveMultiAccount++,s.settings=JSON.stringify(l),window.location.reload())});var u=window.theme;L=e("#input-settings-theme"),L.on("change",function(){n(this.value)}),e(".action-import-docs-settings").click(function(){e("#input-file-import-docs-settings").click()});var d;e("#input-file-import-docs-settings").change(function(n){var i=(n.dataTransfer||n.target).files;e(".modal-settings").modal("hide"),t.each(i,function(t){var n=new FileReader;n.onload=function(t){return function(n){try{d=JSON.parse(n.target.result);var i=parseInt(d.version.match(/^v(\d+)$/)[1],10),r=parseInt(s.version.match(/^v(\d+)$/)[1],10);i>r?c.onError("Incompatible version. Please upgrade StackEdit."):e(".modal-import-docs-settings").modal("show")}catch(o){c.onError("Wrong format: "+t.name)}e("#input-file-import-docs-settings").val("")}}(t),n.readAsText(t)})}),e(".action-import-docs-settings-confirm").click(function(){s.clear();var e=/^file\.|^folder\.|^publish\.|^settings$|^sync\.|^google\.|^author\.|^themeV3$|^version$/;t.each(d,function(t,n){e.test(n)&&(s[n]=t)}),window.location.reload()}),e(".action-export-docs-settings").click(function(){a.saveAs(JSON.stringify(s),"StackEdit local storage.json")}),e(".action-default-settings").click(function(){s.removeItem("settings"),s.removeItem("theme"),l.dropboxFullAccess||s.removeItem("dropbox.lastChangeId"),window.location.reload()}),e(".action-app-reset").click(function(){s.clear(),window.location.reload()}),e(".action-reset-input").click(function(){a.resetModalInputs()});var m;if(r(".tooltip-lazy-rendering","Disable preview rendering while typing in order to offload CPU. Refresh preview after 500 ms of inactivity."),r(".tooltip-default-content",["Thanks for supporting StackEdit by adding a backlink in your documents!

        ",'NOTE: Backlinks in Stack Exchange Q/A are not welcome.'].join("")),r(".tooltip-shortcuts-extension",f),r(".tooltip-usercustom-extension",h),r(".tooltip-template",p),e("div.dropdown-menu").click(function(e){e.stopPropagation()}),e(".modal-non-unique").modal({backdrop:"static",keyboard:!1,show:!1}),t.each(document.querySelectorAll("img"),function(t){var n=e(t),i=n.data("stackeditSrc");i&&n.attr("src",window.baseDir+"/img/"+i)}),window.viewerMode===!1){var g=t.reduce(o.THEME_LIST,function(e,t,n){return e+'"},"");document.getElementById("input-settings-theme").innerHTML=g}}),E}),define("text!WELCOME.md",[],function(){return'Welcome to StackEdit! {#welcome}\n====================\n\n\nHello, I am your first Markdown document within **StackEdit**[^stackedit]. Don\'t delete me, I can be helpful. I can be recovered anyway in the `Utils` tab of the `Settings` dialog.\n\n----------\n\n\nDocuments\n--------------\n\n**StackEdit** stores your documents in your browser, which means all your documents are automatically saved locally and are accessible **offline!**\n\n> **Note:**\n\n> - StackEdit is accessible offline after the application has been loaded for the first time.\n> - Your local documents are not shared between different browsers or computers.\n> - Clearing your browser\'s data may **delete all your local documents!** Make sure your documents are backed up using **Google Drive** or **Dropbox** synchronization (see [ Synchronization](#synchronization) section).\n\n#### Create a document\n\nThe document panel is accessible using button in the navigation bar. You can create a new document by clicking the `New document` sub-menu in the document panel.\n\n#### Switch to another document\n\nAll your local documents are listed in the document panel. You can switch from one to another by clicking a document in the document panel or you can also use Ctrl+[ and Ctrl+] to toggle documents by most recently used.\n\n#### Rename a document\n\nYou can rename the current document by clicking the document title in the navigation bar.\n\n#### Delete a document\n\nYou can delete the current document by clicking the `Delete document` sub-menu in the document panel.\n\n#### Export a document\n\nYou can save the current document to a file using the `Export to disk` sub-menu from the menu panel.\n\n> **Tip:** See [ Publish a document](#publish-a-document) section for a description of the different output formats.\n\n\n----------\n\n\nSynchronization\n--------------------\n\n**StackEdit** can be combined with **Google Drive** and **Dropbox** to have your documents centralized in the *Cloud*. The synchronization mechanism will take care of uploading your modifications or downloading the latest version of your documents.\n\n> **Note:**\n\n> - Full access to **Google Drive** or **Dropbox** is required to be able to import any document in StackEdit. Permission restrictions can be configured in the settings.\n> - Imported documents are downloaded in your browser and are not transmitted to a server.\n> - If you experience problems saving your documents on Google Drive, check and optionally disable browser extensions, such as Disconnect.\n\n#### Open a document\n\nYou can open a document from **Google Drive** or the **Dropbox** by opening the `Synchronize` sub-menu and by clicking `Open from...`. Once opened, any modification in your document will be automatically synchronized with the **Google Drive** / **Dropbox** file.\n\n#### Save a document\n\nYou can save any document by opening the `Synchronize` sub-menu and by clicking `Save on...`. Even if your document is already synchronized with **Google Drive** or **Dropbox**, you can export it to a another location. **StackEdit** can synchronize one document with multiple locations.\n\n#### Synchronize a document\n\nOnce your document is linked to a **Google Drive** or a **Dropbox** file, **StackEdit** will periodically (every 3 minutes) synchronize it by downloading/uploading any modification. Any conflict will be detected, and a local copy of your document will be created as a backup if necessary.\n\nIf you just have modified your document and you want to force the synchronization, click the button in the navigation bar.\n\n> **Note:** The button is disabled when you have no document to synchronize.\n\n#### Manage document synchronization\n\nSince one document can be synchronized with multiple locations, you can list and manage synchronized locations by clicking `Manage synchronization` in the `Synchronize` sub-menu. This will let you remove synchronization locations that are associated to your document.\n\n> **Note:** If you delete the file from **Google Drive** or from **Dropbox**, the document will no longer be synchronized with that location.\n\n----------\n\n\nPublication\n--------------\n\nOnce you are happy with your document, you can publish it on different websites directly from **StackEdit**. As for now, **StackEdit** can publish on **Blogger**, **Dropbox**, **Gist**, **GitHub**, **Google Drive**, **Tumblr**, **WordPress** and on any SSH server.\n\n#### Publish a document\n\nYou can publish your document by opening the `Publish` sub-menu and by choosing a website. In the dialog box, you can choose the publication format:\n\n- Markdown, to publish the Markdown text on a website that can interpret it (**GitHub** for example),\n- HTML, to publish the document converted into HTML (on a blog for example),\n- Template, to have a full control of the output.\n\n> **Note:** The default template is a simple webpage wrapping your document in HTML format. You can customize it in the `Advanced` tab of the `Settings` dialog.\n\n#### Update a publication\n\nAfter publishing, **StackEdit** will keep your document linked to that publication which makes it easy for you to update it. Once you have modified your document and you want to update your publication, click on the button in the navigation bar.\n\n> **Note:** The button is disabled when your document has not been published yet.\n\n#### Manage document publication\n\nSince one document can be published on multiple locations, you can list and manage publish locations by clicking `Manage publication` in the menu. This will let you remove publication locations that are associated to your document.\n\n> **Note:** In some cases, if the file has been removed from the website or the blog, the document will no longer be published on that location.\n\n----------\n\n\nMarkdown Extra\n--------------------\n\n**StackEdit** supports **Markdown Extra**, which extends **Markdown** syntax with some nice features.\n\n> **Tip:** You can disable any **Markdown Extra** feature in the `Extensions` tab of the `Settings` dialog.\n\n\n### Tables\n\n**Markdown Extra** has a special syntax for tables:\n\nItem | Value\n--- | ---\nComputer | $1600\nPhone | $12\nPipe | $1\n\nYou can specify column alignment with one or two colons:\n\n| Item | Value | Qty |\n| :--- | ---: | :---: |\n| Computer | $1600 | 5 |\n| Phone | $12 | 12 |\n| Pipe | $1 | 234 |\n\n\n### Definition Lists\n\n**Markdown Extra** has a special syntax for definition lists too:\n\nTerm 1\nTerm 2\n: Definition A\n: Definition B\n\nTerm 3\n\n: Definition C\n\n: Definition D\n\n > part of definition D\n\n\n### Fenced code blocks\n\nGitHub\'s fenced code blocks[^gfm] are also supported with **Prettify** syntax highlighting:\n\n```\n// Foo\nvar bar = 0;\n```\n\n> **Tip:** To use **Highlight.js** instead of **Prettify**, just configure the `Markdown Extra` extension in the `Settings` dialog.\n\n\n### Footnotes\n\nYou can create footnotes like this[^footnote].\n\n [^footnote]: Here is the *text* of the **footnote**.\n\n\n### SmartyPants\n\nSmartyPants converts ASCII punctuation characters into "smart" typographic punctuation HTML entities. For example:\n\n| | ASCII | HTML |\n---|---|---\n| Single backticks | `\'Isn\'t this fun?\'` | \'Isn\'t this fun?\' |\n| Quotes | `"Isn\'t this fun?"` | "Isn\'t this fun?" |\n| Dashes | `-- is en-dash, --- is em-dash` | -- is en-dash, --- is em-dash |\n\n\n### Table of contents\n\nYou can insert a table of contents using the marker `[TOC]`:\n\n[TOC]\n\n\n### MathJax\n\nYou can render *LaTeX* mathematical expressions using **MathJax**, as on [math.stackexchange.com][1]:\n\nThe *Gamma function* satisfying $\\Gamma(n) = (n-1)!\\quad\\forall n\\in\\mathbb N$ is via the Euler integral\n\n$$\n\\Gamma(z) = \\int_0^\\infty t^{z-1}e^{-t}dt\\,.\n$$\n\n> **Tip:** Make sure you include **MathJax** into your publications to render mathematical expression correctly. Your page/template should include something like:\n\n```\n\n```\n\n> **NOTE:** You can find more information:\n\n> - about **Markdown** syntax [here][2],\n> - about **Markdown Extra** extension [here][3],\n> - about **LaTeX** mathematical expressions [here][4],\n> - about **Prettify** syntax highlighting [here][5],\n> - about **Highlight.js** syntax highlighting [here][6].\n\n [^stackedit]: [StackEdit](https://stackedit.io/) is a full-featured, open-source Markdown editor based on PageDown, the Markdown library used by Stack Overflow and the other Stack Exchange sites.\n\n [^gfm]: **GitHub Flavored Markdown** (GFM) is supported by StackEdit.\n\n\n [1]: http://math.stackexchange.com/\n [2]: http://daringfireball.net/projects/markdown/syntax "Markdown"\n [3]: https://github.com/jmcmanus/pagedown-extra "Pagedown Extra"\n [4]: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference\n [5]: https://code.google.com/p/google-code-prettify/\n [6]: http://highlightjs.org/\n'}),define("fileMgr",["jquery","underscore","constants","core","utils","storage","settings","eventMgr","fileSystem","classes/FileDescriptor","text!WELCOME.md"],function(e,t,n,i,r,o,a,s,l,c,u){var d={};return d.currentFile=void 0,d.selectFile=function(r){if(r=r||d.currentFile,void 0===r){var o=t.size(l);r=0===o?d.createFile(n.WELCOME_DOCUMENT_TITLE,u):t.max(l,function(e){return e.selectTime||0})}d.currentFile!==r&&(d.currentFile=r,r.selectTime=(new Date).getTime(),s.onFileSelected(r),e(".action-edit-document").toggleClass("hide",r.fileIndex!=n.TEMPORARY_FILE_INDEX)),i.initEditor(r)},d.createFile=function(e,i,u,d,p){if(i=void 0!==i?i:a.defaultContent,!e){e=n.DEFAULT_FILE_TITLE;for(var f=2,h=function(t){return t.title==e};t.some(l,h);)e=n.DEFAULT_FILE_TITLE+f++}var m=n.TEMPORARY_FILE_INDEX;if(!p)do m="file."+r.randomString();while(t.has(l,m));d=d||{};var g=t.reduce(d,function(e,t){return r.storeAttributes(t),e+t.syncIndex+";"},";");o[m+".title"]=e,o[m+".content"]=i,o[m+".sync"]=g,o[m+".publish"]=";";var v=new c(m,e,d);return u&&(v.discussionListJSON=u),p||(r.appendIndexToArray("file.list",m),l[m]=v,s.onFileCreated(v)),v},d.deleteFile=function(e){e=e||d.currentFile,e.folder&&(e.folder.removeFile(e),s.onFoldersChanged()),r.removeIndexFromArray("file.list",e.fileIndex),delete l[e.fileIndex],d.currentFile===e&&(d.currentFile=void 0,d.selectFile()),s.onFileDeleted(e)},d.getFileFromSyncIndex=function(e){return t.find(l,function(n){return t.has(n.syncLocations,e)})},d.getFileFromPublishIndex=function(e){return t.find(l,function(n){return t.has(n.publishLocations,e)})},s.addListener("onReady",function(){function t(){o.addClass("hide"),r.removeClass("hide");var t=e.trim(o.val()),n=d.currentFile;t&&t!=n.title&&(n.title=t,s.onTitleChanged(n)),o.val(n.title),i.focus()}var i=e("#wmd-input");d.selectFile();var r=e(".file-title-navbar"),o=e(".input-file-title");e(".action-create-file").click(function(){setTimeout(function(){var e=d.createFile();d.selectFile(e),r.click()},400)}),e(".action-remove-file-confirm").click(function(){e(".modal-remove-file-confirm").modal("show")}),e(".action-remove-file").click(function(){d.deleteFile()}),r.click(function(){if(window.viewerMode!==!0){r.addClass("hide");var e=o.removeClass("hide");setTimeout(function(){e.focus().get(0).select()},10)}}),o.blur(function(){t()}).keyup(function(e){13==e.keyCode&&t(),27==e.keyCode&&(o.val(""),t())}),e(".action-open-stackedit").click(function(){window.location.href="."}),e(".action-edit-document").click(function(){var e=i.val(),t=d.currentFile.title,n=d.createFile(t,e);d.selectFile(n),window.location.href="."}),e(".action-welcome-file").click(function(){var e=d.createFile(n.WELCOME_DOCUMENT_TITLE,u);d.selectFile(e)})}),s.onFileMgrCreated(d),d}),define("classes/Provider",["underscore","utils","settings","eventMgr","fileMgr","editor","diff_match_patch_uncompressed","jsondiffpatch"],function(e,t,n,i,r,o,a,s){function l(e,t){this.providerId=e,this.providerName=t,this.isPublishEnabled=!0}l.prototype.parseDiscussionList=function(t){try{var n=JSON.parse(t);return e.each(n,function(t,n){if(t.discussionIndex!=n||!e.isNumber(t.selectionStart)||!e.isNumber(t.selectionEnd))throw"invalid";t.commentList&&t.commentList.forEach(function(t){if(t.author&&!e.isString(t.author)||!e.isString(t.content))throw"invalid"})}),n}catch(i){}},l.prototype.serializeContent=function(e,t){return t.length>2?e+"":e},l.prototype.parseContent=function(e){var t,n="{}",i=/$/.exec(e);return i&&(t=this.parseDiscussionList(i[1]))&&(e=e.substring(0,i.index),n=i[1]),{content:e,discussionList:t||{},discussionListJSON:n}};var c=new a;c.Match_Threshold=0,c.Patch_DeleteThreshold=0;var u=s.create({objectHash:function(e){return JSON.stringify(e)},textDiff:{minLength:9999999}}),d="merge"==n.conflictMode;return l.prototype.syncMerge=function(n,a,s,l,p,f){function h(e){function t(){(i[1]||r[1])&&(i[1]&&r[1]?(i[1]="⧸⧸"+i[1]+"⧸⧸",r[1]+="⧸⧸",n.push(i),n.push(r)):n.push([0,i[1]+r[1]]),i=[-1,""],r=[1,""])}var n=[],i=[-1,""],r=[1,""],o=20;return e.forEach(function(a,s){function l(){return 0===s||s===e.length-1}var c=a[0],u=a[1];if(0===c)if(l()||u.length>o){if(i[1]||r[1]){var d=/\s/.exec(u);if(d){var p=d.index,f=u.substring(0,p);u=u.substring(p),i[1]+=f,r[1]+=f}}if(u){for(var h=u.length;h&&/\S/.test(u[h-1]);)h--;var m=u.substring(h);u=u.substring(0,h),l()||u.length>o?(t(),n.push([0,u])):(i[1]+=u,r[1]+=u),i[1]+=m,r[1]+=m}}else i[1]+=u,r[1]+=u;else-1===c?i[1]+=u:1===c&&(r[1]+=u)}),i[1]==r[1]?n.push([0,r[1]]):t(),n}var m=n.content,g=n.title,v=n.discussionListJSON,b=n.discussionList,y=t.crc32(m),x=t.crc32(g),w=t.crc32(v),S=t.crc32(s),C=t.crc32(l),E=t.crc32(f),T=a.contentCRC!=y,k=a.contentCRC!=S,_=m!=s&&k,I=_&&T;a.titleCRC=a.titleCRC||x;var D,N,L=a.titleCRC!=x,M=a.titleCRC!=C,A=g!=l&&M,R=A&&L,P=a.discussionListCRC!=w,F=a.discussionListCRC!=E,O=v!=f&&F,B=O&&P,j=[],$=s,G=l,q=p,H=!1,U=!1,z=!1;if(!d&&(I||R||B)||I&&void 0===a.content||R&&void 0===a.title||B&&void 0===a.discussionList)r.createFile(g+" (backup)",m,v),i.onMessage('Conflict detected on "'+g+'". A backup has been created locally.');else{if(I){var V=a.content;D=c.diff_main(V,m),c.diff_cleanupSemantic(D),N=c.patch_make(V,D);var W=c.patch_apply(N,s);if($=W[0],!W[1].every(e.identity)){D=c.diff_main(m,$),D=h(D),$="";var Q;D.forEach(function(e){var t=e[0],n=e[1];0===t||Q?0===t&&Q&&(Q.selectionEnd=$.length,j.push(Q),Q=void 0):Q={selectionStart:$.length,type:"conflict"},$+=n}),Q&&(Q.selectionEnd=$.length,j.push(Q))}}_&&(P&&(H=!0),F?U=!0:(H=!0,q=b)),B&&(z=!0),R&&(N=c.patch_make(a.title,g),G=c.patch_apply(N,l)[0])}var X;if(_){var K=[];r.currentFile===n&&(X={selectionStart:o.selectionMgr.selectionStart,selectionEnd:o.selectionMgr.selectionEnd},K.push(X),n.newDiscussion&&K.push(n.newDiscussion)),H&&(K=K.concat(e.values(b))),O|=o.adjustCommentOffsets(m,$,K)}if(U){var J=e.values(p);o.adjustCommentOffsets(s,$,J)}if(z){var Y=JSON.parse(a.discussionList);D=u.diff(Y,b),u.patch(p,D),e.each(p,function(e,t){e||delete p[t]})}return j.length&&(O=!0,j.forEach(function(n){var i;do i=t.randomString()+t.randomString();while(e.has(q,i));n.discussionIndex=i,q[i]=n})),A&&(n.title=G,i.onTitleChanged(n),i.onMessage('"'+g+'" has been renamed to "'+G+'" on '+this.providerName+".")),(_||O)&&o.watcher.noWatch(e.bind(function(){if(_&&(r.currentFile===n&&(o.setValueNoWatch($),X&&o.selectionMgr.setSelectionStartEnd(X.selectionStart,X.selectionEnd)),n.content=$,i.onContentChanged(n,$)),O){n.discussionList=q;var t=u.diff(b,q),a=!1;e.each(t,function(t,r){e.isArray(t)?1===t.length?i.onDiscussionCreated(n,q[r]):i.onDiscussionRemoved(n,b[r]):a=!0}),a&&i.onCommentsChanged(n)}o.undoMgr.currentMode="sync",o.undoMgr.saveState(),i.onMessage('"'+l+'" has been updated from '+this.providerName+"."),j.length&&i.onMessage('"'+l+'" has conflicts that you have to review.')},this)),{contentCRC:S,titleCRC:C,discussionListCRC:E}},l}),define("classes/AsyncTask",["underscore","constants","utils","eventMgr"],function(e,t,n,i){function r(e){this.finished=!1,this.timeout=t.ASYNC_TASK_DEFAULT_TIMEOUT,this.retryCounter=0,this.runCallbacks=[],this.successCallbacks=[],this.errorCallbacks=[],this.force=e}function o(){if(c===!0)return void(l+u.timeout=t)return void this.error(e);var i=1e3*Math.pow(2,this.retryCounter++);l=n.currentTime+i,c=!1,o()}},r.prototype.enqueue=function(){s.push(this),o()};var u,d=!1,p=!1;return i.addListener("onUserActive",function(){p=!0}),i.addListener("onPeriodicRun",o),r}),define("helpers/dropboxHelper",["jquery","underscore","constants","core","utils","storage","logger","settings","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s,l,c){function u(t){t.onRun(function(){return v===!0?(h=void 0,void t.error(new Error("Operation not available in offline mode.|stopPublish"))):void 0!==h?void t.chain():void e.ajax({url:"libs/dropbox.min.js",dataType:"script",timeout:n.AJAX_TIMEOUT}).done(function(){h=new Dropbox.Client({key:s.dropboxFullAccess===!0?n.DROPBOX_APP_KEY:n.DROPBOX_RESTRICTED_APP_KEY,secret:s.dropboxFullAccess===!0?n.DROPBOX_APP_SECRET:n.DROPBOX_RESTRICTED_APP_SECRET}),h.authDriver(new Dropbox.AuthDriver.Popup({receiverUrl:n.BASE_URL+"html/dropbox-oauth-receiver.html",rememberUser:!0})),t.chain()}).fail(function(e){var n={status:e.status,responseText:e.statusText};p(n,t)})})}function d(e){e.onRun(function(){function t(){r.redirectConfirm("You are being redirected to Dropbox authorization page.",function(){e.chain(i)},function(){e.error(new Error("Operation canceled."))})}function i(){o===!1?e.timeout=n.ASYNC_TASK_LONG_TIMEOUT:h.reset(),h.authenticate({interactive:!o},function(n,i){return i.isAuthenticated()===!0?(m=!0,void e.chain()):o===!0?(o=!1,void e.chain(t)):void e.error(new Error("Access to Dropbox account is not authorized."))})}if(m===!0)return void e.chain();var o=!0;e.chain(i)})}function p(e,n){var r=!0;if(e)if(a.error(e),"string"==typeof e)r=e;else{if(r="Dropbox error ("+e.status+": "+e.responseText+").",401===e.status||403===e.status)return m=!1,r="Access to Dropbox account is not authorized.",void n.retry(new Error(r),1);if(400===e.status&&-1!==e.responseText.indexOf("oauth_nonce"))return t.each(t.keys(o),function(e){0===e.indexOf("dropbox-auth")&&o.removeItem(e)}),m=!1,void n.retry(new Error(r),1);e.status<=0&&(h=void 0,m=!1,i.setOffline(),r="|stopPublish")}n.error(new Error(r))}function f(t){t.onRun(function(){function i(){r.redirectConfirm("You are being redirected to Dropbox Chooser page.",function(){t.chain()},function(){t.error(new Error("Operation canceled."))})}return b===!0?void t.chain():void e.ajax({url:"https://www.dropbox.com/static/api/1/dropbox.js",dataType:"script",timeout:n.AJAX_TIMEOUT}).done(function(){b=!0,t.chain(i)}).fail(function(e){var n={status:e.status,responseText:e.statusText};p(n,t)})})}var h,m=!1,g={},v=!1;l.addListener("onOfflineChanged",function(e){v=e}),g.upload=function(e,t,n){var i,r=new c;u(r),d(r),r.onRun(function(){h.writeFile(e,t,function(t,n){return t?(400===t.status&&(t='Could not upload document into path "'+e+'".'),void p(t,r)):(i=n,void r.chain())})}),r.onSuccess(function(){n(void 0,i)}),r.onError(function(e){n(e)}),r.enqueue()},g.checkChanges=function(e,t){var n=[],i=e||0,r=new c;u(r),d(r),r.onRun(function(){function e(){h.pullChanges(i,function(t,o){return t?void p(t,r):(i=o.cursor(),void 0!==o.changes&&(n=n.concat(o.changes)),void(o.shouldPullAgain?r.chain(e):r.chain()))})}r.chain(e)}),r.onSuccess(function(){t(void 0,n,i)}),r.onError(function(e){t(e)}),r.enqueue()},g.downloadMetadata=function(e,t){var n=[],i=new c;u(i),d(i),i.onRun(function(){function t(){if(0===e.length)return void i.chain();var r=e[0];h.stat(r,function(r,o){return o?(n.push(o),e.shift(),void i.chain(t)):void p(r,i)})}i.chain(t)}),i.onSuccess(function(){t(void 0,n)}),i.onError(function(e){t(e)}),i.enqueue()},g.downloadContent=function(e,n){var i=[],r=new c;u(r),d(r),r.onRun(function(){function n(){if(0===e.length)return void r.chain();var o=e[0];i.push(o);var a;return o.isFile===!0?a=o:void 0!==o.wasRemoved&&(a=o.stat),a?void h.readFile(a.path,function(i,o){return t.isString(o)?(a.content=o,e.shift(),void r.chain(n)):void p(i,r)}):(e.shift(),void r.chain(n))}r.chain(n)}),r.onSuccess(function(){n(void 0,i)}),r.onError(function(e){n(e)}),r.enqueue()};var b=!1;return g.picker=function(e){var t=[],i=new c;i.timeout=n.ASYNC_TASK_LONG_TIMEOUT,u(i),f(i),i.onRun(function(){var e={};e.multiselect=!0,e.linkType="direct",e.success=function(e){for(var n=0;n:"\|?\*]+$/)?0!==e.indexOf("/")?"/"+e:e:void o.onError('"'+e+'" contains invalid characters.')}function c(e){return"sync."+p+"."+encodeURIComponent(e.toLowerCase())}function u(e,n,i,r){r=r||"{}";var o={};return o.provider=f,o.path=e,o.version=n,o.contentCRC=t.crc32(i),o.discussionListCRC=t.crc32(r),o.syncIndex=c(e),h===!0&&(o.content=i,o.discussionList=r),o}function d(t){s.downloadMetadata(t,function(t,n){t||s.downloadContent(n,function(t,n){if(!t){var i=[];e.each(n,function(e){var t=f.parseContent(e.content),n=u(e.path,e.versionTag,t.content,t.discussionListJSON),r={};r[n.syncIndex]=n;var o=a.createFile(e.name,t.content,t.discussionListJSON,r);a.selectFile(o),i.push(o)}),0!==i.length&&o.onSyncImportSuccess(i,f)}})})}var p="dropbox",f=new r(p,"Dropbox");f.defaultPublishFormat="template";var h="merge"==i.conflictMode;return f.importFiles=function(){s.picker(function(t,n){if(!t&&0!==n.length){var i=[];e.each(n,function(e){var t=c(e),n=a.getFileFromSyncIndex(t);return void 0!==n?o.onError('"'+n.title+'" was already imported.'):void i.push(e)}),d(i)}})},f.exportFile=function(e,n,i,r,d){var p=t.getInputTextValue("#input-sync-export-dropbox-path",e);if(p=l(p),void 0===p)return d(!0);var h=c(p),m=a.getFileFromSyncIndex(h);if(void 0!==m){var g=m.title;return o.onError('File path is already synchronized with "'+g+'".'),d(!0)}var v=f.serializeContent(i,r);s.upload(p,v,function(e,t){if(e)return d(e);var n=u(t.path,t.versionTag,i,r);d(void 0,n)})},f.syncUp=function(e,t,n,i,r,o,a,l){if(a.contentCRC==t&&a.discussionListCRC==o)return l(void 0,!1);var c=f.serializeContent(e,r);s.upload(a.path,c,function(n,s){return n?l(n,!0):(a.version=s.versionTag,h===!0&&(a.content=e,a.discussionList=r),a.contentCRC=t,a.titleCRC=i,a.discussionListCRC=o,void l(void 0,!0))})},f.syncDown=function(i){var r=n[p+".lastChangeId"];s.checkChanges(r,function(r,l,u){if(r)return i(r);var d=[];e.each(l,function(e){var t=c(e.path),n=a.getFileFromSyncIndex(t),i=n&&n.syncLocations[t];return i?(e.fileDesc=n,e.syncAttributes=i,e.wasRemoved===!0?void d.push(e):void(i.version!=e.stat.versionTag&&d.push(e))):void 0 -}),s.downloadContent(d,function(e,r){function a(){if(0===r.length)return n[p+".lastChangeId"]=u,i();var e=r.pop(),s=e.fileDesc,l=e.syncAttributes;if(e.wasRemoved===!0)return o.onError('"'+s.title+'" has been removed from Dropbox.'),s.removeSyncLocation(l),o.onSyncRemoved(s,l);var c=e.stat,d=f.parseContent(c.content),m=d.content,g=d.discussionListJSON,v=d.discussionList,b=f.syncMerge(s,l,m,s.title,v,g);l.version=c.versionTag,h===!0&&(l.content=m,l.discussionList=v),l.contentCRC=b.contentCRC,l.discussionListCRC=b.discussionListCRC,t.storeAttributes(l),setTimeout(a,5)}return e?void i(e):void setTimeout(a,5)})})},f.publish=function(e,t,n,i,r){var o=l(e.path);return void 0===o?r(!0):void s.upload(o,i,r)},f.newPublishAttributes=function(e){var n={};return n.path=t.getInputTextValue("#input-publish-dropbox-path",e),e.isPropagationStopped()?void 0:n},f}),define("helpers/googleHelper",["underscore","jquery","constants","core","utils","storage","logger","settings","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s,l,c){function u(t){var n={profile:!0},i=!0;e.each((o[t+".permissions"]||"").split(";"),function(e){e&&(n[e]=!0)}),this.setRefreshFlag=function(){i=!0},this.isAuthorized=function(t){return i===!1&&e.has(n,t)},this.add=function(r){n[r]=!0,o[t+".permissions"]=e.keys(n).join(";"),i=!1},this.getListWithNew=function(t){var i=e.keys(n);return e.has(n,t)||i.push(t),i};var r=o[t+".userId"];this.setUserId=function(e){r=e,o[t+".userId"]=r},this.getUserId=function(){return r}}function d(e){e.onRun(function(){return y===!0?(g=!1,void e.error(new Error("Operation not available in offline mode.|stopPublish"))):g===!0?void e.chain():(window.delayedFunction=function(){gapi.load("client",function(){gapi.client.load("drive","v2",function(){g=!0,e.chain()})})},void t.ajax({url:"https://apis.google.com/js/api.js?onload=runDelayedFunction",dataType:"script",timeout:n.AJAX_TIMEOUT}).fail(function(t){var n={code:t.status,message:t.statusText};h(n,e)}))})}function p(i,o,a){var s=v[a];s||(s=new u(a),v[a]=s),i.onRun(function(){function a(){t.ajax({url:"https://www.googleapis.com/oauth2/v1/tokeninfo",data:{access_token:d.access_token},timeout:n.AJAX_TIMEOUT,type:"GET"}).done(function(e){s.getUserId()&&s.getUserId()!=e.user_id?u():(s.setUserId(e.user_id),s.add(o),s.token=d,i.chain())}).fail(function(e){var t={code:e.status,message:e.statusText};h(t,i)})}function l(){if(m>5)return void i.error(new Error("Unable to authenticate user "+s.getUserId()+", please sign in with Google."));p===!1&&(i.timeout=n.ASYNC_TASK_LONG_TIMEOUT);var t=e.chain(x).pick(s.getListWithNew(o)).flatten().value();gapi.auth.authorize({client_id:n.GOOGLE_CLIENT_ID,scope:t,immediate:p,authuser:p===!1?"":m},function(e){d=gapi.auth.getToken(),gapi.auth.setToken(f),!e||e.error?g===!0&&p===!0?(p=!1,i.chain(c)):i.error(new Error("Access to Google account is not authorized.")):(p===!0&&m++,i.chain(a))})}function c(){return p===!0?void i.chain(l):void r.redirectConfirm("You are being redirected to Google authorization page.",function(){i.chain(l)},function(){i.error(new Error("Operation canceled."))})}function u(){return p=!0,s.token&&s.isAuthorized(o)?void i.chain():(s.getUserId()||(p=!1),void i.chain(c))}var d,p,f=gapi.auth.getToken(),m=0;u()})}function f(e,t){var n=gapi.auth.getToken(),i=v[e];gapi.auth.setToken(i.token),t(),gapi.auth.setToken(n)}function h(t,n){var r;if(t)if(a.error(t),"string"==typeof t)r=t;else{if(r="Google error ("+t.code+": "+t.message+").",t.code>=500&&t.code<600)return void n.retry(new Error(r));if(401===t.code||403===t.code||"token_refresh_required"==t.code)return e.each(v,function(e){e.setRefreshFlag()}),r="Access to Google account is not authorized.",void n.retry(new Error(r),1);(0===t.code||-1===t.code)&&(g=!1,e.each(v,function(e){e.setRefreshFlag()}),i.setOffline(),r="|stopPublish")}n.error(new Error(r))}function m(e){e.onRun(function(){return w===!0?void e.chain():void t.ajax({url:"//www.google.com/jsapi",data:{key:n.GOOGLE_API_KEY},dataType:"script",timeout:n.AJAX_TIMEOUT}).done(function(){google.load("picker","1",{callback:function(){e.chain()}}),w=!0}).fail(function(t){var n={code:t.status,message:t.statusText};h(n,e)})})}var g=!1,v={},b={},y=!1;l.addListener("onOfflineChanged",function(e){y=e});var x={profile:["https://www.googleapis.com/auth/userinfo.profile"],gdrive:["https://www.googleapis.com/auth/drive.install",s.gdriveFullAccess===!0?"https://www.googleapis.com/auth/drive":"https://www.googleapis.com/auth/drive.file"],blogger:["https://www.googleapis.com/auth/blogger"],picasa:["https://www.googleapis.com/auth/photos"]};b.refreshGdriveToken=function(e){var t=new c;d(t);var n=v[e];n&&n.setRefreshFlag(),p(t,"gdrive",e),t.enqueue()},b.upload=function(e,t,n,i,a,s,l,u){var m,g=new c;d(g),p(g,"gdrive",l),g.onRun(function(){var s="-------314159265358979323846",c="\r\n--"+s+"\r\n",u="\r\n--"+s+"--";a=a||"text/x-markdown";var d={title:n,mimeType:a};t&&(d.parents=[{kind:"drive#fileLink",id:t}]);var p="/upload/drive/v2/files",v="POST";e&&(p+="/"+e,v="PUT");var b={"Content-Type":'multipart/mixed; boundary="'+s+'"'},y=r.encodeBase64(i),x=[c,"Content-Type: application/json\r\n\r\n",JSON.stringify(d),c,"Content-Type: ",a,"\r\n","Content-Transfer-Encoding: base64\r\n","\r\n",y,u].join("");f(l,function(){var t=gapi.client.request({path:p,method:v,params:{uploadType:"multipart"},headers:b,body:x});t.execute(function(t){if(t&&t.id)return m=t,m.content=i,void g.chain();var n=t.error;void 0!==n&&void 0!==e&&(404===n.code?n='File ID "'+e+'" not found on Google Drive.|removePublish':412===n.code&&(o.removeItem(l+".gdrive.lastChangeId"),n='Conflict on file ID "'+e+'". Please restart the synchronization.')),h(n,g)})})}),g.onSuccess(function(){u(void 0,m)}),g.onError(function(e){u(e)}),g.enqueue()},b.rename=function(e,t,n,i){var r,o=new c;d(o),p(o,"gdrive",n),o.onRun(function(){var i={title:t};f(n,function(){var t=gapi.client.drive.files.patch({fileId:e,resource:i});t.execute(function(t){if(t&&t.id)return r=t,void o.chain();var n=t.error;void 0!==n&&void 0!==e&&404===n.code&&(n='File ID "'+e+'" not found on Google Drive.|removePublish'),h(n,o)})})}),o.onSuccess(function(){i(void 0,r)}),o.onError(function(e){i(e)}),o.enqueue()},b.checkChanges=function(e,t,n){var i=[],r=e||0,o=new c;d(o),p(o,"gdrive",t),o.onRun(function(){function e(){f(t,function(){var t;t=gapi.client.drive.changes.list(void 0===n?{startChangeId:r+1}:{pageToken:n}),t.execute(function(t){return t&&t.largestChangeId?(r=t.largestChangeId,n=t.nextPageToken,void 0!==t.items&&(i=i.concat(t.items)),void(void 0!==n?o.chain(e):o.chain())):void h(t.error,o)})})}var n;o.chain(e)}),o.onSuccess(function(){n(void 0,i,r)}),o.onError(function(e){n(e)}),o.enqueue()},b.downloadMetadata=function(e,i,r,o){var a=[],s=new c;d(s),o||p(s,"gdrive",i),s.onRun(function(){function r(){if(0===e.length)return void s.chain();var o=e[0],l={},c=v[i];c&&c.token&&(l.Authorization="Bearer "+c.token.access_token),t.ajax({url:"https://www.googleapis.com/drive/v2/files/"+o,headers:l,data:{key:n.GOOGLE_API_KEY},dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(t){a.push(t),e.shift(),s.chain(r)}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&(t='File ID "'+o+'" not found on Google Drive.'),h(t,s)})}s.chain(r)}),s.onSuccess(function(){r(void 0,a)}),s.onError(function(e){r(e)}),s.enqueue()},b.downloadContent=function(e,i,r,o){var a=[],s=new c;s.timeout=n.ASYNC_TASK_LONG_TIMEOUT,d(s),o||p(s,"gdrive",i),s.onRun(function(){function r(){if(0===e.length)return void s.chain();var o=e[0];a.push(o);var l;if("drive#file"==o.kind?l=o:"drive#change"==o.kind&&(l=o.file),!l)return e.shift(),void s.chain(r);var c=l.downloadUrl;0===l.mimeType.indexOf("application/vnd.google-apps.drive-sdk")&&(l.isRealtime=!0,c="https://www.googleapis.com/drive/v2/files/"+l.id+"/realtime");var u={},d=v[i];d&&d.token&&(u.Authorization="Bearer "+d.token.access_token),t.ajax({url:c,headers:u,data:{key:n.GOOGLE_API_KEY},dataType:l.isRealtime?"json":"text",timeout:n.AJAX_TIMEOUT}).done(function(t){l.content=l.isRealtime?t.data.value.content.value:t,e.shift(),s.chain(r)}).fail(function(e){var t={code:e.status,message:e.statusText};h(t,s)})}s.chain(r)}),s.onSuccess(function(){r(void 0,a)}),s.onError(function(e){r(e)}),s.enqueue()},b.uploadImg=function(e,i,r,o){var a,s="google.picasa0",l=new c;d(l),p(l,"picasa",s),l.onRun(function(){var o={Slug:e};e.match(/.jpe?g$/i)?o["Content-Type"]="image/jpeg":e.match(/.png$/i)?o["Content-Type"]="image/png":e.match(/.gif$/i)&&(o["Content-Type"]="image/gif");var c=v[s];c&&c.token&&(o.Authorization="Bearer "+c.token.access_token),t.ajax({url:n.PICASA_PROXY_URL+"upload/"+r,headers:o,data:i,processData:!1,dataType:"xml",timeout:n.AJAX_TIMEOUT,type:"POST"}).done(function(e){a=e,l.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};200==t.code&&(t.message=e.responseText),h(t,l)})}),l.onSuccess(function(){o(void 0,a)}),l.onError(function(e){o(e)}),l.enqueue()};var w=!1;return b.picker=function(e,i,o){function a(){void 0!==s&&(s.setVisible(!1),t(".modal-backdrop, .picker").remove())}var s,l=[],u=new c;u.timeout=n.ASYNC_TASK_LONG_TIMEOUT,d(u),"doc"==i||"folder"==i?p(u,"gdrive",o):(o="google.picasa0",p(u,"picasa",o)),m(u),u.onRun(function(){var e=v[o],c=new google.picker.PickerBuilder;c.setAppId(n.GOOGLE_DRIVE_APP_ID);var d;"doc"==i?(d=new google.picker.DocsView(google.picker.ViewId.DOCS),d.setParent("root"),d.setIncludeFolders(!0),d.setMimeTypes(["text/x-markdown","text/plain","application/octet-stream","application/vnd.google-apps.drive-sdk."+n.GOOGLE_DRIVE_APP_ID].join(",")),c.enableFeature(google.picker.Feature.NAV_HIDDEN),c.enableFeature(google.picker.Feature.MULTISELECT_ENABLED),c.addView(d),e&&e.token&&c.setOAuthToken(e.token.access_token)):"folder"==i?(d=new google.picker.DocsView(google.picker.ViewId.FOLDERS),d.setParent("root"),d.setIncludeFolders(!0),d.setSelectFolderEnabled(!0),d.setMimeTypes("application/vnd.google-apps.folder"),c.enableFeature(google.picker.Feature.NAV_HIDDEN),c.addView(d),e&&e.token&&c.setOAuthToken(e.token.access_token)):"img"==i&&(d=new google.picker.PhotosView,d.setType("flat"),c.addView(d),d=new google.picker.PhotosView,d.setType("ofuser"),c.addView(d),c.addView(google.picker.ViewId.PHOTO_UPLOAD),e&&e.token&&c.setOAuthToken(e.token.access_token)),c.setCallback(function(e){(e.action==google.picker.Action.PICKED||e.action==google.picker.Action.CANCEL)&&(e.action==google.picker.Action.PICKED&&(l=e.docs),a(),u.chain())}),s=c.build(),t(r.createBackdrop()).click(function(){a(),u.chain()}),s.setVisible(!0)}),u.onSuccess(function(){e(void 0,l)}),u.onError(function(t){a(),e(t)}),u.enqueue()},b.uploadBlogger=function(e,i,r,o,a,s,l,u,f){var m="google.blogger0",g=new c;d(g),p(g,"blogger",m),g.onRun(function(){function c(){var e="https://www.googleapis.com/blogger/v3/blogs/"+i+"/posts/",a={kind:"blogger#post",blog:{id:i},labels:o,title:l,content:u},s="POST";void 0!==r&&(e+=r,a.id=r,s="PUT"),t.ajax({url:e,data:JSON.stringify(a),headers:f,type:s,contentType:"application/json",dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){r=e.id,g.chain(d)}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&void 0!==r&&(t="Post "+r+" not found on Blogger.|removePublish"),h(t,g)})}function d(){var e="https://www.googleapis.com/blogger/v3/blogs/"+i+"/posts/"+r;a?e+="/revert":(e+="/publish",s&&(e+="?publishDate="+s.toISOString())),t.ajax({url:e,headers:f,type:"POST",dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(){g.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&(t="Post "+r+" not found on Blogger.|removePublish"),h(t,g)})}function p(){return void 0!==i?void g.chain(c):void t.ajax({url:"https://www.googleapis.com/blogger/v3/blogs/byurl",data:{url:e},headers:f,dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){i=e.id,g.chain(c)}).fail(function(t){var n={code:t.status,message:t.statusText};404===n.code&&(n='Blog "'+e+'" not found on Blogger.|removePublish'),h(n,g)})}var f={},b=v[m];b&&b.token&&(f.Authorization="Bearer "+b.token.access_token),g.chain(p)}),g.onSuccess(function(){f(void 0,i,r)}),g.onError(function(e){f(e)}),g.enqueue()},b.uploadBloggerPage=function(e,i,r,o,a,s,l,u){var f="google.blogger0",m=new c;d(m),p(m,"blogger",f),m.onRun(function(){function o(){var e="https://www.googleapis.com/blogger/v3/blogs/"+i+"/pages/",o={kind:"blogger#page",blog:{id:i},title:s,content:l},a="POST";void 0!==r&&(e+=r,o.id=r,a="PUT"),t.ajax({url:e,data:JSON.stringify(o),headers:c,type:a,contentType:"application/json",dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){r=e.id,m.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&void 0!==r&&(t="Page "+r+" not found on Blogger.|removePublish"),h(t,m)})}function a(){return void 0!==i?void m.chain(o):void t.ajax({url:"https://www.googleapis.com/blogger/v3/blogs/byurl",data:{url:e},headers:c,dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){i=e.id,m.chain(o)}).fail(function(t){var n={code:t.status,message:t.statusText};404===n.code&&(n='Blog "'+e+'" not found on Blogger.|removePublish'),h(n,m)})}var c={},u=v[f];u&&u.token&&(c.Authorization="Bearer "+u.token.access_token),m.chain(a)}),m.onSuccess(function(){u(void 0,i,r)}),m.onError(function(e){u(e)}),m.enqueue()},window.delayedFunction=void 0,window.runDelayedFunction=function(){void 0!==window.delayedFunction&&window.delayedFunction()},b}),define("text!html/dialogExportGdrive.html",[],function(){return'
        \n'}),define("text!html/dialogAutoSyncGdrive.html",[],function(){return'
        \n'}),define("providers/gdriveProviderBuilder",["jquery","underscore","constants","utils","storage","logger","classes/Provider","settings","eventMgr","fileMgr","editor","helpers/googleHelper","text!html/dialogExportGdrive.html","text!html/dialogAutoSyncGdrive.html"],function(e,t,n,i,r,o,a,s,l,c,u,d,p,f){return function(o,u,h){function m(e){return"sync."+o+"."+e}function g(e,t,n,r,o){o=o||"{}";var a={};return a.provider=y,a.id=e,a.etag=t,a.contentCRC=i.crc32(n),a.titleCRC=i.crc32(r),a.discussionListCRC=i.crc32(o),a.syncIndex=m(e),x===!0&&(a.content=n,a.title=r,a.discussionList=o),a}function v(e){d.downloadMetadata(e,b,function(e,n){e||d.downloadContent(n,b,function(e,n){if(!e){var i,r=[];t.each(n,function(e){var t,n=y.parseContent(e.content);if(e.isRealtime)l.onError("Real time synchronization is not supported anymore. Please use standard synchronization.");else{var o=g(e.id,e.etag,n.content,e.title,n.discussionListJSON);t={},t[o.syncIndex]=o}i=c.createFile(e.title,n.content,n.discussionListJSON,t),r.push(i)}),void 0!==i&&(l.onSyncImportSuccess(r,y),c.selectFile(i))}})})}var b="google.gdrive"+h,y=new a(o,u);y.defaultPublishFormat="template",y.exportPreferencesInputIds=[o+"-parentid"];var x="merge"==s.conflictMode;return y.importFiles=function(){d.picker(function(e,n){if(!e&&0!==n.length){var i=[];t.each(n,function(e){var t=m(e.id),n=c.getFileFromSyncIndex(t);return void 0!==n?void l.onError('"'+n.title+'" was already imported.'):void i.push(e.id)}),v(i)}},"doc",b)},y.exportFile=function(e,t,n,r,a){var s=i.getInputTextValue("#input-sync-export-"+o+"-fileid");if(s){var u=m(s),p=c.getFileFromSyncIndex(u);if(void 0!==p)return l.onError('File ID is already synchronized with "'+p.title+'".'),void a(!0)}var f=i.getInputTextValue("#input-sync-export-"+o+"-parentid"),h=y.serializeContent(n,r);d.upload(s,f,t,h,void 0,void 0,b,function(e,i){if(e)return void a(e);var o=g(i.id,i.etag,n,t,r);a(void 0,o)})},y.syncUp=function(e,t,n,i,r,o,a,s){if(a.contentCRC==t&&a.titleCRC==i&&a.discussionListCRC==o)return s(void 0,!1);if(a.isRealtime){var u=c.getFileFromSyncIndex(a.syncIndex);return u.removeSyncLocation(a),l.onSyncRemoved(u,a),l.onError("Real time synchronization is not supported anymore. Please use standard synchronization.")}var p=y.serializeContent(e,r);d.upload(a.id,void 0,n,p,void 0,a.etag,b,function(l,c){return l?void s(l,!0):(a.etag=c.etag,delete a.isRealtime,x===!0&&(a.content=e,a.title=n,a.discussionList=r),a.contentCRC=t,a.titleCRC=i,a.discussionListCRC=o,void s(void 0,!0))})},y.syncDown=function(e){var n=parseInt(r[b+".gdrive.lastChangeId"],10);d.checkChanges(n,b,function(n,o,a){if(n)return void e(n);var s=[];t.each(o,function(e){var t=m(e.fileId),n=c.getFileFromSyncIndex(t),i=n&&n.syncLocations[t];return i?(e.fileDesc=n,e.syncAttributes=i,e.deleted===!0?void s.push(e):void(i.etag!=e.file.etag&&s.push(e))):void 0}),d.downloadContent(s,b,function(t,n){function o(){if(0===n.length)return r[b+".gdrive.lastChangeId"]=a,e();var t=n.pop(),s=t.fileDesc,c=t.syncAttributes;if(t.deleted===!0)return l.onError('"'+s.title+'" has been removed from '+u+"."),s.removeSyncLocation(c),l.onSyncRemoved(s,c);var d=t.file,p=y.parseContent(d.content),f=p.content,h=d.title,m=p.discussionListJSON,g=p.discussionList,v=y.syncMerge(s,c,f,h,g,m);c.etag=d.etag,x===!0&&(c.content=f,c.title=h,c.discussionList=m),c.contentCRC=v.contentCRC,c.titleCRC=v.titleCRC,c.discussionListCRC=v.discussionListCRC,i.storeAttributes(c),setTimeout(o,5)}return t?void e(t):void setTimeout(o,5)})})},y.publish=function(e,t,n,i,r){var o="markdown"!=e.format?"text/html":void 0;d.upload(e.id,void 0,e.fileName||n,i,o,void 0,b,function(t,n){return t?void r(t):(e.id=n.id,void r())})},y.newPublishAttributes=function(e){var t={};return t.id=i.getInputTextValue("#input-publish-"+o+"-fileid"),t.fileName=i.getInputTextValue("#input-publish-"+o+"-filename"),e.isPropagationStopped()?void 0:t},y.setAutosyncDialogConfig=function(){var e=y.autosyncConfig;i.setInputRadio("radio-autosync-"+o+"-mode",e.mode||"off"),i.setInputValue("#input-autosync-"+o+"-parentid",e.parentId)},y.getAutosyncDialogConfig=function(){var e={};return e.mode=i.getInputRadio("radio-autosync-"+o+"-mode"),e.parentId=i.getInputTextValue("#input-autosync-"+o+"-parentid"),e},y.autosyncFile=function(e,t,n,i,r){var o=i.parentId;d.upload(void 0,o,e,t,void 0,void 0,b,function(i,o){if(i)return void r(i);var a=g(o.id,o.etag,t,e,n);r(void 0,a)})},y.isPublishEnabled=s.gdriveMultiAccount>h,l.addListener("onReady",function(){e(".submenu-sync-"+o).toggle(s.gdriveMultiAccount>h);var a=document.querySelector(".modal-upload-"+o);a&&(a.innerHTML=t.template(p,{providerId:o,providerName:u}));var y=document.querySelector(".modal-autosync-"+o);if(y&&(y.innerHTML=t.template(f,{providerId:o,providerName:u})),e(".action-export-"+o+"-choose-folder").click(function(){d.picker(function(t,n){t||0===n.length||(e(".modal-upload-"+o).modal(),i.setInputValue("#input-sync-export-"+o+"-parentid",n[0].id))},"folder",b)}),e(".action-autosync-"+o+"-choose-folder").click(function(){d.picker(function(t,n){t||0===n.length||(e(".modal-autosync-"+o).modal(),i.setInputValue("#input-autosync-"+o+"-parentid",n[0].id))},"folder",b)}),e(".action-remove-google-drive-state").click(function(){r.removeItem("gdrive.state")}),!(h>=s.gdriveMultiAccount)){var x=i.retrieveIgnoreError("gdrive.state"),w=r[b+".userId"];if(void 0!==x){if(w&&x.userId!=w)return void(h===s.gdriveMultiAccount-1&&(3===s.gdriveMultiAccount?(l.onError("None of your 3 Google Drive accounts is able to perform this request."),r.removeItem("gdrive.state")):e(".modal-add-google-drive-account").modal()));if(r.removeItem("gdrive.state"),"create"==x.action)d.upload(void 0,x.folderId,n.GDRIVE_DEFAULT_FILE_TITLE,s.defaultContent,void 0,void 0,b,function(e,t){if(!e){var n=g(t.id,t.etag,t.content,t.title),i={};i[n.syncIndex]=n;var r=c.createFile(t.title,t.content,void 0,i);c.selectFile(r),l.onMessage('"'+t.title+'" created successfully on '+u+".")}});else if("open"==x.action){var S=[];t.each(x.ids,function(e){var t=m(e),n=c.getFileFromSyncIndex(t);void 0!==n?n!==c.currentFile&&c.selectFile(n):S.push(e)}),v(S)}}}}),y}}),define("providers/gdriveProvider",["providers/gdriveProviderBuilder"],function(e){return e("gdrive","Google Drive",0)}),define("providers/gdrivesecProvider",["providers/gdriveProviderBuilder"],function(e){return e("gdrivesec","Google Drive (2nd account)",1)}),define("providers/gdriveterProvider",["providers/gdriveProviderBuilder"],function(e){return e("gdriveter","Google Drive (3rd account)",2)}),define("synchronizer",["jquery","underscore","utils","storage","eventMgr","fileSystem","fileMgr","classes/Provider","providers/dropboxProvider","providers/gdriveProvider","providers/gdrivesecProvider","providers/gdriveterProvider"],function(e,t,n,i,r,o,a,s){function l(e){function i(){function o(){if(0===s.length)return i();var t=s.pop();t.provider.syncUp(c,u,d,p,f,m,t,function(i,r){return r===!0&&(h=!0),i?e(i):(r&&n.storeAttributes(t),void o())})}if(0===r.length)return l(e);var a=r.pop(),s=t.values(a.syncLocations);if(0===s.length)return i();var c=a.content,u=n.crc32(c),d=a.title,p=n.crc32(d),f=a.discussionListJSON,m=n.crc32(f);o()}var r=[];h===!0?(h=!1,r=t.values(o),i()):e()}function c(e){function n(){if(0===i.length)return e();var t=i.pop();return p.hasSync(t)?void t.syncDown(function(t){return t?e(t):void n()}):n()}var i=t.values(f);n()}function u(e){function n(){function o(){if(0===s.length)return n();var t=s.pop();t.autosyncFile(a.title,a.content,a.discussionListJSON,t.autosyncConfig,function(t,n){return t?e(t):(a.addSyncLocation(n),r.onSyncExportSuccess(a,n),void o())})}if(0===i.length)return e();var a=i.pop(),s=t.filter(f,function(e){return"all"==e.autosyncConfig.mode});o()}var i=t.filter(o,function(e){return 0===t.size(e.syncLocations)});n()}function d(i){n.resetModalInputs();var r=n.retrieveIgnoreError(i.providerId+".exportPreferences");r&&t.each(i.exportPreferencesInputIds,function(e){var i=r[e];t.isBoolean(i)?n.setInputChecked("#input-sync-export-"+e,i):n.setInputValue("#input-sync-export-"+e,i)}),e(".modal-upload-"+i.providerId).modal()}var p={},f=t.chain(arguments).map(function(e){return e instanceof s&&[e.providerId,e]}).compact().object().value();!function(){var e={};t.each(o,function(t){n.retrieveIndexArray(t.fileIndex+".sync").forEach(function(o){try{var a=JSON.parse(i[o]);a.syncIndex=o;var s=f[a.provider];if(!s)throw new Error("Invalid provider ID: "+a.provider);a.provider=s,t.syncLocations[o]=a,e[o]=a}catch(l){r.onError(l),n.removeIndexFromArray(t.fileIndex+".sync",o)}})}),Object.keys(i).forEach(function(t){var n=t.match(/sync\.\S+/);n&&!e.hasOwnProperty(n[0])&&i.removeItem(t)})}(),t.each(f,function(e){e.autosyncConfig=n.retrieveIgnoreError(e.providerId+".autosyncConfig")||{}}),p.hasSync=function(e){return t.some(o,function(n){return t.some(n.syncLocations,function(t){return void 0===e||t.provider===e})})};var h=!1,m=!1;r.addListener("onOfflineChanged",function(e){m=e});var g=!1;return p.sync=function(){function e(e){return void 0!==e?(g=!1,r.onSyncRunning(!1),!0):!1}return g===!0||m===!0?!1:(g=!0,r.onSyncRunning(!0),h=!0,u(function(t){e(t)||c(function(t){e(t)||l(function(t){e(t)||(g=!1,r.onSyncRunning(!1),r.onSyncSuccess())})})}),!0)},r.addListener("onFileCreated",function(e){0===t.size(e.syncLocations)&&t.each(f,function(t){"new"==t.autosyncConfig.mode&&t.autosyncFile(e.title,e.content,e.discussionListJSON,t.autosyncConfig,function(t,n){t||(e.addSyncLocation(n),r.onSyncExportSuccess(e,n))})})}),r.addListener("onReady",function(){t.each(f,function(o){e(".action-sync-import-"+o.providerId).click(function(e){o.importFiles(e)}),e(".action-sync-export-dialog-"+o.providerId).click(function(){d(o)}),e(".action-autosync-dialog-"+o.providerId).click(function(){n.resetModalInputs(),o.setAutosyncDialogConfig(o),e(".modal-autosync-"+o.providerId).modal()}),e(".action-sync-export-"+o.providerId).click(function(e){var n=a.currentFile;o.exportFile(e,n.title,n.content,n.discussionListJSON,function(e,t){e||(n.addSyncLocation(t),r.onSyncExportSuccess(n,t))});var s={};t.each(o.exportPreferencesInputIds,function(e){var t=document.getElementById("input-sync-export-"+e);s[e]="checkbox"==t.type?t.checked:t.value}),i[o.providerId+".exportPreferences"]=JSON.stringify(s)}),e(".action-autosync-"+o.providerId).click(function(e){var t=o.getAutosyncDialogConfig(e);void 0!==t&&(i[o.providerId+".autosyncConfig"]=JSON.stringify(t),o.autosyncConfig=t)})})}),r.onSynchronizerCreated(p),p}),define("providers/downloadProvider",["jquery","constants","eventMgr","utils","fileMgr","classes/Provider","classes/AsyncTask"],function(e,t,n,i,r,o,a){var s=new o("download");return s.sharingAttributes=["url"],s.importPublic=function(n,i){var r,o,s=new a(!0);s.onRun(function(){var i=n.url,a=i.lastIndexOf("/");return-1===a?void s.error(new Error("Invalid URL parameter.")):(r=i.substring(a+1),void e.ajax({url:t.DOWNLOAD_PROXY_URL+"download?url="+i,type:"GET",dataType:"text",timeout:t.AJAX_TIMEOUT}).done(function(e){o=e,s.chain()}).fail(function(){s.error(new Error("Unable to access URL "+i))}))}),s.onSuccess(function(){i(void 0,r,o)}),s.onError(function(e){i(e)}),s.enqueue()},n.addListener("onReady",function(){e(".action-import-url").click(function(e){var t=i.getInputTextValue("#input-import-url",e);t&&s.importPublic({url:t},function(e,t,n){if(!e){var i=r.createFile(t,n);r.selectFile(i)}})})}),s}),define("helpers/githubHelper",["jquery","constants","core","utils","storage","logger","settings","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s,l){function c(n){n.onRun(function(){return m===!0?(p=!1,void n.error(new Error("Operation not available in offline mode.|stopPublish"))):p===!0?void n.chain():void e.ajax({url:"libs/github.js",dataType:"script",timeout:t.AJAX_TIMEOUT}).done(function(){p=!0,n.chain()}).fail(function(e){var t={error:e.status,message:e.statusText};d(t,n)})})}function u(n){var o,s;n.onRun(function(){function l(){i.redirectConfirm("You are being redirected to GitHub authorization page.",function(){n.chain(c)},function(){n.error(new Error("Operation canceled."))})}function c(){r.removeItem("githubCode");var e=a.githubFullAccess?"repo,gist":"public_repo,gist";o=i.popupWindow("html/github-oauth-client.html?client_id="+t.GITHUB_CLIENT_ID+"&scope="+e,"stackedit-github-oauth",960,600),o.focus(),s=setInterval(function(){if(o.closed===!0){if(clearInterval(s),o=void 0,s=void 0,h=r.githubCode,void 0===h)return void n.error(new Error(p));r.removeItem("githubCode"),n.chain(u)}},500)}function u(){e.getJSON(t.GATEKEEPER_URL+"authenticate/"+h,function(e){void 0!==e.token?(d=e.token,r.githubToken=d,f=new Github({token:d,auth:"oauth"}),n.chain()):n.error(new Error(p))})}if(void 0!==f)return void n.chain();var d=r.githubToken;if(void 0!==d)return f=new Github({token:d,auth:"oauth"}),void n.chain();var p="Failed to retrieve a token from GitHub.";n.timeout=t.ASYNC_TASK_LONG_TIMEOUT;var h;n.chain(l)}),n.onError(function(){void 0!==s&&clearInterval(s),void 0!==o&&o.close()})}function d(e,t){var i;if(e)if(o.error(e),"string"==typeof e)i=e;else{if(i="Could not publish on GitHub.",401===e.error||403===e.error)return f=void 0,r.removeItem("githubToken"),i="Access to GitHub account is not authorized.",void t.retry(new Error(i),1);e.error<=0&&(p=!1,f=void 0,n.setOffline(),i="|stopPublish")}t.error(new Error(i))}var p,f,h={},m=!1;return s.addListener("onOfflineChanged",function(e){m=e -}),h.upload=function(e,t,n,i,r,o,a){var s=new l;c(s),u(s),s.onRun(function(){function a(){var e=f.getUser();e.show(void 0,function(e,n){return e?void d(e,s):(t=n.login,void s.chain(l))})}function l(){var a=f.getRepo(t,e);a.write(n,i,r,o,function(e){return e?void d(e,s):void s.chain()})}s.chain(t?l:a)}),s.onSuccess(function(){a()}),s.onError(function(e){a(e)}),s.enqueue()},h.uploadGist=function(e,t,n,i,r,o){var a=new l;c(a),u(a),a.onRun(function(){var o=f.getGist(e),s={};s[t]={content:r};var l=o.update;void 0===e&&(l=o.create),l({description:i,"public":n,files:s},function(t,n){return t?(404===t.error&&void 0!==e&&(t="Gist "+e+" not found on GitHub.|removePublish"),void d(t,a)):(e=n.id,void a.chain())})}),a.onSuccess(function(){o(void 0,e)}),a.onError(function(e){o(e)}),a.enqueue()},h.downloadGist=function(e,t,n){var i=new l(!0);c(i);var r,o;i.onRun(function(){var n=new Github({}),a=n.getGist(e);a.read(function(n,a){if(n)return void i.error(new Error("Error trying to access Gist "+e+"."));r=a.description;var s=a.files[t];return void 0===s?void i.error(new Error("Gist "+e+' does not contain "'+t+'".')):(o=s.content,void i.chain())})}),i.onSuccess(function(){n(void 0,r,o)}),i.onError(function(e){n(e)}),i.enqueue()},h}),define("providers/gistProvider",["utils","classes/Provider","helpers/githubHelper"],function(e,t,n){var i=new t("gist","Gist");return i.publishPreferencesInputIds=["gist-public"],i.sharingAttributes=["gistId","filename"],i.publish=function(e,t,i,r,o){n.uploadGist(e.gistId,e.filename,e.isPublic,i,r,function(t,n){return t?void o(t):(e.gistId=n,void o())})},i.newPublishAttributes=function(t){var n={};return n.gistId=e.getInputTextValue("#input-publish-gist-id"),n.filename=e.getInputTextValue("#input-publish-filename",t),n.isPublic=e.getInputChecked("#input-publish-gist-public"),t.isPropagationStopped()?void 0:n},i.importPublic=function(e,t){n.downloadGist(e.gistId,e.filename,t)},i}),define("sharing",["jquery","underscore","constants","utils","eventMgr","fileMgr","classes/AsyncTask","classes/Provider","providers/downloadProvider","providers/gistProvider"],function(e,t,n,i,r,o,a,s){var l={},c=t.chain(arguments).map(function(e){return e instanceof s&&[e.providerId,e]}).compact().object().value(),u=!1;return r.addListener("onOfflineChanged",function(e){u=e}),l.createLink=function(e,i){var r=c[e.provider.providerId];if(void 0!==e.sharingLink||void 0===r||"markdown"!=e.format)return void i();var o=[n.MAIN_URL,"viewer#!provider=",r.providerId];t.each(r.sharingAttributes,function(t){o.push("&"),o.push(t),o.push("="),o.push(encodeURIComponent(e[t]))}),e.sharingLink=o.join(""),i()},r.addListener("onReady",function(){if(window.viewerMode!==!1){var n=i.getURLParameter("provider");void 0===n&&(n="download");var r=c[n];if(void 0!==r){var a={};t.each(r.sharingAttributes,function(e){var t=i.getURLParameter(e);return t?void(a[e]=t):void(a=void 0)}),void 0!==a&&(e("#preview-contents, .navbar .file-title-navbar").hide(),r.importPublic(a,function(t,n,i){if(e("#preview-contents, .navbar .file-title-navbar").show(),!t){var r=o.createFile(n,i,void 0,void 0,!0);o.selectFile(r)}}))}}}),l}),define("providers/bloggerProvider",["underscore","utils","classes/Provider","helpers/googleHelper"],function(e,t,n,i){var r=new n("blogger","Blogger");return r.defaultPublishFormat="html",r.publishPreferencesInputIds=["blogger-url"],r.publish=function(t,n,r,o,a){var s=t.labelList||[];n&&void 0!==n.tags&&(s=n.tags),e.isString(s)&&(s=e.compact(s.split(/[\s,]/)));var l=n&&n.published===!1,c=n&&n.date;i.uploadBlogger(t.blogUrl,t.blogId,t.postId,s,l,c,r,o,function(e,n,i){return e?void a(e):(t.blogId=n,t.postId=i,void a())})},r.newPublishAttributes=function(e){var n={},i=t.getInputTextValue("#input-publish-blogger-url",e);return void 0!==i&&(n.blogUrl=t.checkUrl(i)),n.postId=t.getInputTextValue("#input-publish-postid"),e.isPropagationStopped()?void 0:n},r}),define("providers/bloggerPageProvider",["underscore","utils","classes/Provider","helpers/googleHelper"],function(e,t,n,i){var r=new n("bloggerpage","Blogger Page");return r.defaultPublishFormat="html",r.publishPreferencesInputIds=["blogger-url"],r.publish=function(e,t,n,r,o){var a=t&&t.published===!1,s=t&&t.date;i.uploadBloggerPage(e.blogUrl,e.blogId,e.pageId,a,s,n,r,function(t,n,i){return t?void o(t):(e.blogId=n,e.pageId=i,void o())})},r.newPublishAttributes=function(e){var n={},i=t.getInputTextValue("#input-publish-blogger-url",e);return void 0!==i&&(n.blogUrl=t.checkUrl(i)),n.pageId=t.getInputTextValue("#input-publish-pageid"),e.isPropagationStopped()?void 0:n},r}),define("providers/githubProvider",["utils","classes/Provider","settings","helpers/githubHelper"],function(e,t,n,i){var r=new t("github","GitHub");return r.publishPreferencesInputIds=["github-reponame","github-username","github-branch"],r.publish=function(e,t,r,o,a){var s=n.commitMsg;i.upload(e.repository,e.username,e.branch,e.path,o,s,a)},r.newPublishAttributes=function(t){var n={};return n.repository=e.getInputTextValue("#input-publish-github-reponame",t),n.username=e.getInputTextValue("#input-publish-github-username"),n.branch=e.getInputTextValue("#input-publish-github-branch",t),n.path=e.getInputTextValue("#input-publish-file-path",t),t.isPropagationStopped()?void 0:n},r}),define("helpers/sshHelper",["jquery","constants","core","logger","eventMgr","settings","classes/AsyncTask"],function(e,t,n,i,r,o,a){function s(e){e.onRun(function(){return u===!0?void e.error(new Error("Operation not available in offline mode.|stopPublish")):void e.chain()})}function l(e,t){var r;e&&(i.error(e),"string"==typeof e?r="SSH error: "+e+".":(r="Could not publish on SSH server.",e.code<=0&&(n.setOffline(),r="|stopPublish"))),t.error(new Error(r))}var c={},u=!1;return r.addListener("onOfflineChanged",function(e){u=e}),c.upload=function(n,i,r,c,u,d,p,f){var h=new a;s(h),h.onRun(function(){var a=o.sshProxy+"upload",s={host:n,port:i,username:r,password:c,path:u,title:d,content:p};e.ajax({url:a,data:s,type:"POST",dataType:"json",timeout:t.AJAX_TIMEOUT}).done(function(e){return void 0===e.error?void h.chain():void l(e.error,h)}).fail(function(e){var t={code:e.status,message:e.statusText};l(t,h)})}),h.onSuccess(function(){f()}),h.onError(function(e){f(e)}),h.enqueue()},c}),define("providers/sshProvider",["utils","classes/Provider","helpers/sshHelper"],function(e,t,n){var i=new t("ssh","SSH server");return i.publishPreferencesInputIds=["ssh-host","ssh-port","ssh-username","ssh-password"],i.publish=function(e,t,i,r,o){n.upload(e.host,e.port,e.username,e.password,e.path,i,r,o)},i.newPublishAttributes=function(t){var n={};return n.host=e.getInputTextValue("#input-publish-ssh-host",t,/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/),n.port=e.getInputIntValue("#input-publish-ssh-port",void 0,0),n.username=e.getInputTextValue("#input-publish-ssh-username",t),n.password=e.getInputTextValue("#input-publish-ssh-password",t),n.path=e.getInputTextValue("#input-publish-file-path",t),t.isPropagationStopped()?void 0:n},i}),define("helpers/tumblrHelper",["jquery","constants","core","utils","storage","logger","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s){function l(e){e.onRun(function(){return f===!0?void e.error(new Error("Operation not available in offline mode.|stopPublish")):void e.chain()})}function c(n){var o,a;n.onRun(function(){function s(){e.getJSON(t.TUMBLR_PROXY_URL+"request_token",function(e){void 0!==e.oauth_token?(h=e,n.chain(l)):n.error(new Error(f))})}function l(){i.redirectConfirm("You are being redirected to Tumblr authorization page.",function(){n.chain(c)},function(){n.error(new Error("Operation canceled."))})}function c(){r.removeItem("tumblrVerifier"),o=i.popupWindow("html/tumblr-oauth-client.html?oauth_token="+h.oauth_token,"stackedit-tumblr-oauth",800,600),o.focus(),a=setInterval(function(){if(o.closed===!0){if(clearInterval(a),o=void 0,a=void 0,h.oauth_verifier=r.tumblrVerifier,void 0===h.oauth_verifier)return void n.error(new Error(f));r.removeItem("tumblrVerifier"),n.chain(u)}},500)}function u(){e.getJSON(t.TUMBLR_PROXY_URL+"access_token",h,function(e){void 0!==e.access_token&&void 0!==e.access_token_secret?(r.tumblrOauthParams=JSON.stringify(e),d=e,n.chain()):n.error(new Error(f))})}if(void 0!==d)return void n.chain();var p=r.tumblrOauthParams;if(void 0!==p)return d=JSON.parse(p),void n.chain();var f="Failed to retrieve a token from Tumblr.";n.timeout=t.ASYNC_TASK_LONG_TIMEOUT;var h;n.chain(s)}),n.onError(function(){void 0!==a&&clearInterval(a),void 0!==o&&o.close()})}function u(e,t){var i;if(e)if(o.error(e),"string"==typeof e)i=e;else{if(i="Could not publish on Tumblr.",401===e.code||403===e.code)return d=void 0,r.removeItem("tumblrOauthParams"),i="Access to Tumblr account is not authorized.",void t.retry(new Error(i),1);e.code<=0&&(n.setOffline(),i="|stopPublish")}t.error(new Error(i))}var d,p={},f=!1;return a.addListener("onOfflineChanged",function(e){f=e}),p.upload=function(n,i,r,o,a,p,f,h,m){var g=new s;l(g),c(g),g.onRun(function(){var s=e.extend({blog_hostname:n,post_id:i,tags:r,format:o,state:a,date:p,title:f,content:h},d);e.ajax({url:t.TUMBLR_PROXY_URL+"post",data:s,type:"POST",dataType:"json",timeout:t.AJAX_TIMEOUT}).done(function(e){i=e.id,g.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&void 0!==i&&(t="Post "+i+" not found on Tumblr.|removePublish"),u(t,g)})}),g.onSuccess(function(){m(void 0,i)}),g.onError(function(e){m(e)}),g.enqueue()},p}),define("providers/tumblrProvider",["underscore","settings","utils","classes/Provider","helpers/tumblrHelper"],function(e,t,n,i,r){var o=new i("tumblr","Tumblr");return o.publishPreferencesInputIds=["tumblr-hostname"],o.publish=function(n,i,o,a,s){var l=n.tags||[];i&&void 0!==i.tags&&(l=i.tags),e.isString(l)&&(l=e.compact(l.split(/[\s,]/)));var c=function(){if("html"==n.format)return"html";if("template"==n.format){var e=n.customTmpl||t.template;if(-1!==e.indexOf("documentHTML"))return"html"}return"markdown"}(),u=i&&i.published===!1?"draft":"published",d=i&&i.date;r.upload(n.blogHostname,n.postId,l.join(","),c,u,d,o,a,function(e,t){return e?void s(e):(n.postId=t,void s())})},o.newPublishAttributes=function(e){var t={};return t.blogHostname=n.getInputTextValue("#input-publish-tumblr-hostname",e,/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/),t.postId=n.getInputTextValue("#input-publish-postid"),e.isPropagationStopped()?void 0:t},o}),define("helpers/wordpressHelper",["jquery","constants","core","utils","storage","logger","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s){function l(e){e.onRun(function(){return f===!0?void e.error(new Error("Operation not available in offline mode.|stopPublish")):void e.chain()})}function c(n){var o,a;n.onRun(function(){function s(){i.redirectConfirm("You are being redirected to WordPress authorization page.",function(){n.chain(l)},function(){n.error(new Error("Operation canceled."))})}function l(){r.removeItem("wordpressCode"),o=i.popupWindow("html/wordpress-oauth-client.html?client_id="+t.WORDPRESS_CLIENT_ID,"stackedit-wordpress-oauth",960,600),o.focus(),a=setInterval(function(){if(o.closed===!0){if(clearInterval(a),o=void 0,a=void 0,p=r.wordpressCode,void 0===p)return void n.error(new Error(u));r.removeItem("wordpressCode"),n.chain(c)}},500)}function c(){e.getJSON(t.WORDPRESS_PROXY_URL+"authenticate/"+p,function(e){void 0!==e.token?(d=e.token,r.wordpressToken=d,n.chain()):n.error(new Error(u))})}if(d=r.wordpressToken,void 0!==d)return void n.chain();var u="Failed to retrieve a token from Wordpress.";n.timeout=t.ASYNC_TASK_LONG_TIMEOUT;var p;n.chain(s)}),n.onError(function(){void 0!==a&&clearInterval(a),void 0!==o&&o.close()})}function u(e,t){var i;if(e)if(o.error(e),"string"==typeof e)i=e;else{if(i="Could not publish on WordPress.",400===e.code&&"invalid_token"==e.message||401===e.code||403===e.code)return r.removeItem("wordpressToken"),i="Access to WordPress account is not authorized.",void t.retry(new Error(i),1);e.code<=0&&(n.setOffline(),i="|stopPublish")}t.error(new Error(i))}var d,p={},f=!1;return a.addListener("onOfflineChanged",function(e){f=e}),p.upload=function(n,i,r,o,a,p,f,h){var m=new s;l(m),c(m),m.onRun(function(){var s=t.WORDPRESS_PROXY_URL+"post",l={token:d,site:n,postId:i,tags:r,status:o,date:a,title:p,content:f};e.ajax({url:s,data:l,type:"POST",dataType:"json",timeout:t.AJAX_TIMEOUT}).done(function(e){if(e.body.ID)return i=e.body.ID,void m.chain();var t={code:e.code,message:e.body.error};404===t.code&&("unknown_blog"==t.message?t='Site "'+n+'" not found on WordPress.|removePublish':"unknown_post"==t.message&&(t="Post "+i+" not found on WordPress.|removePublish")),u(t,m)}).fail(function(e){var t={code:e.status,message:e.statusText};u(t,m)})}),m.onSuccess(function(){h(void 0,i)}),m.onError(function(e){h(e)}),m.enqueue()},p}),define("providers/wordpressProvider",["underscore","utils","classes/Provider","helpers/wordpressHelper"],function(e,t,n,i){var r=new n("wordpress","WordPress");return r.defaultPublishFormat="html",r.publishPreferencesInputIds=["wordpress-site"],r.publish=function(t,n,r,o,a){var s=t.tags||[];n&&void 0!==n.tags&&(s=n.tags);var l=n&&n.published===!1?"draft":"publish",c=n&&n.date;e.isString(s)&&(s=e.compact(s.split(/[\s,]/))),i.upload(t.site,t.postId,s.join(","),l,c,r,o,function(e,n){return e?void a(e):(t.postId=n,void a())})},r.newPublishAttributes=function(e){var n={};return n.site=t.getInputTextValue("#input-publish-wordpress-site",e,/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/),n.postId=t.getInputTextValue("#input-publish-postid"),e.isPropagationStopped()?void 0:n},r}),define("publisher",["jquery","underscore","constants","utils","storage","settings","eventMgr","fileSystem","fileMgr","sharing","classes/Provider","classes/AsyncTask","providers/bloggerProvider","providers/bloggerPageProvider","providers/dropboxProvider","providers/gistProvider","providers/githubProvider","providers/gdriveProvider","providers/gdrivesecProvider","providers/gdriveterProvider","providers/sshProvider","providers/tumblrProvider","providers/wordpressProvider"],function(e,t,n,i,r,o,a,s,l,c,u,d){function p(e,t,n){return void 0===t.format&&(t.format=i.getInputRadio("radio-publish-format"),"template"==t.format&&i.getInputChecked("#checkbox-publish-custom-template")&&(t.customTmpl=i.getInputValue("#textarea-publish-custom-template"))),"markdown"==t.format?e.content:"html"==t.format?n.withoutComments:v.applyTemplate(e,t,n)}function f(e,t){if(0===S.length)return void e(t);var n=S.pop(),i=p(y,n,x),r=(y.frontMatter||{}).title||y.title;n.provider.publish(n,y.frontMatter,r,i,function(i){if(void 0!==i){var r=i.toString();if(-1!==r.indexOf("|removePublish")&&(y.removePublishLocation(n),a.onPublishRemoved(y,n)),-1!==r.indexOf("|stopPublish"))return void e(i)}f(e,t||i)})}function h(e,n){var o;do o="publish."+i.randomString();while(t.has(r,o));n.publishIndex=o,e.addPublishLocation(n),a.onNewPublishSuccess(e,n)}function m(n){var r=n.defaultPublishFormat||"markdown";T=n,e(".publish-provider-name").text(n.providerName),e('.modal-publish [class*=" modal-publish-"]').hide().filter(".modal-publish-"+n.providerId).show(),i.resetModalInputs(),i.setInputRadio("radio-publish-format",r),i.setInputChecked("#checkbox-publish-custom-template",!1),i.setInputValue("#textarea-publish-custom-template",o.template);var a=i.retrieveIgnoreError(n.providerId+".publishPreferences");a&&(t.each(n.publishPreferencesInputIds,function(e){var n=a[e];t.isBoolean(n)?i.setInputChecked("#input-publish-"+e,n):i.setInputValue("#input-publish-"+e,n)}),i.setInputRadio("radio-publish-format",a.format),i.setInputChecked("#checkbox-publish-custom-template",void 0!==a.customTmpl),i.setInputValue("#textarea-publish-custom-template",a.customTmpl||o.template)),e(".modal-publish").modal()}function g(e){var n=T,i=n.newPublishAttributes(e);if(void 0!==i){var o=l.currentFile,a=p(o,i,w),s=o.frontMatter&&o.frontMatter.title||o.title;n.publish(i,o.frontMatter,s,a,function(e){void 0===e&&(i.provider=n,c.createLink(i,function(){h(o,i)}))});var u={};t.each(n.publishPreferencesInputIds,function(e){var t=document.getElementById("input-publish-"+e);u[e]="checkbox"==t.type?t.checked:t.value}),u.format=i.format,u.customTmpl=i.customTmpl,r[n.providerId+".publishPreferences"]=JSON.stringify(u)}}var v={},b=t.chain(arguments).map(function(e){return e instanceof u&&e.isPublishEnabled===!0&&[e.providerId,e]}).compact().object().value();!function(){var e={};t.each(s,function(t){i.retrieveIndexArray(t.fileIndex+".publish").forEach(function(n){try{var o=JSON.parse(r[n]);o.publishIndex=n;var s=b[o.provider];if(!s)throw new Error("Invalid provider ID: "+o.provider);o.provider=s,t.publishLocations[n]=o,e[n]=o}catch(l){a.onError(l),i.removeIndexFromArray(t.fileIndex+".publish",n)}})}),Object.keys(r).forEach(function(t){var n=t.match(/publish\.\S+/);n&&!e.hasOwnProperty(n[0])&&r.removeItem(t)})}(),v.applyTemplate=function(e,n,i){try{var r=n&&n.customTmpl||o.template;return t.template(r,{documentTitle:e.title,documentMarkdown:e.content,strippedDocumentMarkdown:e.content.substring(e.frontMatter?e.frontMatter._frontMatter.length:0),documentHTML:i.withoutComments,documentHTMLWithComments:i.withComments,frontMatter:e.frontMatter,publishAttributes:n})}catch(s){return a.onError(s),s.message}};var y,x,w,S=[];a.addListener("onPreviewFinished",function(e,t){w={withComments:e,withoutComments:t}});var C=!1;a.addListener("onOfflineChanged",function(e){C=e});var E=!1;v.publish=function(){E!==!0&&C!==!0&&(E=!0,a.onPublishRunning(!0),y=l.currentFile,x=w,S=t.values(y.publishLocations),f(function(e){E=!1,a.onPublishRunning(!1),void 0===e&&a.onPublishSuccess(y)}))};var T,k=["
      • ",' ',' <%= provider.providerName %>'," ","
      • "].join("");return a.addListener("onReady",function(){if(window.viewerMode===!1){var r=document.querySelector(".menu-panel .publish-on-provider-list"),s=t.reduce(b,function(e,n){return e+t.template(k,{provider:n})},"");r.innerHTML=s,t.each(b,function(t){e(r.querySelector(".action-init-publish-"+t.providerId)).click(function(){m(t)}),e(".action-publish-"+t.providerId).click(function(){m(t)})})}e(".action-process-publish").click(g);var c=e(".publish-custom-template-collapse").collapse({toggle:!1}),u=e("#textarea-publish-custom-template"),p=t.debounce(function(){c.collapse("template"==i.getInputRadio("radio-publish-format")?"show":"hide")},100);e("#checkbox-publish-custom-template").change(function(){u.prop("disabled",!this.checked)}),e("input:radio[name=radio-publish-format]").change(function(){p()}),e(".modal-publish").on("hidden.bs.modal",function(){c.collapse("hide")}),e(".action-download-md").click(function(){var e=l.currentFile.content,t=l.currentFile.title;i.saveAs(e,t+".md")}),e(".action-download-html").click(function(){var e=l.currentFile.title;i.saveAs(w.withoutComments,e+".html")}),e(".action-download-template").click(function(){var e=l.currentFile,t=v.applyTemplate(e,void 0,w);i.saveAs(t,e.title+(-1===o.template.indexOf("documentHTML")?".md":".html"))}),e(".action-download-pdf").click(function(){var e,t=l.currentFile,r=v.applyTemplate(t,{customTmpl:o.pdfTemplate},w),s=new d;s.onRun(function(){if(C===!0)return a.onError("Operation not available in offline mode."),void s.chain();var t=new XMLHttpRequest;t.open("POST",n.HTMLTOPDF_URL,!0),t.setRequestHeader("Content-type","application/x-www-form-urlencoded"),t.setRequestHeader("page-size",o.pdfPageSize),t.responseType="blob",t.onreadystatechange=function(){4==this.readyState&&(200==this.status?e=this.response:a.onError("Error when trying to generate PDF: "+this.status),s.chain())},t.send(r)}),s.onSuccess(function(){void 0!==e&&i.saveAs(e,l.currentFile.title+".pdf")}),s.enqueue()})}),a.onPublisherCreated(v),v}),define("providers/gplusProvider",["jquery","underscore","utils","storage","classes/Provider","eventMgr","helpers/googleHelper"],function(e,t,n,i,r,o,a){function s(e,n){var i;return t.find(e.thumbnails,function(e){var t=!1;return e.url.replace(/^(.*[\/=]s)\d.*?(\/[^\/]+)?$/,function(e,r,o){i=r+n+(o||""),t=!0}),t}),i}function l(){return c.thumbnails?(n.resetModalInputs(),e(".modal-import-image img").prop("src",s(c,128)),n.setInputValue("#input-import-image-title",c.name),f&&n.setInputValue("#input-import-image-size",f.size),void e(".modal-import-image").modal()):(o.onError("Image "+c.name+" is not accessible."),void u(!0))}var c,u,d="gplus",p=new r(d,"Google+"),f=n.retrieveIgnoreError(d+".importImagePreferences");return p.importImage=function(e){u=e,a.picker(function(t,n){return t||0===n.length?void e(t):(c=n[0],void l())},"img")},p.uploadImage=function(t,n,i){u=i,a.uploadImg(t,n,"default",function(n,r){return n||!r?void i(n):(c={name:t,thumbnails:[]},e(r).find("thumbnail").each(function(){c.thumbnails.push({url:e(this).attr("url")})}),void l())})},o.addListener("onReady",function(){e(".action-import-image").click(function(){var e=n.getInputIntValue("#input-import-image-size",void 0,0)||0,t=n.getInputTextValue("#input-import-image-title"),r=s(c,e);t&&(r+=' "'+t+'"'),u(void 0,r),f={},e&&(f.size=e),i[d+".importImagePreferences"]=JSON.stringify(f)})}),p}),define("mediaImporter",["jquery","underscore","constants","classes/Provider","core","eventMgr","providers/gplusProvider"],function(e,t,n,i,r,o){var a={},s=t.chain(arguments).map(function(e){return e instanceof i&&[e.providerId,e]}).compact().object().value();return o.addListener("onReady",function(){function i(i){var o=(i.dataTransfer||i.target).files,a=t.first(o);if(a.name.match(/.(jpe?g|png|gif)$/i)){i.stopPropagation(),i.preventDefault();var l=new FileReader;l.onload=function(t){return function(n){var i=new Uint8Array(n.target.result);s.gplus.uploadImage(t.name,i,function(t,n){if(!t){r.catchModal=!0,e("#wmd-image-button").click(),r.catchModal=!1;var i=r.insertLinkCallback;r.insertLinkCallback=void 0,i(n||null)}})}}(a);var c=a.slice(0,n.IMPORT_IMG_MAX_CONTENT_SIZE);l.readAsArrayBuffer(c)}}function o(e){e.stopPropagation(),e.preventDefault(),e.dataTransfer.dropEffect="copy"}t.each(s,function(t){e(".action-import-image-"+t.providerId).click(function(){var e=r.insertLinkCallback;r.insertLinkCallback=void 0,t.importImage(function(t,n){return t?void e(null):void e(n||null)})})}),e("#wmd-input").each(function(){this.addEventListener("dragover",o,!1),this.addEventListener("drop",i,!1)})}),a}),define("css/css",[],function(){if("undefined"==typeof window)return{load:function(e,t,n){n()}};var e=document.getElementsByTagName("head")[0],t=window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)/)||0,n=!1,i=!0;t[1]||t[7]?n=parseInt(t[1])<6||parseInt(t[7])<=9:t[2]?i=!1:t[4]&&(n=parseInt(t[4])<18);var r={};r.pluginBuilder="./css-builder";var o,a,s,l=function(){o=document.createElement("style"),e.appendChild(o),a=o.styleSheet||o.sheet},c=0,u=[],d=function(e){c++,32==c&&(l(),c=0),a.addImport(e),o.onload=p},p=function(){s();var e=u.shift();e&&(s=e[1],d(e[0]))},f=function(e,t){if(a&&a.addImport||l(),a&&a.addImport)s?u.push([e,t]):(d(e),s=t);else{o.textContent='@import "'+e+'";';var n=setInterval(function(){try{o.sheet.cssRules,clearInterval(n),t()}catch(e){}},10)}},h=function(t,n){var r=document.createElement("link");if(r.type="text/css",r.rel="stylesheet",i)r.onload=function(){r.onload=function(){},setTimeout(n,7)};else var o=setInterval(function(){for(var e=0;eo;++o)if(n=e.attributes[o],r=n.name,"class"!=r){if(i=t.attributes.getNamedItem(r),n.specified!=i.specified)return!1;if(n.specified&&n.nodeValue!==i.nodeValue)return!1}return!0}function p(e,t){for(var n,i=0,r=e.attributes.length;r>i;++i)if(n=e.attributes[i].name,(!t||!k.arrayContains(t,n))&&e.attributes[i].specified&&"class"!=n)return!0;return!1}function f(e,t){for(var n in t)if(t.hasOwnProperty(n)&&e[n]!==t[n])return!1;return!0}function h(e){var t;return e&&1==e.nodeType&&((t=e.parentNode)&&9==t.nodeType&&"on"==t.designMode||D(e)&&!D(e.parentNode))}function m(e){return(D(e)||1!=e.nodeType&&D(e.parentNode))&&!h(e)}function g(e){return e&&1==e.nodeType&&!N.test(T(e,"display"))}function v(e){if(0==e.data.length)return!0;if(L.test(e.data))return!1;var t=T(e.parentNode,"whiteSpace");switch(t){case"pre":case"pre-wrap":case"-moz-pre-wrap":return!1;case"pre-line":if(/[\r\n]/.test(e.data))return!1}return g(e.previousSibling)||g(e.nextSibling)}function b(e,t){return k.isCharacterDataNode(e)?0==t?!!e.previousSibling:t==e.length?!!e.nextSibling:!0:t>0&&ta;++a)"*"==i[a]?this.applyToAnyTagName=!0:this.tagNames.push(i[a].toLowerCase());else this.tagNames=[this.elementTagName]}function E(e,t,n){return new C(e,t,n)}e.requireModules(["WrappedSelection","WrappedRange"]);var T,k=e.dom,_="span",I=function(){function e(e,t,n){return t&&n?" ":""}return function(t,n){t.className&&(t.className=t.className.replace(new RegExp("(?:^|\\s)"+n+"(?:\\s|$)"),e))}}();"undefined"!=typeof window.getComputedStyle?T=function(e,t){return k.getWindow(e).getComputedStyle(e,null)[t]}:"undefined"!=typeof document.documentElement.currentStyle?T=function(e,t){return e.currentStyle[t]}:t.fail("No means of obtaining computed style properties found");var D;!function(){var e=document.createElement("div");D="boolean"==typeof e.isContentEditable?function(e){return e&&1==e.nodeType&&e.isContentEditable}:function(e){return e&&1==e.nodeType&&"false"!=e.contentEditable?"true"==e.contentEditable||D(e.parentNode):!1}}();var N=/^inline(-block|-table)?$/i,L=/[^\r\n\t\f \u200B]/,M=w(!1),A=w(!0);S.prototype={doMerge:function(){for(var e,t,n,i=[],r=0,o=this.textNodes.length;o>r;++r)e=this.textNodes[r],t=e.parentNode,i[r]=e.data,r&&(t.removeChild(e),t.hasChildNodes()||t.parentNode.removeChild(t));return this.firstTextNode.data=n=i.join(""),n},getLength:function(){for(var e=this.textNodes.length,t=0;e--;)t+=this.textNodes[e].length;return t},toString:function(){for(var e=[],t=0,n=this.textNodes.length;n>t;++t)e[t]="'"+this.textNodes[t].data+"'";return"[Merge("+e.join(",")+")]"}};var R=["elementTagName","ignoreWhiteSpace","applyToEditableOnly"],P={"class":"className"};C.prototype={elementTagName:_,elementProperties:{},ignoreWhiteSpace:!0,applyToEditableOnly:!1,hasClass:function(e){return 1==e.nodeType&&k.arrayContains(this.tagNames,e.tagName.toLowerCase())&&i(e,this.cssClass)},getSelfOrAncestorWithClass:function(e){for(;e;){if(this.hasClass(e,this.cssClass))return e;e=e.parentNode}return null},isModifiable:function(e){return!this.applyToEditableOnly||m(e)},isIgnorableWhiteSpaceNode:function(e){return this.ignoreWhiteSpace&&e&&3==e.nodeType&&v(e)},postApply:function(e,t,n){for(var i,r,o,a=e[0],s=e[e.length-1],l=[],c=a,u=s,d=0,p=s.length,f=0,h=e.length;h>f;++f)r=e[f],o=M(r,!n),o?(i||(i=new S(o),l.push(i)),i.textNodes.push(r),r===a&&(c=i.firstTextNode,d=c.length),r===s&&(u=i.firstTextNode,p=i.getLength())):i=null;var m=A(s,!n);if(m&&(i||(i=new S(s),l.push(i)),i.textNodes.push(m)),l.length){for(f=0,h=l.length;h>f;++f)l[f].doMerge();t.setStart(c,d),t.setEnd(u,p)}},createContainer:function(t){var n=t.createElement(this.elementTagName);return e.util.extend(n,this.elementProperties),r(n,this.cssClass),n},applyToTextNode:function(e){var t=e.parentNode;if(1==t.childNodes.length&&k.arrayContains(this.tagNames,t.tagName.toLowerCase()))r(t,this.cssClass);else{var n=this.createContainer(k.getDocument(e));e.parentNode.insertBefore(n,e),n.appendChild(e)}},isRemovable:function(e){return e.tagName.toLowerCase()==this.elementTagName&&a(e)==this.elementSortedClassName&&f(e,this.elementProperties)&&!p(e,this.attrExceptions)&&this.isModifiable(e)},undoToTextNode:function(e,t,n){if(!t.containsNode(n)){var i=t.cloneRange();i.selectNode(n),i.isPointInRange(t.endContainer,t.endOffset)&&(y(n,t.endContainer,t.endOffset,[t]),t.setEndAfter(n)),i.isPointInRange(t.startContainer,t.startOffset)&&(n=y(n,t.startContainer,t.startOffset,[t]))}this.isRemovable(n)?l(n):I(n,this.cssClass)},applyToRange:function(e){e.splitBoundaries();var t=u(e);if(t.length){for(var n,i=0,r=t.length;r>i;++i)n=t[i],this.isIgnorableWhiteSpaceNode(n)||this.getSelfOrAncestorWithClass(n)||!this.isModifiable(n)||this.applyToTextNode(n);e.setStart(t[0],0),n=t[t.length-1],e.setEnd(n,n.length),this.normalize&&this.postApply(t,e,!1)}},applyToSelection:function(t){t=t||window;var n,i=e.getSelection(t),r=i.getAllRanges();i.removeAllRanges();for(var o=r.length;o--;)n=r[o],this.applyToRange(n),i.addRange(n)},undoToRange:function(e){e.splitBoundaries();var t,n,i=u(e),r=i[i.length-1];if(i.length){for(var o=0,a=i.length;a>o;++o)t=i[o],n=this.getSelfOrAncestorWithClass(t),n&&this.isModifiable(t)&&this.undoToTextNode(t,e,n),e.setStart(i[0],0),e.setEnd(r,r.length);this.normalize&&this.postApply(i,e,!0)}},undoToSelection:function(t){t=t||window;var n,i=e.getSelection(t),r=i.getAllRanges(); -i.removeAllRanges();for(var o=0,a=r.length;a>o;++o)n=r[o],this.undoToRange(n),i.addRange(n)},getTextSelectedByRange:function(e,t){var n=t.cloneRange();n.selectNodeContents(e);var i=n.intersection(t),r=i?i.toString():"";return n.detach(),r},isAppliedToRange:function(e){if(e.collapsed)return!!this.getSelfOrAncestorWithClass(e.commonAncestorContainer);for(var t,n=e.getNodes([3]),i=0;t=n[i++];)if(!this.isIgnorableWhiteSpaceNode(t)&&c(e,t)&&this.isModifiable(t)&&!this.getSelfOrAncestorWithClass(t))return!1;return!0},isAppliedToSelection:function(t){t=t||window;for(var n=e.getSelection(t),i=n.getAllRanges(),r=i.length;r--;)if(!this.isAppliedToRange(i[r]))return!1;return!0},toggleRange:function(e){this.isAppliedToRange(e)?this.undoToRange(e):this.applyToRange(e)},toggleSelection:function(e){this.isAppliedToSelection(e)?this.undoToSelection(e):this.applyToSelection(e)},detach:function(){}},C.util={hasClass:i,addClass:r,removeClass:I,hasSameClasses:s,replaceWithOwnChildren:l,elementsHaveSameNonClassAttributes:d,elementHasNonClassAttributes:p,splitNodeAt:y,isEditableElement:D,isEditingHost:h,isEditable:m},e.CssClassApplier=C,e.createCssClassApplier=E}),define("rangy-cssclassapplier",function(){}),requirejs.config({waitSeconds:0,packages:[{name:"css",location:"bower-libs/require-css",main:"css"},{name:"less",location:"bower-libs/require-less",main:"less"}],paths:{jquery:"bower-libs/jquery/jquery",underscore:"bower-libs/underscore/underscore",crel:"bower-libs/crel/crel",jgrowl:"bower-libs/jgrowl/jquery.jgrowl",mousetrap:"bower-libs/mousetrap/mousetrap","mousetrap-record":"bower-libs/mousetrap/plugins/record/mousetrap-record",toMarkdown:"bower-libs/to-markdown/src/to-markdown",text:"bower-libs/requirejs-text/text",mathjax:"../libs/MathJax/MathJax.js?config=TeX-AMS_HTML",bootstrap:"bower-libs/bootstrap/dist/js/bootstrap",requirejs:"bower-libs/requirejs/require","google-code-prettify":"bower-libs/google-code-prettify/src/prettify",highlightjs:"libs/highlight/highlight.pack","jquery-waitforimages":"bower-libs/waitForImages/src/jquery.waitforimages","jquery-ui":"bower-libs/jquery-ui/ui/jquery-ui","jquery-ui-core":"bower-libs/jquery-ui/ui/jquery.ui.core","jquery-ui-widget":"bower-libs/jquery-ui/ui/jquery.ui.widget","jquery-ui-mouse":"bower-libs/jquery-ui/ui/jquery.ui.mouse","jquery-ui-draggable":"bower-libs/jquery-ui/ui/jquery.ui.draggable","jquery-ui-effect":"bower-libs/jquery-ui/ui/jquery.ui.effect","jquery-ui-effect-slide":"bower-libs/jquery-ui/ui/jquery.ui.effect-slide",FileSaver:"bower-libs/FileSaver/FileSaver",stacktrace:"bower-libs/stacktrace/stacktrace","requirejs-text":"bower-libs/requirejs-text/text","bootstrap-tour":"bower-libs/bootstrap-tour/build/js/bootstrap-tour",css_browser_selector:"bower-libs/css_browser_selector/css_browser_selector","pagedown-extra":"bower-libs/pagedown-extra/Markdown.Extra",pagedown:"libs/Markdown.Editor","require-css":"bower-libs/require-css/css",xregexp:"bower-libs/xregexp/xregexp-all",yaml:"bower-libs/yaml.js","yaml.js":"bower-libs/yaml.js","yaml-js":"bower-libs/yaml.js/bin/yaml",css:"bower-libs/require-css/css","css-builder":"bower-libs/require-css/css-builder",normalize:"bower-libs/require-css/normalize",prism:"bower-libs/prism/prism","prism-core":"bower-libs/prism/components/prism-core",MutationObservers:"bower-libs/MutationObservers/MutationObserver",WeakMap:"bower-libs/WeakMap/weakmap",rangy:"bower-libs/rangy/rangy-core","rangy-cssclassapplier":"bower-libs/rangy/rangy-cssclassapplier",diff_match_patch:"bower-libs/google-diff-match-patch-js/diff_match_patch",diff_match_patch_uncompressed:"bower-libs/google-diff-match-patch-js/diff_match_patch_uncompressed",jsondiffpatch:"bower-libs/jsondiffpatch/build/bundle",hammerjs:"bower-libs/hammerjs/hammer"},shim:{underscore:{exports:"_"},mathjax:["libs/mathjax_init"],jgrowl:{deps:["jquery"],exports:"jQuery.jGrowl"},diff_match_patch_uncompressed:{exports:"diff_match_patch"},jsondiffpatch:["diff_match_patch_uncompressed"],rangy:{exports:"rangy"},"rangy-cssclassapplier":["rangy"],mousetrap:{exports:"Mousetrap"},"yaml-js":{exports:"YAML"},"prism-core":{exports:"Prism"},"bower-libs/prism/components/prism-markup":["prism-core"],"libs/prism-latex":["prism-core"],"libs/prism-markdown":["bower-libs/prism/components/prism-markup","libs/prism-latex"],"bootstrap-record":["mousetrap"],toMarkdown:{deps:["jquery"],exports:"toMarkdown"},stacktrace:{exports:"printStackTrace"},FileSaver:{exports:"saveAs"},MutationObservers:["WeakMap"],highlightjs:{exports:"hljs"},"bootstrap-tour":{deps:["bootstrap"],exports:"Tour"},bootstrap:["jquery"],"jquery-waitforimages":["jquery"],pagedown:["libs/Markdown.Converter"],"pagedown-extra":["libs/Markdown.Converter"]}});try{var test="seLocalStorageCheck";localStorage.setItem(test,test),localStorage.removeItem(test);var obj={};Object.defineProperty(obj,"prop",{get:function(){},set:function(){}})}catch(e){throw alert("Your browser is not supported, sorry!"),e}window.viewerMode=/(^| )viewer($| )/.test(document.body.className),window.theme=localStorage.themeV3||"default";var themeModule="less!themes/"+window.theme;-1!==window.baseDir.indexOf("-min")&&(themeModule="css!themes/"+window.theme),require(["jquery","rangy","core","eventMgr","synchronizer","publisher","mediaImporter","css","rangy-cssclassapplier",themeModule],function(e,t,n,i){window.noStart||e(function(){t.init(),n.onReady(),window.applicationCache&&window.applicationCache.addEventListener("updateready",function(){window.applicationCache.status===window.applicationCache.UPDATEREADY&&(window.applicationCache.swapCache(),i.onMessage("New version available!\nJust refresh the page to upgrade."))},!1)})}),define("main",function(){}); \ No newline at end of file +}var S,C,E={},T=!1,k=!1,_=!0,I=0,D=!1,N=a.currentTime;E.setOffline=function(){N=a.currentTime,D===!1&&(D=!0,c.onOfflineChanged(!0))};var L,M,A;return E.initEditor=function(t){if(void 0!==A&&c.onFileClosed(A),A=t,void 0!==M)return i.undoMgr.init(),M.uiManager.setUndoRedoButtonStates();var n=new Markdown.Converter,r={_DoItalicsAndBold:function(e){return e=e.replace(/(\*\*|__)(?=\S)(.+?[*_]*)(?=\S)\1/g,"$2"),e=e.replace(/(\*|_)(?=\S)(.+?)(?=\S)\1/g,"$2")}};n.setOptions(r),M=new Markdown.Editor(n,void 0,{undoManager:i.undoMgr}),M.hooks.set("insertLinkDialog",function(t){return E.insertLinkCallback=t,a.resetModalInputs(),e(".modal-insert-link").modal(),!0}),M.hooks.set("insertImageDialog",function(t){return E.insertLinkCallback=t,E.catchModal?!0:(a.resetModalInputs(),e(".modal-insert-image").modal(),!0)}),c.onPagedownConfigure(M),M.hooks.chain("onPreviewRefresh",c.onAsyncPreview),M.run(),i.undoMgr.init(),e(".wmd-button-row li").addClass("btn btn-success").css("left",0).find("span").hide();var o=e(".wmd-button-group1");e("#wmd-bold-button").append(e('')).appendTo(o),e("#wmd-italic-button").append(e('')).appendTo(o),o=e(".wmd-button-group2"),e("#wmd-link-button").append(e('')).appendTo(o),e("#wmd-quote-button").append(e('')).appendTo(o),e("#wmd-code-button").append(e('')).appendTo(o),e("#wmd-image-button").append(e('')).appendTo(o),o=e(".wmd-button-group3"),e("#wmd-olist-button").append(e('')).appendTo(o),e("#wmd-ulist-button").append(e('')).appendTo(o),e("#wmd-heading-button").append(e('')).appendTo(o),e("#wmd-hr-button").append(e('')).appendTo(o),o=e(".wmd-button-group5"),e("#wmd-undo-button").append(e('')).appendTo(o),e("#wmd-redo-button").append(e('')).appendTo(o)},E.onReady=function(){document.body.className+=" "+l.editMode,document.body.innerHTML=window.viewerMode===!0?d:u,a.init(),e(window).on("offline",E.setOffline),e(window).on("online",b),navigator.onLine===!1&&E.setOffline(),e(document).mousemove(m).keypress(m),r.init(),i.init(),S=window.setInterval(function(){a.updateCurrentTime(),v(),(g()===!0||window.viewerMode===!0)&&(c.onPeriodicRun(),y())},1e3),c.onReady()},c.addListener("onReady",function(){function n(e){if(e=e||"default",u!=e){var t="less!themes/"+e;-1!==window.baseDir.indexOf("-min")&&(t="css!themes/"+e),requirejs.undef(t),require([t]),u=e}}function r(n,i){t.each(document.querySelectorAll(n),function(t){var n=e(t);n.tooltip({html:!0,container:n.parents(".modal-content"),placement:"right",trigger:"manual",title:i}).click(function(){var t=this;m&&m[0]===t||a.defer(function(){e(document).on("click.close-tooltip",function(){m&&m.tooltip("hide"),m=void 0,e(document).off("click.close-tooltip")}),m=e(t).tooltip("show")})})})}e(".modal").on("shown.bs.modal",function(){var t=e(this);setTimeout(function(){t.find(".btn:first").focus(),t.find("button:first").focus(),t.find("input:enabled:visible:first").focus()},50)}).on("hidden.bs.modal",function(){i.focus(),n(window.theme)}).keyup(function(t){13!=t.which||e(t.target).is("textarea")||e(this).find(".modal-footer a:last").click()}),e(".action-insert-link").click(function(t){var n=a.getInputTextValue(e("#input-insert-link"),t);void 0!==n&&(E.insertLinkCallback(n),E.insertLinkCallback=void 0)}),e(".action-insert-image").click(function(t){var n=a.getInputTextValue(e("#input-insert-image"),t);void 0!==n&&(E.insertLinkCallback(n),E.insertLinkCallback=void 0)}),e(".modal-insert-link, .modal-insert-image").on("hidden.bs.modal",function(){void 0!==E.insertLinkCallback&&(E.insertLinkCallback(null),E.insertLinkCallback=void 0)}),e(".action-load-settings").click(function(){x()}),e(".action-apply-settings").click(function(e){w(e),e.isPropagationStopped()||window.location.reload()}),e(".action-add-google-drive-account").click(function(){3!==l.gdriveMultiAccount&&(l.gdriveMultiAccount++,s.settings=JSON.stringify(l),window.location.reload())});var u=window.theme;L=e("#input-settings-theme"),L.on("change",function(){n(this.value)}),e(".action-import-docs-settings").click(function(){e("#input-file-import-docs-settings").click()});var d;e("#input-file-import-docs-settings").change(function(n){var i=(n.dataTransfer||n.target).files;e(".modal-settings").modal("hide"),t.each(i,function(t){var n=new FileReader;n.onload=function(t){return function(n){try{d=JSON.parse(n.target.result);var i=parseInt(d.version.match(/^v(\d+)$/)[1],10),r=parseInt(s.version.match(/^v(\d+)$/)[1],10);i>r?c.onError("Incompatible version. Please upgrade StackEdit."):e(".modal-import-docs-settings").modal("show")}catch(o){c.onError("Wrong format: "+t.name)}e("#input-file-import-docs-settings").val("")}}(t),n.readAsText(t)})}),e(".action-import-docs-settings-confirm").click(function(){s.clear();var e=/^file\.|^folder\.|^publish\.|^settings$|^sync\.|^google\.|^author\.|^themeV3$|^version$/;t.each(d,function(t,n){e.test(n)&&(s[n]=t)}),window.location.reload()}),e(".action-export-docs-settings").click(function(){a.saveAs(JSON.stringify(s),"StackEdit local storage.json")}),e(".action-default-settings").click(function(){s.removeItem("settings"),s.removeItem("theme"),l.dropboxFullAccess||s.removeItem("dropbox.lastChangeId"),window.location.reload()}),e(".action-app-reset").click(function(){s.clear(),window.location.reload()}),e(".action-reset-input").click(function(){a.resetModalInputs()});var m;if(r(".tooltip-lazy-rendering","Disable preview rendering while typing in order to offload CPU. Refresh preview after 500 ms of inactivity."),r(".tooltip-default-content",["Thanks for supporting StackEdit by adding a backlink in your documents!

        ",'NOTE: Backlinks in Stack Exchange Q/A are not welcome.'].join("")),r(".tooltip-shortcuts-extension",f),r(".tooltip-usercustom-extension",h),r(".tooltip-template",p),e("div.dropdown-menu").click(function(e){e.stopPropagation()}),e(".modal-non-unique").modal({backdrop:"static",keyboard:!1,show:!1}),t.each(document.querySelectorAll("img"),function(t){var n=e(t),i=n.data("stackeditSrc");i&&n.attr("src",window.baseDir+"/img/"+i)}),window.viewerMode===!1){var g=t.reduce(o.THEME_LIST,function(e,t,n){return e+'"},"");document.getElementById("input-settings-theme").innerHTML=g}e(".modal-header").append('Give your feedback ')}),E}),define("text!WELCOME.md",[],function(){return'Welcome to StackEdit! {#welcome}\n====================\n\n\nHello, I am your first Markdown document within **StackEdit**[^stackedit]. Don\'t delete me, I can be helpful. I can be recovered anyway in the `Utils` tab of the `Settings` dialog.\n\n----------\n\n\nDocuments\n--------------\n\n**StackEdit** stores your documents in your browser, which means all your documents are automatically saved locally and are accessible **offline!**\n\n> **Note:**\n\n> - StackEdit is accessible offline after the application has been loaded for the first time.\n> - Your local documents are not shared between different browsers or computers.\n> - Clearing your browser\'s data may **delete all your local documents!** Make sure your documents are backed up using **Google Drive** or **Dropbox** synchronization (see [ Synchronization](#synchronization) section).\n\n#### Create a document\n\nThe document panel is accessible using button in the navigation bar. You can create a new document by clicking the `New document` sub-menu in the document panel.\n\n#### Switch to another document\n\nAll your local documents are listed in the document panel. You can switch from one to another by clicking a document in the document panel or you can also use Ctrl+[ and Ctrl+] to toggle documents by most recently used.\n\n#### Rename a document\n\nYou can rename the current document by clicking the document title in the navigation bar.\n\n#### Delete a document\n\nYou can delete the current document by clicking the `Delete document` sub-menu in the document panel.\n\n#### Export a document\n\nYou can save the current document to a file using the `Export to disk` sub-menu from the menu panel.\n\n> **Tip:** See [ Publish a document](#publish-a-document) section for a description of the different output formats.\n\n\n----------\n\n\nSynchronization\n--------------------\n\n**StackEdit** can be combined with **Google Drive** and **Dropbox** to have your documents centralized in the *Cloud*. The synchronization mechanism will take care of uploading your modifications or downloading the latest version of your documents.\n\n> **Note:**\n\n> - Full access to **Google Drive** or **Dropbox** is required to be able to import any document in StackEdit. Permission restrictions can be configured in the settings.\n> - Imported documents are downloaded in your browser and are not transmitted to a server.\n> - If you experience problems saving your documents on Google Drive, check and optionally disable browser extensions, such as Disconnect.\n\n#### Open a document\n\nYou can open a document from **Google Drive** or the **Dropbox** by opening the `Synchronize` sub-menu and by clicking `Open from...`. Once opened, any modification in your document will be automatically synchronized with the **Google Drive** / **Dropbox** file.\n\n#### Save a document\n\nYou can save any document by opening the `Synchronize` sub-menu and by clicking `Save on...`. Even if your document is already synchronized with **Google Drive** or **Dropbox**, you can export it to a another location. **StackEdit** can synchronize one document with multiple locations.\n\n#### Synchronize a document\n\nOnce your document is linked to a **Google Drive** or a **Dropbox** file, **StackEdit** will periodically (every 3 minutes) synchronize it by downloading/uploading any modification. Any conflict will be detected, and a local copy of your document will be created as a backup if necessary.\n\nIf you just have modified your document and you want to force the synchronization, click the button in the navigation bar.\n\n> **Note:** The button is disabled when you have no document to synchronize.\n\n#### Manage document synchronization\n\nSince one document can be synchronized with multiple locations, you can list and manage synchronized locations by clicking `Manage synchronization` in the `Synchronize` sub-menu. This will let you remove synchronization locations that are associated to your document.\n\n> **Note:** If you delete the file from **Google Drive** or from **Dropbox**, the document will no longer be synchronized with that location.\n\n----------\n\n\nPublication\n--------------\n\nOnce you are happy with your document, you can publish it on different websites directly from **StackEdit**. As for now, **StackEdit** can publish on **Blogger**, **Dropbox**, **Gist**, **GitHub**, **Google Drive**, **Tumblr**, **WordPress** and on any SSH server.\n\n#### Publish a document\n\nYou can publish your document by opening the `Publish` sub-menu and by choosing a website. In the dialog box, you can choose the publication format:\n\n- Markdown, to publish the Markdown text on a website that can interpret it (**GitHub** for example),\n- HTML, to publish the document converted into HTML (on a blog for example),\n- Template, to have a full control of the output.\n\n> **Note:** The default template is a simple webpage wrapping your document in HTML format. You can customize it in the `Advanced` tab of the `Settings` dialog.\n\n#### Update a publication\n\nAfter publishing, **StackEdit** will keep your document linked to that publication which makes it easy for you to update it. Once you have modified your document and you want to update your publication, click on the button in the navigation bar.\n\n> **Note:** The button is disabled when your document has not been published yet.\n\n#### Manage document publication\n\nSince one document can be published on multiple locations, you can list and manage publish locations by clicking `Manage publication` in the menu. This will let you remove publication locations that are associated to your document.\n\n> **Note:** In some cases, if the file has been removed from the website or the blog, the document will no longer be published on that location.\n\n----------\n\n\nMarkdown Extra\n--------------------\n\n**StackEdit** supports **Markdown Extra**, which extends **Markdown** syntax with some nice features.\n\n> **Tip:** You can disable any **Markdown Extra** feature in the `Extensions` tab of the `Settings` dialog.\n\n\n### Tables\n\n**Markdown Extra** has a special syntax for tables:\n\nItem | Value\n--- | ---\nComputer | $1600\nPhone | $12\nPipe | $1\n\nYou can specify column alignment with one or two colons:\n\n| Item | Value | Qty |\n| :--- | ---: | :---: |\n| Computer | $1600 | 5 |\n| Phone | $12 | 12 |\n| Pipe | $1 | 234 |\n\n\n### Definition Lists\n\n**Markdown Extra** has a special syntax for definition lists too:\n\nTerm 1\nTerm 2\n: Definition A\n: Definition B\n\nTerm 3\n\n: Definition C\n\n: Definition D\n\n > part of definition D\n\n\n### Fenced code blocks\n\nGitHub\'s fenced code blocks[^gfm] are also supported with **Prettify** syntax highlighting:\n\n```\n// Foo\nvar bar = 0;\n```\n\n> **Tip:** To use **Highlight.js** instead of **Prettify**, just configure the `Markdown Extra` extension in the `Settings` dialog.\n\n\n### Footnotes\n\nYou can create footnotes like this[^footnote].\n\n [^footnote]: Here is the *text* of the **footnote**.\n\n\n### SmartyPants\n\nSmartyPants converts ASCII punctuation characters into "smart" typographic punctuation HTML entities. For example:\n\n| | ASCII | HTML |\n---|---|---\n| Single backticks | `\'Isn\'t this fun?\'` | \'Isn\'t this fun?\' |\n| Quotes | `"Isn\'t this fun?"` | "Isn\'t this fun?" |\n| Dashes | `-- is en-dash, --- is em-dash` | -- is en-dash, --- is em-dash |\n\n\n### Table of contents\n\nYou can insert a table of contents using the marker `[TOC]`:\n\n[TOC]\n\n\n### MathJax\n\nYou can render *LaTeX* mathematical expressions using **MathJax**, as on [math.stackexchange.com][1]:\n\nThe *Gamma function* satisfying $\\Gamma(n) = (n-1)!\\quad\\forall n\\in\\mathbb N$ is via the Euler integral\n\n$$\n\\Gamma(z) = \\int_0^\\infty t^{z-1}e^{-t}dt\\,.\n$$\n\n> **Tip:** Make sure you include **MathJax** into your publications to render mathematical expression correctly. Your page/template should include something like:\n\n```\n\n```\n\n> **NOTE:** You can find more information:\n\n> - about **Markdown** syntax [here][2],\n> - about **Markdown Extra** extension [here][3],\n> - about **LaTeX** mathematical expressions [here][4],\n> - about **Prettify** syntax highlighting [here][5],\n> - about **Highlight.js** syntax highlighting [here][6].\n\n [^stackedit]: [StackEdit](https://stackedit.io/) is a full-featured, open-source Markdown editor based on PageDown, the Markdown library used by Stack Overflow and the other Stack Exchange sites.\n\n [^gfm]: **GitHub Flavored Markdown** (GFM) is supported by StackEdit.\n\n\n [1]: http://math.stackexchange.com/\n [2]: http://daringfireball.net/projects/markdown/syntax "Markdown"\n [3]: https://github.com/jmcmanus/pagedown-extra "Pagedown Extra"\n [4]: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference\n [5]: https://code.google.com/p/google-code-prettify/\n [6]: http://highlightjs.org/\n'}),define("fileMgr",["jquery","underscore","constants","core","utils","storage","settings","eventMgr","fileSystem","classes/FileDescriptor","text!WELCOME.md"],function(e,t,n,i,r,o,a,s,l,c,u){var d={};return d.currentFile=void 0,d.selectFile=function(r){if(r=r||d.currentFile,void 0===r){var o=t.size(l);r=0===o?d.createFile(n.WELCOME_DOCUMENT_TITLE,u):t.max(l,function(e){return e.selectTime||0})}d.currentFile!==r&&(d.currentFile=r,r.selectTime=(new Date).getTime(),s.onFileSelected(r),e(".action-edit-document").toggleClass("hide",r.fileIndex!=n.TEMPORARY_FILE_INDEX)),i.initEditor(r)},d.createFile=function(e,i,u,d,p){if(i=void 0!==i?i:a.defaultContent,!e){e=n.DEFAULT_FILE_TITLE;for(var f=2,h=function(t){return t.title==e};t.some(l,h);)e=n.DEFAULT_FILE_TITLE+f++}var m=n.TEMPORARY_FILE_INDEX;if(!p)do m="file."+r.randomString();while(t.has(l,m));d=d||{};var g=t.reduce(d,function(e,t){return r.storeAttributes(t),e+t.syncIndex+";"},";");o[m+".title"]=e,o[m+".content"]=i,o[m+".sync"]=g,o[m+".publish"]=";";var v=new c(m,e,d);return u&&(v.discussionListJSON=u),p||(r.appendIndexToArray("file.list",m),l[m]=v,s.onFileCreated(v)),v},d.deleteFile=function(e){e=e||d.currentFile,e.folder&&(e.folder.removeFile(e),s.onFoldersChanged()),r.removeIndexFromArray("file.list",e.fileIndex),delete l[e.fileIndex],d.currentFile===e&&(d.currentFile=void 0,d.selectFile()),s.onFileDeleted(e)},d.getFileFromSyncIndex=function(e){return t.find(l,function(n){return t.has(n.syncLocations,e)})},d.getFileFromPublishIndex=function(e){return t.find(l,function(n){return t.has(n.publishLocations,e)})},s.addListener("onReady",function(){function t(){o.addClass("hide"),r.removeClass("hide");var t=e.trim(o.val()),n=d.currentFile;t&&t!=n.title&&(n.title=t,s.onTitleChanged(n)),o.val(n.title),i.focus()}var i=e("#wmd-input");d.selectFile();var r=e(".file-title-navbar"),o=e(".input-file-title");e(".action-create-file").click(function(){setTimeout(function(){var e=d.createFile();d.selectFile(e),r.click()},400)}),e(".action-remove-file-confirm").click(function(){e(".modal-remove-file-confirm").modal("show")}),e(".action-remove-file").click(function(){d.deleteFile()}),r.click(function(){if(window.viewerMode!==!0){r.addClass("hide");var e=o.removeClass("hide");setTimeout(function(){e.focus().get(0).select()},10)}}),o.blur(function(){t()}).keyup(function(e){13==e.keyCode&&t(),27==e.keyCode&&(o.val(""),t())}),e(".action-open-stackedit").click(function(){window.location.href="."}),e(".action-edit-document").click(function(){var e=i.val(),t=d.currentFile.title,n=d.createFile(t,e);d.selectFile(n),window.location.href="."}),e(".action-welcome-file").click(function(){var e=d.createFile(n.WELCOME_DOCUMENT_TITLE,u);d.selectFile(e)})}),s.onFileMgrCreated(d),d}),define("classes/Provider",["underscore","utils","settings","eventMgr","fileMgr","editor","diff_match_patch_uncompressed","jsondiffpatch"],function(e,t,n,i,r,o,a,s){function l(e,t){this.providerId=e,this.providerName=t,this.isPublishEnabled=!0}l.prototype.parseDiscussionList=function(t){try{var n=JSON.parse(t);return e.each(n,function(t,n){if(t.discussionIndex!=n||!e.isNumber(t.selectionStart)||!e.isNumber(t.selectionEnd))throw"invalid";t.commentList&&t.commentList.forEach(function(t){if(t.author&&!e.isString(t.author)||!e.isString(t.content))throw"invalid"})}),n}catch(i){}},l.prototype.serializeContent=function(e,t){return t.length>2?e+"":e},l.prototype.parseContent=function(e){var t,n="{}",i=/$/.exec(e);return i&&(t=this.parseDiscussionList(i[1]))&&(e=e.substring(0,i.index),n=i[1]),{content:e,discussionList:t||{},discussionListJSON:n}};var c=new a;c.Match_Threshold=0,c.Patch_DeleteThreshold=0;var u=s.create({objectHash:function(e){return JSON.stringify(e)},textDiff:{minLength:9999999}}),d="merge"==n.conflictMode;return l.prototype.syncMerge=function(n,a,s,l,p,f){function h(e){function t(){(i[1]||r[1])&&(i[1]&&r[1]?(i[1]="⧸⧸"+i[1]+"⧸⧸",r[1]+="⧸⧸",n.push(i),n.push(r)):n.push([0,i[1]+r[1]]),i=[-1,""],r=[1,""])}var n=[],i=[-1,""],r=[1,""],o=20;return e.forEach(function(a,s){function l(){return 0===s||s===e.length-1}var c=a[0],u=a[1];if(0===c)if(l()||u.length>o){if(i[1]||r[1]){var d=/\s/.exec(u);if(d){var p=d.index,f=u.substring(0,p);u=u.substring(p),i[1]+=f,r[1]+=f}}if(u){for(var h=u.length;h&&/\S/.test(u[h-1]);)h--;var m=u.substring(h);u=u.substring(0,h),l()||u.length>o?(t(),n.push([0,u])):(i[1]+=u,r[1]+=u),i[1]+=m,r[1]+=m}}else i[1]+=u,r[1]+=u;else-1===c?i[1]+=u:1===c&&(r[1]+=u)}),i[1]==r[1]?n.push([0,r[1]]):t(),n}var m=n.content,g=n.title,v=n.discussionListJSON,b=n.discussionList,y=t.crc32(m),x=t.crc32(g),w=t.crc32(v),S=t.crc32(s),C=t.crc32(l),E=t.crc32(f),T=a.contentCRC!=y,k=a.contentCRC!=S,_=m!=s&&k,I=_&&T;a.titleCRC=a.titleCRC||x;var D,N,L=a.titleCRC!=x,M=a.titleCRC!=C,A=g!=l&&M,R=A&&L,P=a.discussionListCRC!=w,F=a.discussionListCRC!=E,O=v!=f&&F,B=O&&P,j=[],$=s,G=l,q=p,H=!1,U=!1,z=!1;if(!d&&(I||R||B)||I&&void 0===a.content||R&&void 0===a.title||B&&void 0===a.discussionList)r.createFile(g+" (backup)",m,v),i.onMessage('Conflict detected on "'+g+'". A backup has been created locally.');else{if(I){var V=a.content;D=c.diff_main(V,m),c.diff_cleanupSemantic(D),N=c.patch_make(V,D);var W=c.patch_apply(N,s);if($=W[0],!W[1].every(e.identity)){D=c.diff_main(m,$),D=h(D),$="";var Q;D.forEach(function(e){var t=e[0],n=e[1];0===t||Q?0===t&&Q&&(Q.selectionEnd=$.length,j.push(Q),Q=void 0):Q={selectionStart:$.length,type:"conflict"},$+=n}),Q&&(Q.selectionEnd=$.length,j.push(Q))}}_&&(P&&(H=!0),F?U=!0:(H=!0,q=b)),B&&(z=!0),R&&(N=c.patch_make(a.title,g),G=c.patch_apply(N,l)[0])}var X;if(_){var K=[];r.currentFile===n&&(X={selectionStart:o.selectionMgr.selectionStart,selectionEnd:o.selectionMgr.selectionEnd},K.push(X),n.newDiscussion&&K.push(n.newDiscussion)),H&&(K=K.concat(e.values(b))),O|=o.adjustCommentOffsets(m,$,K)}if(U){var J=e.values(p);o.adjustCommentOffsets(s,$,J)}if(z){var Y=JSON.parse(a.discussionList);D=u.diff(Y,b),u.patch(p,D),e.each(p,function(e,t){e||delete p[t]})}return j.length&&(O=!0,j.forEach(function(n){var i;do i=t.randomString()+t.randomString();while(e.has(q,i));n.discussionIndex=i,q[i]=n})),A&&(n.title=G,i.onTitleChanged(n),i.onMessage('"'+g+'" has been renamed to "'+G+'" on '+this.providerName+".")),(_||O)&&o.watcher.noWatch(e.bind(function(){if(_&&(r.currentFile===n&&(o.setValueNoWatch($),X&&o.selectionMgr.setSelectionStartEnd(X.selectionStart,X.selectionEnd)),n.content=$,i.onContentChanged(n,$)),O){n.discussionList=q;var t=u.diff(b,q),a=!1;e.each(t,function(t,r){e.isArray(t)?1===t.length?i.onDiscussionCreated(n,q[r]):i.onDiscussionRemoved(n,b[r]):a=!0}),a&&i.onCommentsChanged(n)}o.undoMgr.currentMode="sync",o.undoMgr.saveState(),i.onMessage('"'+l+'" has been updated from '+this.providerName+"."),j.length&&i.onMessage('"'+l+'" has conflicts that you have to review.')},this)),{contentCRC:S,titleCRC:C,discussionListCRC:E}},l}),define("classes/AsyncTask",["underscore","constants","utils","eventMgr"],function(e,t,n,i){function r(e){this.finished=!1,this.timeout=t.ASYNC_TASK_DEFAULT_TIMEOUT,this.retryCounter=0,this.runCallbacks=[],this.successCallbacks=[],this.errorCallbacks=[],this.force=e}function o(){if(c===!0)return void(l+u.timeout=t)return void this.error(e);var i=1e3*Math.pow(2,this.retryCounter++);l=n.currentTime+i,c=!1,o()}},r.prototype.enqueue=function(){s.push(this),o()};var u,d=!1,p=!1;return i.addListener("onUserActive",function(){p=!0}),i.addListener("onPeriodicRun",o),r}),define("helpers/dropboxHelper",["jquery","underscore","constants","core","utils","storage","logger","settings","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s,l,c){function u(t){t.onRun(function(){return v===!0?(h=void 0,void t.error(new Error("Operation not available in offline mode.|stopPublish"))):void 0!==h?void t.chain():void e.ajax({url:"libs/dropbox.min.js",dataType:"script",timeout:n.AJAX_TIMEOUT}).done(function(){h=new Dropbox.Client({key:s.dropboxFullAccess===!0?n.DROPBOX_APP_KEY:n.DROPBOX_RESTRICTED_APP_KEY,secret:s.dropboxFullAccess===!0?n.DROPBOX_APP_SECRET:n.DROPBOX_RESTRICTED_APP_SECRET}),h.authDriver(new Dropbox.AuthDriver.Popup({receiverUrl:n.BASE_URL+"html/dropbox-oauth-receiver.html",rememberUser:!0})),t.chain()}).fail(function(e){var n={status:e.status,responseText:e.statusText};p(n,t)})})}function d(e){e.onRun(function(){function t(){r.redirectConfirm("You are being redirected to Dropbox authorization page.",function(){e.chain(i)},function(){e.error(new Error("Operation canceled."))})}function i(){o===!1?e.timeout=n.ASYNC_TASK_LONG_TIMEOUT:h.reset(),h.authenticate({interactive:!o},function(n,i){return i.isAuthenticated()===!0?(m=!0,void e.chain()):o===!0?(o=!1,void e.chain(t)):void e.error(new Error("Access to Dropbox account is not authorized."))})}if(m===!0)return void e.chain();var o=!0;e.chain(i)})}function p(e,n){var r=!0;if(e)if(a.error(e),"string"==typeof e)r=e;else{if(r="Dropbox error ("+e.status+": "+e.responseText+").",401===e.status||403===e.status)return m=!1,r="Access to Dropbox account is not authorized.",void n.retry(new Error(r),1);if(400===e.status&&-1!==e.responseText.indexOf("oauth_nonce"))return t.each(t.keys(o),function(e){0===e.indexOf("dropbox-auth")&&o.removeItem(e)}),m=!1,void n.retry(new Error(r),1);e.status<=0&&(h=void 0,m=!1,i.setOffline(),r="|stopPublish")}n.error(new Error(r))}function f(t){t.onRun(function(){function i(){r.redirectConfirm("You are being redirected to Dropbox Chooser page.",function(){t.chain()},function(){t.error(new Error("Operation canceled."))})}return b===!0?void t.chain():void e.ajax({url:"https://www.dropbox.com/static/api/1/dropbox.js",dataType:"script",timeout:n.AJAX_TIMEOUT}).done(function(){b=!0,t.chain(i)}).fail(function(e){var n={status:e.status,responseText:e.statusText};p(n,t)})})}var h,m=!1,g={},v=!1;l.addListener("onOfflineChanged",function(e){v=e}),g.upload=function(e,t,n){var i,r=new c;u(r),d(r),r.onRun(function(){h.writeFile(e,t,function(t,n){return t?(400===t.status&&(t='Could not upload document into path "'+e+'".'),void p(t,r)):(i=n,void r.chain())})}),r.onSuccess(function(){n(void 0,i)}),r.onError(function(e){n(e)}),r.enqueue()},g.checkChanges=function(e,t){var n=[],i=e||0,r=new c;u(r),d(r),r.onRun(function(){function e(){h.pullChanges(i,function(t,o){return t?void p(t,r):(i=o.cursor(),void 0!==o.changes&&(n=n.concat(o.changes)),void(o.shouldPullAgain?r.chain(e):r.chain()))})}r.chain(e)}),r.onSuccess(function(){t(void 0,n,i)}),r.onError(function(e){t(e)}),r.enqueue()},g.downloadMetadata=function(e,t){var n=[],i=new c;u(i),d(i),i.onRun(function(){function t(){if(0===e.length)return void i.chain();var r=e[0];h.stat(r,function(r,o){return o?(n.push(o),e.shift(),void i.chain(t)):void p(r,i)})}i.chain(t)}),i.onSuccess(function(){t(void 0,n)}),i.onError(function(e){t(e)}),i.enqueue()},g.downloadContent=function(e,n){var i=[],r=new c;u(r),d(r),r.onRun(function(){function n(){if(0===e.length)return void r.chain();var o=e[0];i.push(o);var a;return o.isFile===!0?a=o:void 0!==o.wasRemoved&&(a=o.stat),a?void h.readFile(a.path,function(i,o){return t.isString(o)?(a.content=o,e.shift(),void r.chain(n)):void p(i,r)}):(e.shift(),void r.chain(n))}r.chain(n)}),r.onSuccess(function(){n(void 0,i)}),r.onError(function(e){n(e)}),r.enqueue()};var b=!1;return g.picker=function(e){var t=[],i=new c;i.timeout=n.ASYNC_TASK_LONG_TIMEOUT,u(i),f(i),i.onRun(function(){var e={};e.multiselect=!0,e.linkType="direct",e.success=function(e){for(var n=0;n:"\|?\*]+$/)?0!==e.indexOf("/")?"/"+e:e:void o.onError('"'+e+'" contains invalid characters.')}function c(e){return"sync."+p+"."+encodeURIComponent(e.toLowerCase())}function u(e,n,i,r){r=r||"{}";var o={};return o.provider=f,o.path=e,o.version=n,o.contentCRC=t.crc32(i),o.discussionListCRC=t.crc32(r),o.syncIndex=c(e),h===!0&&(o.content=i,o.discussionList=r),o}function d(t){s.downloadMetadata(t,function(t,n){t||s.downloadContent(n,function(t,n){if(!t){var i=[];e.each(n,function(e){var t=f.parseContent(e.content),n=u(e.path,e.versionTag,t.content,t.discussionListJSON),r={};r[n.syncIndex]=n;var o=a.createFile(e.name,t.content,t.discussionListJSON,r);a.selectFile(o),i.push(o)}),0!==i.length&&o.onSyncImportSuccess(i,f)}})})}var p="dropbox",f=new r(p,"Dropbox");f.defaultPublishFormat="template";var h="merge"==i.conflictMode;return f.importFiles=function(){s.picker(function(t,n){if(!t&&0!==n.length){var i=[];e.each(n,function(e){var t=c(e),n=a.getFileFromSyncIndex(t);return void 0!==n?o.onError('"'+n.title+'" was already imported.'):void i.push(e)}),d(i)}})},f.exportFile=function(e,n,i,r,d){var p=t.getInputTextValue("#input-sync-export-dropbox-path",e);if(p=l(p),void 0===p)return d(!0);var h=c(p),m=a.getFileFromSyncIndex(h);if(void 0!==m){var g=m.title;return o.onError('File path is already synchronized with "'+g+'".'),d(!0)}var v=f.serializeContent(i,r);s.upload(p,v,function(e,t){if(e)return d(e);var n=u(t.path,t.versionTag,i,r);d(void 0,n)})},f.syncUp=function(e,t,n,i,r,o,a,l){if(a.contentCRC==t&&a.discussionListCRC==o)return l(void 0,!1);var c=f.serializeContent(e,r);s.upload(a.path,c,function(n,s){return n?l(n,!0):(a.version=s.versionTag,h===!0&&(a.content=e,a.discussionList=r),a.contentCRC=t,a.titleCRC=i,a.discussionListCRC=o,void l(void 0,!0))})},f.syncDown=function(i){var r=n[p+".lastChangeId"];s.checkChanges(r,function(r,l,u){if(r)return i(r);var d=[];e.each(l,function(e){var t=c(e.path),n=a.getFileFromSyncIndex(t),i=n&&n.syncLocations[t]; +return i?(e.fileDesc=n,e.syncAttributes=i,e.wasRemoved===!0?void d.push(e):void(i.version!=e.stat.versionTag&&d.push(e))):void 0}),s.downloadContent(d,function(e,r){function a(){if(0===r.length)return n[p+".lastChangeId"]=u,i();var e=r.pop(),s=e.fileDesc,l=e.syncAttributes;if(e.wasRemoved===!0)return o.onError('"'+s.title+'" has been removed from Dropbox.'),s.removeSyncLocation(l),o.onSyncRemoved(s,l);var c=e.stat,d=f.parseContent(c.content),m=d.content,g=d.discussionListJSON,v=d.discussionList,b=f.syncMerge(s,l,m,s.title,v,g);l.version=c.versionTag,h===!0&&(l.content=m,l.discussionList=v),l.contentCRC=b.contentCRC,l.discussionListCRC=b.discussionListCRC,t.storeAttributes(l),setTimeout(a,5)}return e?void i(e):void setTimeout(a,5)})})},f.publish=function(e,t,n,i,r){var o=l(e.path);return void 0===o?r(!0):void s.upload(o,i,r)},f.newPublishAttributes=function(e){var n={};return n.path=t.getInputTextValue("#input-publish-dropbox-path",e),e.isPropagationStopped()?void 0:n},f}),define("helpers/googleHelper",["underscore","jquery","constants","core","utils","storage","logger","settings","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s,l,c){function u(t){var n={profile:!0},i=!0;e.each((o[t+".permissions"]||"").split(";"),function(e){e&&(n[e]=!0)}),this.setRefreshFlag=function(){i=!0},this.isAuthorized=function(t){return i===!1&&e.has(n,t)},this.add=function(r){n[r]=!0,o[t+".permissions"]=e.keys(n).join(";"),i=!1},this.getListWithNew=function(t){var i=e.keys(n);return e.has(n,t)||i.push(t),i};var r=o[t+".userId"];this.setUserId=function(e){r=e,o[t+".userId"]=r},this.getUserId=function(){return r}}function d(e){e.onRun(function(){return y===!0?(g=!1,void e.error(new Error("Operation not available in offline mode.|stopPublish"))):g===!0?void e.chain():(window.delayedFunction=function(){gapi.load("client",function(){gapi.client.load("drive","v2",function(){g=!0,e.chain()})})},void t.ajax({url:"https://apis.google.com/js/api.js?onload=runDelayedFunction",dataType:"script",timeout:n.AJAX_TIMEOUT}).fail(function(t){var n={code:t.status,message:t.statusText};h(n,e)}))})}function p(i,o,a){var s=v[a];s||(s=new u(a),v[a]=s),i.onRun(function(){function a(){t.ajax({url:"https://www.googleapis.com/oauth2/v1/tokeninfo",data:{access_token:d.access_token},timeout:n.AJAX_TIMEOUT,type:"GET"}).done(function(e){s.getUserId()&&s.getUserId()!=e.user_id?u():(s.setUserId(e.user_id),s.add(o),s.token=d,i.chain())}).fail(function(e){var t={code:e.status,message:e.statusText};h(t,i)})}function l(){if(m>5)return void i.error(new Error("Unable to authenticate user "+s.getUserId()+", please sign in with Google."));p===!1&&(i.timeout=n.ASYNC_TASK_LONG_TIMEOUT);var t=e.chain(x).pick(s.getListWithNew(o)).flatten().value();gapi.auth.authorize({client_id:n.GOOGLE_CLIENT_ID,scope:t,immediate:p,authuser:p===!1?"":m},function(e){d=gapi.auth.getToken(),gapi.auth.setToken(f),!e||e.error?g===!0&&p===!0?(p=!1,i.chain(c)):i.error(new Error("Access to Google account is not authorized.")):(p===!0&&m++,i.chain(a))})}function c(){return p===!0?void i.chain(l):void r.redirectConfirm("You are being redirected to Google authorization page.",function(){i.chain(l)},function(){i.error(new Error("Operation canceled."))})}function u(){return p=!0,s.token&&s.isAuthorized(o)?void i.chain():(s.getUserId()||(p=!1),void i.chain(c))}var d,p,f=gapi.auth.getToken(),m=0;u()})}function f(e,t){var n=gapi.auth.getToken(),i=v[e];gapi.auth.setToken(i.token),t(),gapi.auth.setToken(n)}function h(t,n){var r;if(t)if(a.error(t),"string"==typeof t)r=t;else{if(r="Google error ("+t.code+": "+t.message+").",t.code>=500&&t.code<600)return void n.retry(new Error(r));if(401===t.code||403===t.code||"token_refresh_required"==t.code)return e.each(v,function(e){e.setRefreshFlag()}),r="Access to Google account is not authorized.",void n.retry(new Error(r),1);(0===t.code||-1===t.code)&&(g=!1,e.each(v,function(e){e.setRefreshFlag()}),i.setOffline(),r="|stopPublish")}n.error(new Error(r))}function m(e){e.onRun(function(){return w===!0?void e.chain():void t.ajax({url:"//www.google.com/jsapi",data:{key:n.GOOGLE_API_KEY},dataType:"script",timeout:n.AJAX_TIMEOUT}).done(function(){google.load("picker","1",{callback:function(){e.chain()}}),w=!0}).fail(function(t){var n={code:t.status,message:t.statusText};h(n,e)})})}var g=!1,v={},b={},y=!1;l.addListener("onOfflineChanged",function(e){y=e});var x={profile:["https://www.googleapis.com/auth/userinfo.profile"],gdrive:["https://www.googleapis.com/auth/drive.install",s.gdriveFullAccess===!0?"https://www.googleapis.com/auth/drive":"https://www.googleapis.com/auth/drive.file"],blogger:["https://www.googleapis.com/auth/blogger"],picasa:["https://www.googleapis.com/auth/photos"]};b.refreshGdriveToken=function(e){var t=new c;d(t);var n=v[e];n&&n.setRefreshFlag(),p(t,"gdrive",e),t.enqueue()},b.upload=function(e,t,n,i,a,s,l,u){var m,g=new c;d(g),p(g,"gdrive",l),g.onRun(function(){var s="-------314159265358979323846",c="\r\n--"+s+"\r\n",u="\r\n--"+s+"--";a=a||"text/x-markdown";var d={title:n,mimeType:a};t&&(d.parents=[{kind:"drive#fileLink",id:t}]);var p="/upload/drive/v2/files",v="POST";e&&(p+="/"+e,v="PUT");var b={"Content-Type":'multipart/mixed; boundary="'+s+'"'},y=r.encodeBase64(i),x=[c,"Content-Type: application/json\r\n\r\n",JSON.stringify(d),c,"Content-Type: ",a,"\r\n","Content-Transfer-Encoding: base64\r\n","\r\n",y,u].join("");f(l,function(){var t=gapi.client.request({path:p,method:v,params:{uploadType:"multipart"},headers:b,body:x});t.execute(function(t){if(t&&t.id)return m=t,m.content=i,void g.chain();var n=t.error;void 0!==n&&void 0!==e&&(404===n.code?n='File ID "'+e+'" not found on Google Drive.|removePublish':412===n.code&&(o.removeItem(l+".gdrive.lastChangeId"),n='Conflict on file ID "'+e+'". Please restart the synchronization.')),h(n,g)})})}),g.onSuccess(function(){u(void 0,m)}),g.onError(function(e){u(e)}),g.enqueue()},b.rename=function(e,t,n,i){var r,o=new c;d(o),p(o,"gdrive",n),o.onRun(function(){var i={title:t};f(n,function(){var t=gapi.client.drive.files.patch({fileId:e,resource:i});t.execute(function(t){if(t&&t.id)return r=t,void o.chain();var n=t.error;void 0!==n&&void 0!==e&&404===n.code&&(n='File ID "'+e+'" not found on Google Drive.|removePublish'),h(n,o)})})}),o.onSuccess(function(){i(void 0,r)}),o.onError(function(e){i(e)}),o.enqueue()},b.checkChanges=function(e,t,n){var i=[],r=e||0,o=new c;d(o),p(o,"gdrive",t),o.onRun(function(){function e(){f(t,function(){var t;t=gapi.client.drive.changes.list(void 0===n?{startChangeId:r+1}:{pageToken:n}),t.execute(function(t){return t&&t.largestChangeId?(r=t.largestChangeId,n=t.nextPageToken,void 0!==t.items&&(i=i.concat(t.items)),void(void 0!==n?o.chain(e):o.chain())):void h(t.error,o)})})}var n;o.chain(e)}),o.onSuccess(function(){n(void 0,i,r)}),o.onError(function(e){n(e)}),o.enqueue()},b.downloadMetadata=function(e,i,r,o){var a=[],s=new c;d(s),o||p(s,"gdrive",i),s.onRun(function(){function r(){if(0===e.length)return void s.chain();var o=e[0],l={},c=v[i];c&&c.token&&(l.Authorization="Bearer "+c.token.access_token),t.ajax({url:"https://www.googleapis.com/drive/v2/files/"+o,headers:l,data:{key:n.GOOGLE_API_KEY},dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(t){a.push(t),e.shift(),s.chain(r)}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&(t='File ID "'+o+'" not found on Google Drive.'),h(t,s)})}s.chain(r)}),s.onSuccess(function(){r(void 0,a)}),s.onError(function(e){r(e)}),s.enqueue()},b.downloadContent=function(e,i,r,o){var a=[],s=new c;s.timeout=n.ASYNC_TASK_LONG_TIMEOUT,d(s),o||p(s,"gdrive",i),s.onRun(function(){function r(){if(0===e.length)return void s.chain();var o=e[0];a.push(o);var l;if("drive#file"==o.kind?l=o:"drive#change"==o.kind&&(l=o.file),!l)return e.shift(),void s.chain(r);var c=l.downloadUrl;0===l.mimeType.indexOf("application/vnd.google-apps.drive-sdk")&&(l.isRealtime=!0,c="https://www.googleapis.com/drive/v2/files/"+l.id+"/realtime");var u={},d=v[i];d&&d.token&&(u.Authorization="Bearer "+d.token.access_token),t.ajax({url:c,headers:u,data:{key:n.GOOGLE_API_KEY},dataType:l.isRealtime?"json":"text",timeout:n.AJAX_TIMEOUT}).done(function(t){l.content=l.isRealtime?t.data.value.content.value:t,e.shift(),s.chain(r)}).fail(function(e){var t={code:e.status,message:e.statusText};h(t,s)})}s.chain(r)}),s.onSuccess(function(){r(void 0,a)}),s.onError(function(e){r(e)}),s.enqueue()},b.uploadImg=function(e,i,r,o){var a,s="google.picasa0",l=new c;d(l),p(l,"picasa",s),l.onRun(function(){var o={Slug:e};e.match(/.jpe?g$/i)?o["Content-Type"]="image/jpeg":e.match(/.png$/i)?o["Content-Type"]="image/png":e.match(/.gif$/i)&&(o["Content-Type"]="image/gif");var c=v[s];c&&c.token&&(o.Authorization="Bearer "+c.token.access_token),t.ajax({url:n.PICASA_PROXY_URL+"upload/"+r,headers:o,data:i,processData:!1,dataType:"xml",timeout:n.AJAX_TIMEOUT,type:"POST"}).done(function(e){a=e,l.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};200==t.code&&(t.message=e.responseText),h(t,l)})}),l.onSuccess(function(){o(void 0,a)}),l.onError(function(e){o(e)}),l.enqueue()};var w=!1;return b.picker=function(e,i,o){function a(){void 0!==s&&(s.setVisible(!1),t(".modal-backdrop, .picker").remove())}var s,l=[],u=new c;u.timeout=n.ASYNC_TASK_LONG_TIMEOUT,d(u),"doc"==i||"folder"==i?p(u,"gdrive",o):(o="google.picasa0",p(u,"picasa",o)),m(u),u.onRun(function(){var e=v[o],c=new google.picker.PickerBuilder;c.setAppId(n.GOOGLE_DRIVE_APP_ID);var d;"doc"==i?(d=new google.picker.DocsView(google.picker.ViewId.DOCS),d.setParent("root"),d.setIncludeFolders(!0),d.setMimeTypes(["text/x-markdown","text/plain","application/octet-stream","application/vnd.google-apps.drive-sdk."+n.GOOGLE_DRIVE_APP_ID].join(",")),c.enableFeature(google.picker.Feature.NAV_HIDDEN),c.enableFeature(google.picker.Feature.MULTISELECT_ENABLED),c.addView(d),e&&e.token&&c.setOAuthToken(e.token.access_token)):"folder"==i?(d=new google.picker.DocsView(google.picker.ViewId.FOLDERS),d.setParent("root"),d.setIncludeFolders(!0),d.setSelectFolderEnabled(!0),d.setMimeTypes("application/vnd.google-apps.folder"),c.enableFeature(google.picker.Feature.NAV_HIDDEN),c.addView(d),e&&e.token&&c.setOAuthToken(e.token.access_token)):"img"==i&&(d=new google.picker.PhotosView,d.setType("flat"),c.addView(d),d=new google.picker.PhotosView,d.setType("ofuser"),c.addView(d),c.addView(google.picker.ViewId.PHOTO_UPLOAD),e&&e.token&&c.setOAuthToken(e.token.access_token)),c.setCallback(function(e){(e.action==google.picker.Action.PICKED||e.action==google.picker.Action.CANCEL)&&(e.action==google.picker.Action.PICKED&&(l=e.docs),a(),u.chain())}),s=c.build(),t(r.createBackdrop()).click(function(){a(),u.chain()}),s.setVisible(!0)}),u.onSuccess(function(){e(void 0,l)}),u.onError(function(t){a(),e(t)}),u.enqueue()},b.uploadBlogger=function(e,i,r,o,a,s,l,u,f){var m="google.blogger0",g=new c;d(g),p(g,"blogger",m),g.onRun(function(){function c(){var e="https://www.googleapis.com/blogger/v3/blogs/"+i+"/posts/",a={kind:"blogger#post",blog:{id:i},labels:o,title:l,content:u},s="POST";void 0!==r&&(e+=r,a.id=r,s="PUT"),t.ajax({url:e,data:JSON.stringify(a),headers:f,type:s,contentType:"application/json",dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){r=e.id,g.chain(d)}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&void 0!==r&&(t="Post "+r+" not found on Blogger.|removePublish"),h(t,g)})}function d(){var e="https://www.googleapis.com/blogger/v3/blogs/"+i+"/posts/"+r;a?e+="/revert":(e+="/publish",s&&(e+="?publishDate="+s.toISOString())),t.ajax({url:e,headers:f,type:"POST",dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(){g.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&(t="Post "+r+" not found on Blogger.|removePublish"),h(t,g)})}function p(){return void 0!==i?void g.chain(c):void t.ajax({url:"https://www.googleapis.com/blogger/v3/blogs/byurl",data:{url:e},headers:f,dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){i=e.id,g.chain(c)}).fail(function(t){var n={code:t.status,message:t.statusText};404===n.code&&(n='Blog "'+e+'" not found on Blogger.|removePublish'),h(n,g)})}var f={},b=v[m];b&&b.token&&(f.Authorization="Bearer "+b.token.access_token),g.chain(p)}),g.onSuccess(function(){f(void 0,i,r)}),g.onError(function(e){f(e)}),g.enqueue()},b.uploadBloggerPage=function(e,i,r,o,a,s,l,u){var f="google.blogger0",m=new c;d(m),p(m,"blogger",f),m.onRun(function(){function o(){var e="https://www.googleapis.com/blogger/v3/blogs/"+i+"/pages/",o={kind:"blogger#page",blog:{id:i},title:s,content:l},a="POST";void 0!==r&&(e+=r,o.id=r,a="PUT"),t.ajax({url:e,data:JSON.stringify(o),headers:c,type:a,contentType:"application/json",dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){r=e.id,m.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&void 0!==r&&(t="Page "+r+" not found on Blogger.|removePublish"),h(t,m)})}function a(){return void 0!==i?void m.chain(o):void t.ajax({url:"https://www.googleapis.com/blogger/v3/blogs/byurl",data:{url:e},headers:c,dataType:"json",timeout:n.AJAX_TIMEOUT}).done(function(e){i=e.id,m.chain(o)}).fail(function(t){var n={code:t.status,message:t.statusText};404===n.code&&(n='Blog "'+e+'" not found on Blogger.|removePublish'),h(n,m)})}var c={},u=v[f];u&&u.token&&(c.Authorization="Bearer "+u.token.access_token),m.chain(a)}),m.onSuccess(function(){u(void 0,i,r)}),m.onError(function(e){u(e)}),m.enqueue()},window.delayedFunction=void 0,window.runDelayedFunction=function(){void 0!==window.delayedFunction&&window.delayedFunction()},b}),define("text!html/dialogExportGdrive.html",[],function(){return'
        \n'}),define("text!html/dialogAutoSyncGdrive.html",[],function(){return'
        \n'}),define("providers/gdriveProviderBuilder",["jquery","underscore","constants","utils","storage","logger","classes/Provider","settings","eventMgr","fileMgr","editor","helpers/googleHelper","text!html/dialogExportGdrive.html","text!html/dialogAutoSyncGdrive.html"],function(e,t,n,i,r,o,a,s,l,c,u,d,p,f){return function(o,u,h){function m(e){return"sync."+o+"."+e}function g(e,t,n,r,o){o=o||"{}";var a={};return a.provider=y,a.id=e,a.etag=t,a.contentCRC=i.crc32(n),a.titleCRC=i.crc32(r),a.discussionListCRC=i.crc32(o),a.syncIndex=m(e),x===!0&&(a.content=n,a.title=r,a.discussionList=o),a}function v(e){d.downloadMetadata(e,b,function(e,n){e||d.downloadContent(n,b,function(e,n){if(!e){var i,r=[];t.each(n,function(e){var t,n=y.parseContent(e.content);if(e.isRealtime)l.onError("Real time synchronization is not supported anymore. Please use standard synchronization.");else{var o=g(e.id,e.etag,n.content,e.title,n.discussionListJSON);t={},t[o.syncIndex]=o}i=c.createFile(e.title,n.content,n.discussionListJSON,t),r.push(i)}),void 0!==i&&(l.onSyncImportSuccess(r,y),c.selectFile(i))}})})}var b="google.gdrive"+h,y=new a(o,u);y.defaultPublishFormat="template",y.exportPreferencesInputIds=[o+"-parentid"];var x="merge"==s.conflictMode;return y.importFiles=function(){d.picker(function(e,n){if(!e&&0!==n.length){var i=[];t.each(n,function(e){var t=m(e.id),n=c.getFileFromSyncIndex(t);return void 0!==n?void l.onError('"'+n.title+'" was already imported.'):void i.push(e.id)}),v(i)}},"doc",b)},y.exportFile=function(e,t,n,r,a){var s=i.getInputTextValue("#input-sync-export-"+o+"-fileid");if(s){var u=m(s),p=c.getFileFromSyncIndex(u);if(void 0!==p)return l.onError('File ID is already synchronized with "'+p.title+'".'),void a(!0)}var f=i.getInputTextValue("#input-sync-export-"+o+"-parentid"),h=y.serializeContent(n,r);d.upload(s,f,t,h,void 0,void 0,b,function(e,i){if(e)return void a(e);var o=g(i.id,i.etag,n,t,r);a(void 0,o)})},y.syncUp=function(e,t,n,i,r,o,a,s){if(a.contentCRC==t&&a.titleCRC==i&&a.discussionListCRC==o)return s(void 0,!1);if(a.isRealtime){var u=c.getFileFromSyncIndex(a.syncIndex);return u.removeSyncLocation(a),l.onSyncRemoved(u,a),l.onError("Real time synchronization is not supported anymore. Please use standard synchronization.")}var p=y.serializeContent(e,r);d.upload(a.id,void 0,n,p,void 0,a.etag,b,function(l,c){return l?void s(l,!0):(a.etag=c.etag,delete a.isRealtime,x===!0&&(a.content=e,a.title=n,a.discussionList=r),a.contentCRC=t,a.titleCRC=i,a.discussionListCRC=o,void s(void 0,!0))})},y.syncDown=function(e){var n=parseInt(r[b+".gdrive.lastChangeId"],10);d.checkChanges(n,b,function(n,o,a){if(n)return void e(n);var s=[];t.each(o,function(e){var t=m(e.fileId),n=c.getFileFromSyncIndex(t),i=n&&n.syncLocations[t];return i?(e.fileDesc=n,e.syncAttributes=i,e.deleted===!0?void s.push(e):void(i.etag!=e.file.etag&&s.push(e))):void 0}),d.downloadContent(s,b,function(t,n){function o(){if(0===n.length)return r[b+".gdrive.lastChangeId"]=a,e();var t=n.pop(),s=t.fileDesc,c=t.syncAttributes;if(t.deleted===!0)return l.onError('"'+s.title+'" has been removed from '+u+"."),s.removeSyncLocation(c),l.onSyncRemoved(s,c);var d=t.file,p=y.parseContent(d.content),f=p.content,h=d.title,m=p.discussionListJSON,g=p.discussionList,v=y.syncMerge(s,c,f,h,g,m);c.etag=d.etag,x===!0&&(c.content=f,c.title=h,c.discussionList=m),c.contentCRC=v.contentCRC,c.titleCRC=v.titleCRC,c.discussionListCRC=v.discussionListCRC,i.storeAttributes(c),setTimeout(o,5)}return t?void e(t):void setTimeout(o,5)})})},y.publish=function(e,t,n,i,r){var o="markdown"!=e.format?"text/html":void 0;d.upload(e.id,void 0,e.fileName||n,i,o,void 0,b,function(t,n){return t?void r(t):(e.id=n.id,void r())})},y.newPublishAttributes=function(e){var t={};return t.id=i.getInputTextValue("#input-publish-"+o+"-fileid"),t.fileName=i.getInputTextValue("#input-publish-"+o+"-filename"),e.isPropagationStopped()?void 0:t},y.setAutosyncDialogConfig=function(){var e=y.autosyncConfig;i.setInputRadio("radio-autosync-"+o+"-mode",e.mode||"off"),i.setInputValue("#input-autosync-"+o+"-parentid",e.parentId)},y.getAutosyncDialogConfig=function(){var e={};return e.mode=i.getInputRadio("radio-autosync-"+o+"-mode"),e.parentId=i.getInputTextValue("#input-autosync-"+o+"-parentid"),e},y.autosyncFile=function(e,t,n,i,r){var o=i.parentId;d.upload(void 0,o,e,t,void 0,void 0,b,function(i,o){if(i)return void r(i);var a=g(o.id,o.etag,t,e,n);r(void 0,a)})},y.isPublishEnabled=s.gdriveMultiAccount>h,l.addListener("onReady",function(){e(".submenu-sync-"+o).toggle(s.gdriveMultiAccount>h);var a=document.querySelector(".modal-upload-"+o);a&&(a.innerHTML=t.template(p,{providerId:o,providerName:u}));var y=document.querySelector(".modal-autosync-"+o);if(y&&(y.innerHTML=t.template(f,{providerId:o,providerName:u})),e(".action-export-"+o+"-choose-folder").click(function(){d.picker(function(t,n){t||0===n.length||(e(".modal-upload-"+o).modal(),i.setInputValue("#input-sync-export-"+o+"-parentid",n[0].id))},"folder",b)}),e(".action-autosync-"+o+"-choose-folder").click(function(){d.picker(function(t,n){t||0===n.length||(e(".modal-autosync-"+o).modal(),i.setInputValue("#input-autosync-"+o+"-parentid",n[0].id))},"folder",b)}),e(".action-remove-google-drive-state").click(function(){r.removeItem("gdrive.state")}),!(h>=s.gdriveMultiAccount)){var x=i.retrieveIgnoreError("gdrive.state"),w=r[b+".userId"];if(void 0!==x){if(w&&x.userId!=w)return void(h===s.gdriveMultiAccount-1&&(3===s.gdriveMultiAccount?(l.onError("None of your 3 Google Drive accounts is able to perform this request."),r.removeItem("gdrive.state")):e(".modal-add-google-drive-account").modal()));if(r.removeItem("gdrive.state"),"create"==x.action)d.upload(void 0,x.folderId,n.GDRIVE_DEFAULT_FILE_TITLE,s.defaultContent,void 0,void 0,b,function(e,t){if(!e){var n=g(t.id,t.etag,t.content,t.title),i={};i[n.syncIndex]=n;var r=c.createFile(t.title,t.content,void 0,i);c.selectFile(r),l.onMessage('"'+t.title+'" created successfully on '+u+".")}});else if("open"==x.action){var S=[];t.each(x.ids,function(e){var t=m(e),n=c.getFileFromSyncIndex(t);void 0!==n?n!==c.currentFile&&c.selectFile(n):S.push(e)}),v(S)}}}}),y}}),define("providers/gdriveProvider",["providers/gdriveProviderBuilder"],function(e){return e("gdrive","Google Drive",0)}),define("providers/gdrivesecProvider",["providers/gdriveProviderBuilder"],function(e){return e("gdrivesec","Google Drive (2nd account)",1)}),define("providers/gdriveterProvider",["providers/gdriveProviderBuilder"],function(e){return e("gdriveter","Google Drive (3rd account)",2)}),define("synchronizer",["jquery","underscore","utils","storage","eventMgr","fileSystem","fileMgr","classes/Provider","providers/dropboxProvider","providers/gdriveProvider","providers/gdrivesecProvider","providers/gdriveterProvider"],function(e,t,n,i,r,o,a,s){function l(e){function i(){function o(){if(0===s.length)return i();var t=s.pop();t.provider.syncUp(c,u,d,p,f,m,t,function(i,r){return r===!0&&(h=!0),i?e(i):(r&&n.storeAttributes(t),void o())})}if(0===r.length)return l(e);var a=r.pop(),s=t.values(a.syncLocations);if(0===s.length)return i();var c=a.content,u=n.crc32(c),d=a.title,p=n.crc32(d),f=a.discussionListJSON,m=n.crc32(f);o()}var r=[];h===!0?(h=!1,r=t.values(o),i()):e()}function c(e){function n(){if(0===i.length)return e();var t=i.pop();return p.hasSync(t)?void t.syncDown(function(t){return t?e(t):void n()}):n()}var i=t.values(f);n()}function u(e){function n(){function o(){if(0===s.length)return n();var t=s.pop();t.autosyncFile(a.title,a.content,a.discussionListJSON,t.autosyncConfig,function(t,n){return t?e(t):(a.addSyncLocation(n),r.onSyncExportSuccess(a,n),void o())})}if(0===i.length)return e();var a=i.pop(),s=t.filter(f,function(e){return"all"==e.autosyncConfig.mode});o()}var i=t.filter(o,function(e){return 0===t.size(e.syncLocations)});n()}function d(i){n.resetModalInputs();var r=n.retrieveIgnoreError(i.providerId+".exportPreferences");r&&t.each(i.exportPreferencesInputIds,function(e){var i=r[e];t.isBoolean(i)?n.setInputChecked("#input-sync-export-"+e,i):n.setInputValue("#input-sync-export-"+e,i)}),e(".modal-upload-"+i.providerId).modal()}var p={},f=t.chain(arguments).map(function(e){return e instanceof s&&[e.providerId,e]}).compact().object().value();!function(){var e={};t.each(o,function(t){n.retrieveIndexArray(t.fileIndex+".sync").forEach(function(o){try{var a=JSON.parse(i[o]);a.syncIndex=o;var s=f[a.provider];if(!s)throw new Error("Invalid provider ID: "+a.provider);a.provider=s,t.syncLocations[o]=a,e[o]=a}catch(l){r.onError(l),n.removeIndexFromArray(t.fileIndex+".sync",o)}})}),Object.keys(i).forEach(function(t){var n=t.match(/sync\.\S+/);n&&!e.hasOwnProperty(n[0])&&i.removeItem(t)})}(),t.each(f,function(e){e.autosyncConfig=n.retrieveIgnoreError(e.providerId+".autosyncConfig")||{}}),p.hasSync=function(e){return t.some(o,function(n){return t.some(n.syncLocations,function(t){return void 0===e||t.provider===e})})};var h=!1,m=!1;r.addListener("onOfflineChanged",function(e){m=e});var g=!1;return p.sync=function(){function e(e){return void 0!==e?(g=!1,r.onSyncRunning(!1),!0):!1}return g===!0||m===!0?!1:(g=!0,r.onSyncRunning(!0),h=!0,u(function(t){e(t)||c(function(t){e(t)||l(function(t){e(t)||(g=!1,r.onSyncRunning(!1),r.onSyncSuccess())})})}),!0)},r.addListener("onFileCreated",function(e){0===t.size(e.syncLocations)&&t.each(f,function(t){"new"==t.autosyncConfig.mode&&t.autosyncFile(e.title,e.content,e.discussionListJSON,t.autosyncConfig,function(t,n){t||(e.addSyncLocation(n),r.onSyncExportSuccess(e,n))})})}),r.addListener("onReady",function(){t.each(f,function(o){e(".action-sync-import-"+o.providerId).click(function(e){o.importFiles(e)}),e(".action-sync-export-dialog-"+o.providerId).click(function(){d(o)}),e(".action-autosync-dialog-"+o.providerId).click(function(){n.resetModalInputs(),o.setAutosyncDialogConfig(o),e(".modal-autosync-"+o.providerId).modal()}),e(".action-sync-export-"+o.providerId).click(function(e){var n=a.currentFile;o.exportFile(e,n.title,n.content,n.discussionListJSON,function(e,t){e||(n.addSyncLocation(t),r.onSyncExportSuccess(n,t))});var s={};t.each(o.exportPreferencesInputIds,function(e){var t=document.getElementById("input-sync-export-"+e);s[e]="checkbox"==t.type?t.checked:t.value}),i[o.providerId+".exportPreferences"]=JSON.stringify(s)}),e(".action-autosync-"+o.providerId).click(function(e){var t=o.getAutosyncDialogConfig(e);void 0!==t&&(i[o.providerId+".autosyncConfig"]=JSON.stringify(t),o.autosyncConfig=t)})})}),r.onSynchronizerCreated(p),p}),define("providers/downloadProvider",["jquery","constants","eventMgr","utils","fileMgr","classes/Provider","classes/AsyncTask"],function(e,t,n,i,r,o,a){var s=new o("download");return s.sharingAttributes=["url"],s.importPublic=function(n,i){var r,o,s=new a(!0);s.onRun(function(){var i=n.url,a=i.lastIndexOf("/");return-1===a?void s.error(new Error("Invalid URL parameter.")):(r=i.substring(a+1),void e.ajax({url:t.DOWNLOAD_PROXY_URL+"download?url="+i,type:"GET",dataType:"text",timeout:t.AJAX_TIMEOUT}).done(function(e){o=e,s.chain()}).fail(function(){s.error(new Error("Unable to access URL "+i))}))}),s.onSuccess(function(){i(void 0,r,o)}),s.onError(function(e){i(e)}),s.enqueue()},n.addListener("onReady",function(){e(".action-import-url").click(function(e){var t=i.getInputTextValue("#input-import-url",e);t&&s.importPublic({url:t},function(e,t,n){if(!e){var i=r.createFile(t,n);r.selectFile(i)}})})}),s}),define("helpers/githubHelper",["jquery","constants","core","utils","storage","logger","settings","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s,l){function c(n){n.onRun(function(){return m===!0?(p=!1,void n.error(new Error("Operation not available in offline mode.|stopPublish"))):p===!0?void n.chain():void e.ajax({url:"libs/github.js",dataType:"script",timeout:t.AJAX_TIMEOUT}).done(function(){p=!0,n.chain()}).fail(function(e){var t={error:e.status,message:e.statusText};d(t,n)})})}function u(n){var o,s;n.onRun(function(){function l(){i.redirectConfirm("You are being redirected to GitHub authorization page.",function(){n.chain(c)},function(){n.error(new Error("Operation canceled."))})}function c(){r.removeItem("githubCode");var e=a.githubFullAccess?"repo,gist":"public_repo,gist";o=i.popupWindow("html/github-oauth-client.html?client_id="+t.GITHUB_CLIENT_ID+"&scope="+e,"stackedit-github-oauth",960,600),o.focus(),s=setInterval(function(){if(o.closed===!0){if(clearInterval(s),o=void 0,s=void 0,h=r.githubCode,void 0===h)return void n.error(new Error(p));r.removeItem("githubCode"),n.chain(u)}},500)}function u(){e.getJSON(t.GATEKEEPER_URL+"authenticate/"+h,function(e){void 0!==e.token?(d=e.token,r.githubToken=d,f=new Github({token:d,auth:"oauth"}),n.chain()):n.error(new Error(p))})}if(void 0!==f)return void n.chain();var d=r.githubToken;if(void 0!==d)return f=new Github({token:d,auth:"oauth"}),void n.chain();var p="Failed to retrieve a token from GitHub.";n.timeout=t.ASYNC_TASK_LONG_TIMEOUT;var h;n.chain(l)}),n.onError(function(){void 0!==s&&clearInterval(s),void 0!==o&&o.close()})}function d(e,t){var i;if(e)if(o.error(e),"string"==typeof e)i=e;else{if(i="Could not publish on GitHub.",401===e.error||403===e.error)return f=void 0,r.removeItem("githubToken"),i="Access to GitHub account is not authorized.",void t.retry(new Error(i),1); +e.error<=0&&(p=!1,f=void 0,n.setOffline(),i="|stopPublish")}t.error(new Error(i))}var p,f,h={},m=!1;return s.addListener("onOfflineChanged",function(e){m=e}),h.upload=function(e,t,n,i,r,o,a){var s=new l;c(s),u(s),s.onRun(function(){function a(){var e=f.getUser();e.show(void 0,function(e,n){return e?void d(e,s):(t=n.login,void s.chain(l))})}function l(){var a=f.getRepo(t,e);a.write(n,i,r,o,function(e){return e?void d(e,s):void s.chain()})}s.chain(t?l:a)}),s.onSuccess(function(){a()}),s.onError(function(e){a(e)}),s.enqueue()},h.uploadGist=function(e,t,n,i,r,o){var a=new l;c(a),u(a),a.onRun(function(){var o=f.getGist(e),s={};s[t]={content:r};var l=o.update;void 0===e&&(l=o.create),l({description:i,"public":n,files:s},function(t,n){return t?(404===t.error&&void 0!==e&&(t="Gist "+e+" not found on GitHub.|removePublish"),void d(t,a)):(e=n.id,void a.chain())})}),a.onSuccess(function(){o(void 0,e)}),a.onError(function(e){o(e)}),a.enqueue()},h.downloadGist=function(e,t,n){var i=new l(!0);c(i);var r,o;i.onRun(function(){var n=new Github({}),a=n.getGist(e);a.read(function(n,a){if(n)return void i.error(new Error("Error trying to access Gist "+e+"."));r=a.description;var s=a.files[t];return void 0===s?void i.error(new Error("Gist "+e+' does not contain "'+t+'".')):(o=s.content,void i.chain())})}),i.onSuccess(function(){n(void 0,r,o)}),i.onError(function(e){n(e)}),i.enqueue()},h}),define("providers/gistProvider",["utils","classes/Provider","helpers/githubHelper"],function(e,t,n){var i=new t("gist","Gist");return i.publishPreferencesInputIds=["gist-public"],i.sharingAttributes=["gistId","filename"],i.publish=function(e,t,i,r,o){n.uploadGist(e.gistId,e.filename,e.isPublic,i,r,function(t,n){return t?void o(t):(e.gistId=n,void o())})},i.newPublishAttributes=function(t){var n={};return n.gistId=e.getInputTextValue("#input-publish-gist-id"),n.filename=e.getInputTextValue("#input-publish-filename",t),n.isPublic=e.getInputChecked("#input-publish-gist-public"),t.isPropagationStopped()?void 0:n},i.importPublic=function(e,t){n.downloadGist(e.gistId,e.filename,t)},i}),define("sharing",["jquery","underscore","constants","utils","eventMgr","fileMgr","classes/AsyncTask","classes/Provider","providers/downloadProvider","providers/gistProvider"],function(e,t,n,i,r,o,a,s){var l={},c=t.chain(arguments).map(function(e){return e instanceof s&&[e.providerId,e]}).compact().object().value(),u=!1;return r.addListener("onOfflineChanged",function(e){u=e}),l.createLink=function(e,i){var r=c[e.provider.providerId];if(void 0!==e.sharingLink||void 0===r||"markdown"!=e.format)return void i();var o=[n.MAIN_URL,"viewer#!provider=",r.providerId];t.each(r.sharingAttributes,function(t){o.push("&"),o.push(t),o.push("="),o.push(encodeURIComponent(e[t]))}),e.sharingLink=o.join(""),i()},r.addListener("onReady",function(){if(window.viewerMode!==!1){var n=i.getURLParameter("provider");void 0===n&&(n="download");var r=c[n];if(void 0!==r){var a={};t.each(r.sharingAttributes,function(e){var t=i.getURLParameter(e);return t?void(a[e]=t):void(a=void 0)}),void 0!==a&&(e("#preview-contents, .navbar .file-title-navbar").hide(),r.importPublic(a,function(t,n,i){if(e("#preview-contents, .navbar .file-title-navbar").show(),!t){var r=o.createFile(n,i,void 0,void 0,!0);o.selectFile(r)}}))}}}),l}),define("providers/bloggerProvider",["underscore","utils","classes/Provider","helpers/googleHelper"],function(e,t,n,i){var r=new n("blogger","Blogger");return r.defaultPublishFormat="html",r.publishPreferencesInputIds=["blogger-url"],r.publish=function(t,n,r,o,a){var s=t.labelList||[];n&&void 0!==n.tags&&(s=n.tags),e.isString(s)&&(s=e.compact(s.split(/[\s,]/)));var l=n&&n.published===!1,c=n&&n.date;i.uploadBlogger(t.blogUrl,t.blogId,t.postId,s,l,c,r,o,function(e,n,i){return e?void a(e):(t.blogId=n,t.postId=i,void a())})},r.newPublishAttributes=function(e){var n={},i=t.getInputTextValue("#input-publish-blogger-url",e);return void 0!==i&&(n.blogUrl=t.checkUrl(i)),n.postId=t.getInputTextValue("#input-publish-postid"),e.isPropagationStopped()?void 0:n},r}),define("providers/bloggerPageProvider",["underscore","utils","classes/Provider","helpers/googleHelper"],function(e,t,n,i){var r=new n("bloggerpage","Blogger Page");return r.defaultPublishFormat="html",r.publishPreferencesInputIds=["blogger-url"],r.publish=function(e,t,n,r,o){var a=t&&t.published===!1,s=t&&t.date;i.uploadBloggerPage(e.blogUrl,e.blogId,e.pageId,a,s,n,r,function(t,n,i){return t?void o(t):(e.blogId=n,e.pageId=i,void o())})},r.newPublishAttributes=function(e){var n={},i=t.getInputTextValue("#input-publish-blogger-url",e);return void 0!==i&&(n.blogUrl=t.checkUrl(i)),n.pageId=t.getInputTextValue("#input-publish-pageid"),e.isPropagationStopped()?void 0:n},r}),define("providers/githubProvider",["utils","classes/Provider","settings","helpers/githubHelper"],function(e,t,n,i){var r=new t("github","GitHub");return r.publishPreferencesInputIds=["github-reponame","github-username","github-branch"],r.publish=function(e,t,r,o,a){var s=n.commitMsg;i.upload(e.repository,e.username,e.branch,e.path,o,s,a)},r.newPublishAttributes=function(t){var n={};return n.repository=e.getInputTextValue("#input-publish-github-reponame",t),n.username=e.getInputTextValue("#input-publish-github-username"),n.branch=e.getInputTextValue("#input-publish-github-branch",t),n.path=e.getInputTextValue("#input-publish-file-path",t),t.isPropagationStopped()?void 0:n},r}),define("helpers/sshHelper",["jquery","constants","core","logger","eventMgr","settings","classes/AsyncTask"],function(e,t,n,i,r,o,a){function s(e){e.onRun(function(){return u===!0?void e.error(new Error("Operation not available in offline mode.|stopPublish")):void e.chain()})}function l(e,t){var r;e&&(i.error(e),"string"==typeof e?r="SSH error: "+e+".":(r="Could not publish on SSH server.",e.code<=0&&(n.setOffline(),r="|stopPublish"))),t.error(new Error(r))}var c={},u=!1;return r.addListener("onOfflineChanged",function(e){u=e}),c.upload=function(n,i,r,c,u,d,p,f){var h=new a;s(h),h.onRun(function(){var a=o.sshProxy+"upload",s={host:n,port:i,username:r,password:c,path:u,title:d,content:p};e.ajax({url:a,data:s,type:"POST",dataType:"json",timeout:t.AJAX_TIMEOUT}).done(function(e){return void 0===e.error?void h.chain():void l(e.error,h)}).fail(function(e){var t={code:e.status,message:e.statusText};l(t,h)})}),h.onSuccess(function(){f()}),h.onError(function(e){f(e)}),h.enqueue()},c}),define("providers/sshProvider",["utils","classes/Provider","helpers/sshHelper"],function(e,t,n){var i=new t("ssh","SSH server");return i.publishPreferencesInputIds=["ssh-host","ssh-port","ssh-username","ssh-password"],i.publish=function(e,t,i,r,o){n.upload(e.host,e.port,e.username,e.password,e.path,i,r,o)},i.newPublishAttributes=function(t){var n={};return n.host=e.getInputTextValue("#input-publish-ssh-host",t,/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/),n.port=e.getInputIntValue("#input-publish-ssh-port",void 0,0),n.username=e.getInputTextValue("#input-publish-ssh-username",t),n.password=e.getInputTextValue("#input-publish-ssh-password",t),n.path=e.getInputTextValue("#input-publish-file-path",t),t.isPropagationStopped()?void 0:n},i}),define("helpers/tumblrHelper",["jquery","constants","core","utils","storage","logger","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s){function l(e){e.onRun(function(){return f===!0?void e.error(new Error("Operation not available in offline mode.|stopPublish")):void e.chain()})}function c(n){var o,a;n.onRun(function(){function s(){e.getJSON(t.TUMBLR_PROXY_URL+"request_token",function(e){void 0!==e.oauth_token?(h=e,n.chain(l)):n.error(new Error(f))})}function l(){i.redirectConfirm("You are being redirected to Tumblr authorization page.",function(){n.chain(c)},function(){n.error(new Error("Operation canceled."))})}function c(){r.removeItem("tumblrVerifier"),o=i.popupWindow("html/tumblr-oauth-client.html?oauth_token="+h.oauth_token,"stackedit-tumblr-oauth",800,600),o.focus(),a=setInterval(function(){if(o.closed===!0){if(clearInterval(a),o=void 0,a=void 0,h.oauth_verifier=r.tumblrVerifier,void 0===h.oauth_verifier)return void n.error(new Error(f));r.removeItem("tumblrVerifier"),n.chain(u)}},500)}function u(){e.getJSON(t.TUMBLR_PROXY_URL+"access_token",h,function(e){void 0!==e.access_token&&void 0!==e.access_token_secret?(r.tumblrOauthParams=JSON.stringify(e),d=e,n.chain()):n.error(new Error(f))})}if(void 0!==d)return void n.chain();var p=r.tumblrOauthParams;if(void 0!==p)return d=JSON.parse(p),void n.chain();var f="Failed to retrieve a token from Tumblr.";n.timeout=t.ASYNC_TASK_LONG_TIMEOUT;var h;n.chain(s)}),n.onError(function(){void 0!==a&&clearInterval(a),void 0!==o&&o.close()})}function u(e,t){var i;if(e)if(o.error(e),"string"==typeof e)i=e;else{if(i="Could not publish on Tumblr.",401===e.code||403===e.code)return d=void 0,r.removeItem("tumblrOauthParams"),i="Access to Tumblr account is not authorized.",void t.retry(new Error(i),1);e.code<=0&&(n.setOffline(),i="|stopPublish")}t.error(new Error(i))}var d,p={},f=!1;return a.addListener("onOfflineChanged",function(e){f=e}),p.upload=function(n,i,r,o,a,p,f,h,m){var g=new s;l(g),c(g),g.onRun(function(){var s=e.extend({blog_hostname:n,post_id:i,tags:r,format:o,state:a,date:p,title:f,content:h},d);e.ajax({url:t.TUMBLR_PROXY_URL+"post",data:s,type:"POST",dataType:"json",timeout:t.AJAX_TIMEOUT}).done(function(e){i=e.id,g.chain()}).fail(function(e){var t={code:e.status,message:e.statusText};404===t.code&&void 0!==i&&(t="Post "+i+" not found on Tumblr.|removePublish"),u(t,g)})}),g.onSuccess(function(){m(void 0,i)}),g.onError(function(e){m(e)}),g.enqueue()},p}),define("providers/tumblrProvider",["underscore","settings","utils","classes/Provider","helpers/tumblrHelper"],function(e,t,n,i,r){var o=new i("tumblr","Tumblr");return o.publishPreferencesInputIds=["tumblr-hostname"],o.publish=function(n,i,o,a,s){var l=n.tags||[];i&&void 0!==i.tags&&(l=i.tags),e.isString(l)&&(l=e.compact(l.split(/[\s,]/)));var c=function(){if("html"==n.format)return"html";if("template"==n.format){var e=n.customTmpl||t.template;if(-1!==e.indexOf("documentHTML"))return"html"}return"markdown"}(),u=i&&i.published===!1?"draft":"published",d=i&&i.date;r.upload(n.blogHostname,n.postId,l.join(","),c,u,d,o,a,function(e,t){return e?void s(e):(n.postId=t,void s())})},o.newPublishAttributes=function(e){var t={};return t.blogHostname=n.getInputTextValue("#input-publish-tumblr-hostname",e,/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/),t.postId=n.getInputTextValue("#input-publish-postid"),e.isPropagationStopped()?void 0:t},o}),define("helpers/wordpressHelper",["jquery","constants","core","utils","storage","logger","eventMgr","classes/AsyncTask"],function(e,t,n,i,r,o,a,s){function l(e){e.onRun(function(){return f===!0?void e.error(new Error("Operation not available in offline mode.|stopPublish")):void e.chain()})}function c(n){var o,a;n.onRun(function(){function s(){i.redirectConfirm("You are being redirected to WordPress authorization page.",function(){n.chain(l)},function(){n.error(new Error("Operation canceled."))})}function l(){r.removeItem("wordpressCode"),o=i.popupWindow("html/wordpress-oauth-client.html?client_id="+t.WORDPRESS_CLIENT_ID,"stackedit-wordpress-oauth",960,600),o.focus(),a=setInterval(function(){if(o.closed===!0){if(clearInterval(a),o=void 0,a=void 0,p=r.wordpressCode,void 0===p)return void n.error(new Error(u));r.removeItem("wordpressCode"),n.chain(c)}},500)}function c(){e.getJSON(t.WORDPRESS_PROXY_URL+"authenticate/"+p,function(e){void 0!==e.token?(d=e.token,r.wordpressToken=d,n.chain()):n.error(new Error(u))})}if(d=r.wordpressToken,void 0!==d)return void n.chain();var u="Failed to retrieve a token from Wordpress.";n.timeout=t.ASYNC_TASK_LONG_TIMEOUT;var p;n.chain(s)}),n.onError(function(){void 0!==a&&clearInterval(a),void 0!==o&&o.close()})}function u(e,t){var i;if(e)if(o.error(e),"string"==typeof e)i=e;else{if(i="Could not publish on WordPress.",400===e.code&&"invalid_token"==e.message||401===e.code||403===e.code)return r.removeItem("wordpressToken"),i="Access to WordPress account is not authorized.",void t.retry(new Error(i),1);e.code<=0&&(n.setOffline(),i="|stopPublish")}t.error(new Error(i))}var d,p={},f=!1;return a.addListener("onOfflineChanged",function(e){f=e}),p.upload=function(n,i,r,o,a,p,f,h){var m=new s;l(m),c(m),m.onRun(function(){var s=t.WORDPRESS_PROXY_URL+"post",l={token:d,site:n,postId:i,tags:r,status:o,date:a,title:p,content:f};e.ajax({url:s,data:l,type:"POST",dataType:"json",timeout:t.AJAX_TIMEOUT}).done(function(e){if(e.body.ID)return i=e.body.ID,void m.chain();var t={code:e.code,message:e.body.error};404===t.code&&("unknown_blog"==t.message?t='Site "'+n+'" not found on WordPress.|removePublish':"unknown_post"==t.message&&(t="Post "+i+" not found on WordPress.|removePublish")),u(t,m)}).fail(function(e){var t={code:e.status,message:e.statusText};u(t,m)})}),m.onSuccess(function(){h(void 0,i)}),m.onError(function(e){h(e)}),m.enqueue()},p}),define("providers/wordpressProvider",["underscore","utils","classes/Provider","helpers/wordpressHelper"],function(e,t,n,i){var r=new n("wordpress","WordPress");return r.defaultPublishFormat="html",r.publishPreferencesInputIds=["wordpress-site"],r.publish=function(t,n,r,o,a){var s=t.tags||[];n&&void 0!==n.tags&&(s=n.tags);var l=n&&n.published===!1?"draft":"publish",c=n&&n.date;e.isString(s)&&(s=e.compact(s.split(/[\s,]/))),i.upload(t.site,t.postId,s.join(","),l,c,r,o,function(e,n){return e?void a(e):(t.postId=n,void a())})},r.newPublishAttributes=function(e){var n={};return n.site=t.getInputTextValue("#input-publish-wordpress-site",e,/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/),n.postId=t.getInputTextValue("#input-publish-postid"),e.isPropagationStopped()?void 0:n},r}),define("publisher",["jquery","underscore","constants","utils","storage","settings","eventMgr","fileSystem","fileMgr","sharing","classes/Provider","classes/AsyncTask","providers/bloggerProvider","providers/bloggerPageProvider","providers/dropboxProvider","providers/gistProvider","providers/githubProvider","providers/gdriveProvider","providers/gdrivesecProvider","providers/gdriveterProvider","providers/sshProvider","providers/tumblrProvider","providers/wordpressProvider"],function(e,t,n,i,r,o,a,s,l,c,u,d){function p(e,t,n){return void 0===t.format&&(t.format=i.getInputRadio("radio-publish-format"),"template"==t.format&&i.getInputChecked("#checkbox-publish-custom-template")&&(t.customTmpl=i.getInputValue("#textarea-publish-custom-template"))),"markdown"==t.format?e.content:"html"==t.format?n.withoutComments:v.applyTemplate(e,t,n)}function f(e,t){if(0===S.length)return void e(t);var n=S.pop(),i=p(y,n,x),r=(y.frontMatter||{}).title||y.title;n.provider.publish(n,y.frontMatter,r,i,function(i){if(void 0!==i){var r=i.toString();if(-1!==r.indexOf("|removePublish")&&(y.removePublishLocation(n),a.onPublishRemoved(y,n)),-1!==r.indexOf("|stopPublish"))return void e(i)}f(e,t||i)})}function h(e,n){var o;do o="publish."+i.randomString();while(t.has(r,o));n.publishIndex=o,e.addPublishLocation(n),a.onNewPublishSuccess(e,n)}function m(n){var r=n.defaultPublishFormat||"markdown";T=n,e(".publish-provider-name").text(n.providerName),e('.modal-publish [class*=" modal-publish-"]').hide().filter(".modal-publish-"+n.providerId).show(),i.resetModalInputs(),i.setInputRadio("radio-publish-format",r),i.setInputChecked("#checkbox-publish-custom-template",!1),i.setInputValue("#textarea-publish-custom-template",o.template);var a=i.retrieveIgnoreError(n.providerId+".publishPreferences");a&&(t.each(n.publishPreferencesInputIds,function(e){var n=a[e];t.isBoolean(n)?i.setInputChecked("#input-publish-"+e,n):i.setInputValue("#input-publish-"+e,n)}),i.setInputRadio("radio-publish-format",a.format),i.setInputChecked("#checkbox-publish-custom-template",void 0!==a.customTmpl),i.setInputValue("#textarea-publish-custom-template",a.customTmpl||o.template)),e(".modal-publish").modal()}function g(e){var n=T,i=n.newPublishAttributes(e);if(void 0!==i){var o=l.currentFile,a=p(o,i,w),s=o.frontMatter&&o.frontMatter.title||o.title;n.publish(i,o.frontMatter,s,a,function(e){void 0===e&&(i.provider=n,c.createLink(i,function(){h(o,i)}))});var u={};t.each(n.publishPreferencesInputIds,function(e){var t=document.getElementById("input-publish-"+e);u[e]="checkbox"==t.type?t.checked:t.value}),u.format=i.format,u.customTmpl=i.customTmpl,r[n.providerId+".publishPreferences"]=JSON.stringify(u)}}var v={},b=t.chain(arguments).map(function(e){return e instanceof u&&e.isPublishEnabled===!0&&[e.providerId,e]}).compact().object().value();!function(){var e={};t.each(s,function(t){i.retrieveIndexArray(t.fileIndex+".publish").forEach(function(n){try{var o=JSON.parse(r[n]);o.publishIndex=n;var s=b[o.provider];if(!s)throw new Error("Invalid provider ID: "+o.provider);o.provider=s,t.publishLocations[n]=o,e[n]=o}catch(l){a.onError(l),i.removeIndexFromArray(t.fileIndex+".publish",n)}})}),Object.keys(r).forEach(function(t){var n=t.match(/publish\.\S+/);n&&!e.hasOwnProperty(n[0])&&r.removeItem(t)})}(),v.applyTemplate=function(e,n,i){try{var r=n&&n.customTmpl||o.template;return t.template(r,{documentTitle:e.title,documentMarkdown:e.content,strippedDocumentMarkdown:e.content.substring(e.frontMatter?e.frontMatter._frontMatter.length:0),documentHTML:i.withoutComments,documentHTMLWithComments:i.withComments,frontMatter:e.frontMatter,publishAttributes:n})}catch(s){return a.onError(s),s.message}};var y,x,w,S=[];a.addListener("onPreviewFinished",function(e,t){w={withComments:e,withoutComments:t}});var C=!1;a.addListener("onOfflineChanged",function(e){C=e});var E=!1;v.publish=function(){E!==!0&&C!==!0&&(E=!0,a.onPublishRunning(!0),y=l.currentFile,x=w,S=t.values(y.publishLocations),f(function(e){E=!1,a.onPublishRunning(!1),void 0===e&&a.onPublishSuccess(y)}))};var T,k=["
      • ",' ',' <%= provider.providerName %>'," ","
      • "].join("");return a.addListener("onReady",function(){if(window.viewerMode===!1){var r=document.querySelector(".menu-panel .publish-on-provider-list"),s=t.reduce(b,function(e,n){return e+t.template(k,{provider:n})},"");r.innerHTML=s,t.each(b,function(t){e(r.querySelector(".action-init-publish-"+t.providerId)).click(function(){m(t)}),e(".action-publish-"+t.providerId).click(function(){m(t)})})}e(".action-process-publish").click(g);var c=e(".publish-custom-template-collapse").collapse({toggle:!1}),u=e("#textarea-publish-custom-template"),p=t.debounce(function(){c.collapse("template"==i.getInputRadio("radio-publish-format")?"show":"hide")},100);e("#checkbox-publish-custom-template").change(function(){u.prop("disabled",!this.checked)}),e("input:radio[name=radio-publish-format]").change(function(){p()}),e(".modal-publish").on("hidden.bs.modal",function(){c.collapse("hide")}),e(".action-download-md").click(function(){var e=l.currentFile.content,t=l.currentFile.title;i.saveAs(e,t+".md")}),e(".action-download-html").click(function(){var e=l.currentFile.title;i.saveAs(w.withoutComments,e+".html")}),e(".action-download-template").click(function(){var e=l.currentFile,t=v.applyTemplate(e,void 0,w);i.saveAs(t,e.title+(-1===o.template.indexOf("documentHTML")?".md":".html"))}),e(".action-download-pdf").click(function(){var e,t=l.currentFile,r=v.applyTemplate(t,{customTmpl:o.pdfTemplate},w),s=new d;s.onRun(function(){if(C===!0)return a.onError("Operation not available in offline mode."),void s.chain();var t=new XMLHttpRequest;t.open("POST",n.HTMLTOPDF_URL,!0),t.setRequestHeader("Content-type","application/x-www-form-urlencoded"),t.setRequestHeader("page-size",o.pdfPageSize),t.responseType="blob",t.onreadystatechange=function(){4==this.readyState&&(200==this.status?e=this.response:a.onError("Error when trying to generate PDF: "+this.status),s.chain())},t.send(r)}),s.onSuccess(function(){void 0!==e&&i.saveAs(e,l.currentFile.title+".pdf")}),s.enqueue()})}),a.onPublisherCreated(v),v}),define("providers/gplusProvider",["jquery","underscore","utils","storage","classes/Provider","eventMgr","helpers/googleHelper"],function(e,t,n,i,r,o,a){function s(e,n){var i;return t.find(e.thumbnails,function(e){var t=!1;return e.url.replace(/^(.*[\/=]s)\d.*?(\/[^\/]+)?$/,function(e,r,o){i=r+n+(o||""),t=!0}),t}),i}function l(){return c.thumbnails?(n.resetModalInputs(),e(".modal-import-image img").prop("src",s(c,128)),n.setInputValue("#input-import-image-title",c.name),f&&n.setInputValue("#input-import-image-size",f.size),void e(".modal-import-image").modal()):(o.onError("Image "+c.name+" is not accessible."),void u(!0))}var c,u,d="gplus",p=new r(d,"Google+"),f=n.retrieveIgnoreError(d+".importImagePreferences");return p.importImage=function(e){u=e,a.picker(function(t,n){return t||0===n.length?void e(t):(c=n[0],void l())},"img")},p.uploadImage=function(t,n,i){u=i,a.uploadImg(t,n,"default",function(n,r){return n||!r?void i(n):(c={name:t,thumbnails:[]},e(r).find("thumbnail").each(function(){c.thumbnails.push({url:e(this).attr("url")})}),void l())})},o.addListener("onReady",function(){e(".action-import-image").click(function(){var e=n.getInputIntValue("#input-import-image-size",void 0,0)||0,t=n.getInputTextValue("#input-import-image-title"),r=s(c,e);t&&(r+=' "'+t+'"'),u(void 0,r),f={},e&&(f.size=e),i[d+".importImagePreferences"]=JSON.stringify(f)})}),p}),define("mediaImporter",["jquery","underscore","constants","classes/Provider","core","eventMgr","providers/gplusProvider"],function(e,t,n,i,r,o){var a={},s=t.chain(arguments).map(function(e){return e instanceof i&&[e.providerId,e]}).compact().object().value();return o.addListener("onReady",function(){function i(i){var o=(i.dataTransfer||i.target).files,a=t.first(o);if(a.name.match(/.(jpe?g|png|gif)$/i)){i.stopPropagation(),i.preventDefault();var l=new FileReader;l.onload=function(t){return function(n){var i=new Uint8Array(n.target.result);s.gplus.uploadImage(t.name,i,function(t,n){if(!t){r.catchModal=!0,e("#wmd-image-button").click(),r.catchModal=!1;var i=r.insertLinkCallback;r.insertLinkCallback=void 0,i(n||null)}})}}(a);var c=a.slice(0,n.IMPORT_IMG_MAX_CONTENT_SIZE);l.readAsArrayBuffer(c)}}function o(e){e.stopPropagation(),e.preventDefault(),e.dataTransfer.dropEffect="copy"}t.each(s,function(t){e(".action-import-image-"+t.providerId).click(function(){var e=r.insertLinkCallback;r.insertLinkCallback=void 0,t.importImage(function(t,n){return t?void e(null):void e(n||null)})})}),e("#wmd-input").each(function(){this.addEventListener("dragover",o,!1),this.addEventListener("drop",i,!1)})}),a}),define("css/css",[],function(){if("undefined"==typeof window)return{load:function(e,t,n){n()}};var e=document.getElementsByTagName("head")[0],t=window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)/)||0,n=!1,i=!0;t[1]||t[7]?n=parseInt(t[1])<6||parseInt(t[7])<=9:t[2]?i=!1:t[4]&&(n=parseInt(t[4])<18);var r={};r.pluginBuilder="./css-builder";var o,a,s,l=function(){o=document.createElement("style"),e.appendChild(o),a=o.styleSheet||o.sheet},c=0,u=[],d=function(e){c++,32==c&&(l(),c=0),a.addImport(e),o.onload=p},p=function(){s();var e=u.shift();e&&(s=e[1],d(e[0]))},f=function(e,t){if(a&&a.addImport||l(),a&&a.addImport)s?u.push([e,t]):(d(e),s=t);else{o.textContent='@import "'+e+'";';var n=setInterval(function(){try{o.sheet.cssRules,clearInterval(n),t()}catch(e){}},10)}},h=function(t,n){var r=document.createElement("link");if(r.type="text/css",r.rel="stylesheet",i)r.onload=function(){r.onload=function(){},setTimeout(n,7)};else var o=setInterval(function(){for(var e=0;eo;++o)if(n=e.attributes[o],r=n.name,"class"!=r){if(i=t.attributes.getNamedItem(r),n.specified!=i.specified)return!1;if(n.specified&&n.nodeValue!==i.nodeValue)return!1}return!0}function p(e,t){for(var n,i=0,r=e.attributes.length;r>i;++i)if(n=e.attributes[i].name,(!t||!k.arrayContains(t,n))&&e.attributes[i].specified&&"class"!=n)return!0;return!1}function f(e,t){for(var n in t)if(t.hasOwnProperty(n)&&e[n]!==t[n])return!1;return!0}function h(e){var t;return e&&1==e.nodeType&&((t=e.parentNode)&&9==t.nodeType&&"on"==t.designMode||D(e)&&!D(e.parentNode))}function m(e){return(D(e)||1!=e.nodeType&&D(e.parentNode))&&!h(e)}function g(e){return e&&1==e.nodeType&&!N.test(T(e,"display"))}function v(e){if(0==e.data.length)return!0;if(L.test(e.data))return!1;var t=T(e.parentNode,"whiteSpace");switch(t){case"pre":case"pre-wrap":case"-moz-pre-wrap":return!1;case"pre-line":if(/[\r\n]/.test(e.data))return!1}return g(e.previousSibling)||g(e.nextSibling)}function b(e,t){return k.isCharacterDataNode(e)?0==t?!!e.previousSibling:t==e.length?!!e.nextSibling:!0:t>0&&ta;++a)"*"==i[a]?this.applyToAnyTagName=!0:this.tagNames.push(i[a].toLowerCase());else this.tagNames=[this.elementTagName]}function E(e,t,n){return new C(e,t,n)}e.requireModules(["WrappedSelection","WrappedRange"]);var T,k=e.dom,_="span",I=function(){function e(e,t,n){return t&&n?" ":""}return function(t,n){t.className&&(t.className=t.className.replace(new RegExp("(?:^|\\s)"+n+"(?:\\s|$)"),e))}}();"undefined"!=typeof window.getComputedStyle?T=function(e,t){return k.getWindow(e).getComputedStyle(e,null)[t]}:"undefined"!=typeof document.documentElement.currentStyle?T=function(e,t){return e.currentStyle[t]}:t.fail("No means of obtaining computed style properties found");var D;!function(){var e=document.createElement("div");D="boolean"==typeof e.isContentEditable?function(e){return e&&1==e.nodeType&&e.isContentEditable}:function(e){return e&&1==e.nodeType&&"false"!=e.contentEditable?"true"==e.contentEditable||D(e.parentNode):!1}}();var N=/^inline(-block|-table)?$/i,L=/[^\r\n\t\f \u200B]/,M=w(!1),A=w(!0);S.prototype={doMerge:function(){for(var e,t,n,i=[],r=0,o=this.textNodes.length;o>r;++r)e=this.textNodes[r],t=e.parentNode,i[r]=e.data,r&&(t.removeChild(e),t.hasChildNodes()||t.parentNode.removeChild(t));return this.firstTextNode.data=n=i.join(""),n},getLength:function(){for(var e=this.textNodes.length,t=0;e--;)t+=this.textNodes[e].length;return t},toString:function(){for(var e=[],t=0,n=this.textNodes.length;n>t;++t)e[t]="'"+this.textNodes[t].data+"'";return"[Merge("+e.join(",")+")]"}};var R=["elementTagName","ignoreWhiteSpace","applyToEditableOnly"],P={"class":"className"};C.prototype={elementTagName:_,elementProperties:{},ignoreWhiteSpace:!0,applyToEditableOnly:!1,hasClass:function(e){return 1==e.nodeType&&k.arrayContains(this.tagNames,e.tagName.toLowerCase())&&i(e,this.cssClass)},getSelfOrAncestorWithClass:function(e){for(;e;){if(this.hasClass(e,this.cssClass))return e;e=e.parentNode}return null},isModifiable:function(e){return!this.applyToEditableOnly||m(e)},isIgnorableWhiteSpaceNode:function(e){return this.ignoreWhiteSpace&&e&&3==e.nodeType&&v(e)},postApply:function(e,t,n){for(var i,r,o,a=e[0],s=e[e.length-1],l=[],c=a,u=s,d=0,p=s.length,f=0,h=e.length;h>f;++f)r=e[f],o=M(r,!n),o?(i||(i=new S(o),l.push(i)),i.textNodes.push(r),r===a&&(c=i.firstTextNode,d=c.length),r===s&&(u=i.firstTextNode,p=i.getLength())):i=null;var m=A(s,!n);if(m&&(i||(i=new S(s),l.push(i)),i.textNodes.push(m)),l.length){for(f=0,h=l.length;h>f;++f)l[f].doMerge();t.setStart(c,d),t.setEnd(u,p)}},createContainer:function(t){var n=t.createElement(this.elementTagName);return e.util.extend(n,this.elementProperties),r(n,this.cssClass),n},applyToTextNode:function(e){var t=e.parentNode;if(1==t.childNodes.length&&k.arrayContains(this.tagNames,t.tagName.toLowerCase()))r(t,this.cssClass);else{var n=this.createContainer(k.getDocument(e));e.parentNode.insertBefore(n,e),n.appendChild(e)}},isRemovable:function(e){return e.tagName.toLowerCase()==this.elementTagName&&a(e)==this.elementSortedClassName&&f(e,this.elementProperties)&&!p(e,this.attrExceptions)&&this.isModifiable(e)},undoToTextNode:function(e,t,n){if(!t.containsNode(n)){var i=t.cloneRange();i.selectNode(n),i.isPointInRange(t.endContainer,t.endOffset)&&(y(n,t.endContainer,t.endOffset,[t]),t.setEndAfter(n)),i.isPointInRange(t.startContainer,t.startOffset)&&(n=y(n,t.startContainer,t.startOffset,[t]))}this.isRemovable(n)?l(n):I(n,this.cssClass)},applyToRange:function(e){e.splitBoundaries();var t=u(e);if(t.length){for(var n,i=0,r=t.length;r>i;++i)n=t[i],this.isIgnorableWhiteSpaceNode(n)||this.getSelfOrAncestorWithClass(n)||!this.isModifiable(n)||this.applyToTextNode(n);e.setStart(t[0],0),n=t[t.length-1],e.setEnd(n,n.length),this.normalize&&this.postApply(t,e,!1)}},applyToSelection:function(t){t=t||window;var n,i=e.getSelection(t),r=i.getAllRanges();i.removeAllRanges();for(var o=r.length;o--;)n=r[o],this.applyToRange(n),i.addRange(n)},undoToRange:function(e){e.splitBoundaries();var t,n,i=u(e),r=i[i.length-1];if(i.length){for(var o=0,a=i.length;a>o;++o)t=i[o],n=this.getSelfOrAncestorWithClass(t),n&&this.isModifiable(t)&&this.undoToTextNode(t,e,n),e.setStart(i[0],0),e.setEnd(r,r.length); +this.normalize&&this.postApply(i,e,!0)}},undoToSelection:function(t){t=t||window;var n,i=e.getSelection(t),r=i.getAllRanges();i.removeAllRanges();for(var o=0,a=r.length;a>o;++o)n=r[o],this.undoToRange(n),i.addRange(n)},getTextSelectedByRange:function(e,t){var n=t.cloneRange();n.selectNodeContents(e);var i=n.intersection(t),r=i?i.toString():"";return n.detach(),r},isAppliedToRange:function(e){if(e.collapsed)return!!this.getSelfOrAncestorWithClass(e.commonAncestorContainer);for(var t,n=e.getNodes([3]),i=0;t=n[i++];)if(!this.isIgnorableWhiteSpaceNode(t)&&c(e,t)&&this.isModifiable(t)&&!this.getSelfOrAncestorWithClass(t))return!1;return!0},isAppliedToSelection:function(t){t=t||window;for(var n=e.getSelection(t),i=n.getAllRanges(),r=i.length;r--;)if(!this.isAppliedToRange(i[r]))return!1;return!0},toggleRange:function(e){this.isAppliedToRange(e)?this.undoToRange(e):this.applyToRange(e)},toggleSelection:function(e){this.isAppliedToSelection(e)?this.undoToSelection(e):this.applyToSelection(e)},detach:function(){}},C.util={hasClass:i,addClass:r,removeClass:I,hasSameClasses:s,replaceWithOwnChildren:l,elementsHaveSameNonClassAttributes:d,elementHasNonClassAttributes:p,splitNodeAt:y,isEditableElement:D,isEditingHost:h,isEditable:m},e.CssClassApplier=C,e.createCssClassApplier=E}),define("rangy-cssclassapplier",function(){}),requirejs.config({waitSeconds:0,packages:[{name:"css",location:"bower-libs/require-css",main:"css"},{name:"less",location:"bower-libs/require-less",main:"less"}],paths:{jquery:"bower-libs/jquery/jquery",underscore:"bower-libs/underscore/underscore",crel:"bower-libs/crel/crel",jgrowl:"bower-libs/jgrowl/jquery.jgrowl",mousetrap:"bower-libs/mousetrap/mousetrap","mousetrap-record":"bower-libs/mousetrap/plugins/record/mousetrap-record",toMarkdown:"bower-libs/to-markdown/src/to-markdown",text:"bower-libs/requirejs-text/text",mathjax:"../libs/MathJax/MathJax.js?config=TeX-AMS_HTML",bootstrap:"bower-libs/bootstrap/dist/js/bootstrap",requirejs:"bower-libs/requirejs/require","google-code-prettify":"bower-libs/google-code-prettify/src/prettify",highlightjs:"libs/highlight/highlight.pack","jquery-waitforimages":"bower-libs/waitForImages/src/jquery.waitforimages","jquery-ui":"bower-libs/jquery-ui/ui/jquery-ui","jquery-ui-core":"bower-libs/jquery-ui/ui/jquery.ui.core","jquery-ui-widget":"bower-libs/jquery-ui/ui/jquery.ui.widget","jquery-ui-mouse":"bower-libs/jquery-ui/ui/jquery.ui.mouse","jquery-ui-draggable":"bower-libs/jquery-ui/ui/jquery.ui.draggable","jquery-ui-effect":"bower-libs/jquery-ui/ui/jquery.ui.effect","jquery-ui-effect-slide":"bower-libs/jquery-ui/ui/jquery.ui.effect-slide",FileSaver:"bower-libs/FileSaver/FileSaver",stacktrace:"bower-libs/stacktrace/stacktrace","requirejs-text":"bower-libs/requirejs-text/text","bootstrap-tour":"bower-libs/bootstrap-tour/build/js/bootstrap-tour",css_browser_selector:"bower-libs/css_browser_selector/css_browser_selector","pagedown-extra":"bower-libs/pagedown-extra/Markdown.Extra",pagedown:"libs/Markdown.Editor","require-css":"bower-libs/require-css/css",xregexp:"bower-libs/xregexp/xregexp-all",yaml:"bower-libs/yaml.js","yaml.js":"bower-libs/yaml.js","yaml-js":"bower-libs/yaml.js/bin/yaml",css:"bower-libs/require-css/css","css-builder":"bower-libs/require-css/css-builder",normalize:"bower-libs/require-css/normalize",prism:"bower-libs/prism/prism","prism-core":"bower-libs/prism/components/prism-core",MutationObservers:"bower-libs/MutationObservers/MutationObserver",WeakMap:"bower-libs/WeakMap/weakmap",rangy:"bower-libs/rangy/rangy-core","rangy-cssclassapplier":"bower-libs/rangy/rangy-cssclassapplier",diff_match_patch:"bower-libs/google-diff-match-patch-js/diff_match_patch",diff_match_patch_uncompressed:"bower-libs/google-diff-match-patch-js/diff_match_patch_uncompressed",jsondiffpatch:"bower-libs/jsondiffpatch/build/bundle",hammerjs:"bower-libs/hammerjs/hammer"},shim:{underscore:{exports:"_"},mathjax:["libs/mathjax_init"],jgrowl:{deps:["jquery"],exports:"jQuery.jGrowl"},diff_match_patch_uncompressed:{exports:"diff_match_patch"},jsondiffpatch:["diff_match_patch_uncompressed"],rangy:{exports:"rangy"},"rangy-cssclassapplier":["rangy"],mousetrap:{exports:"Mousetrap"},"yaml-js":{exports:"YAML"},"prism-core":{exports:"Prism"},"bower-libs/prism/components/prism-markup":["prism-core"],"libs/prism-latex":["prism-core"],"libs/prism-markdown":["bower-libs/prism/components/prism-markup","libs/prism-latex"],"bootstrap-record":["mousetrap"],toMarkdown:{deps:["jquery"],exports:"toMarkdown"},stacktrace:{exports:"printStackTrace"},FileSaver:{exports:"saveAs"},MutationObservers:["WeakMap"],highlightjs:{exports:"hljs"},"bootstrap-tour":{deps:["bootstrap"],exports:"Tour"},bootstrap:["jquery"],"jquery-waitforimages":["jquery"],pagedown:["libs/Markdown.Converter"],"pagedown-extra":["libs/Markdown.Converter"]}});try{var test="seLocalStorageCheck";localStorage.setItem(test,test),localStorage.removeItem(test);var obj={};Object.defineProperty(obj,"prop",{get:function(){},set:function(){}})}catch(e){throw alert("Your browser is not supported, sorry!"),e}window.viewerMode=/(^| )viewer($| )/.test(document.body.className),window.theme=localStorage.themeV3||"default";var themeModule="less!themes/"+window.theme;-1!==window.baseDir.indexOf("-min")&&(themeModule="css!themes/"+window.theme),require(["jquery","rangy","core","eventMgr","synchronizer","publisher","mediaImporter","css","rangy-cssclassapplier",themeModule],function(e,t,n,i){window.noStart||e(function(){t.init(),n.onReady(),window.applicationCache&&window.applicationCache.addEventListener("updateready",function(){window.applicationCache.status===window.applicationCache.UPDATEREADY&&(window.applicationCache.swapCache(),i.onMessage("New version available!\nJust refresh the page to upgrade."))},!1)})}),define("main",function(){}); \ No newline at end of file diff --git a/public/res-min/themes/default.css b/public/res-min/themes/default.css index 7acd62a5..14a49773 100644 --- a/public/res-min/themes/default.css +++ b/public/res-min/themes/default.css @@ -1317,6 +1317,7 @@ a{-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, .list-group-item{padding:10px 15px;margin-bottom:0}.list-group .list-group-item{border-radius:0} a.list-group-item:hover,a.list-group-item:focus{color:#036;border-top-color:rgba(0,128,255,0.1);border-bottom-color:rgba(0,128,255,0.1)} .bring-to-front{z-index:1050 !important} +.dialog-header-message{position:absolute;top:12px;right:55px;font-weight:bold} .btn{padding:8px 11px;-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s;transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s} .btn-default:hover,.btn-default:focus,.btn-default:active,.open .btn-default.dropdown-toggle{color:#036;border-color:rgba(0,128,255,0.1);background-color:rgba(102,128,153,0.04) !important} .btn-primary:hover,.btn-primary:focus,.btn-primary:active,.open .btn-primary.dropdown-toggle{color:#036;border-color:rgba(0,128,255,0.1);background-color:#dae3eb !important} diff --git a/public/res-min/themes/gray.css b/public/res-min/themes/gray.css index 0bb83dad..c5ece24e 100644 --- a/public/res-min/themes/gray.css +++ b/public/res-min/themes/gray.css @@ -1317,6 +1317,7 @@ a{-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, .list-group-item{padding:10px 15px;margin-bottom:0}.list-group .list-group-item{border-radius:0} a.list-group-item:hover,a.list-group-item:focus{color:#343434;border-top-color:rgba(128,128,128,0.1);border-bottom-color:rgba(128,128,128,0.1)} .bring-to-front{z-index:1050 !important} +.dialog-header-message{position:absolute;top:12px;right:55px;font-weight:bold} .btn{padding:8px 11px;-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s;transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s} .btn-default:hover,.btn-default:focus,.btn-default:active,.open .btn-default.dropdown-toggle{color:#343434;border-color:rgba(128,128,128,0.1);background-color:rgba(128,128,128,0.04) !important} .btn-primary:hover,.btn-primary:focus,.btn-primary:active,.open .btn-primary.dropdown-toggle{color:#343434;border-color:rgba(128,128,128,0.1);background-color:#e3e3e3 !important} diff --git a/public/res-min/themes/night.css b/public/res-min/themes/night.css index c16fd10d..75a9ff8a 100644 --- a/public/res-min/themes/night.css +++ b/public/res-min/themes/night.css @@ -1317,6 +1317,7 @@ a{-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, .list-group-item{padding:10px 15px;margin-bottom:0}.list-group .list-group-item{border-radius:0} a.list-group-item:hover,a.list-group-item:focus{color:#b3b3b3;border-top-color:rgba(255,255,255,0.1);border-bottom-color:rgba(255,255,255,0.1)} .bring-to-front{z-index:1050 !important} +.dialog-header-message{position:absolute;top:12px;right:55px;font-weight:bold} .btn{padding:8px 11px;-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s;transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s} .btn-default:hover,.btn-default:focus,.btn-default:active,.open .btn-default.dropdown-toggle{color:#b3b3b3;border-color:rgba(255,255,255,0.1);background-color:rgba(255,255,255,0.04) !important} .btn-primary:hover,.btn-primary:focus,.btn-primary:active,.open .btn-primary.dropdown-toggle{color:#b3b3b3;border-color:rgba(255,255,255,0.1);background-color:#525252 !important} diff --git a/public/res-min/themes/original.css b/public/res-min/themes/original.css index 6a2263de..eb8f6fcd 100644 --- a/public/res-min/themes/original.css +++ b/public/res-min/themes/original.css @@ -1317,6 +1317,7 @@ a{-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, .list-group-item{padding:10px 15px;margin-bottom:0}.list-group .list-group-item{border-radius:0} a.list-group-item:hover,a.list-group-item:focus{color:#4e4e4e;border-top-color:rgba(154,154,154,0.1);border-bottom-color:rgba(154,154,154,0.1)} .bring-to-front{z-index:1050 !important} +.dialog-header-message{position:absolute;top:12px;right:55px;font-weight:bold} .btn{padding:8px 11px;-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s;transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s} .btn-default:hover,.btn-default:focus,.btn-default:active,.open .btn-default.dropdown-toggle{color:#4e4e4e;border-color:rgba(154,154,154,0.1);background-color:rgba(154,154,154,0.16) !important} .btn-primary:hover,.btn-primary:focus,.btn-primary:active,.open .btn-primary.dropdown-toggle{color:#4e4e4e;border-color:rgba(154,154,154,0.1);background-color:#dcdcdc !important} diff --git a/public/res-min/themes/school.css b/public/res-min/themes/school.css index b402b7fb..cd786a25 100644 --- a/public/res-min/themes/school.css +++ b/public/res-min/themes/school.css @@ -1317,6 +1317,7 @@ a{-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, .list-group-item{padding:10px 15px;margin-bottom:0}.list-group .list-group-item{border-radius:0} a.list-group-item:hover,a.list-group-item:focus{color:#2d2d2d;border-top-color:rgba(121,121,121,0.1);border-bottom-color:rgba(121,121,121,0.1)} .bring-to-front{z-index:1050 !important} +.dialog-header-message{position:absolute;top:12px;right:55px;font-weight:bold} .btn{padding:8px 11px;-webkit-transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s;transition:background-color ease-in-out .15s, color ease-in-out .15s, border-color ease-in-out .15s} .btn-default:hover,.btn-default:focus,.btn-default:active,.open .btn-default.dropdown-toggle{color:#2d2d2d;border-color:rgba(121,121,121,0.1);background-color:rgba(143,134,104,0.04) !important} .btn-primary:hover,.btn-primary:focus,.btn-primary:active,.open .btn-primary.dropdown-toggle{color:#2d2d2d;border-color:rgba(121,121,121,0.1);background-color:#dcdcdc !important} diff --git a/public/res/core.js b/public/res/core.js index ddfbc2a4..d5be9e8a 100644 --- a/public/res/core.js +++ b/public/res/core.js @@ -139,7 +139,7 @@ define([ utils.setInputValue("#input-settings-pdf-page-size", settings.pdfPageSize); // SSH proxy utils.setInputValue("#input-settings-ssh-proxy", settings.sshProxy); - + // Load extension settings eventMgr.onLoadSettings(); } @@ -196,36 +196,7 @@ define([ storage.themeV3 = theme; } } -/* - var $navbarElt; - var $leftBtnElts; - var $rightBtnElts; - var $btnDropdown; - var $titleContainer; - var marginWidth = 18 * 2 + 25 + 25; - var titleWidth = 18 + 348; - var leftButtonsWidth = 18 * 5 + 80 + 160 + 160 + 40 + 80; - var rightButtonsWidth = 18 + 80; - var buttonsDropdownWidth = 40; - function adjustWindow() { - if(!window.viewerMode) { - var maxWidth = $navbarElt.width(); - if(marginWidth + titleWidth + leftButtonsWidth + rightButtonsWidth > maxWidth) { - $btnDropdown.show().find('.dropdown-menu').append($leftBtnElts); - if(marginWidth + titleWidth + rightButtonsWidth + buttonsDropdownWidth > maxWidth) { - $btnDropdown.find('.dropdown-menu').append($rightBtnElts); - } - else { - $titleContainer.before($rightBtnElts); - } - } - else { - $btnDropdown.hide().after($leftBtnElts); - $titleContainer.before($rightBtnElts); - } - } - } -*/ + // Create the PageDown editor var pagedownEditor; var fileDesc; @@ -258,7 +229,7 @@ define([ undoManager: editor.undoMgr }); - // Custom insert link dialog + // Custom insert link dialog pagedownEditor.hooks.set("insertLinkDialog", function(callback) { core.insertLinkCallback = callback; utils.resetModalInputs(); @@ -275,7 +246,7 @@ define([ $(".modal-insert-image").modal(); return true; }); - + eventMgr.onPagedownConfigure(pagedownEditor); pagedownEditor.hooks.chain("onPreviewRefresh", eventMgr.onAsyncPreview); pagedownEditor.run(); @@ -314,10 +285,10 @@ define([ else { document.body.innerHTML = bodyIndexHTML; } - + // Initialize utils library utils.init(); - + // listen to online/offline events $(window).on('offline', core.setOffline); $(window).on('online', setOnline); @@ -328,9 +299,9 @@ define([ // Detect user activity $(document).mousemove(setUserActive).keypress(setUserActive); - layout.init(); + layout.init(); editor.init(); - + // Do periodic tasks intervalId = window.setInterval(function() { utils.updateCurrentTime(); @@ -346,7 +317,7 @@ define([ // Other initialization that are not prioritary eventMgr.addListener("onReady", function() { - + $('.modal').on('shown.bs.modal', function() { var $elt = $(this); setTimeout(function() { @@ -368,7 +339,7 @@ define([ $(this).find(".modal-footer a:last").click(); } }); - + // Click events on "insert link" and "insert image" dialog buttons $(".action-insert-link").click(function(e) { var value = utils.getInputTextValue($("#input-insert-link"), e); @@ -567,6 +538,8 @@ define([ }, ''); document.getElementById('input-settings-theme').innerHTML = themeOptions; } + + $('.modal-header').append('Give your feedback '); }); return core; diff --git a/public/res/styles/main.less b/public/res/styles/main.less index f30d1827..a778426e 100644 --- a/public/res/styles/main.less +++ b/public/res/styles/main.less @@ -268,6 +268,13 @@ a { z-index: 1050 !important; } +.dialog-header-message { + position: absolute; + top: 12px; + right: 55px; + font-weight: bold; +} + /******************* * Buttons