(function () {
	CKEDITOR.plugins.add("cursor", {
		init: function (editor) {
			var handleCursor = function () {
				var selection = editor.getSelection();
				var range = selection.getRanges()[0];

				var startCon = range.startContainer.getAscendant("p", true);
				var endCon = range.endContainer.getAscendant("p", true);

				if (startCon.$.isSameNode(endCon.$)) {
					if (range.startOffset === range.endOffset) return;

					var mark = new CKEDITOR.dom.element("mark", editor.document);
					mark.$.textContent = selection.getSelectedText();

					editor.insertElement(mark);
				} else {
					var startText = startCon.getText();
					var startMark = new CKEDITOR.dom.element("mark", editor.document);
					startCon.$.textContent = startText.slice(0, range.startOffset);
					startMark.$.textContent = startText.slice(range.startOffset);
					startCon.$.append(startMark.$);

					var endText = endCon.getText();
					var endMark = new CKEDITOR.dom.element("mark", editor.document);
					endCon.$.textContent = endText.slice(range.endOffset);
					endMark.$.textContent = endText.slice(0, range.endOffset);
					endCon.$.prepend(endMark.$);
				}
			};

			editor.on("contentDom", function () {
				var editable = editor.editable();

				// editable.attachListener(editor.document, "mouseup", handleCursor);
				// editable.attachListener(editor.document, "keyup", handleCursor);
			});
		}
	});
})();
