Projekt

Obecné

Profil

Stáhnout (110 KB) Statistiky
| Větev: | Tag: | Revize:
1
"no use strict";
2
!(function(window) {
3
if (typeof window.window != "undefined" && window.document)
4
    return;
5
if (window.require && window.define)
6
    return;
7

    
8
if (!window.console) {
9
    window.console = function() {
10
        var msgs = Array.prototype.slice.call(arguments, 0);
11
        postMessage({type: "log", data: msgs});
12
    };
13
    window.console.error =
14
    window.console.warn = 
15
    window.console.log =
16
    window.console.trace = window.console;
17
}
18
window.window = window;
19
window.ace = window;
20

    
21
window.onerror = function(message, file, line, col, err) {
22
    postMessage({type: "error", data: {
23
        message: message,
24
        data: err.data,
25
        file: file,
26
        line: line, 
27
        col: col,
28
        stack: err.stack
29
    }});
30
};
31

    
32
window.normalizeModule = function(parentId, moduleName) {
33
    // normalize plugin requires
34
    if (moduleName.indexOf("!") !== -1) {
35
        var chunks = moduleName.split("!");
36
        return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]);
37
    }
38
    // normalize relative requires
39
    if (moduleName.charAt(0) == ".") {
40
        var base = parentId.split("/").slice(0, -1).join("/");
41
        moduleName = (base ? base + "/" : "") + moduleName;
42
        
43
        while (moduleName.indexOf(".") !== -1 && previous != moduleName) {
44
            var previous = moduleName;
45
            moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
46
        }
47
    }
48
    
49
    return moduleName;
50
};
51

    
52
window.require = function require(parentId, id) {
53
    if (!id) {
54
        id = parentId;
55
        parentId = null;
56
    }
57
    if (!id.charAt)
58
        throw new Error("worker.js require() accepts only (parentId, id) as arguments");
59

    
60
    id = window.normalizeModule(parentId, id);
61

    
62
    var module = window.require.modules[id];
63
    if (module) {
64
        if (!module.initialized) {
65
            module.initialized = true;
66
            module.exports = module.factory().exports;
67
        }
68
        return module.exports;
69
    }
70
   
71
    if (!window.require.tlns)
72
        return console.log("unable to load " + id);
73
    
74
    var path = resolveModuleId(id, window.require.tlns);
75
    if (path.slice(-3) != ".js") path += ".js";
76
    
77
    window.require.id = id;
78
    window.require.modules[id] = {}; // prevent infinite loop on broken modules
79
    importScripts(path);
80
    return window.require(parentId, id);
81
};
82
function resolveModuleId(id, paths) {
83
    var testPath = id, tail = "";
84
    while (testPath) {
85
        var alias = paths[testPath];
86
        if (typeof alias == "string") {
87
            return alias + tail;
88
        } else if (alias) {
89
            return  alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name);
90
        } else if (alias === false) {
91
            return "";
92
        }
93
        var i = testPath.lastIndexOf("/");
94
        if (i === -1) break;
95
        tail = testPath.substr(i) + tail;
96
        testPath = testPath.slice(0, i);
97
    }
98
    return id;
99
}
100
window.require.modules = {};
101
window.require.tlns = {};
102

    
103
window.define = function(id, deps, factory) {
104
    if (arguments.length == 2) {
105
        factory = deps;
106
        if (typeof id != "string") {
107
            deps = id;
108
            id = window.require.id;
109
        }
110
    } else if (arguments.length == 1) {
111
        factory = id;
112
        deps = [];
113
        id = window.require.id;
114
    }
115
    
116
    if (typeof factory != "function") {
117
        window.require.modules[id] = {
118
            exports: factory,
119
            initialized: true
120
        };
121
        return;
122
    }
123

    
124
    if (!deps.length)
125
        // If there is no dependencies, we inject "require", "exports" and
126
        // "module" as dependencies, to provide CommonJS compatibility.
127
        deps = ["require", "exports", "module"];
128

    
129
    var req = function(childId) {
130
        return window.require(id, childId);
131
    };
132

    
133
    window.require.modules[id] = {
134
        exports: {},
135
        factory: function() {
136
            var module = this;
137
            var returnExports = factory.apply(this, deps.slice(0, factory.length).map(function(dep) {
138
                switch (dep) {
139
                    // Because "require", "exports" and "module" aren't actual
140
                    // dependencies, we must handle them seperately.
141
                    case "require": return req;
142
                    case "exports": return module.exports;
143
                    case "module":  return module;
144
                    // But for all other dependencies, we can just go ahead and
145
                    // require them.
146
                    default:        return req(dep);
147
                }
148
            }));
149
            if (returnExports)
150
                module.exports = returnExports;
151
            return module;
152
        }
153
    };
154
};
155
window.define.amd = {};
156
require.tlns = {};
157
window.initBaseUrls  = function initBaseUrls(topLevelNamespaces) {
158
    for (var i in topLevelNamespaces)
159
        require.tlns[i] = topLevelNamespaces[i];
160
};
161

    
162
window.initSender = function initSender() {
163

    
164
    var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter;
165
    var oop = window.require("ace/lib/oop");
166
    
167
    var Sender = function() {};
168
    
169
    (function() {
170
        
171
        oop.implement(this, EventEmitter);
172
                
173
        this.callback = function(data, callbackId) {
174
            postMessage({
175
                type: "call",
176
                id: callbackId,
177
                data: data
178
            });
179
        };
180
    
181
        this.emit = function(name, data) {
182
            postMessage({
183
                type: "event",
184
                name: name,
185
                data: data
186
            });
187
        };
188
        
189
    }).call(Sender.prototype);
190
    
191
    return new Sender();
192
};
193

    
194
var main = window.main = null;
195
var sender = window.sender = null;
196

    
197
window.onmessage = function(e) {
198
    var msg = e.data;
199
    if (msg.event && sender) {
200
        sender._signal(msg.event, msg.data);
201
    }
202
    else if (msg.command) {
203
        if (main[msg.command])
204
            main[msg.command].apply(main, msg.args);
205
        else if (window[msg.command])
206
            window[msg.command].apply(window, msg.args);
207
        else
208
            throw new Error("Unknown command:" + msg.command);
209
    }
210
    else if (msg.init) {
211
        window.initBaseUrls(msg.tlns);
212
        require("ace/lib/es5-shim");
213
        sender = window.sender = window.initSender();
214
        var clazz = require(msg.module)[msg.classname];
215
        main = window.main = new clazz(sender);
216
    }
217
};
218
})(this);
219

    
220
ace.define("ace/lib/oop",[], function(require, exports, module) {
221
"use strict";
222

    
223
exports.inherits = function(ctor, superCtor) {
224
    ctor.super_ = superCtor;
225
    ctor.prototype = Object.create(superCtor.prototype, {
226
        constructor: {
227
            value: ctor,
228
            enumerable: false,
229
            writable: true,
230
            configurable: true
231
        }
232
    });
233
};
234

    
235
exports.mixin = function(obj, mixin) {
236
    for (var key in mixin) {
237
        obj[key] = mixin[key];
238
    }
239
    return obj;
240
};
241

    
242
exports.implement = function(proto, mixin) {
243
    exports.mixin(proto, mixin);
244
};
245

    
246
});
247

    
248
ace.define("ace/lib/lang",[], function(require, exports, module) {
249
"use strict";
250

    
251
exports.last = function(a) {
252
    return a[a.length - 1];
253
};
254

    
255
exports.stringReverse = function(string) {
256
    return string.split("").reverse().join("");
257
};
258

    
259
exports.stringRepeat = function (string, count) {
260
    var result = '';
261
    while (count > 0) {
262
        if (count & 1)
263
            result += string;
264

    
265
        if (count >>= 1)
266
            string += string;
267
    }
268
    return result;
269
};
270

    
271
var trimBeginRegexp = /^\s\s*/;
272
var trimEndRegexp = /\s\s*$/;
273

    
274
exports.stringTrimLeft = function (string) {
275
    return string.replace(trimBeginRegexp, '');
276
};
277

    
278
exports.stringTrimRight = function (string) {
279
    return string.replace(trimEndRegexp, '');
280
};
281

    
282
exports.copyObject = function(obj) {
283
    var copy = {};
284
    for (var key in obj) {
285
        copy[key] = obj[key];
286
    }
287
    return copy;
288
};
289

    
290
exports.copyArray = function(array){
291
    var copy = [];
292
    for (var i=0, l=array.length; i<l; i++) {
293
        if (array[i] && typeof array[i] == "object")
294
            copy[i] = this.copyObject(array[i]);
295
        else 
296
            copy[i] = array[i];
297
    }
298
    return copy;
299
};
300

    
301
exports.deepCopy = function deepCopy(obj) {
302
    if (typeof obj !== "object" || !obj)
303
        return obj;
304
    var copy;
305
    if (Array.isArray(obj)) {
306
        copy = [];
307
        for (var key = 0; key < obj.length; key++) {
308
            copy[key] = deepCopy(obj[key]);
309
        }
310
        return copy;
311
    }
312
    if (Object.prototype.toString.call(obj) !== "[object Object]")
313
        return obj;
314
    
315
    copy = {};
316
    for (var key in obj)
317
        copy[key] = deepCopy(obj[key]);
318
    return copy;
319
};
320

    
321
exports.arrayToMap = function(arr) {
322
    var map = {};
323
    for (var i=0; i<arr.length; i++) {
324
        map[arr[i]] = 1;
325
    }
326
    return map;
327

    
328
};
329

    
330
exports.createMap = function(props) {
331
    var map = Object.create(null);
332
    for (var i in props) {
333
        map[i] = props[i];
334
    }
335
    return map;
336
};
337
exports.arrayRemove = function(array, value) {
338
  for (var i = 0; i <= array.length; i++) {
339
    if (value === array[i]) {
340
      array.splice(i, 1);
341
    }
342
  }
343
};
344

    
345
exports.escapeRegExp = function(str) {
346
    return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
347
};
348

    
349
exports.escapeHTML = function(str) {
350
    return ("" + str).replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;");
351
};
352

    
353
exports.getMatchOffsets = function(string, regExp) {
354
    var matches = [];
355

    
356
    string.replace(regExp, function(str) {
357
        matches.push({
358
            offset: arguments[arguments.length-2],
359
            length: str.length
360
        });
361
    });
362

    
363
    return matches;
364
};
365
exports.deferredCall = function(fcn) {
366
    var timer = null;
367
    var callback = function() {
368
        timer = null;
369
        fcn();
370
    };
371

    
372
    var deferred = function(timeout) {
373
        deferred.cancel();
374
        timer = setTimeout(callback, timeout || 0);
375
        return deferred;
376
    };
377

    
378
    deferred.schedule = deferred;
379

    
380
    deferred.call = function() {
381
        this.cancel();
382
        fcn();
383
        return deferred;
384
    };
385

    
386
    deferred.cancel = function() {
387
        clearTimeout(timer);
388
        timer = null;
389
        return deferred;
390
    };
391
    
392
    deferred.isPending = function() {
393
        return timer;
394
    };
395

    
396
    return deferred;
397
};
398

    
399

    
400
exports.delayedCall = function(fcn, defaultTimeout) {
401
    var timer = null;
402
    var callback = function() {
403
        timer = null;
404
        fcn();
405
    };
406

    
407
    var _self = function(timeout) {
408
        if (timer == null)
409
            timer = setTimeout(callback, timeout || defaultTimeout);
410
    };
411

    
412
    _self.delay = function(timeout) {
413
        timer && clearTimeout(timer);
414
        timer = setTimeout(callback, timeout || defaultTimeout);
415
    };
416
    _self.schedule = _self;
417

    
418
    _self.call = function() {
419
        this.cancel();
420
        fcn();
421
    };
422

    
423
    _self.cancel = function() {
424
        timer && clearTimeout(timer);
425
        timer = null;
426
    };
427

    
428
    _self.isPending = function() {
429
        return timer;
430
    };
431

    
432
    return _self;
433
};
434
});
435

    
436
ace.define("ace/range",[], function(require, exports, module) {
437
"use strict";
438
var comparePoints = function(p1, p2) {
439
    return p1.row - p2.row || p1.column - p2.column;
440
};
441
var Range = function(startRow, startColumn, endRow, endColumn) {
442
    this.start = {
443
        row: startRow,
444
        column: startColumn
445
    };
446

    
447
    this.end = {
448
        row: endRow,
449
        column: endColumn
450
    };
451
};
452

    
453
(function() {
454
    this.isEqual = function(range) {
455
        return this.start.row === range.start.row &&
456
            this.end.row === range.end.row &&
457
            this.start.column === range.start.column &&
458
            this.end.column === range.end.column;
459
    };
460
    this.toString = function() {
461
        return ("Range: [" + this.start.row + "/" + this.start.column +
462
            "] -> [" + this.end.row + "/" + this.end.column + "]");
463
    };
464

    
465
    this.contains = function(row, column) {
466
        return this.compare(row, column) == 0;
467
    };
468
    this.compareRange = function(range) {
469
        var cmp,
470
            end = range.end,
471
            start = range.start;
472

    
473
        cmp = this.compare(end.row, end.column);
474
        if (cmp == 1) {
475
            cmp = this.compare(start.row, start.column);
476
            if (cmp == 1) {
477
                return 2;
478
            } else if (cmp == 0) {
479
                return 1;
480
            } else {
481
                return 0;
482
            }
483
        } else if (cmp == -1) {
484
            return -2;
485
        } else {
486
            cmp = this.compare(start.row, start.column);
487
            if (cmp == -1) {
488
                return -1;
489
            } else if (cmp == 1) {
490
                return 42;
491
            } else {
492
                return 0;
493
            }
494
        }
495
    };
496
    this.comparePoint = function(p) {
497
        return this.compare(p.row, p.column);
498
    };
499
    this.containsRange = function(range) {
500
        return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
501
    };
502
    this.intersects = function(range) {
503
        var cmp = this.compareRange(range);
504
        return (cmp == -1 || cmp == 0 || cmp == 1);
505
    };
506
    this.isEnd = function(row, column) {
507
        return this.end.row == row && this.end.column == column;
508
    };
509
    this.isStart = function(row, column) {
510
        return this.start.row == row && this.start.column == column;
511
    };
512
    this.setStart = function(row, column) {
513
        if (typeof row == "object") {
514
            this.start.column = row.column;
515
            this.start.row = row.row;
516
        } else {
517
            this.start.row = row;
518
            this.start.column = column;
519
        }
520
    };
521
    this.setEnd = function(row, column) {
522
        if (typeof row == "object") {
523
            this.end.column = row.column;
524
            this.end.row = row.row;
525
        } else {
526
            this.end.row = row;
527
            this.end.column = column;
528
        }
529
    };
530
    this.inside = function(row, column) {
531
        if (this.compare(row, column) == 0) {
532
            if (this.isEnd(row, column) || this.isStart(row, column)) {
533
                return false;
534
            } else {
535
                return true;
536
            }
537
        }
538
        return false;
539
    };
540
    this.insideStart = function(row, column) {
541
        if (this.compare(row, column) == 0) {
542
            if (this.isEnd(row, column)) {
543
                return false;
544
            } else {
545
                return true;
546
            }
547
        }
548
        return false;
549
    };
550
    this.insideEnd = function(row, column) {
551
        if (this.compare(row, column) == 0) {
552
            if (this.isStart(row, column)) {
553
                return false;
554
            } else {
555
                return true;
556
            }
557
        }
558
        return false;
559
    };
560
    this.compare = function(row, column) {
561
        if (!this.isMultiLine()) {
562
            if (row === this.start.row) {
563
                return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
564
            }
565
        }
566

    
567
        if (row < this.start.row)
568
            return -1;
569

    
570
        if (row > this.end.row)
571
            return 1;
572

    
573
        if (this.start.row === row)
574
            return column >= this.start.column ? 0 : -1;
575

    
576
        if (this.end.row === row)
577
            return column <= this.end.column ? 0 : 1;
578

    
579
        return 0;
580
    };
581
    this.compareStart = function(row, column) {
582
        if (this.start.row == row && this.start.column == column) {
583
            return -1;
584
        } else {
585
            return this.compare(row, column);
586
        }
587
    };
588
    this.compareEnd = function(row, column) {
589
        if (this.end.row == row && this.end.column == column) {
590
            return 1;
591
        } else {
592
            return this.compare(row, column);
593
        }
594
    };
595
    this.compareInside = function(row, column) {
596
        if (this.end.row == row && this.end.column == column) {
597
            return 1;
598
        } else if (this.start.row == row && this.start.column == column) {
599
            return -1;
600
        } else {
601
            return this.compare(row, column);
602
        }
603
    };
604
    this.clipRows = function(firstRow, lastRow) {
605
        if (this.end.row > lastRow)
606
            var end = {row: lastRow + 1, column: 0};
607
        else if (this.end.row < firstRow)
608
            var end = {row: firstRow, column: 0};
609

    
610
        if (this.start.row > lastRow)
611
            var start = {row: lastRow + 1, column: 0};
612
        else if (this.start.row < firstRow)
613
            var start = {row: firstRow, column: 0};
614

    
615
        return Range.fromPoints(start || this.start, end || this.end);
616
    };
617
    this.extend = function(row, column) {
618
        var cmp = this.compare(row, column);
619

    
620
        if (cmp == 0)
621
            return this;
622
        else if (cmp == -1)
623
            var start = {row: row, column: column};
624
        else
625
            var end = {row: row, column: column};
626

    
627
        return Range.fromPoints(start || this.start, end || this.end);
628
    };
629

    
630
    this.isEmpty = function() {
631
        return (this.start.row === this.end.row && this.start.column === this.end.column);
632
    };
633
    this.isMultiLine = function() {
634
        return (this.start.row !== this.end.row);
635
    };
636
    this.clone = function() {
637
        return Range.fromPoints(this.start, this.end);
638
    };
639
    this.collapseRows = function() {
640
        if (this.end.column == 0)
641
            return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0);
642
        else
643
            return new Range(this.start.row, 0, this.end.row, 0);
644
    };
645
    this.toScreenRange = function(session) {
646
        var screenPosStart = session.documentToScreenPosition(this.start);
647
        var screenPosEnd = session.documentToScreenPosition(this.end);
648

    
649
        return new Range(
650
            screenPosStart.row, screenPosStart.column,
651
            screenPosEnd.row, screenPosEnd.column
652
        );
653
    };
654
    this.moveBy = function(row, column) {
655
        this.start.row += row;
656
        this.start.column += column;
657
        this.end.row += row;
658
        this.end.column += column;
659
    };
660

    
661
}).call(Range.prototype);
662
Range.fromPoints = function(start, end) {
663
    return new Range(start.row, start.column, end.row, end.column);
664
};
665
Range.comparePoints = comparePoints;
666

    
667
Range.comparePoints = function(p1, p2) {
668
    return p1.row - p2.row || p1.column - p2.column;
669
};
670

    
671

    
672
exports.Range = Range;
673
});
674

    
675
ace.define("ace/apply_delta",[], function(require, exports, module) {
676
"use strict";
677

    
678
function throwDeltaError(delta, errorText){
679
    console.log("Invalid Delta:", delta);
680
    throw "Invalid Delta: " + errorText;
681
}
682

    
683
function positionInDocument(docLines, position) {
684
    return position.row    >= 0 && position.row    <  docLines.length &&
685
           position.column >= 0 && position.column <= docLines[position.row].length;
686
}
687

    
688
function validateDelta(docLines, delta) {
689
    if (delta.action != "insert" && delta.action != "remove")
690
        throwDeltaError(delta, "delta.action must be 'insert' or 'remove'");
691
    if (!(delta.lines instanceof Array))
692
        throwDeltaError(delta, "delta.lines must be an Array");
693
    if (!delta.start || !delta.end)
694
       throwDeltaError(delta, "delta.start/end must be an present");
695
    var start = delta.start;
696
    if (!positionInDocument(docLines, delta.start))
697
        throwDeltaError(delta, "delta.start must be contained in document");
698
    var end = delta.end;
699
    if (delta.action == "remove" && !positionInDocument(docLines, end))
700
        throwDeltaError(delta, "delta.end must contained in document for 'remove' actions");
701
    var numRangeRows = end.row - start.row;
702
    var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0));
703
    if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars)
