6     'smartxml/transformations',
 
   8 ], function($, _, Backbone, events, transformations, coreTransformations) {
 
  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, {
 
  25     transform: function(Transformation, args) {
 
  26         var transformation = new Transformation(this.document, this, args);
 
  27         return this.document.transform(transformation);
 
  30     _setNativeNode: function(nativeNode) {
 
  31         this.nativeNode = nativeNode;
 
  32         this._$ = $(nativeNode);
 
  36         var clone = this._$.clone(true, true);
 
  37         clone.find('*').addBack().each(function() {
 
  38             var clonedData = $(this).data();
 
  39             _.pairs(clonedData).forEach(function(pair) {
 
  42                 if(_.isFunction(value.clone)) {
 
  43                     clonedData[key] = value.clone();
 
  47         return this.document.createDocumentNode(clone[0]);
 
  50     getPath: function(ancestor) {
 
  51         if(!(this.document.containsNode(this))) {
 
  55         var nodePath = [this].concat(this.parents()),
 
  57         ancestor = ancestor || this.document.root;
 
  59         nodePath.some(function(node, i) {
 
  60             if(node.sameNode(ancestor)) {
 
  66         if(idx !== 'undefined') {
 
  67             nodePath = nodePath.slice(0, idx);
 
  69         toret = nodePath.map(function(node) {return node.getIndex(); });
 
  75         return this.document.root.sameNode(this);
 
  78     sameNode: function(otherNode) {
 
  79         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
 
  83         var parentNode = this.nativeNode.parentNode;
 
  84         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
 
  85             return this.document.createDocumentNode(parentNode);
 
  91         var parent = this.parent(),
 
  92             parents = parent ? parent.parents() : [];
 
  94             parents.unshift(parent);
 
 100         var myIdx = this.getIndex();
 
 101         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
 
 108         var myIdx = this.getIndex(),
 
 109             parentContents = this.parent().contents();
 
 110         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
 
 113     isSurroundedByTextElements: function() {
 
 114         var prev = this.prev(),
 
 116         return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
 
 119     triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
 
 120         var node = (metaData && metaData.node) ? metaData.node : this,
 
 121             event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
 
 122         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
 
 123             this.document.trigger('change', event);
 
 125         if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
 
 126              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
 
 127              this.document.trigger('change', event);
 
 131     getNodeInsertion: function(node) {
 
 132         return this.document.getNodeInsertion(node);
 
 135     getIndex: function() {
 
 139         return this.parent().indexOf(this);
 
 144 var ElementNode = function(nativeNode, document) {
 
 145     DocumentNode.call(this, nativeNode, document);
 
 147 ElementNode.prototype = Object.create(DocumentNode.prototype);
 
 149 $.extend(ElementNode.prototype, {
 
 150     nodeType: Node.ELEMENT_NODE,
 
 152     setData: function(key, value) {
 
 153         if(value !== undefined) {
 
 154             this._$.data(key, value);
 
 156             this._$.removeData(_.keys(this._$.data()));
 
 161     getData: function(key) {
 
 163             return this._$.data(key);
 
 165         return this._$.data();
 
 168     getTagName: function() {
 
 169         return this.nativeNode.tagName.toLowerCase();
 
 172     contents: function(selector) {
 
 174             document = this.document;
 
 176             this._$.children(selector).each(function() {
 
 177                 toret.push(document.createDocumentNode(this));
 
 180             this._$.contents().each(function() {
 
 181                 toret.push(document.createDocumentNode(this));
 
 187     indexOf: function(node) {
 
 188         return this._$.contents().index(node._$);
 
 191     getAttr: function(name) {
 
 192         return this._$.attr(name);
 
 195     getAttrs: function() {
 
 197         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
 
 198             toret.push(this.nativeNode.attributes[i]);
 
 204         var wrapper = $('<div>');
 
 205         wrapper.append(this._getXMLDOMToDump());
 
 206         return wrapper.html();
 
 209     _getXMLDOMToDump: function() {
 
 215 var TextNode = function(nativeNode, document) {
 
 216     DocumentNode.call(this, nativeNode, document);
 
 218 TextNode.prototype = Object.create(DocumentNode.prototype);
 
 220 $.extend(TextNode.prototype, {
 
 221     nodeType: Node.TEXT_NODE,
 
 223     getText: function() {
 
 224         return this.nativeNode.data;
 
 227     triggerTextChangeEvent: function() {
 
 228         var event = new events.ChangeEvent('nodeTextChange', {node: this});
 
 229         this.document.trigger('change', event);
 
 234 var parseXML = function(xml) {
 
 235     var toret = $($.trim(xml));
 
 237         throw new Error('Unable to parse XML: ' + xml);
 
 243 var registerTransformation = function(desc, name, target) {
 
 244     var Transformation = transformations.createContextTransformation(desc, name);
 
 245     target[name] = function() {
 
 247             args = Array.prototype.slice.call(arguments, 0);
 
 248         return instance.transform(Transformation, args);
 
 252 var registerMethod = function(methodName, method, target) {
 
 253     if(target[methodName]) {
 
 254         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
 
 255             .replace('{target}', target)
 
 256             .replace('{methodName}', methodName)
 
 259     target[methodName] = method;
 
 263 var Document = function(xml) {
 
 267     this._transactionStack = [];
 
 268     this._transformationLevel = 0;
 
 270     this._nodeMethods = {};
 
 271     this._textNodeMethods = {};
 
 272     this._elementNodeMethods = {};
 
 273     this._nodeTransformations = {};
 
 274     this._textNodeTransformations = {};
 
 275     this._elementNodeTransformations = {};
 
 277     this.registerExtension(coreTransformations);
 
 280 $.extend(Document.prototype, Backbone.Events, {
 
 281     ElementNodeFactory: ElementNode,
 
 282     TextNodeFactory: TextNode,
 
 284     createDocumentNode: function(from) {
 
 285         if(!(from instanceof Node)) {
 
 286             if(typeof from === 'string') {
 
 287                 from = parseXML(from);
 
 288                 this.normalizeXML(from);
 
 290                 if(from.text !== undefined) {
 
 291                     /* globals document */
 
 292                     from = document.createTextNode(from.text);
 
 295                         throw new Error('tagName missing');
 
 297                     var node = $('<' + from.tagName + '>');
 
 299                     _.keys(from.attrs || {}).forEach(function(key) {
 
 300                         node.attr(key, from.attrs[key]);
 
 307         var Factory, typeMethods, typeTransformations;
 
 308         if(from.nodeType === Node.TEXT_NODE) {
 
 309             Factory = this.TextNodeFactory;
 
 310             typeMethods = this._textNodeMethods;
 
 311             typeTransformations = this._textNodeTransformations;
 
 312         } else if(from.nodeType === Node.ELEMENT_NODE) {
 
 313             Factory = this.ElementNodeFactory;
 
 314             typeMethods = this._elementNodeMethods;
 
 315             typeTransformations = this._elementNodeTransformations;
 
 317         var toret = new Factory(from, this);
 
 318         _.extend(toret, this._nodeMethods);
 
 319         _.extend(toret, typeMethods);
 
 321         _.extend(toret, this._nodeTransformations);
 
 322         _.extend(toret, typeTransformations);
 
 324         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
 
 325         _.keys(toret.__super__).forEach(function(key) {
 
 326             toret.__super__[key] = _.bind(toret.__super__[key], toret);
 
 332     loadXML: function(xml, options) {
 
 333         options = options || {};
 
 334         this._defineDocumentProperties($(parseXML(xml)));
 
 335         this.normalizeXML(this.dom);
 
 336         if(!options.silent) {
 
 337             this.trigger('contentSet');
 
 341     normalizeXML: function(nativeNode) {
 
 342         void(nativeNode); // noop
 
 346         return this.root.toXML();
 
 349     containsNode: function(node) {
 
 350         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
 
 353     getSiblingParents: function(params) {
 
 354         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
 
 355             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
 
 356             noSiblingParents = null;
 
 358         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
 
 359             return noSiblingParents;
 
 363         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
 
 364             if(parents1[i].sameNode(parents2[i])) {
 
 369         return {node1: parents1[i], node2: parents2[i]};
 
 372     trigger: function() {
 
 373         Backbone.Events.trigger.apply(this, arguments);
 
 376     getNodeInsertion: function(node) {
 
 378         if(node instanceof DocumentNode) {
 
 379             insertion.ofNode = node;
 
 380             insertion.insertsNew = !this.containsNode(node);
 
 382           insertion.ofNode = this.createDocumentNode(node);
 
 383           insertion.insertsNew = true;
 
 388     registerMethod: function(methodName, method, dstName) {
 
 392             documentNode: doc._nodeMethods,
 
 393             textNode: doc._textNodeMethods,
 
 394             elementNode: doc._elementNodeMethods
 
 396         registerMethod(methodName, method, destination);
 
 399     registerTransformation: function(desc, name, dstName) {
 
 403             documentNode: doc._nodeTransformations,
 
 404             textNode: doc._textNodeTransformations,
 
 405             elementNode: doc._elementNodeTransformations
 
 407         registerTransformation(desc, name, destination);
 
 410     registerExtension: function(extension) {
 
 413         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
 
 414             var dstExtension = extension[dstName];
 
 416                 if(dstExtension.methods) {
 
 417                     _.pairs(dstExtension.methods).forEach(function(pair) {
 
 418                         var methodName = pair[0],
 
 421                         doc.registerMethod(methodName, method, dstName);
 
 426                 if(dstExtension.transformations) {
 
 427                     _.pairs(dstExtension.transformations).forEach(function(pair) {
 
 430                         doc.registerTransformation(desc, name, dstName);
 
 437     transform: function(Transformation, args) {
 
 438         var toret, transformation;
 
 440         if(typeof Transformation === 'function') {
 
 441             transformation = new Transformation(this, this, args);
 
 443             transformation = Transformation;
 
 446             this._transformationLevel++;
 
 447             toret = transformation.run({beUndoable:this._transformationLevel === 1});
 
 448             if(this._transformationLevel === 1 && !this._undoInProgress) {
 
 449                 if(this._transactionInProgress) {
 
 450                     this._transactionStack.push(transformation);
 
 452                     this.undoStack.push(transformation);
 
 455             if(!this._undoInProgress && this._transformationLevel === 1) {
 
 458             this._transformationLevel--;
 
 461             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
 
 465         var transformationObject = this.undoStack.pop(),
 
 467             transformations, stopAt;
 
 469         if(transformationObject) {
 
 470             this._undoInProgress = true;
 
 472             if(_.isArray(transformationObject)) {
 
 473                 // We will modify this array in a minute so make sure we work on a copy.
 
 474                 transformations = transformationObject.slice(0);
 
 476                 // Lets normalize single transformation to a transaction containing one transformation.
 
 477                 transformations = [transformationObject];
 
 480             if(transformations.length > 1) {
 
 481                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
 
 483                 transformations.some(function(t, idx) {
 
 484                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
 
 489                 if(stopAt !== undefined) {
 
 490                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
 
 491                     transformations = transformations.slice(0, stopAt+1);
 
 495             transformations.reverse();
 
 496             transformations.forEach(function(t) {
 
 500             this._undoInProgress = false;
 
 501             this.redoStack.push(transformationObject);
 
 505         var transformationObject = this.redoStack.pop(),
 
 507         if(transformationObject) {
 
 508             this._transformationLevel++;
 
 509             transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
 
 510             transformations.forEach(function(t) {
 
 511                 t.run({beUndoable: true});
 
 513             this._transformationLevel--;
 
 514             this.undoStack.push(transformationObject);
 
 518     startTransaction: function() {
 
 519         if(this._transactionInProgress) {
 
 520             throw new Error('Nested transactions not supported!');
 
 522         this._transactionInProgress = true;
 
 525     endTransaction: function() {
 
 526         if(!this._transactionInProgress) {
 
 527             throw new Error('End of transaction requested, but there is no transaction in progress!');
 
 529         this._transactionInProgress = false;
 
 530         if(this._transactionStack.length) {
 
 531             this.undoStack.push(this._transactionStack);
 
 532             this._transactionStack = [];
 
 536     getNodeByPath: function(path) {
 
 537         var toret = this.root;
 
 538         path.forEach(function(idx) {
 
 539             toret = toret.contents()[idx];
 
 544     _defineDocumentProperties: function($document) {
 
 546         Object.defineProperty(doc, 'root', {get: function() {
 
 547             return doc.createDocumentNode($document[0]);
 
 548         }, configurable: true});
 
 549         Object.defineProperty(doc, 'dom', {get: function() {
 
 551         }, configurable: true});
 
 557     documentFromXML: function(xml) {
 
 558         var doc = new Document(xml);
 
 562     elementNodeFromXML: function(xml) {
 
 563         return this.documentFromXML(xml).root;
 
 567     DocumentNode: DocumentNode,
 
 568     ElementNode: ElementNode,