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),
 
  38         clone.find('*').addBack().each(function() {
 
  40                 clonedData = $(this).data();
 
  42             _.pairs(clonedData).forEach(function(pair) {
 
  45                 if(_.isFunction(value.clone)) {
 
  46                     clonedData[key] = value.clone(node.document.createDocumentNode(el));
 
  50         return this.document.createDocumentNode(clone[0]);
 
  53     getPath: function(ancestor) {
 
  54         if(!(this.document.containsNode(this))) {
 
  58         var nodePath = [this].concat(this.parents()),
 
  60         ancestor = ancestor || this.document.root;
 
  62         nodePath.some(function(node, i) {
 
  63             if(node.sameNode(ancestor)) {
 
  69         if(idx !== undefined) {
 
  70             nodePath = nodePath.slice(0, idx);
 
  72         toret = nodePath.map(function(node) {return node.getIndex(); });
 
  78         return this.document.root.sameNode(this);
 
  81     sameNode: function(otherNode) {
 
  82         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
 
  86         var parentNode = this.nativeNode.parentNode;
 
  87         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
 
  88             return this.document.createDocumentNode(parentNode);
 
  94         var parent = this.parent(),
 
  95             parents = parent ? parent.parents() : [];
 
  97             parents.unshift(parent);
 
 103         var myIdx = this.getIndex();
 
 104         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
 
 111         var myIdx = this.getIndex(),
 
 112             parentContents = this.parent().contents();
 
 113         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
 
 116     isSurroundedByTextElements: function() {
 
 117         var prev = this.prev(),
 
 119         return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
 
 122     triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
 
 123         var node = (metaData && metaData.node) ? metaData.node : this,
 
 124             event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
 
 125         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
 
 126             if(type === 'nodeMoved') {
 
 127                 event.meta.parent = origParent;
 
 129             this.document.trigger('change', event);
 
 131         if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
 
 132              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
 
 133              this.document.trigger('change', event);
 
 137     getNodeInsertion: function(node) {
 
 138         return this.document.getNodeInsertion(node);
 
 141     getIndex: function() {
 
 145         return this.parent().indexOf(this);
 
 150 var ElementNode = function(nativeNode, document) {
 
 151     DocumentNode.call(this, nativeNode, document);
 
 153 ElementNode.prototype = Object.create(DocumentNode.prototype);
 
 155 $.extend(ElementNode.prototype, {
 
 156     nodeType: Node.ELEMENT_NODE,
 
 158     setData: function(key, value) {
 
 159         if(value !== undefined) {
 
 160             this._$.data(key, value);
 
 162             this._$.removeData(_.keys(this._$.data()));
 
 167     getData: function(key) {
 
 169             return this._$.data(key);
 
 171         return this._$.data();
 
 174     getTagName: function() {
 
 175         return this.nativeNode.tagName.toLowerCase();
 
 178     contents: function(selector) {
 
 180             document = this.document;
 
 182             this._$.children(selector).each(function() {
 
 183                 toret.push(document.createDocumentNode(this));
 
 186             this._$.contents().each(function() {
 
 187                 toret.push(document.createDocumentNode(this));
 
 193     indexOf: function(node) {
 
 194         return this._$.contents().index(node._$);
 
 197     getAttr: function(name) {
 
 198         return this._$.attr(name);
 
 201     getAttrs: function() {
 
 203         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
 
 204             toret.push(this.nativeNode.attributes[i]);
 
 209     containsNode: function(node) {
 
 210         return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
 
 214         var wrapper = $('<div>');
 
 215         wrapper.append(this._getXMLDOMToDump());
 
 216         return wrapper.html();
 
 219     _getXMLDOMToDump: function() {
 
 225 var TextNode = function(nativeNode, document) {
 
 226     DocumentNode.call(this, nativeNode, document);
 
 228 TextNode.prototype = Object.create(DocumentNode.prototype);
 
 230 $.extend(TextNode.prototype, {
 
 231     nodeType: Node.TEXT_NODE,
 
 233     getText: function() {
 
 234         return this.nativeNode.data;
 
 237     triggerTextChangeEvent: function() {
 
 238         var event = new events.ChangeEvent('nodeTextChange', {node: this});
 
 239         this.document.trigger('change', event);
 
 244 var parseXML = function(xml) {
 
 245     var toret = $($.trim(xml));
 
 247         throw new Error('Unable to parse XML: ' + xml);
 
 253 var registerTransformation = function(desc, name, target) {
 
 254     var Transformation = transformations.createContextTransformation(desc, name);
 
 255     target[name] = function() {
 
 257             args = Array.prototype.slice.call(arguments, 0);
 
 258         return instance.transform(Transformation, args);
 
 262 var registerMethod = function(methodName, method, target) {
 
 263     if(target[methodName]) {
 
 264         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
 
 265             .replace('{target}', target)
 
 266             .replace('{methodName}', methodName)
 
 269     target[methodName] = method;
 
 273 var Document = function(xml, extensions) {
 
 276     this._currentTransaction = null;
 
 277     this._transformationLevel = 0;
 
 279     this._nodeMethods = {};
 
 280     this._textNodeMethods = {};
 
 281     this._elementNodeMethods = {};
 
 282     this._nodeTransformations = {};
 
 283     this._textNodeTransformations = {};
 
 284     this._elementNodeTransformations = {};
 
 286     this.registerExtension(coreTransformations);
 
 288     (extensions || []).forEach(function(extension) {
 
 289         this.registerExtension(extension);
 
 294 $.extend(Document.prototype, Backbone.Events, {
 
 295     ElementNodeFactory: ElementNode,
 
 296     TextNodeFactory: TextNode,
 
 298     createDocumentNode: function(from) {
 
 299         if(!(from instanceof Node)) {
 
 300             if(typeof from === 'string') {
 
 301                 from = parseXML(from);
 
 302                 this.normalizeXML(from);
 
 304                 if(from.text !== undefined) {
 
 305                     /* globals document */
 
 306                     from = document.createTextNode(from.text);
 
 309                         throw new Error('tagName missing');
 
 311                     var node = $('<' + from.tagName + '>');
 
 313                     _.keys(from.attrs || {}).forEach(function(key) {
 
 314                         node.attr(key, from.attrs[key]);
 
 321         var Factory, typeMethods, typeTransformations;
 
 322         if(from.nodeType === Node.TEXT_NODE) {
 
 323             Factory = this.TextNodeFactory;
 
 324             typeMethods = this._textNodeMethods;
 
 325             typeTransformations = this._textNodeTransformations;
 
 326         } else if(from.nodeType === Node.ELEMENT_NODE) {
 
 327             Factory = this.ElementNodeFactory;
 
 328             typeMethods = this._elementNodeMethods;
 
 329             typeTransformations = this._elementNodeTransformations;
 
 331         var toret = new Factory(from, this);
 
 332         _.extend(toret, this._nodeMethods);
 
 333         _.extend(toret, typeMethods);
 
 335         _.extend(toret, this._nodeTransformations);
 
 336         _.extend(toret, typeTransformations);
 
 338         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
 
 339         _.keys(toret.__super__).forEach(function(key) {
 
 340             toret.__super__[key] = _.bind(toret.__super__[key], toret);
 
 346     loadXML: function(xml, options) {
 
 347         options = options || {};
 
 348         this._defineDocumentProperties($(parseXML(xml)));
 
 349         this.normalizeXML(this.dom);
 
 350         if(!options.silent) {
 
 351             this.trigger('contentSet');
 
 355     normalizeXML: function(nativeNode) {
 
 356         void(nativeNode); // noop
 
 360         return this.root.toXML();
 
 363     containsNode: function(node) {
 
 364         return this.root && this.root.containsNode(node);
 
 367     getSiblingParents: function(params) {
 
 368         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
 
 369             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
 
 370             noSiblingParents = null;
 
 372         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
 
 373             return noSiblingParents;
 
 376         var stop = Math.min(parents1.length, parents2.length),
 
 378         for(i = 0; i < stop; i++) {
 
 379             if(parents1[i].sameNode(parents2[i])) {
 
 387         return {node1: parents1[i], node2: parents2[i]};
 
 390     trigger: function() {
 
 391         Backbone.Events.trigger.apply(this, arguments);
 
 394     getNodeInsertion: function(node) {
 
 396         if(node instanceof DocumentNode) {
 
 397             insertion.ofNode = node;
 
 398             insertion.insertsNew = !this.containsNode(node);
 
 400           insertion.ofNode = this.createDocumentNode(node);
 
 401           insertion.insertsNew = true;
 
 406     registerMethod: function(methodName, method, dstName) {
 
 410             documentNode: doc._nodeMethods,
 
 411             textNode: doc._textNodeMethods,
 
 412             elementNode: doc._elementNodeMethods
 
 414         registerMethod(methodName, method, destination);
 
 417     registerTransformation: function(desc, name, dstName) {
 
 421             documentNode: doc._nodeTransformations,
 
 422             textNode: doc._textNodeTransformations,
 
 423             elementNode: doc._elementNodeTransformations
 
 425         registerTransformation(desc, name, destination);
 
 428     registerExtension: function(extension) {
 
 431         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
 
 432             var dstExtension = extension[dstName];
 
 434                 if(dstExtension.methods) {
 
 435                     _.pairs(dstExtension.methods).forEach(function(pair) {
 
 436                         var methodName = pair[0],
 
 439                         doc.registerMethod(methodName, method, dstName);
 
 444                 if(dstExtension.transformations) {
 
 445                     _.pairs(dstExtension.transformations).forEach(function(pair) {
 
 448                         doc.registerTransformation(desc, name, dstName);
 
 455     ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
 
 456         var hasChanged = false,
 
 457             changeMonitor = function() {
 
 461         this.on('change', changeMonitor);
 
 462         action.call(context);
 
 463         this.off('change', changeMonitor);
 
 466             if(documentChangedHandler) {
 
 467                 documentChangedHandler.call(context);
 
 470             if(documentUnchangedHandler) {
 
 471                 documentUnchangedHandler.call(context);
 
 476     transform: function(Transformation, args) {
 
 477         var toret, transformation;
 
 479         if(!this._currentTransaction) {
 
 480             return this.transaction(function() {
 
 481                 return this.transform(Transformation, args);
 
 485         if(typeof Transformation === 'function') {
 
 486             transformation = new Transformation(this, this, args);
 
 488             transformation = Transformation;
 
 491             this._transformationLevel++;
 
 496                     toret = transformation.run({beUndoable:this._transformationLevel === 1});
 
 499                     if(this._transformationLevel === 1 && !this._undoInProgress) {
 
 500                         this._currentTransaction.pushTransformation(transformation);
 
 502                     if(!this._undoInProgress && this._transformationLevel === 1) {
 
 508             this._transformationLevel--;
 
 511             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
 
 515         var transaction = this.undoStack.pop(),
 
 517             transformations, stopAt;
 
 520             this._undoInProgress = true;
 
 522             // We will modify this array in a minute so make sure we work on a copy.
 
 523             transformations = transaction.transformations.slice(0);
 
 525             if(transformations.length > 1) {
 
 526                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
 
 528                 transformations.some(function(t, idx) {
 
 529                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
 
 534                 if(stopAt !== undefined) {
 
 535                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
 
 536                     transformations = transformations.slice(0, stopAt+1);
 
 540             transformations.reverse();
 
 541             transformations.forEach(function(t) {
 
 545             this._undoInProgress = false;
 
 546             this.redoStack.push(transaction);
 
 550         var transaction = this.redoStack.pop();
 
 552             this._transformationLevel++;
 
 553             transaction.transformations.forEach(function(t) {
 
 554                 t.run({beUndoable: true});
 
 556             this._transformationLevel--;
 
 557             this.undoStack.push(transaction);
 
 561     startTransaction: function(metadata) {
 
 562         if(this._currentTransaction) {
 
 563             throw new Error('Nested transactions not supported!');
 
 565         this._currentTransaction = new Transaction([], metadata);
 
 568     endTransaction: function() {
 
 569         if(!this._currentTransaction) {
 
 570             throw new Error('End of transaction requested, but there is no transaction in progress!');
 
 572         if(this._currentTransaction.hasTransformations()) {
 
 573             this.undoStack.push(this._currentTransaction);
 
 575         this._currentTransaction = null;
 
 578     transaction: function(callback, context, metadata) {
 
 580         this.startTransaction(metadata);
 
 581         toret = callback.call(context);
 
 582         this.endTransaction();
 
 586     getNodeByPath: function(path) {
 
 587         var toret = this.root;
 
 588         path.forEach(function(idx) {
 
 589             toret = toret.contents()[idx];
 
 594     _defineDocumentProperties: function($document) {
 
 596         Object.defineProperty(doc, 'root', {get: function() {
 
 600             return doc.createDocumentNode($document[0]);
 
 601         }, configurable: true});
 
 602         Object.defineProperty(doc, 'dom', {get: function() {
 
 607         }, configurable: true});
 
 611 var Transaction = function(transformations, metadata) {
 
 612     this.transformations = transformations || [];
 
 613     this.metadata = metadata;
 
 615 $.extend(Transaction.prototype, {
 
 616     pushTransformation: function(transformation) {
 
 617         this.transformations.push(transformation);
 
 619     hasTransformations: function() {
 
 620         return this.transformations.length > 0;
 
 626     documentFromXML: function(xml) {
 
 627         var doc = new Document(xml);
 
 631     elementNodeFromXML: function(xml) {
 
 632         return this.documentFromXML(xml).root;
 
 636     DocumentNode: DocumentNode,
 
 637     ElementNode: ElementNode,