704
        throwDeltaError(delta, "delta.range must match delta lines");
705
}
706

    
707
exports.applyDelta = function(docLines, delta, doNotValidate) {
708
    
709
    var row = delta.start.row;
710
    var startColumn = delta.start.column;
711
    var line = docLines[row] || "";
712
    switch (delta.action) {
713
        case "insert":
714
            var lines = delta.lines;
715
            if (lines.length === 1) {
716
                docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn);
717
            } else {
718
                var args = [row, 1].concat(delta.lines);
719
                docLines.splice.apply(docLines, args);
720
                docLines[row] = line.substring(0, startColumn) + docLines[row];
721
                docLines[row + delta.lines.length - 1] += line.substring(startColumn);
722
            }
723
            break;
724
        case "remove":
725
            var endColumn = delta.end.column;
726
            var endRow = delta.end.row;
727
            if (row === endRow) {
728
                docLines[row] = line.substring(0, startColumn) + line.substring(endColumn);
729
            } else {
730
                docLines.splice(
731
                    row, endRow - row + 1,
732
                    line.substring(0, startColumn) + docLines[endRow].substring(endColumn)
733
                );
734
            }
735
            break;
736
    }
737
};
738
});
739

    
740
ace.define("ace/lib/event_emitter",[], function(require, exports, module) {
741
"use strict";
742

    
743
var EventEmitter = {};
744
var stopPropagation = function() { this.propagationStopped = true; };
745
var preventDefault = function() { this.defaultPrevented = true; };
746

    
747
EventEmitter._emit =
748
EventEmitter._dispatchEvent = function(eventName, e) {
749
    this._eventRegistry || (this._eventRegistry = {});
750
    this._defaultHandlers || (this._defaultHandlers = {});
751

    
752
    var listeners = this._eventRegistry[eventName] || [];
753
    var defaultHandler = this._defaultHandlers[eventName];
754
    if (!listeners.length && !defaultHandler)
755
        return;
756

    
757
    if (typeof e != "object" || !e)
758
        e = {};
759

    
760
    if (!e.type)
761
        e.type = eventName;
762
    if (!e.stopPropagation)
763
        e.stopPropagation = stopPropagation;
764
    if (!e.preventDefault)
765
        e.preventDefault = preventDefault;
766

    
767
    listeners = listeners.slice();
768
    for (var i=0; i<listeners.length; i++) {
769
        listeners[i](e, this);
770
        if (e.propagationStopped)
771
            break;
772
    }
773
    
774
    if (defaultHandler && !e.defaultPrevented)
775
        return defaultHandler(e, this);
776
};
777

    
778

    
779
EventEmitter._signal = function(eventName, e) {
780
    var listeners = (this._eventRegistry || {})[eventName];
781
    if (!listeners)
782
        return;
783
    listeners = listeners.slice();
784
    for (var i=0; i<listeners.length; i++)
785
        listeners[i](e, this);
786
};
787

    
788
EventEmitter.once = function(eventName, callback) {
789
    var _self = this;
790
    this.on(eventName, function newCallback() {
791
        _self.off(eventName, newCallback);
792
        callback.apply(null, arguments);
793
    });
794
    if (!callback) {
795
        return new Promise(function(resolve) {
796
            callback = resolve;
797
        });
798
    }
799
};
800

    
801

    
802
EventEmitter.setDefaultHandler = function(eventName, callback) {
803
    var handlers = this._defaultHandlers;
804
    if (!handlers)
805
        handlers = this._defaultHandlers = {_disabled_: {}};
806
    
807
    if (handlers[eventName]) {
808
        var old = handlers[eventName];
809
        var disabled = handlers._disabled_[eventName];
810
        if (!disabled)
811
            handlers._disabled_[eventName] = disabled = [];
812
        disabled.push(old);
813
        var i = disabled.indexOf(callback);
814
        if (i != -1) 
815
            disabled.splice(i, 1);
816
    }
817
    handlers[eventName] = callback;
818
};
819
EventEmitter.removeDefaultHandler = function(eventName, callback) {
820
    var handlers = this._defaultHandlers;
821
    if (!handlers)
822
        return;
823
    var disabled = handlers._disabled_[eventName];
824
    
825
    if (handlers[eventName] == callback) {
826
        if (disabled)
827
            this.setDefaultHandler(eventName, disabled.pop());
828
    } else if (disabled) {
829
        var i = disabled.indexOf(callback);
830
        if (i != -1)
831
            disabled.splice(i, 1);
832
    }
833
};
834

    
835
EventEmitter.on =
836
EventEmitter.addEventListener = function(eventName, callback, capturing) {
837
    this._eventRegistry = this._eventRegistry || {};
838

    
839
    var listeners = this._eventRegistry[eventName];
840
    if (!listeners)
841
        listeners = this._eventRegistry[eventName] = [];
842

    
843
    if (listeners.indexOf(callback) == -1)
844
        listeners[capturing ? "unshift" : "push"](callback);
845
    return callback;
846
};
847

    
848
EventEmitter.off =
849
EventEmitter.removeListener =
850
EventEmitter.removeEventListener = function(eventName, callback) {
851
    this._eventRegistry = this._eventRegistry || {};
852

    
853
    var listeners = this._eventRegistry[eventName];
854
    if (!listeners)
855
        return;
856

    
857
    var index = listeners.indexOf(callback);
858
    if (index !== -1)
859
        listeners.splice(index, 1);
860
};
861

    
862
EventEmitter.removeAllListeners = function(eventName) {
863
    if (!eventName) this._eventRegistry = this._defaultHandlers = undefined;
864
    if (this._eventRegistry) this._eventRegistry[eventName] = undefined;
865
    if (this._defaultHandlers) this._defaultHandlers[eventName] = undefined;
866
};
867

    
868
exports.EventEmitter = EventEmitter;
869

    
870
});
871

    
872
ace.define("ace/anchor",[], function(require, exports, module) {
873
"use strict";
874

    
875
var oop = require("./lib/oop");
876
var EventEmitter = require("./lib/event_emitter").EventEmitter;
877

    
878
var Anchor = exports.Anchor = function(doc, row, column) {
879
    this.$onChange = this.onChange.bind(this);
880
    this.attach(doc);
881
    
882
    if (typeof column == "undefined")
883
        this.setPosition(row.row, row.column);
884
    else
885
        this.setPosition(row, column);
886
};
887

    
888
(function() {
889

    
890
    oop.implement(this, EventEmitter);
891
    this.getPosition = function() {
892
        return this.$clipPositionToDocument(this.row, this.column);
893
    };
894
    this.getDocument = function() {
895
        return this.document;
896
    };
897
    this.$insertRight = false;
898
    this.onChange = function(delta) {
899
        if (delta.start.row == delta.end.row && delta.start.row != this.row)
900
            return;
901

    
902
        if (delta.start.row > this.row)
903
            return;
904
            
905
        var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight);
906
        this.setPosition(point.row, point.column, true);
907
    };
908
    
909
    function $pointsInOrder(point1, point2, equalPointsInOrder) {
910
        var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
911
        return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
912
    }
913
            
914
    function $getTransformedPoint(delta, point, moveIfEqual) {
915
        var deltaIsInsert = delta.action == "insert";
916
        var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row    - delta.start.row);
917
        var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
918
        var deltaStart = delta.start;
919
        var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
920
        if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
921
            return {
922
                row: point.row,
923
                column: point.column
924
            };
925
        }
926
        if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
927
            return {
928
                row: point.row + deltaRowShift,
929
                column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
930
            };
931
        }
932
        
933
        return {
934
            row: deltaStart.row,
935
            column: deltaStart.column
936
        };
937
    }
938
    this.setPosition = function(row, column, noClip) {
939
        var pos;
940
        if (noClip) {
941
            pos = {
942
                row: row,
943
                column: column
944
            };
945
        } else {
946
            pos = this.$clipPositionToDocument(row, column);
947
        }
948

    
949
        if (this.row == pos.row && this.column == pos.column)
950
            return;
951

    
952
        var old = {
953
            row: this.row,
954
            column: this.column
955
        };
956

    
957
        this.row = pos.row;
958
        this.column = pos.column;
959
        this._signal("change", {
960
            old: old,
961
            value: pos
962
        });
963
    };
964
    this.detach = function() {
965
        this.document.off("change", this.$onChange);
966
    };
967
    this.attach = function(doc) {
968
        this.document = doc || this.document;
969
        this.document.on("change", this.$onChange);
970
    };
971
    this.$clipPositionToDocument = function(row, column) {
972
        var pos = {};
973

    
974
        if (row >= this.document.getLength()) {
975
            pos.row = Math.max(0, this.document.getLength() - 1);
976
            pos.column = this.document.getLine(pos.row).length;
977
        }
978
        else if (row < 0) {
979
            pos.row = 0;
980
            pos.column = 0;
981
        }
982
        else {
983
            pos.row = row;
984
            pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
985
        }
986

    
987
        if (column < 0)
988
            pos.column = 0;
989

    
990
        return pos;
991
    };
