6 ], function($, _, Backbone, events) {
 
  11 var TEXT_NODE = Node.TEXT_NODE;
 
  14 var DocumentNode = function(nativeNode, document) {
 
  16         throw new Error('undefined document for a node');
 
  18     this.document = document;
 
  19     this._setNativeNode(nativeNode);
 
  23 $.extend(DocumentNode.prototype, {
 
  24     _setNativeNode: function(nativeNode) {
 
  25         this.nativeNode = nativeNode;
 
  26         this._$ = $(nativeNode);
 
  34     sameNode: function(otherNode) {
 
  35         return otherNode && this.nativeNode === otherNode.nativeNode;
 
  39         return this.nativeNode.parentNode ? this.document.createElementNode(this.nativeNode.parentNode) : null;
 
  42     after: function(node) {
 
  43         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
 
  44         this._$.after(node.nativeNode);
 
  48     before: function(node) {
 
  49         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
 
  50         this._$.before(node.nativeNode);
 
  54     wrapWith: function(node) {
 
  55         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
 
  64     triggerChangeEvent: function(type, metaData) {
 
  65         var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
 
  66         this.document.trigger('change', event);
 
  70 var ElementNode = function(nativeNode, document) {
 
  71     DocumentNode.call(this, nativeNode, document);
 
  73 ElementNode.prototype = Object.create(DocumentNode.prototype);
 
  75 $.extend(ElementNode.prototype, {
 
  76     nodeType: Node.ELEMENT_NODE,
 
  78     setData: function(key, value) {
 
  79         if(value !== undefined) {
 
  80             this._$.data(key, value);
 
  82             this._$.removeData(_.keys(this._$.data()));
 
  87     getData: function(key) {
 
  89             return this._$.data(key);
 
  91         return this._$.data();
 
  94     getTagName: function() {
 
  95         return this.nativeNode.tagName.toLowerCase();
 
  98     contents: function() {
 
 100             document = this.document;
 
 101         this._$.contents().each(function() {
 
 102             if(this.nodeType === Node.ELEMENT_NODE) {
 
 103                 toret.push(document.createElementNode(this));
 
 105             else if(this.nodeType === Node.TEXT_NODE) {
 
 106                 toret.push(document.createTextNode(this));
 
 112     indexOf: function(node) {
 
 113         return this._$.contents().index(node._$);
 
 116     setTag: function(tagName) {
 
 117         var node = this.document.createElementNode({tagName: tagName}),
 
 118             oldTagName = this.getTagName(),
 
 119             myContents = this._$.contents();
 
 121         this.getAttrs().forEach(function(attribute) {
 
 122             node.setAttr(attribute.name, attribute.value, true);
 
 124         node.setData(this.getData());
 
 126         if(this.sameNode(this.document.root)) {
 
 127             defineDocumentProperties(this.document, node._$);
 
 129         this._$.replaceWith(node._$);
 
 130         this._setNativeNode(node._$[0]);
 
 131         this._$.append(myContents);
 
 132         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
 
 135     getAttr: function(name) {
 
 136         return this._$.attr(name);
 
 139     setAttr: function(name, value, silent) {
 
 140         var oldVal = this.getAttr(name);
 
 141         this._$.attr(name, value);
 
 143             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
 
 147     getAttrs: function() {
 
 149         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
 
 150             toret.push(this.nativeNode.attributes[i]);
 
 155     append: function(node) {
 
 156         node = node instanceof DocumentNode ? node : this.document.createElementNode(node);
 
 157         this._$.append(node.nativeNode);
 
 160     prepend: function(node) {
 
 161         node = node instanceof DocumentNode ? node : this.document.createElementNode(node);
 
 162         this._$.prepend(node.nativeNode);
 
 165     unwrapContent: function() {
 
 166         var parent = this.parent();
 
 171         var parentContents = parent.contents(),
 
 172             myContents = this.contents(),
 
 173             myIdx = parent.indexOf(this);
 
 175         if(myContents.length === 0) {
 
 176             return this.detach();
 
 179         var moveLeftRange, moveRightRange, leftMerged;
 
 181         if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
 
 182             parentContents[myIdx-1].appendText(myContents[0].getText());
 
 183             myContents[0].detach();
 
 184             moveLeftRange = true;
 
 190         if(!(leftMerged && myContents.length === 1)) {
 
 191             if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
 
 192                 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
 
 193                 myContents[myContents.length-1].detach();
 
 194                 moveRightRange = true;
 
 198         var childrenLength = this.contents().length;
 
 199         this.contents().forEach(function(child) {
 
 206             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
 
 207             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
 
 211     wrapText: function(params) {
 
 212         return this.document._wrapText(_.extend({inside: this}, params));
 
 216         var wrapper = $('<div>');
 
 217         wrapper.append(this._getXMLDOMToDump());
 
 218         return wrapper.html();
 
 221     _getXMLDOMToDump: function() {
 
 226 var TextNode = function(nativeNode, document) {
 
 227     DocumentNode.call(this, nativeNode, document);
 
 229 TextNode.prototype = Object.create(DocumentNode.prototype);
 
 231 $.extend(TextNode.prototype, {
 
 232     nodeType: Node.TEXT_NODE,
 
 234     getText: function() {
 
 235         return this.nativeNode.data;
 
 238     setText: function(text) {
 
 239         this.nativeNode.data = text;
 
 240         this.triggerTextChangeEvent();
 
 243     appendText: function(text) {
 
 244         this.nativeNode.data = this.nativeNode.data + text;
 
 245         this.triggerTextChangeEvent();
 
 248     prependText: function(text) {
 
 249         this.nativeNode.data = text + this.nativeNode.data;
 
 250         this.triggerTextChangeEvent();
 
 253     wrapWith: function(desc) {
 
 254         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
 
 255             return this.document._wrapText({
 
 256                 inside: this.parent(),
 
 257                 textNodeIdx: this.parent().indexOf(this),
 
 258                 offsetStart: Math.min(desc.start, desc.end),
 
 259                 offsetEnd: Math.max(desc.start, desc.end),
 
 260                 _with: {tag: desc.tagName, attrs: desc.attrs}
 
 263             return DocumentNode.prototype.wrapWith.call(this, desc);
 
 267     triggerTextChangeEvent: function() {
 
 268         var event = new events.ChangeEvent('nodeTextChange', {node: this});
 
 269         this.document.trigger('change', event);
 
 274 var parseXML = function(xml) {
 
 278 var Document = function(xml) {
 
 282 $.extend(Document.prototype, Backbone.Events, {
 
 283     ElementNodeFactory: ElementNode,
 
 284     TextNodeFactory: TextNode,
 
 286     createElementNode: function(from) {
 
 287         if(!(from instanceof HTMLElement)) {
 
 289                 from = document.createTextNode(from.text);
 
 291                 var node = $('<' + from.tagName + '>');
 
 293                 _.keys(from.attrs || {}).forEach(function(key) {
 
 294                     node.attr(key, from.attrs[key]);
 
 300         return new this.ElementNodeFactory(from, this);
 
 303     createTextNode: function(nativeNode) {
 
 304         return new this.TextNodeFactory(nativeNode, this);
 
 307     loadXML: function(xml, options) {
 
 308         options = options || {};
 
 309         defineDocumentProperties(this, $(parseXML(xml)));
 
 310         if(!options.silent) {
 
 311             this.trigger('contentSet');
 
 316         return this.root.toXML();
 
 319     wrapNodes: function(params) {
 
 320         if(!(params.element1.parent().sameNode(params.element2.parent()))) {
 
 321             throw new Error('Wrapping non-sibling nodes not supported.');
 
 324         var parent = params.element1.parent(),
 
 325             parentContents = parent.contents(),
 
 326             wrapper = this.createElementNode({
 
 327                 tagName: params._with.tagName,
 
 328                 attrs: params._with.attrs}),
 
 329             idx1 = parent.indexOf(params.element1),
 
 330             idx2 = parent.indexOf(params.element2);
 
 338         var insertingMethod, insertingTarget;
 
 340             insertingMethod = 'prepend';
 
 341             insertingTarget = parent;
 
 343             insertingMethod = 'after';
 
 344             insertingTarget = parentContents[idx1-1];
 
 347         for(var i = idx1; i <= idx2; i++) {
 
 348             wrapper.append(parentContents[i].detach());
 
 351         insertingTarget[insertingMethod](wrapper);
 
 355     _wrapText: function(params) {
 
 356         params = _.extend({textNodeIdx: 0}, params);
 
 357         if(typeof params.textNodeIdx === 'number') {
 
 358             params.textNodeIdx = [params.textNodeIdx];
 
 361         var contentsInside = params.inside.contents(),
 
 362             idx1 = Math.min.apply(Math, params.textNodeIdx),
 
 363             idx2 = Math.max.apply(Math, params.textNodeIdx),
 
 364             textNode1 = contentsInside[idx1],
 
 365             textNode2 = contentsInside[idx2],
 
 366             sameNode = textNode1.sameNode(textNode2),
 
 367             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
 
 368             prefixInside = textNode1.getText().substr(params.offsetStart),
 
 369             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
 
 370             suffixOutside = textNode2.getText().substr(params.offsetEnd)
 
 373         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
 
 374             throw new Error('Wrapping text in non-sibling text nodes not supported.');
 
 377         var wrapperElement = this.createElementNode({tagName: params._with.tag, attrs: params._with.attrs});
 
 378         textNode1.after(wrapperElement);
 
 381         if(prefixOutside.length > 0) {
 
 382             wrapperElement.before({text:prefixOutside});
 
 385             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
 
 386             wrapperElement.append({text: core});
 
 389             if(prefixInside.length > 0) {
 
 390                 wrapperElement.append({text: prefixInside});
 
 392             for(var i = idx1 + 1; i < idx2; i++) {
 
 393                 wrapperElement.append(contentsInside[i]);
 
 395             if(suffixInside.length > 0) {
 
 396                 wrapperElement.append({text: suffixInside});
 
 399         if(suffixOutside.length > 0) {
 
 400             wrapperElement.after({text: suffixOutside});
 
 402         return wrapperElement;
 
 406 var defineDocumentProperties = function(doc, $document) {
 
 407     Object.defineProperty(doc, 'root', {get: function() {
 
 408         return doc.createElementNode($document[0]);
 
 409     }, configurable: true});
 
 410     Object.defineProperty(doc, 'dom', {get: function() {
 
 412     }, configurable: true});
 
 416     documentFromXML: function(xml) {
 
 417         return new Document(parseXML(xml));
 
 420     elementNodeFromXML: function(xml) {
 
 421         return this.documentFromXML(xml).root;
 
 425     DocumentNode: DocumentNode,
 
 426     ElementNode: ElementNode