/* SCEditor v3.1.1 | (C) 2017, Sam Clarke | sceditor.com/license */

!function(){"use strict";sceditor.plugins.undo=function(){var n,o,r,i,a=this,s="",c=0,u=!1,d=!1,l=!1,e=50,t=[],g=0;function f(e){var t;d=!0,o.sourceMode(e.sourceMode),e.sourceMode?(o.val(e.value,!1),o.sourceEditorCaret(e.caret)):(o.getBody().innerHTML=e.value,function(e,t){try{var n=t.startPositions,o=t.endPositions;e.setStart(S(r,n),n[0]),e.setEnd(S(r,o),o[0])}catch(e){console&&console.warn&&console.warn("[SCEditor] Undo plugin lost caret",e)}}(t=o.getRangeHelper().selectedRange(),e.caret),o.getRangeHelper().selectRange(t)),o.focus(),d=!1}function p(e,t){var n=e[t];e[t]=function(){var e=u;!e&&!d&&i&&o.getRangeHelper().hasSelection()&&h(),u=!0,n.apply(this,arguments),e||(u=!1,d||(v(),s=""))}}function v(){g&&(t.length-=g,g=0),0<e&&t.length>e&&t.shift(),i={},h(),t.push(i)}function h(){var e,t=o.sourceMode();i.caret=t?o.sourceEditorCaret():(e=o.getRangeHelper().selectedRange(),r.normalize(),{startPositions:y(e.startContainer,e.startOffset),endPositions:y(e.endContainer,e.endOffset)}),i.sourceMode=t,i.value=t?o.getSourceEditorValue(!1):o.getBody().innerHTML}function E(){n===document.activeElement&&a.signalSelectionchangedEvent()}function y(e,t){for(var n=[t],o=e;o&&"BODY"!==o.tagName;)n.push(function(e){var t=0;for(;e=e.previousSibling;)t++;return t}(o)),o=o.parentNode;return n}function S(e,t){for(var n=t.length-1;e&&0<n;n--)e=e.childNodes[t[n]];return e}a.init=function(){e=(o=this).undoLimit||e,o.addShortcut("ctrl+z",a.undo),o.addShortcut("ctrl+shift+z",a.redo),o.addShortcut("ctrl+y",a.redo)},a.signalReady=function(){function e(e){"historyUndo"===e.inputType?(a.undo(),e.preventDefault()):"historyRedo"===e.inputType&&(a.redo(),e.preventDefault())}function t(){s="",v()}n=o.getContentAreaContainer().nextSibling,r=o.getBody(),v(),p(o,"setWysiwygEditorValue"),p(o,"setSourceEditorValue"),p(o,"sourceEditorInsertText"),p(o.getRangeHelper(),"insertNode"),p(o,"toggleSourceMode"),r.addEventListener("beforeinput",e),n.addEventListener("beforeinput",e),r.addEventListener("compositionend",t),n.addEventListener("compositionend",t),document.addEventListener("selectionchange",E)},a.destroy=function(){document.removeEventListener("selectionchange",E)},a.undo=function(){return i=null,g<t.length-1&&(g++,f(t[t.length-1-g])),!1},a.redo=function(){return 0<g&&(g--,f(t[t.length-1-g])),!1},a.signalSelectionchangedEvent=function(){d||l?l=!1:(i&&h(),s="")},a.signalInputEvent=function(e){var t=e.inputType;if(l=!0,t&&!e.isComposing)switch(e.inputType){case"deleteContentBackward":i&&s===t&&c<20?h():(v(),c=0),s=t;break;case"insertText":c+=e.data?e.data.length:1,i&&s===t&&c<20&&!/\s$/.test(e.data)?h():(v(),c=0),s=t;break;default:s="sce-misc",c=0,v()}}}}();