992

    
993
}).call(Anchor.prototype);
994

    
995
});
996

    
997
ace.define("ace/document",[], function(require, exports, module) {
998
"use strict";
999

    
1000
var oop = require("./lib/oop");
1001
var applyDelta = require("./apply_delta").applyDelta;
1002
var EventEmitter = require("./lib/event_emitter").EventEmitter;
1003
var Range = require("./range").Range;
1004
var Anchor = require("./anchor").Anchor;
1005

    
1006
var Document = function(textOrLines) {
1007
    this.$lines = [""];
1008
    if (textOrLines.length === 0) {
1009
        this.$lines = [""];
1010
    } else if (Array.isArray(textOrLines)) {
1011
        this.insertMergedLines({row: 0, column: 0}, textOrLines);
1012
    } else {
1013
        this.insert({row: 0, column:0}, textOrLines);
1014
    }
1015
};
1016

    
1017
(function() {
1018

    
1019
    oop.implement(this, EventEmitter);
1020
    this.setValue = function(text) {
1021
        var len = this.getLength() - 1;
1022
        this.remove(new Range(0, 0, len, this.getLine(len).length));
1023
        this.insert({row: 0, column: 0}, text);
1024
    };
1025
    this.getValue = function() {
1026
        return this.getAllLines().join(this.getNewLineCharacter());
1027
    };
1028
    this.createAnchor = function(row, column) {
1029
        return new Anchor(this, row, column);
1030
    };
1031
    if ("aaa".split(/a/).length === 0) {
1032
        this.$split = function(text) {
1033
            return text.replace(/\r\n|\r/g, "\n").split("\n");
1034
        };
1035
    } else {
1036
        this.$split = function(text) {
1037
            return text.split(/\r\n|\r|\n/);
1038
        };
1039
    }
1040

    
1041

    
1042
    this.$detectNewLine = function(text) {
1043
        var match = text.match(/^.*?(\r\n|\r|\n)/m);
1044
        this.$autoNewLine = match ? match[1] : "\n";
1045
        this._signal("changeNewLineMode");
1046
    };
1047
    this.getNewLineCharacter = function() {
1048
        switch (this.$newLineMode) {
1049
          case "windows":
1050
            return "\r\n";
1051
          case "unix":
1052
            return "\n";
1053
          default:
1054
            return this.$autoNewLine || "\n";
1055
        }
1056
    };
1057

    
1058
    this.$autoNewLine = "";
1059
    this.$newLineMode = "auto";
1060
    this.setNewLineMode = function(newLineMode) {
1061
        if (this.$newLineMode === newLineMode)
1062
            return;
1063

    
1064
        this.$newLineMode = newLineMode;
1065
        this._signal("changeNewLineMode");
1066
    };
1067
    this.getNewLineMode = function() {
1068
        return this.$newLineMode;
1069
    };
1070
    this.isNewLine = function(text) {
1071
        return (text == "\r\n" || text == "\r" || text == "\n");
1072
    };
1073
    this.getLine = function(row) {
1074
        return this.$lines[row] || "";
1075
    };
1076
    this.getLines = function(firstRow, lastRow) {
1077
        return this.$lines.slice(firstRow, lastRow + 1);
1078
    };
1079
    this.getAllLines = function() {
1080
        return this.getLines(0, this.getLength());
1081
    };
1082
    this.getLength = function() {
1083
        return this.$lines.length;
1084
    };
1085
    this.getTextRange = function(range) {
1086
        return this.getLinesForRange(range).join(this.getNewLineCharacter());
1087
    };
1088
    this.getLinesForRange = function(range) {
1089
        var lines;
1090
        if (range.start.row === range.end.row) {
1091
            lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)];
1092
        } else {
1093
            lines = this.getLines(range.start.row, range.end.row);
1094
            lines[0] = (lines[0] || "").substring(range.start.column);
1095
            var l = lines.length - 1;
1096
            if (range.end.row - range.start.row == l)
1097
                lines[l] = lines[l].substring(0, range.end.column);
1098
        }
1099
        return lines;
1100
    };
1101
    this.insertLines = function(row, lines) {
1102
        console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead.");
1103
        return this.insertFullLines(row, lines);
1104
    };
1105
    this.removeLines = function(firstRow, lastRow) {
1106
        console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead.");
1107
        return this.removeFullLines(firstRow, lastRow);
1108
    };
1109
    this.insertNewLine = function(position) {
1110
        console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.");
1111
        return this.insertMergedLines(position, ["", ""]);
1112
    };
1113
    this.insert = function(position, text) {
1114
        if (this.getLength() <= 1)
1115
            this.$detectNewLine(text);
1116
        
1117
        return this.insertMergedLines(position, this.$split(text));
1118
    };
1119
    this.insertInLine = function(position, text) {
1120
        var start = this.clippedPos(position.row, position.column);
1121
        var end = this.pos(position.row, position.column + text.length);
1122
        
1123
        this.applyDelta({
1124
            start: start,
1125
            end: end,
1126
            action: "insert",
1127
            lines: [text]
1128
        }, true);
1129
        
1130
        return this.clonePos(end);
1131
    };
1132
    
1133
    this.clippedPos = function(row, column) {
1134
        var length = this.getLength();
1135
        if (row === undefined) {
1136
            row = length;
1137
        } else if (row < 0) {
1138
            row = 0;
1139
        } else if (row >= length) {
1140
            row = length - 1;
1141
            column = undefined;
1142
        }
1143
        var line = this.getLine(row);
1144
        if (column == undefined)
1145
            column = line.length;
1146
        column = Math.min(Math.max(column, 0), line.length);
1147
        return {row: row, column: column};
1148
    };
1149
    
1150
    this.clonePos = function(pos) {
1151
        return {row: pos.row, column: pos.column};
1152
    };
1153
    
1154
    this.pos = function(row, column) {
1155
        return {row: row, column: column};
1156
    };
1157
    
1158
    this.$clipPosition = function(position) {
1159
        var length = this.getLength();
1160
        if (position.row >= length) {
1161
            position.row = Math.max(0, length - 1);
1162
            position.column = this.getLine(length - 1).length;
1163
        } else {
1164
            position.row = Math.max(0, position.row);
1165
            position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length);
1166
        }
1167
        return position;
1168
    };
1169
    this.insertFullLines = function(row, lines) {
1170
        row = Math.min(Math.max(row, 0), this.getLength());
1171
        var column = 0;
1172
        if (row < this.getLength()) {
1173
            lines = lines.concat([""]);
1174
            column = 0;
1175
        } else {
1176
            lines = [""].concat(lines);
1177
            row--;
1178
            column = this.$lines[row].length;
1179
        }
1180
        this.insertMergedLines({row: row, column: column}, lines);
1181
    };    
1182
    this.insertMergedLines = function(position, lines) {
1183
        var start = this.clippedPos(position.row, position.column);
1184
        var end = {
1185
            row: start.row + lines.length - 1,
1186
            column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length
1187
        };
1188
        
1189
        this.applyDelta({
1190
            start: start,
1191
            end: end,
1192
            action: "insert",
1193
            lines: lines
1194
        });
1195
        
1196
        return this.clonePos(end);
1197
    };
1198
    this.remove = function(range) {
1199
        var start = this.clippedPos(range.start.row, range.start.column);
1200
        var end = this.clippedPos(range.end.row, range.end.column);
1201
        this.applyDelta({
1202
            start: start,
1203
            end: end,
1204
            action: "remove",
1205
            lines: this.getLinesForRange({start: start, end: end})
1206
        });
1207
        return this.clonePos(start);
1208
    };
1209
    this.removeInLine = function(row, startColumn, endColumn) {
1210
        var start = this.clippedPos(row, startColumn);
1211
        var end = this.clippedPos(row, endColumn);
1212
        
1213
        this.applyDelta({
1214
            start: start,
1215
            end: end,
1216
            action: "remove",
1217
            lines: this.getLinesForRange({start: start, end: end})
1218
        }, true);
1219
        
1220
        return this.clonePos(start);
1221
    };
1222
    this.removeFullLines = function(firstRow, lastRow) {
1223
        firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1);
1224
        lastRow  = Math.min(Math.max(0, lastRow ), this.getLength() - 1);
1225
        var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0;
1226
        var deleteLastNewLine  = lastRow  < this.getLength() - 1;
1227
        var startRow = ( deleteFirstNewLine ? firstRow - 1                  : firstRow                    );
1228
        var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0                           );
1229
        var endRow   = ( deleteLastNewLine  ? lastRow + 1                   : lastRow                     );
1230
        var endCol   = ( deleteLastNewLine  ? 0                             : this.getLine(endRow).length ); 
1231
        var range = new Range(startRow, startCol, endRow, endCol);
1232
        var deletedLines = this.$lines.slice(firstRow, lastRow + 1);
1233
        
1234
        this.applyDelta({
1235
            start: range.start,
1236
            end: range.end,
1237
            action: "remove",
1238
            lines: this.getLinesForRange(range)
1239
        });
1240
        return deletedLines;
1241
    };
1242
    this.removeNewLine = function(row) {
1243
        if (row < this.getLength() - 1 && row >= 0) {
1244
            this.applyDelta({
1245
                start: this.pos(row, this.getLine(row).length),
1246
                end: this.pos(row + 1, 0),
1247
                action: "remove",
1248
                lines: ["", ""]
1249
            });
1250
        }
1251
    };
1252
    this.replace = function(range, text) {
1253
        if (!(range instanceof Range))
1254
            range = Range.fromPoints(range.start, range.end);
1255
        if (text.length === 0 && range.isEmpty())
1256
            return range.start;
1257
        if (text == this.getTextRange(range))
1258
            return range.end;
1259

    
1260
        this.remove(range);
1261
        var end;
1262
        if (text) {
1263
            end = this.insert(range.start, text);
1264
        }
1265
        else {
1266
            end = range.start;
1267
        }
1268
        
1269
        return end;
1270
    };
1271
    this.applyDeltas = function(deltas) {
1272
        for (var i=0; i<deltas.length; i++) {
1273
            this.applyDelta(deltas[i]);
1274
        }
1275
    };
1276
    this.revertDeltas = function(deltas) {
1277
        for (var i=deltas.length-1; i>=0; i--) {
1278
            this.revertDelta(deltas[i]);
1279
        }
1280
    };
1281
    this.applyDelta = function(delta, doNotValidate) {
1282
        var isInsert = delta.action == "insert";
1283
        if (isInsert ? delta.lines.length <= 1 && !delta.lines[0]
1284
            : !Range.comparePoints(delta.start, delta.end)) {
1285
            return;
1286
        }
1287
        
1288
        if (isInsert && delta.lines.length > 20000) {
1289
            this.$splitAndapplyLargeDelta(delta, 20000);
1290
        }
1291
        else {
1292
            applyDelta(this.$lines, delta, doNotValidate);
1293
            this._signal("change", delta);
1294
        }
1295
    };
1296
    
1297
    this.$safeApplyDelta = function(delta) {
1298
        var docLength = this.$lines.length;
1299
        if (
1300
            delta.action == "remove" && delta.start.row < docLength && delta.end.row < docLength
1301
            || delta.action == "insert" && delta.start.row <= docLength
1302
        ) {
1303
            this.applyDelta(delta);
1304
        }
1305
    };
1306
    
1307
    this.$splitAndapplyLargeDelta = function(delta, MAX) {
1308
        var lines = delta.lines;
1309
        var l = lines.length - MAX + 1;
1310
        var row = delta.start.row; 
1311
        var column = delta.start.column;
1312
        for (var from = 0, to = 0; from < l; from = to) {
1313
            to += MAX - 1;
1314
            var chunk = lines.slice(from, to);
1315
            chunk.push("");
1316
            this.applyDelta({
1317
                start: this.pos(row + from, column),
1318
                end: this.pos(row + to, column = 0),
1319
                action: delta.action,
1320
                lines: chunk
1321
            }, true);
1322
        }
1323
        delta.lines = lines.slice(from);
1324
        delta.start.row = row + from;
1325
        delta.start.column = column;
1326
        this.applyDelta(delta, true);
1327
    };
1328
    this.revertDelta = function(delta) {
1329
        this.$safeApplyDelta({
1330
            start: this.clonePos(delta.start),
1331
            end: this.clonePos(delta.end),
1332
            action: (delta.action == "insert" ? "remove" : "insert"),
1333
            lines: delta.lines.slice()
1334
        });
1335
    };
1336
    this.indexToPosition = function(index, startRow) {
1337
        var lines = this.$lines || this.getAllLines();
1338
        var newlineLength = this.getNewLineCharacter().length;
1339
        for (var i = startRow || 0, l = lines.length; i < l; i++) {
1340
            index -= lines[i].length + newlineLength;
1341
            if (index < 0)
1342
                return {row: i, column: index + lines[i].length + newlineLength};
1343
        }
1344
        return {row: l-1, column: index + lines[l-1].length + newlineLength};
1345
    };
1346
    this.positionToIndex = function(pos, startRow) {
1347
        var lines = this.$lines || this.getAllLines();
1348
        var newlineLength = this.getNewLineCharacter().length;
1349
        var index = 0;
1350
        var row = Math.min(pos.row, lines.length);
1351
        for (var i = startRow || 0; i < row; ++i)
1352
            index += lines[i].length + newlineLength;
1353

    
1354
        return index + pos.column;
1355
    };
1356

    
1357
}).call(Document.prototype);
1358

    
1359
exports.Document = Document;
1360
});
1361

    
1362
ace.define("ace/worker/mirror",[], function(require, exports, module) {
1363
"use strict";
1364

    
1365
var Range = require("../range").Range;
1366
var Document = require("../document").Document;
1367
var lang = require("../lib/lang");
1368
    
1369
var Mirror = exports.Mirror = function(sender) {
1370
    this.sender = sender;
1371
    var doc = this.doc = new Document("");
1372
    
1373
    var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this));
1374
    
1375
    var _self = this;
1376
    sender.on("change", function(e) {
1377
        var data = e.data;
1378
        if (data[0].start) {
1379
            doc.applyDeltas(data);
1380
        } else {
1381
            for (var i = 0; i < data.length; i += 2) {
1382
                if (Array.isArray(data[i+1])) {
1383
                    var d = {action: "insert", start: data[i], lines: data[i+1]};
1384
                } else {
1385
                    var d = {action: "remove", start: data[i], end: data[i+1]};
1386
                }
1387
                doc.applyDelta(d, true);
1388
            }
1389
        }
1390
        if (_self.$timeout)
1391
            return deferredUpdate.schedule(_self.$timeout);
1392
        _self.onUpdate();
1393
    });
1394
};
1395

    
1396
(function() {
1397
    
1398
    this.$timeout = 500;
1399
    
1400
    this.setTimeout = function(timeout) {
1401
        this.$timeout = timeout;
1402
    };
1403
    
1404
    this.setValue = function(value) {
1405
        this.doc.setValue(value);
1406
        this.deferredUpdate.schedule(this.$timeout);
1407
    };
1408
    
1409
    this.getValue = function(callbackId) {
1410
        this.sender.callback(this.doc.getValue(), callbackId);
1411
    };
1412
    
1413
    this.onUpdate = function() {
1414
    };
1415
    
1416
    this.isPending = function() {
1417
        return this.deferredUpdate.isPending();
1418
    };
1419
    
1420
}).call(Mirror.prototype);
1421

    
1422
});
1423

    
1424
ace.define("ace/mode/xml/sax",[], function(require, exports, module) {
1425
var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
1426
var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\u00B7\u0300-\u036F\\ux203F-\u2040]");
1427
var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
1428
var S_TAG = 0;//tag name offerring
1429
var S_ATTR = 1;//attr name offerring 
1430
var S_ATTR_S=2;//attr name end and space offer
1431
var S_EQ = 3;//=space?
1432
var S_V = 4;//attr value(no quot value only)
1433
var S_E = 5;//attr value end and no space(quot end)
1434
var S_S = 6;//(attr value end || tag end ) && (space offer)
1435
var S_C = 7;//closed el<el />
1436

    
1437
function XMLReader(){
1438
	
1439
}
1440

    
1441
XMLReader.prototype = {
1442
	parse:function(source,defaultNSMap,entityMap){
1443
		var domBuilder = this.domBuilder;
1444
		domBuilder.startDocument();
1445
		_copy(defaultNSMap ,defaultNSMap = {})
1446
		parse(source,defaultNSMap,entityMap,
1447
				domBuilder,this.errorHandler);
1448
		domBuilder.endDocument();
1449
	}
1450
}
1451
function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
1452
  function fixedFromCharCode(code) {
1453
		if (code > 0xffff) {
1454
			code -= 0x10000;
1455
			var surrogate1 = 0xd800 + (code >> 10)
1456
				, surrogate2 = 0xdc00 + (code & 0x3ff);
1457

    
1458
			return String.fromCharCode(surrogate1, surrogate2);
1459
		} else {
1460
			return String.fromCharCode(code);
1461
		}
1462
	}
1463
	function entityReplacer(a){
1464
		var k = a.slice(1,-1);
1465
		if(k in entityMap){
1466
			return entityMap[k]; 
1467
		}else if(k.charAt(0) === '#'){
1468
			return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
1469
		}else{
1470
			errorHandler.error('entity not found:'+a);
1471
			return a;
1472
		}
1473
	}
1474
	function appendText(end){//has some bugs
1475
		var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
1476
		locator&&position(start);
1477
		domBuilder.characters(xt,0,end-start);
1478
		start = end
1479
	}
1480
	function position(start,m){
1481
		while(start>=endPos && (m = linePattern.exec(source))){
1482
			startPos = m.index;
1483
			endPos = startPos + m[0].length;
1484
			locator.lineNumber++;
1485
		}
1486
		locator.columnNumber = start-startPos+1;
1487
	}
1488
	var startPos = 0;
1489
	var endPos = 0;
1490
	var linePattern = /.+(?:\r\n?|\n)|.*$/g
1491
	var locator = domBuilder.locator;
1492
	
1493
	var parseStack = [{currentNSMap:defaultNSMapCopy}]
1494
	var closeMap = {};
1495
	var start = 0;
1496
	while(true){
1497
		var i = source.indexOf('<',start);
1498
		if(i<0){
1499
			if(!source.substr(start).match(/^\s*$/)){
1500
				var doc = domBuilder.document;
1501
    			var text = doc.createTextNode(source.substr(start));
1502
    			doc.appendChild(text);
1503
    			domBuilder.currentElement = text;
1504
			}
1505
			return;
1506
		}
1507
		if(i>start){
1508
			appendText(i);
1509
		}
1510
		switch(source.charAt(i+1)){
1511
		case '/':
1512
			var end = source.indexOf('>',i+3);
1513
			var tagName = source.substring(i+2,end);
1514
			var config;
1515
			if (parseStack.length > 1) {
1516
				config = parseStack.pop();
1517
			} else {
1518
				errorHandler.fatalError("end tag name not found for: "+tagName);
1519
				break;
1520
			}
1521
			var localNSMap = config.localNSMap;
1522
			
1523
	        if(config.tagName != tagName){
1524
	            errorHandler.fatalError("end tag name: " + tagName + " does not match the current start tagName: "+config.tagName );
1525
	        }
1526
			domBuilder.endElement(config.uri,config.localName,tagName);
1527
			if(localNSMap){
1528
				for(var prefix in localNSMap){
1529
					domBuilder.endPrefixMapping(prefix) ;
1530
				}
1531
			}
1532
			end++;
1533
			break;
1534
		case '?':// <?...?>
1535
			locator&&position(i);
1536
			end = parseInstruction(source,i,domBuilder);
1537
			break;
1538
		case '!':// <!doctype,<![CDATA,<!--
1539
			locator&&position(i);
1540
			end = parseDCC(source,i,domBuilder,errorHandler);
1541
			break;
1542
		default:
1543
			try{
1544
				locator&&position(i);
1545
				
1546
				var el = new ElementAttributes();
1547
				var end = parseElementStartPart(source,i,el,entityReplacer,errorHandler);
1548
				var len = el.length;
1549
				if(len && locator){
1550
					var backup = copyLocator(locator,{});
1551
					for(var i = 0;i<len;i++){
1552
						var a = el[i];
1553
						position(a.offset);
1554
						a.offset = copyLocator(locator,{});
1555
					}
1556
					copyLocator(backup,locator);
1557
				}
1558
				if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
1559
					el.closed = true;
1560
					if(!entityMap.nbsp){
1561
						errorHandler.warning('unclosed xml attribute');
1562
					}
1563
				}
1564
				appendElement(el,domBuilder,parseStack);
1565
				
1566
				
1567
				if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
1568
					end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
1569
				}else{
1570
					end++;
1571
				}
1572
			}catch(e){
1573
				errorHandler.error('element parse error: '+e);
1574
				end = -1;
1575
			}
1576

    
1577
		}
1578
		if(end<0){
1579
			appendText(i+1);
1580
		}else{
1581
			start = end;
1582
		}
1583
	}
1584
}
1585
function copyLocator(f,t){
1586
	t.lineNumber = f.lineNumber;
1587
	t.columnNumber = f.columnNumber;
1588
	return t;
1589
	
1590
}
1591
function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
1592
	var attrName;
1593
	var value;
1594
	var p = ++start;
1595
	var s = S_TAG;//status
1596
	while(true){
1597
		var c = source.charAt(p);
1598
		switch(c){
1599
		case '=':
1600
			if(s === S_ATTR){//attrName
1601
				attrName = source.slice(start,p);
1602
				s = S_EQ;
1603
			}else if(s === S_ATTR_S){
1604
				s = S_EQ;
1605
			}else{
1606
				throw new Error('attribute equal must after attrName');
1607
			}
1608
			break;
1609
		case '\'':
1610
		case '"':
1611
			if(s === S_EQ){//equal
1612
				start = p+1;
1613
				p = source.indexOf(c,start)
1614
				if(p>0){
1615
					value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
1616
					el.add(attrName,value,start-1);
1617
					s = S_E;
1618
				}else{
1619
					throw new Error('attribute value no end \''+c+'\' match');
1620
				}
1621
			}else if(s == S_V){
1622
				value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
1623
				el.add(attrName,value,start);
1624
				errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
1625
				start = p+1;
1626
				s = S_E
1627
			}else{
1628
				throw new Error('attribute value must after "="');
1629
			}
1630
			break;
1631
		case '/':
1632
			switch(s){
1633
			case S_TAG:
1634
				el.setTagName(source.slice(start,p));
1635
			case S_E:
1636
			case S_S:
1637
			case S_C:
1638
				s = S_C;
1639
				el.closed = true;
1640
			case S_V:
1641
			case S_ATTR:
1642
			case S_ATTR_S:
1643
				break;
1644
			default:
1645
				throw new Error("attribute invalid close char('/')")
1646
			}
1647
			break;
1648
		case ''://end document
1649
			errorHandler.error('unexpected end of input');
1650
		case '>':
1651
			switch(s){
1652
			case S_TAG:
1653
				el.setTagName(source.slice(start,p));
1654
			case S_E:
1655
			case S_S:
1656
			case S_C:
1657
				break;//normal
1658
			case S_V://Compatible state
1659
			case S_ATTR:
1660
				value = source.slice(start,p);
1661
				if(value.slice(-1) === '/'){
1662
					el.closed  = true;
1663
					value = value.slice(0,-1)
1664
				}
1665
			case S_ATTR_S:
1666
				if(s === S_ATTR_S){
1667
					value = attrName;
1668
				}
1669
				if(s == S_V){
1670
					errorHandler.warning('attribute "'+value+'" missed quot(")!!');
1671
					el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
1672
				}else{
1673
					errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
1674
					el.add(value,value,start)
1675
				}
1676
				break;
1677
			case S_EQ:
1678
				throw new Error('attribute value missed!!');
1679
			}
1680
			return p;
1681
		case '\u0080':
1682
			c = ' ';
1683
		default:
1684
			if(c<= ' '){//space
1685
				switch(s){
1686
				case S_TAG:
1687
					el.setTagName(source.slice(start,p));//tagName
1688
					s = S_S;
1689
					break;
1690
				case S_ATTR:
1691
					attrName = source.slice(start,p)
1692
					s = S_ATTR_S;
1693
					break;
1694
				case S_V:
1695
					var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
1696
					errorHandler.warning('attribute "'+value+'" missed quot(")!!');
1697
					el.add(attrName,value,start)
1698
				case S_E:
1699
					s = S_S;
1700
					break;
1701
				}
1702
			}else{//not space
1703
				switch(s){
1704
				case S_ATTR_S:
1705
					errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead!!')
1706
					el.add(attrName,attrName,start);
1707
					start = p;
1708
					s = S_ATTR;
1709
					break;
1710
				case S_E:
1711
					errorHandler.warning('attribute space is required"'+attrName+'"!!')
1712
				case S_S:
1713
					s = S_ATTR;
1714
					start = p;
1715
					break;
1716
				case S_EQ:
1717
					s = S_V;
1718
					start = p;
1719
					break;
1720
				case S_C:
1721
					throw new Error("elements closed character '/' and '>' must be connected to");
1722
				}
1723
			}
1724
		}
1725
		p++;
1726
	}
1727
}
1728
function appendElement(el,domBuilder,parseStack){
1729
	var tagName = el.tagName;
1730
	var localNSMap = null;
1731
	var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
1732
	var i = el.length;
1733
	while(i--){
1734
		var a = el[i];
1735
		var qName = a.qName;
1736
		var value = a.value;
1737
		var nsp = qName.indexOf(':');
1738
		if(nsp>0){
1739
			var prefix = a.prefix = qName.slice(0,nsp);
1740
			var localName = qName.slice(nsp+1);
1741
			var nsPrefix = prefix === 'xmlns' && localName
1742
		}else{
1743
			localName = qName;
1744
			prefix = null
1745
			nsPrefix = qName === 'xmlns' && ''
1746
		}
1747
		a.localName = localName ;
1748
		if(nsPrefix !== false){//hack!!
1749
			if(localNSMap == null){
1750
				localNSMap = {}
1751
				_copy(currentNSMap,currentNSMap={})
1752
			}
1753
			currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
1754
			a.uri = 'http://www.w3.org/2000/xmlns/'
1755
			domBuilder.startPrefixMapping(nsPrefix, value) 
1756
		}
1757
	}
1758
	var i = el.length;
1759
	while(i--){
1760
		a = el[i];
1761
		var prefix = a.prefix;
1762
		if(prefix){//no prefix attribute has no namespace
1763
			if(prefix === 'xml'){
1764
				a.uri = 'http://www.w3.org/XML/1998/namespace';
1765
			}if(prefix !== 'xmlns'){
1766
				a.uri = currentNSMap[prefix]
1767
			}
1768
		}
1769
	}
1770
	var nsp = tagName.indexOf(':');
1771
	if(nsp>0){
1772
		prefix = el.prefix = tagName.slice(0,nsp);
1773
		localName = el.localName = tagName.slice(nsp+1);
1774
	}else{
1775
		prefix = null;//important!!
1776
		localName = el.localName = tagName;
1777
	}
1778
	var ns = el.uri = currentNSMap[prefix || ''];
1779
	domBuilder.startElement(ns,localName,tagName,el);
1780
	if(el.closed){
1781
		domBuilder.endElement(ns,localName,tagName);
1782
		if(localNSMap){
1783
			for(prefix in localNSMap){
1784
				domBuilder.endPrefixMapping(prefix) 
1785
			}
1786
		}
1787
	}else{
1788
		el.currentNSMap = currentNSMap;
1789
		el.localNSMap = localNSMap;
1790
		parseStack.push(el);
1791
	}
1792
}
1793
function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
1794
	if(/^(?:script|textarea)$/i.test(tagName)){
1795
		var elEndStart =  source.indexOf('</'+tagName+'>',elStartEnd);
1796
		var text = source.substring(elStartEnd+1,elEndStart);
1797
		if(/[&<]/.test(text)){
1798
			if(/^script$/i.test(tagName)){
1799
					domBuilder.characters(text,0,text.length);
1800
					return elEndStart;
1801
			}//}else{//text area
1802
				text = text.replace(/&#?\w+;/g,entityReplacer);
1803
				domBuilder.characters(text,0,text.length);
1804
				return elEndStart;
1805
			
1806
		}
1807
	}
1808
	return elStartEnd+1;
1809
}
1810
function fixSelfClosed(source,elStartEnd,tagName,closeMap){
1811
	var pos = closeMap[tagName];
1812
	if(pos == null){
1813
		pos = closeMap[tagName] = source.lastIndexOf('</'+tagName+'>')
1814
	}
1815
	return pos<elStartEnd;
1816
}
1817
function _copy(source,target){
1818
	for(var n in source){target[n] = source[n]}
1819
}
1820
function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
1821
	var next= source.charAt(start+2)
1822
	switch(next){
1823
	case '-':
1824
		if(source.charAt(start + 3) === '-'){
1825
			var end = source.indexOf('-->',start+4);
1826
			if(end>start){
1827
				domBuilder.comment(source,start+4,end-start-4);
1828
				return end+3;
1829
			}else{
1830
				errorHandler.error("Unclosed comment");
1831
				return -1;
1832
			}
1833
		}else{
1834
			return -1;
1835
		}
1836
	default:
1837
		if(source.substr(start+3,6) == 'CDATA['){
1838
			var end = source.indexOf(']]>',start+9);
1839
			if (end > start) {
1840
				domBuilder.startCDATA();
1841
				domBuilder.characters(source,start+9,end-start-9);
1842
				domBuilder.endCDATA() 
1843
				return end+3;
1844
			} else {
1845
				errorHandler.error("Unclosed CDATA");
1846
				return -1;
1847
			}
1848
		}
1849
		var matchs = split(source,start);
1850
		var len = matchs.length;
1851
		if(len>1 && /!doctype/i.test(matchs[0][0])){
1852
			var name = matchs[1][0];
1853
			var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
1854
			var sysid = len>4 && matchs[4][0];
1855
			var lastMatch = matchs[len-1]
1856
			domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
1857
					sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
1858
			domBuilder.endDTD();
1859
			
1860
			return lastMatch.index+lastMatch[0].length
1861
		}
1862
	}
1863
	return -1;
1864
}
1865

    
1866

    
1867

    
1868
function parseInstruction(source,start,domBuilder){
1869
	var end = source.indexOf('?>',start);
1870
	if(end){
1871
		var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
1872
		if(match){
1873
			var len = match[0].length;
1874
			domBuilder.processingInstruction(match[1], match[2]) ;
1875
			return end+2;
1876
		}else{//error
1877
			return -1;
1878
		}
1879
	}
1880
	return -1;
1881
}
1882
function ElementAttributes(source){
1883
	
1884
}
1885
ElementAttributes.prototype = {
1886
	setTagName:function(tagName){
1887
		if(!tagNamePattern.test(tagName)){
1888
			throw new Error('invalid tagName:'+tagName)
1889
		}
1890
		this.tagName = tagName
1891
	},
1892
	add:function(qName,value,offset){
1893
		if(!tagNamePattern.test(qName)){
1894
			throw new Error('invalid attribute:'+qName)
1895
		}
1896
		this[this.length++] = {qName:qName,value:value,offset:offset}
1897
	},
1898
	length:0,
1899
	getLocalName:function(i){return this[i].localName},
1900
	getOffset:function(i){return this[i].offset},
1901
	getQName:function(i){return this[i].qName},
1902
	getURI:function(i){return this[i].uri},
1903
	getValue:function(i){return this[i].value}
1904
}
1905

    
1906

    
1907

    
1908

    
1909
function _set_proto_(thiz,parent){
1910
	thiz.__proto__ = parent;
1911
	return thiz;
1912
}
1913
if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
1914
	_set_proto_ = function(thiz,parent){
1915
		function p(){};
1916
		p.prototype = parent;
1917
		p = new p();
1918
		for(parent in thiz){
1919
			p[parent] = thiz[parent];
1920
		}
1921
		return p;
1922
	}
1923
}
1924

    
1925
function split(source,start){
1926
	var match;
1927
	var buf = [];
1928
	var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
1929
	reg.lastIndex = start;
1930
	reg.exec(source);//skip <
1931
	while(match = reg.exec(source)){
1932
		buf.push(match);
1933
		if(match[1])return buf;
1934
	}
1935
}
1936

    
1937
return XMLReader;
1938
});
1939

    
1940
ace.define("ace/mode/xml/dom",[], function(require, exports, module) {
1941

    
1942
function copy(src,dest){
1943
	for(var p in src){
1944
		dest[p] = src[p];
1945
	}
1946
}
1947
function _extends(Class,Super){
1948
	var t = function(){};
1949
	var pt = Class.prototype;
1950
	if(Object.create){
1951
		var ppt = Object.create(Super.prototype);
1952
		pt.__proto__ = ppt;
1953
	}
1954
	if(!(pt instanceof Super)){
1955
		t.prototype = Super.prototype;
1956
		t = new t();
1957
		copy(pt,t);
1958
		Class.prototype = pt = t;
1959
	}
1960
	if(pt.constructor != Class){
1961
		if(typeof Class != 'function'){
1962
			console.error("unknown Class:"+Class);
1963
		}
1964
		pt.constructor = Class;
1965
	}
1966
}
1967
var htmlns = 'http://www.w3.org/1999/xhtml' ;
1968
var NodeType = {};
1969
var ELEMENT_NODE                = NodeType.ELEMENT_NODE                = 1;
1970
var ATTRIBUTE_NODE              = NodeType.ATTRIBUTE_NODE              = 2;
1971
var TEXT_NODE                   = NodeType.TEXT_NODE                   = 3;
1972
var CDATA_SECTION_NODE          = NodeType.CDATA_SECTION_NODE          = 4;
1973
var ENTITY_REFERENCE_NODE       = NodeType.ENTITY_REFERENCE_NODE       = 5;
1974
var ENTITY_NODE                 = NodeType.ENTITY_NODE                 = 6;
1975
var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
1976
var COMMENT_NODE                = NodeType.COMMENT_NODE                = 8;
1977
var DOCUMENT_NODE               = NodeType.DOCUMENT_NODE               = 9;
1978
var DOCUMENT_TYPE_NODE          = NodeType.DOCUMENT_TYPE_NODE          = 10;
1979
var DOCUMENT_FRAGMENT_NODE      = NodeType.DOCUMENT_FRAGMENT_NODE      = 11;
1980
var NOTATION_NODE               = NodeType.NOTATION_NODE               = 12;
1981
var ExceptionCode = {};
1982
var ExceptionMessage = {};
1983
var INDEX_SIZE_ERR              = ExceptionCode.INDEX_SIZE_ERR              = ((ExceptionMessage[1]="Index size error"),1);
1984
var DOMSTRING_SIZE_ERR          = ExceptionCode.DOMSTRING_SIZE_ERR          = ((ExceptionMessage[2]="DOMString size error"),2);
1985
var HIERARCHY_REQUEST_ERR       = ExceptionCode.HIERARCHY_REQUEST_ERR       = ((ExceptionMessage[3]="Hierarchy request error"),3);
1986
var WRONG_DOCUMENT_ERR          = ExceptionCode.WRONG_DOCUMENT_ERR          = ((ExceptionMessage[4]="Wrong document"),4);
1987
var INVALID_CHARACTER_ERR       = ExceptionCode.INVALID_CHARACTER_ERR       = ((ExceptionMessage[5]="Invalid character"),5);
1988
var NO_DATA_ALLOWED_ERR         = ExceptionCode.NO_DATA_ALLOWED_ERR         = ((ExceptionMessage[6]="No data allowed"),6);
1989
var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
1990
var NOT_FOUND_ERR               = ExceptionCode.NOT_FOUND_ERR               = ((ExceptionMessage[8]="Not found"),8);
1991
var NOT_SUPPORTED_ERR           = ExceptionCode.NOT_SUPPORTED_ERR           = ((ExceptionMessage[9]="Not supported"),9);
1992
var INUSE_ATTRIBUTE_ERR         = ExceptionCode.INUSE_ATTRIBUTE_ERR         = ((ExceptionMessage[10]="Attribute in use"),10);
1993
var INVALID_STATE_ERR        	= ExceptionCode.INVALID_STATE_ERR        	= ((ExceptionMessage[11]="Invalid state"),11);
1994
var SYNTAX_ERR               	= ExceptionCode.SYNTAX_ERR               	= ((ExceptionMessage[12]="Syntax error"),12);
1995
var INVALID_MODIFICATION_ERR 	= ExceptionCode.INVALID_MODIFICATION_ERR 	= ((ExceptionMessage[13]="Invalid modification"),13);
1996
var NAMESPACE_ERR            	= ExceptionCode.NAMESPACE_ERR           	= ((ExceptionMessage[14]="Invalid namespace"),14);
1997
var INVALID_ACCESS_ERR       	= ExceptionCode.INVALID_ACCESS_ERR      	= ((ExceptionMessage[15]="Invalid access"),15);
1998

    
1999

    
2000
function DOMException(code, message) {
2001
	if(message instanceof Error){
2002
		var error = message;
2003
	}else{
2004
		error = this;
2005
		Error.call(this, ExceptionMessage[code]);
2006
		this.message = ExceptionMessage[code];
2007
		if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
2008
	}
2009
	error.code = code;
2010
	if(message) this.message = this.message + ": " + message;
2011
	return error;
2012
};
2013
DOMException.prototype = Error.prototype;
2014
copy(ExceptionCode,DOMException)
2015
function NodeList() {
2016
};
2017
NodeList.prototype = {
2018
	length:0,
2019
	item: function(index) {
2020
		return this[index] || null;
2021
	}
2022
};
2023
function LiveNodeList(node,refresh){
2024
	this._node = node;
2025
	this._refresh = refresh;
2026
	_updateLiveList(this);
2027
}
2028
function _updateLiveList(list){
2029
	var inc = list._node._inc || list._node.ownerDocument._inc;
2030
	if(list._inc != inc){
2031
		var ls = list._refresh(list._node);
2032
		__set__(list,'length',ls.length);
2033
		copy(ls,list);
2034
		list._inc = inc;
2035
	}
2036
}
2037
LiveNodeList.prototype.item = function(i){
2038
	_updateLiveList(this);
2039
	return this[i];
2040
}
2041

    
2042
_extends(LiveNodeList,NodeList);
2043
function NamedNodeMap() {
2044
};
2045

    
2046
function _findNodeIndex(list,node){
2047
	var i = list.length;
2048
	while(i--){
2049
		if(list[i] === node){return i}
2050
	}
2051
}
2052

    
2053
function _addNamedNode(el,list,newAttr,oldAttr){
2054
	if(oldAttr){
2055
		list[_findNodeIndex(list,oldAttr)] = newAttr;
2056
	}else{
2057
		list[list.length++] = newAttr;
2058
	}
2059
	if(el){
2060
		newAttr.ownerElement = el;
2061
		var doc = el.ownerDocument;
2062
		if(doc){
2063
			oldAttr && _onRemoveAttribute(doc,el,oldAttr);
2064
			_onAddAttribute(doc,el,newAttr);
2065
		}
2066
	}
2067
}
2068
function _removeNamedNode(el,list,attr){
2069
	var i = _findNodeIndex(list,attr);
2070
	if(i>=0){
2071
		var lastIndex = list.length-1;
2072
		while(i<lastIndex){
2073
			list[i] = list[++i];
2074
		}
2075
		list.length = lastIndex;
2076
		if(el){
2077
			var doc = el.ownerDocument;
2078
			if(doc){
2079
				_onRemoveAttribute(doc,el,attr);
2080
				attr.ownerElement = null;
2081
			}
2082
		}
2083
	}else{
2084
		throw new DOMException(NOT_FOUND_ERR,new Error());
2085
	}
2086
}
2087
NamedNodeMap.prototype = {
2088
	length:0,
2089
	item:NodeList.prototype.item,
2090
	getNamedItem: function(key) {
2091
		var i = this.length;
2092
		while(i--){
2093
			var attr = this[i];
2094
			if(attr.nodeName == key){
2095
				return attr;
2096
			}
2097
		}
2098
	},
2099
	setNamedItem: function(attr) {
2100
		var el = attr.ownerElement;
2101
		if(el && el!=this._ownerElement){
2102
			throw new DOMException(INUSE_ATTRIBUTE_ERR);
2103
		}
2104
		var oldAttr = this.getNamedItem(attr.nodeName);
2105
		_addNamedNode(this._ownerElement,this,attr,oldAttr);
2106
		return oldAttr;
2107
	},
2108
	setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
2109
		var el = attr.ownerElement, oldAttr;
2110
		if(el && el!=this._ownerElement){
2111
			throw new DOMException(INUSE_ATTRIBUTE_ERR);
2112
		}
2113
		oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
2114
		_addNamedNode(this._ownerElement,this,attr,oldAttr);
2115
		return oldAttr;
2116
	},
2117
	removeNamedItem: function(key) {
2118
		var attr = this.getNamedItem(key);
2119
		_removeNamedNode(this._ownerElement,this,attr);
2120
		return attr;
2121

    
2122

    
2123
	},// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
2124
	removeNamedItemNS:function(namespaceURI,localName){
2125
		var attr = this.getNamedItemNS(namespaceURI,localName);
2126
		_removeNamedNode(this._ownerElement,this,attr);
2127
		return attr;
2128
	},
2129
	getNamedItemNS: function(namespaceURI, localName) {
2130
		var i = this.length;
2131
		while(i--){
2132
			var node = this[i];
2133
			if(node.localName == localName && node.namespaceURI == namespaceURI){
2134
				return node;
2135
			}
2136
		}
2137
		return null;
2138
	}
2139
};
2140
function DOMImplementation(/* Object */ features) {
2141
	this._features = {};
2142
	if (features) {
2143
		for (var feature in features) {
2144
			 this._features = features[feature];
2145
		}
2146
	}
2147
};
2148

    
2149
DOMImplementation.prototype = {
2150
	hasFeature: function(/* string */ feature, /* string */ version) {
2151
		var versions = this._features[feature.toLowerCase()];
2152
		if (versions && (!version || version in versions)) {
2153
			return true;
2154
		} else {
2155
			return false;
2156
		}
2157
	},
2158
	createDocument:function(namespaceURI,  qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
2159
		var doc = new Document();
2160
		doc.implementation = this;
2161
		doc.childNodes = new NodeList();
2162
		doc.doctype = doctype;
2163
		if(doctype){
2164
			doc.appendChild(doctype);
2165
		}
2166
		if(qualifiedName){
2167
			var root = doc.createElementNS(namespaceURI,qualifiedName);
2168
			doc.appendChild(root);
2169
		}
2170
		return doc;
2171
	},
2172
	createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
2173
		var node = new DocumentType();
2174
		node.name = qualifiedName;
2175
		node.nodeName = qualifiedName;
2176
		node.publicId = publicId;
2177
		node.systemId = systemId;
2178
		return node;
2179
	}
2180
};
2181

    
2182
function Node() {
2183
};
2184

    
2185
Node.prototype = {
2186
	firstChild : null,
2187
	lastChild : null,
2188
	previousSibling : null,
2189
	nextSibling : null,
2190
	attributes : null,
2191
	parentNode : null,
2192
	childNodes : null,
2193
	ownerDocument : null,
2194
	nodeValue : null,
2195
	namespaceURI : null,
2196
	prefix : null,
2197
	localName : null,
2198
	insertBefore:function(newChild, refChild){//raises
2199
		return _insertBefore(this,newChild,refChild);
2200
	},
2201
	replaceChild:function(newChild, oldChild){//raises
2202
		this.insertBefore(newChild,oldChild);
2203
		if(oldChild){
2204
			this.removeChild(oldChild);
2205
		}
2206
	},
2207
	removeChild:function(oldChild){
2208
		return _removeChild(this,oldChild);
2209
	},
2210
	appendChild:function(newChild){
2211
		return this.insertBefore(newChild,null);
2212
	},
2213
	hasChildNodes:function(){
2214
		return this.firstChild != null;
2215
	},
2216
	cloneNode:function(deep){
2217
		return cloneNode(this.ownerDocument||this,this,deep);
2218
	},
2219
	normalize:function(){
2220
		var child = this.firstChild;
2221
		while(child){
2222
			var next = child.nextSibling;
2223
			if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
2224
				this.removeChild(next);
2225
				child.appendData(next.data);
2226
			}else{
2227
				child.normalize();
2228
				child = next;
2229
			}
2230
		}
2231
	},
2232
	isSupported:function(feature, version){
2233
		return this.ownerDocument.implementation.hasFeature(feature,version);
2234
	},
2235
    hasAttributes:function(){
2236
    	return this.attributes.length>0;
2237
    },
2238
    lookupPrefix:function(namespaceURI){
2239
    	var el = this;
2240
    	while(el){
2241
    		var map = el._nsMap;
2242
    		if(map){
2243
    			for(var n in map){
2244
    				if(map[n] == namespaceURI){
2245
    					return n;
2246
    				}
2247
    			}
2248
    		}
2249
    		el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2250
    	}
2251
    	return null;
2252
    },
2253
    lookupNamespaceURI:function(prefix){
2254
    	var el = this;
2255
    	while(el){
2256
    		var map = el._nsMap;
2257
    		if(map){
2258
    			if(prefix in map){
2259
    				return map[prefix] ;
2260
    			}
2261
    		}
2262
    		el = el.nodeType == 2?el.ownerDocument : el.parentNode;
2263
    	}
2264
    	return null;
2265
    },
2266
    isDefaultNamespace:function(namespaceURI){
2267
    	var prefix = this.lookupPrefix(namespaceURI);
2268
    	return prefix == null;
2269
    }
2270
};
2271

    
2272

    
2273
function _xmlEncoder(c){
2274
	return c == '<' && '&lt;' ||
2275
         c == '>' && '&gt;' ||
2276
         c == '&' && '&amp;' ||
2277
         c == '"' && '&quot;' ||
2278
         '&#'+c.charCodeAt()+';';
2279
}
2280

    
2281

    
2282
copy(NodeType,Node);
2283
copy(NodeType,Node.prototype);
2284
function _visitNode(node,callback){
2285
	if(callback(node)){
2286
		return true;
2287
	}
2288
	if(node = node.firstChild){
2289
		do{
2290
			if(_visitNode(node,callback)){return true}
2291
        }while(node=node.nextSibling)
2292
    }
2293
}
2294

    
2295

    
2296

    
2297
function Document(){
2298
}
2299
function _onAddAttribute(doc,el,newAttr){
2300
	doc && doc._inc++;
2301
	var ns = newAttr.namespaceURI ;
2302
	if(ns == 'http://www.w3.org/2000/xmlns/'){
2303
		el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
2304
	}
2305
}
2306
function _onRemoveAttribute(doc,el,newAttr,remove){
2307
	doc && doc._inc++;
2308
	var ns = newAttr.namespaceURI ;
2309
	if(ns == 'http://www.w3.org/2000/xmlns/'){
2310
		delete el._nsMap[newAttr.prefix?newAttr.localName:''];
2311
	}
2312
}
2313
function _onUpdateChild(doc,el,newChild){
2314
	if(doc && doc._inc){
2315
		doc._inc++;
2316
		var cs = el.childNodes;
2317
		if(newChild){
2318
			cs[cs.length++] = newChild;
2319
		}else{
2320
			var child = el.firstChild;
2321
			var i = 0;
2322
			while(child){
2323
				cs[i++] = child;
2324
				child =child.nextSibling;
2325
			}
2326
			cs.length = i;
2327
		}
2328
	}
2329
}
2330
function _removeChild(parentNode,child){
2331
	var previous = child.previousSibling;
2332
	var next = child.nextSibling;
2333
	if(previous){
2334
		previous.nextSibling = next;
2335
	}else{
2336
		parentNode.firstChild = next
2337
	}
2338
	if(next){
2339
		next.previousSibling = previous;
2340
	}else{
2341
		parentNode.lastChild = previous;
2342
	}
2343
	_onUpdateChild(parentNode.ownerDocument,parentNode);
2344
	return child;
2345
}
2346
function _insertBefore(parentNode,newChild,nextChild){
2347
	var cp = newChild.parentNode;
2348
	if(cp){
2349
		cp.removeChild(newChild);//remove and update
2350
	}
2351
	if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
2352
		var newFirst = newChild.firstChild;
2353
		if (newFirst == null) {
2354
			return newChild;
2355
		}
2356
		var newLast = newChild.lastChild;
2357
	}else{
2358
		newFirst = newLast = newChild;
2359
	}
2360
	var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
2361

    
2362
	newFirst.previousSibling = pre;
2363
	newLast.nextSibling = nextChild;
2364

    
2365

    
2366
	if(pre){
2367
		pre.nextSibling = newFirst;
2368
	}else{
2369
		parentNode.firstChild = newFirst;
2370
	}
2371
	if(nextChild == null){
2372
		parentNode.lastChild = newLast;
2373
	}else{
2374
		nextChild.previousSibling = newLast;
2375
	}
2376
	do{
2377
		newFirst.parentNode = parentNode;
2378
	}while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
2379
	_onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
2380
	if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
2381
		newChild.firstChild = newChild.lastChild = null;
2382
	}
2383
	return newChild;
2384
}
2385
function _appendSingleChild(parentNode,newChild){
2386
	var cp = newChild.parentNode;
2387
	if(cp){
2388
		var pre = parentNode.lastChild;
2389
		cp.removeChild(newChild);//remove and update
2390
		var pre = parentNode.lastChild;
2391
	}
2392
	var pre = parentNode.lastChild;
2393
	newChild.parentNode = parentNode;
2394
	newChild.previousSibling = pre;
2395
	newChild.nextSibling = null;
2396
	if(pre){
2397
		pre.nextSibling = newChild;
2398
	}else{
2399
		parentNode.firstChild = newChild;
2400
	}
2401
	parentNode.lastChild = newChild;
2402
	_onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
2403
	return newChild;
2404
}
2405
Document.prototype = {
2406
	nodeName :  '#document',
2407
	nodeType :  DOCUMENT_NODE,
2408
	doctype :  null,
2409
	documentElement :  null,
2410
	_inc : 1,
2411

    
2412
	insertBefore :  function(newChild, refChild){//raises
2413
		if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
2414
			var child = newChild.firstChild;
2415
			while(child){
2416
				var next = child.nextSibling;
2417
				this.insertBefore(child,refChild);
2418
				child = next;
2419
			}
2420
			return newChild;
2421
		}
2422
		if(this.documentElement == null && newChild.nodeType == 1){
2423
			this.documentElement = newChild;
2424
		}
2425

    
2426
		return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
2427
	},
2428
	removeChild :  function(oldChild){
2429
		if(this.documentElement == oldChild){
2430
			this.documentElement = null;
2431
		}
2432
		return _removeChild(this,oldChild);
2433
	},
2434
	importNode : function(importedNode,deep){
2435
		return importNode(this,importedNode,deep);
2436
	},
2437
	getElementById :	function(id){
2438
		var rtv = null;
2439
		_visitNode(this.documentElement,function(node){
2440
			if(node.nodeType == 1){
2441
				if(node.getAttribute('id') == id){
2442
					rtv = node;
2443
					return true;
2444
				}
2445
			}
2446
		});
2447
		return rtv;
2448
	},
2449
	createElement :	function(tagName){
2450
		var node = new Element();
2451
		node.ownerDocument = this;
2452
		node.nodeName = tagName;
2453
		node.tagName = tagName;
2454
		node.childNodes = new NodeList();
2455
		var attrs	= node.attributes = new NamedNodeMap();
2456
		attrs._ownerElement = node;
2457
		return node;
2458
	},
2459
	createDocumentFragment :	function(){
2460
		var node = new DocumentFragment();
2461
		node.ownerDocument = this;
2462
		node.childNodes = new NodeList();
2463
		return node;
2464
	},
2465
	createTextNode :	function(data){
2466
		var node = new Text();
2467
		node.ownerDocument = this;
2468
		node.appendData(data);
2469
		return node;
2470
	},
2471
	createComment :	function(data){
2472
		var node = new Comment();
2473
		node.ownerDocument = this;
2474
		node.appendData(data);
2475
		return node;
2476
	},
2477
	createCDATASection :	function(data){
2478
		var node = new CDATASection();
2479
		node.ownerDocument = this;
2480
		node.appendData(data);
2481
		return node;
2482
	},
2483
	createProcessingInstruction :	function(target,data){
2484
		var node = new ProcessingInstruction();
2485
		node.ownerDocument = this;
2486
		node.tagName = node.target = target;
2487
		node.nodeValue= node.data = data;
2488
		return node;
2489
	},
2490
	createAttribute :	function(name){
2491
		var node = new Attr();
2492
		node.ownerDocument	= this;
2493
		node.name = name;
2494
		node.nodeName	= name;
2495
		node.localName = name;
2496
		node.specified = true;
2497
		return node;
2498
	},
2499
	createEntityReference :	function(name){
2500
		var node = new EntityReference();
2501
		node.ownerDocument	= this;
2502
		node.nodeName	= name;
2503
		return node;
2504
	},
2505
	createElementNS :	function(namespaceURI,qualifiedName){
2506
		var node = new Element();
2507
		var pl = qualifiedName.split(':');
2508
		var attrs	= node.attributes = new NamedNodeMap();
2509
		node.childNodes = new NodeList();
2510
		node.ownerDocument = this;
2511
		node.nodeName = qualifiedName;
2512
		node.tagName = qualifiedName;
2513
		node.namespaceURI = namespaceURI;
2514
		if(pl.length == 2){
2515
			node.prefix = pl[0];
2516
			node.localName = pl[1];
2517
		}else{
2518
			node.localName = qualifiedName;
2519
		}
2520
		attrs._ownerElement = node;
2521
		return node;
2522
	},
2523
	createAttributeNS :	function(namespaceURI,qualifiedName){
2524
		var node = new Attr();
2525
		var pl = qualifiedName.split(':');
2526
		node.ownerDocument = this;
2527
		node.nodeName = qualifiedName;
2528
		node.name = qualifiedName;
2529
		node.namespaceURI = namespaceURI;
2530
		node.specified = true;
2531
		if(pl.length == 2){
2532
			node.prefix = pl[0];
2533
			node.localName = pl[1];
2534
		}else{
2535
			node.localName = qualifiedName;
2536
		}
2537
		return node;
2538
	}
2539
};
2540
_extends(Document,Node);
2541

    
2542

    
2543
function Element() {
2544
	this._nsMap = {};
2545
};
2546
Element.prototype = {
2547
	nodeType : ELEMENT_NODE,
2548
	hasAttribute : function(name){
2549
		return this.getAttributeNode(name)!=null;
2550
	},
2551
	getAttribute : function(name){
2552
		var attr = this.getAttributeNode(name);
2553
		return attr && attr.value || '';
2554
	},
2555
	getAttributeNode : function(name){
2556
		return this.attributes.getNamedItem(name);
2557
	},
2558
	setAttribute : function(name, value){
2559
		var attr = this.ownerDocument.createAttribute(name);
2560
		attr.value = attr.nodeValue = "" + value;
2561
		this.setAttributeNode(attr);
2562
	},
2563
	removeAttribute : function(name){
2564
		var attr = this.getAttributeNode(name);
2565
		attr && this.removeAttributeNode(attr);
2566
	},
2567
	appendChild:function(newChild){
2568
		if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
2569
			return this.insertBefore(newChild,null);
2570
		}else{
2571
			return _appendSingleChild(this,newChild);
2572
		}
2573
	},
2574
	setAttributeNode : function(newAttr){
2575
		return this.attributes.setNamedItem(newAttr);
2576
	},
2577
	setAttributeNodeNS : function(newAttr){
2578
		return this.attributes.setNamedItemNS(newAttr);
2579
	},
2580
	removeAttributeNode : function(oldAttr){
2581
		return this.attributes.removeNamedItem(oldAttr.nodeName);
2582
	},
2583
	removeAttributeNS : function(namespaceURI, localName){
2584
		var old = this.getAttributeNodeNS(namespaceURI, localName);
2585
		old && this.removeAttributeNode(old);
2586
	},
2587

    
2588
	hasAttributeNS : function(namespaceURI, localName){
2589
		return this.getAttributeNodeNS(namespaceURI, localName)!=null;
2590
	},
2591
	getAttributeNS : function(namespaceURI, localName){
2592
		var attr = this.getAttributeNodeNS(namespaceURI, localName);
2593
		return attr && attr.value || '';
2594
	},
2595
	setAttributeNS : function(namespaceURI, qualifiedName, value){
2596
		var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
2597
		attr.value = attr.nodeValue = "" + value;
2598
		this.setAttributeNode(attr);
2599
	},
2600
	getAttributeNodeNS : function(namespaceURI, localName){
2601
		return this.attributes.getNamedItemNS(namespaceURI, localName);
2602
	},
2603

    
2604
	getElementsByTagName : function(tagName){
2605
		return new LiveNodeList(this,function(base){
2606
			var ls = [];
2607
			_visitNode(base,function(node){
2608
				if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
2609
					ls.push(node);
2610
				}
2611
			});
2612
			return ls;
2613
		});
2614
	},
2615
	getElementsByTagNameNS : function(namespaceURI, localName){
2616
		return new LiveNodeList(this,function(base){
2617
			var ls = [];
2618
			_visitNode(base,function(node){
2619
				if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
2620
					ls.push(node);
2621
				}
2622
			});
2623
			return ls;
2624
		});
2625
	}
2626
};
2627
Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
2628
Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
2629

    
2630

    
2631
_extends(Element,Node);
2632
function Attr() {
2633
};
2634
Attr.prototype.nodeType = ATTRIBUTE_NODE;
2635
_extends(Attr,Node);
2636

    
2637

    
2638
function CharacterData() {
2639
};
2640
CharacterData.prototype = {
2641
	data : '',
2642
	substringData : function(offset, count) {
2643
		return this.data.substring(offset, offset+count);
2644
	},
2645
	appendData: function(text) {
2646
		text = this.data+text;
2647
		this.nodeValue = this.data = text;
2648
		this.length = text.length;
2649
	},
2650
	insertData: function(offset,text) {
2651
		this.replaceData(offset,0,text);
2652
	},
2653
	appendChild:function(newChild){
2654
			throw new Error(ExceptionMessage[3]);
2655
		return Node.prototype.appendChild.apply(this,arguments);
2656
	},
2657
	deleteData: function(offset, count) {
2658
		this.replaceData(offset,count,"");
2659
	},
2660
	replaceData: function(offset, count, text) {
2661
		var start = this.data.substring(0,offset);
2662
		var end = this.data.substring(offset+count);
2663
		text = start + text + end;
2664
		this.nodeValue = this.data = text;
2665
		this.length = text.length;
2666
	}
2667
}
2668
_extends(CharacterData,Node);
2669
function Text() {
2670
};
2671
Text.prototype = {
2672
	nodeName : "#text",
2673
	nodeType : TEXT_NODE,
2674
	splitText : function(offset) {
2675
		var text = this.data;
2676
		var newText = text.substring(offset);
2677
		text = text.substring(0, offset);
2678
		this.data = this.nodeValue = text;
2679
		this.length = text.length;
2680
		var newNode = this.ownerDocument.createTextNode(newText);
2681
		if(this.parentNode){
2682
			this.parentNode.insertBefore(newNode, this.nextSibling);
2683
		}
2684
		return newNode;
2685
	}
2686
}
2687
_extends(Text,CharacterData);
2688
function Comment() {
2689
};
2690
Comment.prototype = {
2691
	nodeName : "#comment",
2692
	nodeType : COMMENT_NODE
2693
}
2694
_extends(Comment,CharacterData);
2695

    
2696
function CDATASection() {
2697
};
2698
CDATASection.prototype = {
2699
	nodeName : "#cdata-section",
2700
	nodeType : CDATA_SECTION_NODE
2701
}
2702
_extends(CDATASection,CharacterData);
2703

    
2704

    
2705
function DocumentType() {
2706
}
2707
DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
2708
_extends(DocumentType,Node);
2709

    
2710
function Notation() {
2711
}
2712
Notation.prototype.nodeType = NOTATION_NODE;
2713
_extends(Notation,Node);
2714

    
2715
function Entity() {
2716
}
2717
Entity.prototype.nodeType = ENTITY_NODE;
2718
_extends(Entity,Node);
2719

    
2720
function EntityReference() {
2721
}
2722
EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
2723
_extends(EntityReference,Node);
2724

    
2725
function DocumentFragment() {
2726
}
2727
DocumentFragment.prototype.nodeName =	"#document-fragment";
2728
DocumentFragment.prototype.nodeType =	DOCUMENT_FRAGMENT_NODE;
2729
_extends(DocumentFragment,Node);
2730

    
2731

    
2732
function ProcessingInstruction() {
2733
}
2734
ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
2735
_extends(ProcessingInstruction,Node);
2736
function XMLSerializer(){}
2737
XMLSerializer.prototype.serializeToString = function(node){
2738
	var buf = [];
2739
	serializeToString(node,buf);
2740
	return buf.join('');
2741
}
2742
Node.prototype.toString =function(){
2743
	return XMLSerializer.prototype.serializeToString(this);
2744
}
2745
function serializeToString(node,buf){
2746
	switch(node.nodeType){
2747
	case ELEMENT_NODE:
2748
		var attrs = node.attributes;
2749
		var len = attrs.length;
2750
		var child = node.firstChild;
2751
		var nodeName = node.tagName;
2752
		var isHTML = htmlns === node.namespaceURI;
2753
		buf.push('<',nodeName);
2754
		for(var i=0;i<len;i++){
2755
			serializeToString(attrs.item(i),buf);
2756
		}
2757
		if(child || isHTML && !/^(?:meta|link|img|br|hr|input|button)$/i.test(nodeName)){
2758
			buf.push('>');
2759
			if(isHTML && /^script$/i.test(nodeName)){
2760
				if(child){
2761
					buf.push(child.data);
2762
				}
2763
			}else{
2764
				while(child){
2765
					serializeToString(child,buf);
2766
					child = child.nextSibling;
2767
				}
2768
			}
2769
			buf.push('</',nodeName,'>');
2770
		}else{
2771
			buf.push('/>');
2772
		}
2773
		return;
2774
	case DOCUMENT_NODE:
2775
	case DOCUMENT_FRAGMENT_NODE:
2776
		var child = node.firstChild;
2777
		while(child){
2778
			serializeToString(child,buf);
2779
			child = child.nextSibling;
2780
		}
2781
		return;
2782
	case ATTRIBUTE_NODE:
2783
		return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
2784
	case TEXT_NODE:
2785
		return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
2786
	case CDATA_SECTION_NODE:
2787
		return buf.push( '<![CDATA[',node.data,']]>');
2788
	case COMMENT_NODE:
2789
		return buf.push( "<!--",node.data,"-->");
2790
	case DOCUMENT_TYPE_NODE:
2791
		var pubid = node.publicId;
2792
		var sysid = node.systemId;
2793
		buf.push('<!DOCTYPE ',node.name);
2794
		if(pubid){
2795
			buf.push(' PUBLIC "',pubid);
2796
			if (sysid && sysid!='.') {
2797
				buf.push( '" "',sysid);
2798
			}
2799
			buf.push('">');
2800
		}else if(sysid && sysid!='.'){
2801
			buf.push(' SYSTEM "',sysid,'">');
2802
		}else{
2803
			var sub = node.internalSubset;
2804
			if(sub){
2805
				buf.push(" [",sub,"]");
2806
			}
2807
			buf.push(">");
2808
		}
2809
		return;
2810
	case PROCESSING_INSTRUCTION_NODE:
2811
		return buf.push( "<?",node.target," ",node.data,"?>");
2812
	case ENTITY_REFERENCE_NODE:
2813
		return buf.push( '&',node.nodeName,';');
2814
	default:
2815
		buf.push('??',node.nodeName);
2816
	}
2817
}
2818
function importNode(doc,node,deep){
2819
	var node2;
2820
	switch (node.nodeType) {
2821
	case ELEMENT_NODE:
2822
		node2 = node.cloneNode(false);
2823
		node2.ownerDocument = doc;
2824
	case DOCUMENT_FRAGMENT_NODE:
2825
		break;
2826
	case ATTRIBUTE_NODE:
2827
		deep = true;
2828
		break;
2829
	}
2830
	if(!node2){
2831
		node2 = node.cloneNode(false);//false
2832
	}
2833
	node2.ownerDocument = doc;
2834
	node2.parentNode = null;
2835
	if(deep){
2836
		var child = node.firstChild;
2837
		while(child){
2838
			node2.appendChild(importNode(doc,child,deep));
2839
			child = child.nextSibling;
2840
		}
2841
	}
2842
	return node2;
2843
}
2844
function cloneNode(doc,node,deep){
2845
	var node2 = new node.constructor();
2846
	for(var n in node){
2847
		var v = node[n];
2848
		if(typeof v != 'object' ){
2849
			if(v != node2[n]){
2850
				node2[n] = v;
2851
			}
2852
		}
2853
	}
2854
	if(node.childNodes){
2855
		node2.childNodes = new NodeList();
2856
	}
2857
	node2.ownerDocument = doc;
2858
	switch (node2.nodeType) {
2859
	case ELEMENT_NODE:
2860
		var attrs	= node.attributes;
2861
		var attrs2	= node2.attributes = new NamedNodeMap();
2862
		var len = attrs.length;
2863
		attrs2._ownerElement = node2;
2864
		for(var i=0;i<len;i++){
2865
			node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
2866
		}
2867
		break;
2868
	case ATTRIBUTE_NODE:
2869
		deep = true;
2870
	}
2871
	if(deep){
2872
		var child = node.firstChild;
2873
		while(child){
2874
			node2.appendChild(cloneNode(doc,child,deep));
2875
			child = child.nextSibling;
2876
		}
2877
	}
2878
	return node2;
2879
}
2880

    
2881
function __set__(object,key,value){
2882
	object[key] = value;
2883
}
2884
function getTextContent(node){
2885
	switch(node.nodeType){
2886
	case 1:
2887
	case 11:
2888
		var buf = [];
2889
		node = node.firstChild;
2890
		while(node){
2891
			if(node.nodeType!==7 && node.nodeType !==8){
2892
				buf.push(getTextContent(node));
2893
			}
2894
			node = node.nextSibling;
2895
		}
2896
		return buf.join('');
2897
	default:
2898
		return node.nodeValue;
2899
	}
2900
}
2901
try{
2902
	if(Object.defineProperty){
2903
		Object.defineProperty(LiveNodeList.prototype,'length',{
2904
			get:function(){
2905
				_updateLiveList(this);
2906
				return this.$$length;
2907
			}
2908
		});
2909
		Object.defineProperty(Node.prototype,'textContent',{
2910
			get:function(){
2911
				return getTextContent(this);
2912
			},
2913
			set:function(data){
2914
				switch(this.nodeType){
2915
				case 1:
2916
				case 11:
2917
					while(this.firstChild){
2918
						this.removeChild(this.firstChild);
2919
					}
2920
					if(data || String(data)){
2921
						this.appendChild(this.ownerDocument.createTextNode(data));
2922
					}
2923
					break;
2924
				default:
2925
					this.data = data;
2926
					this.value = value;
2927
					this.nodeValue = data;
2928
				}
2929
			}
2930
		});
2931

    
2932
		__set__ = function(object,key,value){
2933
			object['$$'+key] = value;
2934
		};
2935
	}
2936
}catch(e){//ie8
2937
}
2938

    
2939
return DOMImplementation;
2940
});
2941

    
2942
ace.define("ace/mode/xml/dom-parser",[], function(require, exports, module) {
2943
	'use strict';
2944

    
2945
	var XMLReader = require('./sax'),
2946
		DOMImplementation = require('./dom');
2947

    
2948
function DOMParser(options){
2949
	this.options = options ||{locator:{}};
2950
	
2951
}
2952
DOMParser.prototype.parseFromString = function(source,mimeType){	
2953
	var options = this.options;
2954
	var sax =  new XMLReader();
2955
	var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
2956
	var errorHandler = options.errorHandler;
2957
	var locator = options.locator;
2958
	var defaultNSMap = options.xmlns||{};
2959
	var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
2960
	if(locator){
2961
		domBuilder.setDocumentLocator(locator)
2962
	}
2963
	
2964
	sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
2965
	sax.domBuilder = options.domBuilder || domBuilder;
2966
	if(/\/x?html?$/.test(mimeType)){
2967
		entityMap.nbsp = '\xa0';
2968
		entityMap.copy = '\xa9';
2969
		defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
2970
	}
2971
	if(source){
2972
		sax.parse(source,defaultNSMap,entityMap);
2973
	}else{
2974
		sax.errorHandler.error("invalid document source");
2975
	}
2976
	return domBuilder.document;
2977
}
2978
function buildErrorHandler(errorImpl,domBuilder,locator){
2979
	if(!errorImpl){
2980
		if(domBuilder instanceof DOMHandler){
2981
			return domBuilder;
2982
		}
2983
		errorImpl = domBuilder ;
2984
	}
2985
	var errorHandler = {}
2986
	var isCallback = errorImpl instanceof Function;
2987
	locator = locator||{}
2988
	function build(key){
2989
		var fn = errorImpl[key];
2990
		if(!fn){
2991
			if(isCallback){
2992
				fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
2993
			}else{
2994
				var i=arguments.length;
2995
				while(--i){
2996
					if(fn = errorImpl[arguments[i]]){
2997
						break;
2998
					}
2999
				}
3000
			}
3001
		}
3002
		errorHandler[key] = fn && function(msg){
3003
			fn(msg+_locator(locator), msg, locator);
3004
		}||function(){};
3005
	}
3006
	build('warning','warn');
3007
	build('error','warn','warning');
3008
	build('fatalError','warn','warning','error');
3009
	return errorHandler;
3010
}
3011
function DOMHandler() {
3012
    this.cdata = false;
3013
}
3014
function position(locator,node){
3015
	node.lineNumber = locator.lineNumber;
3016
	node.columnNumber = locator.columnNumber;
3017
} 
3018
DOMHandler.prototype = {
3019
	startDocument : function() {
3020
    	this.document = new DOMImplementation().createDocument(null, null, null);
3021
    	if (this.locator) {
3022
        	this.document.documentURI = this.locator.systemId;
3023
    	}
3024
	},
3025
	startElement:function(namespaceURI, localName, qName, attrs) {
3026
		var doc = this.document;
3027
	    var el = doc.createElementNS(namespaceURI, qName||localName);
3028
	    var len = attrs.length;
3029
	    appendElement(this, el);
3030
	    this.currentElement = el;
3031
	    
3032
		this.locator && position(this.locator,el)
3033
	    for (var i = 0 ; i < len; i++) {
3034
	        var namespaceURI = attrs.getURI(i);
3035
	        var value = attrs.getValue(i);
3036
	        var qName = attrs.getQName(i);
3037
			var attr = doc.createAttributeNS(namespaceURI, qName);
3038
			if( attr.getOffset){
3039
				position(attr.getOffset(1),attr)
3040
			}
3041
			attr.value = attr.nodeValue = value;
3042
			el.setAttributeNode(attr)
3043
	    }
3044
	},
3045
	endElement:function(namespaceURI, localName, qName) {
3046
		var current = this.currentElement
3047
	    var tagName = current.tagName;
3048
	    this.currentElement = current.parentNode;
3049
	},
3050
	startPrefixMapping:function(prefix, uri) {
3051
	},
3052
	endPrefixMapping:function(prefix) {
3053
	},
3054
	processingInstruction:function(target, data) {
3055
	    var ins = this.document.createProcessingInstruction(target, data);
3056
	    this.locator && position(this.locator,ins)
3057
	    appendElement(this, ins);
3058
	},
3059
	ignorableWhitespace:function(ch, start, length) {
3060
	},
3061
	characters:function(chars, start, length) {
3062
		chars = _toString.apply(this,arguments)
3063
		if(this.currentElement && chars){
3064
			if (this.cdata) {
3065
				var charNode = this.document.createCDATASection(chars);
3066
				this.currentElement.appendChild(charNode);
3067
			} else {
3068
				var charNode = this.document.createTextNode(chars);
3069
				this.currentElement.appendChild(charNode);
3070
			}
3071
			this.locator && position(this.locator,charNode)
3072
		}
3073
	},
3074
	skippedEntity:function(name) {
3075
	},
3076
	endDocument:function() {
3077
		this.document.normalize();
3078
	},
3079
	setDocumentLocator:function (locator) {
3080
	    if(this.locator = locator){// && !('lineNumber' in locator)){
3081
	    	locator.lineNumber = 0;
3082
	    }
3083
	},
3084
	comment:function(chars, start, length) {
3085
		chars = _toString.apply(this,arguments)
3086
	    var comm = this.document.createComment(chars);
3087
	    this.locator && position(this.locator,comm)
3088
	    appendElement(this, comm);
3089
	},
3090
	
3091
	startCDATA:function() {
3092
	    this.cdata = true;
3093
	},
3094
	endCDATA:function() {
3095
	    this.cdata = false;
3096
	},
3097
	
3098
	startDTD:function(name, publicId, systemId) {
3099
		var impl = this.document.implementation;
3100
	    if (impl && impl.createDocumentType) {
3101
	        var dt = impl.createDocumentType(name, publicId, systemId);
3102
	        this.locator && position(this.locator,dt)
3103
	        appendElement(this, dt);
3104
	    }
3105
	},
3106
	warning:function(error) {
3107
		console.warn(error,_locator(this.locator));
3108
	},
3109
	error:function(error) {
3110
		console.error(error,_locator(this.locator));
3111
	},
3112
	fatalError:function(error) {
3113
		console.error(error,_locator(this.locator));
3114
	    throw error;
3115
	}
3116
}
3117
function _locator(l){
3118
	if(l){
3119
		return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
3120
	}
3121
}
3122
function _toString(chars,start,length){
3123
	if(typeof chars == 'string'){
3124
		return chars.substr(start,length)
3125
	}else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
3126
		if(chars.length >= start+length || start){
3127
			return new java.lang.String(chars,start,length)+'';
3128
		}
3129
		return chars;
3130
	}
3131
}
3132
"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
3133
	DOMHandler.prototype[key] = function(){return null}
3134
})
3135
function appendElement (hander,node) {
3136
    if (!hander.currentElement) {
3137
        hander.document.appendChild(node);
3138
    } else {
3139
        hander.currentElement.appendChild(node);
3140
    }
3141
}//appendChild and setAttributeNS are preformance key
3142

    
3143
return {
3144
		DOMParser: DOMParser
3145
	 };
3146
});
3147

    
3148
ace.define("ace/mode/xml_worker",[], function(require, exports, module) {
3149
"use strict";
3150

    
3151
var oop = require("../lib/oop");
3152
var lang = require("../lib/lang");
3153
var Mirror = require("../worker/mirror").Mirror;
3154
var DOMParser = require("./xml/dom-parser").DOMParser;
3155

    
3156
var Worker = exports.Worker = function(sender) {
3157
    Mirror.call(this, sender);
3158
    this.setTimeout(400);
3159
    this.context = null;
3160
};
3161

    
3162
oop.inherits(Worker, Mirror);
3163

    
3164
(function() {
3165

    
3166
    this.setOptions = function(options) {
3167
        this.context = options.context;
3168
    };
3169

    
3170
    this.onUpdate = function() {
3171
        var value = this.doc.getValue();
3172
        if (!value)
3173
            return;
3174
        var parser = new DOMParser();
3175
        var errors = [];
3176
        parser.options.errorHandler = {
3177
            fatalError: function(fullMsg, errorMsg, locator) {
3178
                errors.push({
3179
                    row: locator.lineNumber,
3180
                    column: locator.columnNumber,
3181
                    text: errorMsg,
3182
                    type: "error"
3183
                });
3184
            },
3185
            error: function(fullMsg, errorMsg, locator) {
3186
                errors.push({
3187
                    row: locator.lineNumber,
3188
                    column: locator.columnNumber,
3189
                    text: errorMsg,
3190
                    type: "error"
3191
                });
3192
            },
3193
            warning: function(fullMsg, errorMsg, locator) {
3194
                errors.push({
3195
                    row: locator.lineNumber,
3196
                    column: locator.columnNumber,
3197
                    text: errorMsg,
3198
                    type: "warning"
3199
                });
3200
            }
3201
        };
3202
        
3203
        parser.parseFromString(value);
3204
        this.sender.emit("error", errors);
3205
    };
3206

    
3207
}).call(Worker.prototype);
3208

    
3209
});
3210

    
3211
ace.define("ace/lib/es5-shim",[], function(require, exports, module) {
3212

    
3213
function Empty() {}
3214

    
3215
if (!Function.prototype.bind) {
3216
    Function.prototype.bind = function bind(that) { // .length is 1
3217
        var target = this;
3218
        if (typeof target != "function") {
3219
            throw new TypeError("Function.prototype.bind called on incompatible " + target);
3220
        }
3221
        var args = slice.call(arguments, 1); // for normal call
3222
        var bound = function () {
3223

    
3224
            if (this instanceof bound) {
3225

    
3226
                var result = target.apply(
3227
                    this,
3228
                    args.concat(slice.call(arguments))
3229
                );
3230
                if (Object(result) === result) {
3231
                    return result;
3232
                }
3233
                return this;
3234

    
3235
            } else {
3236
                return target.apply(
3237
                    that,
3238
                    args.concat(slice.call(arguments))
3239
                );
3240

    
3241
            }
3242

    
3243
        };
3244
        if(target.prototype) {
3245
            Empty.prototype = target.prototype;
3246
            bound.prototype = new Empty();
3247
            Empty.prototype = null;
3248
        }
3249
        return bound;
3250
    };
3251
}
3252
var call = Function.prototype.call;
3253
var prototypeOfArray = Array.prototype;
3254
var prototypeOfObject = Object.prototype;
3255
var slice = prototypeOfArray.slice;
3256
var _toString = call.bind(prototypeOfObject.toString);
3257
var owns = call.bind(prototypeOfObject.hasOwnProperty);
3258
var defineGetter;
3259
var defineSetter;
3260
var lookupGetter;
3261
var lookupSetter;
3262
var supportsAccessors;
3263
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
3264
    defineGetter = call.bind(prototypeOfObject.__defineGetter__);
3265
    defineSetter = call.bind(prototypeOfObject.__defineSetter__);
3266
    lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
3267
    lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
3268
}
3269
if ([1,2].splice(0).length != 2) {
3270
    if(function() { // test IE < 9 to splice bug - see issue #138
3271
        function makeArray(l) {
3272
            var a = new Array(l+2);
3273
            a[0] = a[1] = 0;
3274
            return a;
3275
        }
3276
        var array = [], lengthBefore;
3277
        
3278
        array.splice.apply(array, makeArray(20));
3279
        array.splice.apply(array, makeArray(26));
3280

    
3281
        lengthBefore = array.length; //46
3282
        array.splice(5, 0, "XXX"); // add one element
3283

    
3284
        lengthBefore + 1 == array.length
3285

    
3286
        if (lengthBefore + 1 == array.length) {
3287
            return true;// has right splice implementation without bugs
3288
        }
3289
    }()) {//IE 6/7
3290
        var array_splice = Array.prototype.splice;
3291
        Array.prototype.splice = function(start, deleteCount) {
3292
            if (!arguments.length) {
3293
                return [];
3294
            } else {
3295
                return array_splice.apply(this, [
3296
                    start === void 0 ? 0 : start,
3297
                    deleteCount === void 0 ? (this.length - start) : deleteCount
3298
                ].concat(slice.call(arguments, 2)))
3299
            }
3300
        };
3301
    } else {//IE8
3302
        Array.prototype.splice = function(pos, removeCount){
3303
            var length = this.length;
3304
            if (pos > 0) {
3305
                if (pos > length)
3306
                    pos = length;
3307
            } else if (pos == void 0) {
3308
                pos = 0;
3309
            } else if (pos < 0) {
3310
                pos = Math.max(length + pos, 0);
3311
            }
3312

    
3313
            if (!(pos+removeCount < length))
3314
                removeCount = length - pos;
3315

    
3316
            var removed = this.slice(pos, pos+removeCount);
3317
            var insert = slice.call(arguments, 2);
3318
            var add = insert.length;            
3319
            if (pos === length) {
3320
                if (add) {
3321
                    this.push.apply(this, insert);
3322
                }
3323
            } else {
3324
                var remove = Math.min(removeCount, length - pos);
3325
                var tailOldPos = pos + remove;
3326
                var tailNewPos = tailOldPos + add - remove;
3327
                var tailCount = length - tailOldPos;
3328
                var lengthAfterRemove = length - remove;
3329

    
3330
                if (tailNewPos < tailOldPos) { // case A
3331
                    for (var i = 0; i < tailCount; ++i) {
3332
                        this[tailNewPos+i] = this[tailOldPos+i];
3333
                    }
3334
                } else if (tailNewPos > tailOldPos) { // case B
3335
                    for (i = tailCount; i--; ) {
3336
                        this[tailNewPos+i] = this[tailOldPos+i];
3337
                    }
3338
                } // else, add == remove (nothing to do)
3339

    
3340
                if (add && pos === lengthAfterRemove) {
3341
                    this.length = lengthAfterRemove; // truncate array
3342
                    this.push.apply(this, insert);
3343
                } else {
3344
                    this.length = lengthAfterRemove + add; // reserves space
3345
                    for (i = 0; i < add; ++i) {
3346
                        this[pos+i] = insert[i];
3347
                    }
3348
                }
3349
            }
3350
            return removed;
3351
        };
3352
    }
3353
}
3354
if (!Array.isArray) {
3355
    Array.isArray = function isArray(obj) {
3356
        return _toString(obj) == "[object Array]";
3357
    };
3358
}
3359
var boxedString = Object("a"),
3360
    splitString = boxedString[0] != "a" || !(0 in boxedString);
3361

    
3362
if (!Array.prototype.forEach) {
3363
    Array.prototype.forEach = function forEach(fun /*, thisp*/) {
3364
        var object = toObject(this),
3365
            self = splitString && _toString(this) == "[object String]" ?
3366
                this.split("") :
3367
                object,
3368
            thisp = arguments[1],
3369
            i = -1,
3370
            length = self.length >>> 0;
3371
        if (_toString(fun) != "[object Function]") {
3372
            throw new TypeError(); // TODO message
3373
        }
3374

    
3375
        while (++i < length) {
3376
            if (i in self) {
3377
                fun.call(thisp, self[i], i, object);
3378
            }
3379
        }
3380
    };
3381
}
3382
if (!Array.prototype.map) {
3383
    Array.prototype.map = function map(fun /*, thisp*/) {
3384
        var object = toObject(this),
3385
            self = splitString && _toString(this) == "[object String]" ?
3386
                this.split("") :
3387
                object,
3388
            length = self.length >>> 0,
3389
            result = Array(length),
3390
            thisp = arguments[1];
3391
        if (_toString(fun) != "[object Function]") {
3392
            throw new TypeError(fun + " is not a function");
3393
        }
3394

    
3395
        for (var i = 0; i < length; i++) {
3396
            if (i in self)
3397
                result[i] = fun.call(thisp, self[i], i, object);
3398
        }
3399
        return result;
3400
    };
3401
}
3402
if (!Array.prototype.filter) {
3403
    Array.prototype.filter = function filter(fun /*, thisp */) {
3404
        var object = toObject(this),
3405
            self = splitString && _toString(this) == "[object String]" ?
3406
                this.split("") :
3407
                    object,
3408
            length = self.length >>> 0,
3409
            result = [],
3410
            value,
3411
            thisp = arguments[1];
3412
        if (_toString(fun) != "[object Function]") {
3413
            throw new TypeError(fun + " is not a function");
3414
        }
3415

    
3416
        for (var i = 0; i < length; i++) {
3417
            if (i in self) {
3418
                value = self[i];
3419
                if (fun.call(thisp, value, i, object)) {
3420
                    result.push(value);
3421
                }
3422
            }
3423
        }
3424
        return result;
3425
    };
3426
}
3427
if (!Array.prototype.every) {
3428
    Array.prototype.every = function every(fun /*, thisp */) {
3429
        var object = toObject(this),
3430
            self = splitString && _toString(this) == "[object String]" ?
3431
                this.split("") :
3432
                object,
3433
            length = self.length >>> 0,
3434
            thisp = arguments[1];
3435
        if (_toString(fun) != "[object Function]") {
3436
            throw new TypeError(fun + " is not a function");
3437
        }
3438

    
3439
        for (var i = 0; i < length; i++) {
3440
            if (i in self && !fun.call(thisp, self[i], i, object)) {
3441
                return false;
3442
            }
3443
        }
3444
        return true;
3445
    };
3446
}
3447
if (!Array.prototype.some) {
3448
    Array.prototype.some = function some(fun /*, thisp */) {
3449
        var object = toObject(this),
3450
            self = splitString && _toString(this) == "[object String]" ?
3451
                this.split("") :
3452
                object,
3453
            length = self.length >>> 0,
3454
            thisp = arguments[1];
3455
        if (_toString(fun) != "[object Function]") {
3456
            throw new TypeError(fun + " is not a function");
3457
        }
3458

    
3459
        for (var i = 0; i < length; i++) {
3460
            if (i in self && fun.call(thisp, self[i], i, object)) {
3461
                return true;
3462
            }
3463
        }
3464
        return false;
3465
    };
3466
}
3467
if (!Array.prototype.reduce) {
3468
    Array.prototype.reduce = function reduce(fun /*, initial*/) {
3469
        var object = toObject(this),
3470
            self = splitString && _toString(this) == "[object String]" ?
3471
                this.split("") :
3472
                object,
3473
            length = self.length >>> 0;
3474
        if (_toString(fun) != "[object Function]") {
3475
            throw new TypeError(fun + " is not a function");
3476
        }
3477
        if (!length && arguments.length == 1) {
3478
            throw new TypeError("reduce of empty array with no initial value");
3479
        }
3480

    
3481
        var i = 0;
3482
        var result;
3483
        if (arguments.length >= 2) {
3484
            result = arguments[1];
3485
        } else {
3486
            do {
3487
                if (i in self) {
3488
                    result = self[i++];
3489
                    break;
3490
                }
3491
                if (++i >= length) {
3492
                    throw new TypeError("reduce of empty array with no initial value");
3493
                }
3494
            } while (true);
3495
        }
3496

    
3497
        for (; i < length; i++) {
3498
            if (i in self) {
3499
                result = fun.call(void 0, result, self[i], i, object);
3500
            }
3501
        }
3502

    
3503
        return result;
3504
    };
3505
}
3506
if (!Array.prototype.reduceRight) {
3507
    Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
3508
        var object = toObject(this),
3509
            self = splitString && _toString(this) == "[object String]" ?
3510
                this.split("") :
3511
                object,
3512
            length = self.length >>> 0;
3513
        if (_toString(fun) != "[object Function]") {
3514
            throw new TypeError(fun + " is not a function");
3515
        }
3516
        if (!length && arguments.length == 1) {
3517
            throw new TypeError("reduceRight of empty array with no initial value");
3518
        }
3519

    
3520
        var result, i = length - 1;
3521
        if (arguments.length >= 2) {
3522
            result = arguments[1];
3523
        } else {
3524
            do {
3525
                if (i in self) {
3526
                    result = self[i--];
3527
                    break;
3528
                }
3529
                if (--i < 0) {
3530
                    throw new TypeError("reduceRight of empty array with no initial value");
3531
                }
3532
            } while (true);
3533
        }
3534

    
3535
        do {
3536
            if (i in this) {
3537
                result = fun.call(void 0, result, self[i], i, object);
3538
            }
3539
        } while (i--);
3540

    
3541
        return result;
3542
    };
3543
}
3544
if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
3545
    Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
3546
        var self = splitString && _toString(this) == "[object String]" ?
3547
                this.split("") :
3548
                toObject(this),
3549
            length = self.length >>> 0;
3550

    
3551
        if (!length) {
3552
            return -1;
3553
        }
3554

    
3555
        var i = 0;
3556
        if (arguments.length > 1) {
3557
            i = toInteger(arguments[1]);
3558
        }
3559
        i = i >= 0 ? i : Math.max(0, length + i);
3560
        for (; i < length; i++) {
3561
            if (i in self && self[i] === sought) {
3562
                return i;
3563
            }
3564
        }
3565
        return -1;
3566
    };
3567
}
3568
if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
3569
    Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
3570
        var self = splitString && _toString(this) == "[object String]" ?
3571
                this.split("") :
3572
                toObject(this),
3573
            length = self.length >>> 0;
3574

    
3575
        if (!length) {
3576
            return -1;
3577
        }
3578
        var i = length - 1;
3579
        if (arguments.length > 1) {
3580
            i = Math.min(i, toInteger(arguments[1]));
3581
        }
3582
        i = i >= 0 ? i : length - Math.abs(i);
3583
        for (; i >= 0; i--) {
3584
            if (i in self && sought === self[i]) {
3585
                return i;
3586
            }
3587
        }
3588
        return -1;
3589
    };
3590
}
3591
if (!Object.getPrototypeOf) {
3592
    Object.getPrototypeOf = function getPrototypeOf(object) {
3593
        return object.__proto__ || (
3594
            object.constructor ?
3595
            object.constructor.prototype :
3596
            prototypeOfObject
3597
        );
3598
    };
3599
}
3600
if (!Object.getOwnPropertyDescriptor) {
3601
    var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
3602
                         "non-object: ";
3603
    Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
3604
        if ((typeof object != "object" && typeof object != "function") || object === null)
3605
            throw new TypeError(ERR_NON_OBJECT + object);
3606
        if (!owns(object, property))
3607
            return;
3608

    
3609
        var descriptor, getter, setter;
3610
        descriptor =  { enumerable: true, configurable: true };
3611
        if (supportsAccessors) {
3612
            var prototype = object.__proto__;
3613
            object.__proto__ = prototypeOfObject;
3614

    
3615
            var getter = lookupGetter(object, property);
3616
            var setter = lookupSetter(object, property);
3617
            object.__proto__ = prototype;
3618

    
3619
            if (getter || setter) {
3620
                if (getter) descriptor.get = getter;
3621
                if (setter) descriptor.set = setter;
3622
                return descriptor;
3623
            }
3624
        }
3625
        descriptor.value = object[property];
3626
        return descriptor;
3627
    };
3628
}
3629
if (!Object.getOwnPropertyNames) {
3630
    Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
3631
        return Object.keys(object);
3632
    };
3633
}
3634
if (!Object.create) {
3635
    var createEmpty;
3636
    if (Object.prototype.__proto__ === null) {
3637
        createEmpty = function () {
3638
            return { "__proto__": null };
3639
        };
3640
    } else {
3641
        createEmpty = function () {
3642
            var empty = {};
3643
            for (var i in empty)
3644
                empty[i] = null;
3645
            empty.constructor =
3646
            empty.hasOwnProperty =
3647
            empty.propertyIsEnumerable =
3648
            empty.isPrototypeOf =
3649
            empty.toLocaleString =
3650
            empty.toString =
3651
            empty.valueOf =
3652
            empty.__proto__ = null;
3653
            return empty;
3654
        }
3655
    }
3656

    
3657
    Object.create = function create(prototype, properties) {
3658
        var object;
3659
        if (prototype === null) {
3660
            object = createEmpty();
3661
        } else {
3662
            if (typeof prototype != "object")
3663
                throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
3664
            var Type = function () {};
3665
            Type.prototype = prototype;
3666
            object = new Type();
3667
            object.__proto__ = prototype;
3668
        }
3669
        if (properties !== void 0)
3670
            Object.defineProperties(object, properties);
3671
        return object;
3672
    };
3673
}
3674

    
3675
function doesDefinePropertyWork(object) {
3676
    try {
3677
        Object.defineProperty(object, "sentinel", {});
3678
        return "sentinel" in object;
3679
    } catch (exception) {
3680
    }
3681
}
3682
if (Object.defineProperty) {
3683
    var definePropertyWorksOnObject = doesDefinePropertyWork({});
3684
    var definePropertyWorksOnDom = typeof document == "undefined" ||
3685
        doesDefinePropertyWork(document.createElement("div"));
3686
    if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
3687
        var definePropertyFallback = Object.defineProperty;
3688
    }
3689
}
3690

    
3691
if (!Object.defineProperty || definePropertyFallback) {
3692
    var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
3693
    var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
3694
    var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
3695
                                      "on this javascript engine";
3696

    
3697
    Object.defineProperty = function defineProperty(object, property, descriptor) {
3698
        if ((typeof object != "object" && typeof object != "function") || object === null)
3699
            throw new TypeError(ERR_NON_OBJECT_TARGET + object);
3700
        if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
3701
            throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
3702
        if (definePropertyFallback) {
3703
            try {
3704
                return definePropertyFallback.call(Object, object, property, descriptor);
3705
            } catch (exception) {
3706
            }
3707
        }
3708
        if (owns(descriptor, "value")) {
3709

    
3710
            if (supportsAccessors && (lookupGetter(object, property) ||
3711
                                      lookupSetter(object, property)))
3712
            {
3713
                var prototype = object.__proto__;
3714
                object.__proto__ = prototypeOfObject;
3715
                delete object[property];
3716
                object[property] = descriptor.value;
3717
                object.__proto__ = prototype;
3718
            } else {
3719
                object[property] = descriptor.value;
3720
            }
3721
        } else {
3722
            if (!supportsAccessors)
3723
                throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
3724
            if (owns(descriptor, "get"))
3725
                defineGetter(object, property, descriptor.get);
3726
            if (owns(descriptor, "set"))
3727
                defineSetter(object, property, descriptor.set);
3728
        }
3729

    
3730
        return object;
3731
    };
3732
}
3733
if (!Object.defineProperties) {
3734
    Object.defineProperties = function defineProperties(object, properties) {
3735
        for (var property in properties) {
3736
            if (owns(properties, property))
3737
                Object.defineProperty(object, property, properties[property]);
3738
        }
3739
        return object;
3740
    };
3741
}
3742
if (!Object.seal) {
3743
    Object.seal = function seal(object) {
3744
        return object;
3745
    };
3746
}
3747
if (!Object.freeze) {
3748
    Object.freeze = function freeze(object) {
3749
        return object;
3750
    };
3751
}
3752
try {
3753
    Object.freeze(function () {});
3754
} catch (exception) {
3755
    Object.freeze = (function freeze(freezeObject) {
3756
        return function freeze(object) {
3757
            if (typeof object == "function") {
3758
                return object;
3759
            } else {
3760
                return freezeObject(object);
3761
            }
3762
        };
3763
    })(Object.freeze);
3764
}
3765
if (!Object.preventExtensions) {
3766
    Object.preventExtensions = function preventExtensions(object) {
3767
        return object;
3768
    };
3769
}
3770
if (!Object.isSealed) {
3771
    Object.isSealed = function isSealed(object) {
3772
        return false;
3773
    };
3774
}
3775
if (!Object.isFrozen) {
3776
    Object.isFrozen = function isFrozen(object) {
3777
        return false;
3778
    };
3779
}
3780
if (!Object.isExtensible) {
3781
    Object.isExtensible = function isExtensible(object) {
3782
        if (Object(object) === object) {
3783
            throw new TypeError(); // TODO message
3784
        }
3785
        var name = '';
3786
        while (owns(object, name)) {
3787
            name += '?';
3788
        }
3789
        object[name] = true;
3790
        var returnValue = owns(object, name);
3791
        delete object[name];
3792
        return returnValue;
3793
    };
3794
}
3795
if (!Object.keys) {
3796
    var hasDontEnumBug = true,
3797
        dontEnums = [
3798
            "toString",
3799
            "toLocaleString",
3800
            "valueOf",
3801
            "hasOwnProperty",
3802
            "isPrototypeOf",
3803
            "propertyIsEnumerable",
3804
            "constructor"
3805
        ],
3806
        dontEnumsLength = dontEnums.length;
3807

    
3808
    for (var key in {"toString": null}) {
3809
        hasDontEnumBug = false;
3810
    }
3811

    
3812
    Object.keys = function keys(object) {
3813

    
3814
        if (
3815
            (typeof object != "object" && typeof object != "function") ||
3816
            object === null
3817
        ) {
3818
            throw new TypeError("Object.keys called on a non-object");
3819
        }
3820

    
3821
        var keys = [];
3822
        for (var name in object) {
3823
            if (owns(object, name)) {
3824
                keys.push(name);
3825
            }
3826
        }
3827

    
3828
        if (hasDontEnumBug) {
3829
            for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
3830
                var dontEnum = dontEnums[i];
3831
                if (owns(object, dontEnum)) {
3832
                    keys.push(dontEnum);
3833
                }
3834
            }
3835
        }
3836
        return keys;
3837
    };
3838

    
3839
}
3840
if (!Date.now) {
3841
    Date.now = function now() {
3842
        return new Date().getTime();
3843
    };
3844
}
3845
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003" +
3846
    "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
3847
    "\u2029\uFEFF";
3848
if (!String.prototype.trim) {
3849
    ws = "[" + ws + "]";
3850
    var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
3851
        trimEndRegexp = new RegExp(ws + ws + "*$");
3852
    String.prototype.trim = function trim() {
3853
        return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
3854
    };
3855
}
3856

    
3857
function toInteger(n) {
3858
    n = +n;
3859
    if (n !== n) { // isNaN
3860
        n = 0;
3861
    } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
3862
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
3863
    }
3864
    return n;
3865
}
3866

    
3867
function isPrimitive(input) {
3868
    var type = typeof input;
3869
    return (
3870
        input === null ||
3871
        type === "undefined" ||
3872
        type === "boolean" ||
3873
        type === "number" ||
3874
        type === "string"
3875
    );
3876
}
3877

    
3878
function toPrimitive(input) {
3879
    var val, valueOf, toString;
3880
    if (isPrimitive(input)) {
3881
        return input;
3882
    }
3883
    valueOf = input.valueOf;
3884
    if (typeof valueOf === "function") {
3885
        val = valueOf.call(input);
3886
        if (isPrimitive(val)) {
3887
            return val;
3888
        }
3889
    }
3890
    toString = input.toString;
3891
    if (typeof toString === "function") {
3892
        val = toString.call(input);
3893
        if (isPrimitive(val)) {
3894
            return val;
3895
        }
3896
    }
3897
    throw new TypeError();
3898
}
3899
var toObject = function (o) {
3900
    if (o == null) { // this matches both null and undefined
3901
        throw new TypeError("can't convert "+o+" to object");
3902
    }
3903
    return Object(o);
3904
};
3905

    
3906
});
(243-243/244)