Home page Forum Wiki Mail Jabber Devel NIX-FILES

AltLUG Git

Git-repositories of Altai Linux User Group

In autorun mode, moduleDone is called without matching moduleStart. Fix issue #184
[qunit.git] / qunit / qunit.js
1 /**
2  * QUnit v1.3.0pre - A JavaScript Unit Testing Framework
3  *
4  * http://docs.jquery.com/QUnit
5  *
6  * Copyright (c) 2012 John Resig, Jörn Zaefferer
7  * Dual licensed under the MIT (MIT-LICENSE.txt)
8  * or GPL (GPL-LICENSE.txt) licenses.
9  */
10
11 (function(window) {
12
13 var defined = {
14         setTimeout: typeof window.setTimeout !== "undefined",
15         sessionStorage: (function() {
16                 var x = "qunit-test-string";
17                 try {
18                         sessionStorage.setItem(x, x);
19                         sessionStorage.removeItem(x);
20                         return true;
21                 } catch(e) {
22                         return false;
23                 }
24         })()
25 };
26
27 var     testId = 0,
28         toString = Object.prototype.toString,
29         hasOwn = Object.prototype.hasOwnProperty;
30
31 var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
32         this.name = name;
33         this.testName = testName;
34         this.expected = expected;
35         this.testEnvironmentArg = testEnvironmentArg;
36         this.async = async;
37         this.callback = callback;
38         this.assertions = [];
39 };
40 Test.prototype = {
41         init: function() {
42                 var tests = id("qunit-tests");
43                 if (tests) {
44                         var b = document.createElement("strong");
45                                 b.innerHTML = "Running " + this.name;
46                         var li = document.createElement("li");
47                                 li.appendChild( b );
48                                 li.className = "running";
49                                 li.id = this.id = "test-output" + testId++;
50                         tests.appendChild( li );
51                 }
52         },
53         setup: function() {
54                 if (this.module != config.previousModule) {
55                         if ( config.previousModule ) {
56                                 runLoggingCallbacks('moduleDone', QUnit, {
57                                         name: config.previousModule,
58                                         failed: config.moduleStats.bad,
59                                         passed: config.moduleStats.all - config.moduleStats.bad,
60                                         total: config.moduleStats.all
61                                 } );
62                         }
63                         config.previousModule = this.module;
64                         config.moduleStats = { all: 0, bad: 0 };
65                         runLoggingCallbacks( 'moduleStart', QUnit, {
66                                 name: this.module
67                         } );
68                 } else if (config.autorun) {
69                         runLoggingCallbacks( 'moduleStart', QUnit, {
70                                 name: this.module
71                         } );
72                 }
73
74                 config.current = this;
75                 this.testEnvironment = extend({
76                         setup: function() {},
77                         teardown: function() {}
78                 }, this.moduleTestEnvironment);
79                 if (this.testEnvironmentArg) {
80                         extend(this.testEnvironment, this.testEnvironmentArg);
81                 }
82
83                 runLoggingCallbacks( 'testStart', QUnit, {
84                         name: this.testName,
85                         module: this.module
86                 });
87
88                 // allow utility functions to access the current test environment
89                 // TODO why??
90                 QUnit.current_testEnvironment = this.testEnvironment;
91
92                 try {
93                         if ( !config.pollution ) {
94                                 saveGlobal();
95                         }
96
97                         this.testEnvironment.setup.call(this.testEnvironment);
98                 } catch(e) {
99                         QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
100                 }
101         },
102         run: function() {
103                 config.current = this;
104                 if ( this.async ) {
105                         QUnit.stop();
106                 }
107
108                 if ( config.notrycatch ) {
109                         this.callback.call(this.testEnvironment);
110                         return;
111                 }
112                 try {
113                         this.callback.call(this.testEnvironment);
114                 } catch(e) {
115                         fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
116                         QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
117                         // else next test will carry the responsibility
118                         saveGlobal();
119
120                         // Restart the tests if they're blocking
121                         if ( config.blocking ) {
122                                 QUnit.start();
123                         }
124                 }
125         },
126         teardown: function() {
127                 config.current = this;
128                 try {
129                         this.testEnvironment.teardown.call(this.testEnvironment);
130                         checkPollution();
131                 } catch(e) {
132                         QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
133                 }
134         },
135         finish: function() {
136                 config.current = this;
137                 if ( this.expected != null && this.expected != this.assertions.length ) {
138                         QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
139                 }
140
141                 var good = 0, bad = 0,
142                         tests = id("qunit-tests");
143
144                 config.stats.all += this.assertions.length;
145                 config.moduleStats.all += this.assertions.length;
146
147                 if ( tests ) {
148                         var ol = document.createElement("ol");
149
150                         for ( var i = 0; i < this.assertions.length; i++ ) {
151                                 var assertion = this.assertions[i];
152
153                                 var li = document.createElement("li");
154                                 li.className = assertion.result ? "pass" : "fail";
155                                 li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
156                                 ol.appendChild( li );
157
158                                 if ( assertion.result ) {
159                                         good++;
160                                 } else {
161                                         bad++;
162                                         config.stats.bad++;
163                                         config.moduleStats.bad++;
164                                 }
165                         }
166
167                         // store result when possible
168                         if ( QUnit.config.reorder && defined.sessionStorage ) {
169                                 if (bad) {
170                                         sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
171                                 } else {
172                                         sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
173                                 }
174                         }
175
176                         if (bad == 0) {
177                                 ol.style.display = "none";
178                         }
179
180                         var b = document.createElement("strong");
181                         b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
182
183                         var a = document.createElement("a");
184                         a.innerHTML = "Rerun";
185                         a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
186
187                         addEvent(b, "click", function() {
188                                 var next = b.nextSibling.nextSibling,
189                                         display = next.style.display;
190                                 next.style.display = display === "none" ? "block" : "none";
191                         });
192
193                         addEvent(b, "dblclick", function(e) {
194                                 var target = e && e.target ? e.target : window.event.srcElement;
195                                 if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
196                                         target = target.parentNode;
197                                 }
198                                 if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
199                                         window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
200                                 }
201                         });
202
203                         var li = id(this.id);
204                         li.className = bad ? "fail" : "pass";
205                         li.removeChild( li.firstChild );
206                         li.appendChild( b );
207                         li.appendChild( a );
208                         li.appendChild( ol );
209
210                 } else {
211                         for ( var i = 0; i < this.assertions.length; i++ ) {
212                                 if ( !this.assertions[i].result ) {
213                                         bad++;
214                                         config.stats.bad++;
215                                         config.moduleStats.bad++;
216                                 }
217                         }
218                 }
219
220                 try {
221                         QUnit.reset();
222                 } catch(e) {
223                         fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
224                 }
225
226                 runLoggingCallbacks( 'testDone', QUnit, {
227                         name: this.testName,
228                         module: this.module,
229                         failed: bad,
230                         passed: this.assertions.length - bad,
231                         total: this.assertions.length
232                 } );
233         },
234
235         queue: function() {
236                 var test = this;
237                 synchronize(function() {
238                         test.init();
239                 });
240                 function run() {
241                         // each of these can by async
242                         synchronize(function() {
243                                 test.setup();
244                         });
245                         synchronize(function() {
246                                 test.run();
247                         });
248                         synchronize(function() {
249                                 test.teardown();
250                         });
251                         synchronize(function() {
252                                 test.finish();
253                         });
254                 }
255                 // defer when previous test run passed, if storage is available
256                 var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
257                 if (bad) {
258                         run();
259                 } else {
260                         synchronize(run, true);
261                 };
262         }
263
264 };
265
266 var QUnit = {
267
268         // call on start of module test to prepend name to all tests
269         module: function(name, testEnvironment) {
270                 config.currentModule = name;
271                 config.currentModuleTestEnviroment = testEnvironment;
272         },
273
274         asyncTest: function(testName, expected, callback) {
275                 if ( arguments.length === 2 ) {
276                         callback = expected;
277                         expected = null;
278                 }
279
280                 QUnit.test(testName, expected, callback, true);
281         },
282
283         test: function(testName, expected, callback, async) {
284                 var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>', testEnvironmentArg;
285
286                 if ( arguments.length === 2 ) {
287                         callback = expected;
288                         expected = null;
289                 }
290                 // is 2nd argument a testEnvironment?
291                 if ( expected && typeof expected === 'object') {
292                         testEnvironmentArg = expected;
293                         expected = null;
294                 }
295
296                 if ( config.currentModule ) {
297                         name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
298                 }
299
300                 if ( !validTest(config.currentModule + ": " + testName) ) {
301                         return;
302                 }
303
304                 var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
305                 test.module = config.currentModule;
306                 test.moduleTestEnvironment = config.currentModuleTestEnviroment;
307                 test.queue();
308         },
309
310         /**
311          * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
312          */
313         expect: function(asserts) {
314                 config.current.expected = asserts;
315         },
316
317         /**
318          * Asserts true.
319          * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
320          */
321         ok: function(a, msg) {
322                 a = !!a;
323                 var details = {
324                         result: a,
325                         message: msg
326                 };
327                 msg = escapeInnerText(msg);
328                 runLoggingCallbacks( 'log', QUnit, details );
329                 config.current.assertions.push({
330                         result: a,
331                         message: msg
332                 });
333         },
334
335         /**
336          * Checks that the first two arguments are equal, with an optional message.
337          * Prints out both actual and expected values.
338          *
339          * Prefered to ok( actual == expected, message )
340          *
341          * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
342          *
343          * @param Object actual
344          * @param Object expected
345          * @param String message (optional)
346          */
347         equal: function(actual, expected, message) {
348                 QUnit.push(expected == actual, actual, expected, message);
349         },
350
351         notEqual: function(actual, expected, message) {
352                 QUnit.push(expected != actual, actual, expected, message);
353         },
354
355         deepEqual: function(actual, expected, message) {
356                 QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
357         },
358
359         notDeepEqual: function(actual, expected, message) {
360                 QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
361         },
362
363         strictEqual: function(actual, expected, message) {
364                 QUnit.push(expected === actual, actual, expected, message);
365         },
366
367         notStrictEqual: function(actual, expected, message) {
368                 QUnit.push(expected !== actual, actual, expected, message);
369         },
370
371         raises: function(block, expected, message) {
372                 var actual, ok = false;
373
374                 if (typeof expected === 'string') {
375                         message = expected;
376                         expected = null;
377                 }
378
379                 try {
380                         block();
381                 } catch (e) {
382                         actual = e;
383                 }
384
385                 if (actual) {
386                         // we don't want to validate thrown error
387                         if (!expected) {
388                                 ok = true;
389                         // expected is a regexp
390                         } else if (QUnit.objectType(expected) === "regexp") {
391                                 ok = expected.test(actual);
392                         // expected is a constructor
393                         } else if (actual instanceof expected) {
394                                 ok = true;
395                         // expected is a validation function which returns true is validation passed
396                         } else if (expected.call({}, actual) === true) {
397                                 ok = true;
398                         }
399                 }
400
401                 QUnit.ok(ok, message);
402         },
403
404         start: function(count) {
405                 config.semaphore -= count || 1;
406                 if (config.semaphore > 0) {
407                         // don't start until equal number of stop-calls
408                         return;
409                 }
410                 if (config.semaphore < 0) {
411                         // ignore if start is called more often then stop
412                         config.semaphore = 0;
413                 }
414                 // A slight delay, to avoid any current callbacks
415                 if ( defined.setTimeout ) {
416                         window.setTimeout(function() {
417                                 if (config.semaphore > 0) {
418                                         return;
419                                 }
420                                 if ( config.timeout ) {
421                                         clearTimeout(config.timeout);
422                                 }
423
424                                 config.blocking = false;
425                                 process(true);
426                         }, 13);
427                 } else {
428                         config.blocking = false;
429                         process(true);
430                 }
431         },
432
433         stop: function(count) {
434                 config.semaphore += count || 1;
435                 config.blocking = true;
436
437                 if ( config.testTimeout && defined.setTimeout ) {
438                         clearTimeout(config.timeout);
439                         config.timeout = window.setTimeout(function() {
440                                 QUnit.ok( false, "Test timed out" );
441                                 config.semaphore = 1;
442                                 QUnit.start();
443                         }, config.testTimeout);
444                 }
445         }
446 };
447
448 //We want access to the constructor's prototype
449 (function() {
450         function F(){};
451         F.prototype = QUnit;
452         QUnit = new F();
453         //Make F QUnit's constructor so that we can add to the prototype later
454         QUnit.constructor = F;
455 })();
456
457 // deprecated; still export them to window to provide clear error messages
458 // next step: remove entirely
459 QUnit.equals = function() {
460         throw new Error("QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead");
461 };
462 QUnit.same = function() {
463         throw new Error("QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead");
464 };
465
466 // Maintain internal state
467 var config = {
468         // The queue of tests to run
469         queue: [],
470
471         // block until document ready
472         blocking: true,
473
474         // when enabled, show only failing tests
475         // gets persisted through sessionStorage and can be changed in UI via checkbox
476         hidepassed: false,
477
478         // by default, run previously failed tests first
479         // very useful in combination with "Hide passed tests" checked
480         reorder: true,
481
482         // by default, modify document.title when suite is done
483         altertitle: true,
484
485         urlConfig: ['noglobals', 'notrycatch'],
486
487         //logging callback queues
488         begin: [],
489         done: [],
490         log: [],
491         testStart: [],
492         testDone: [],
493         moduleStart: [],
494         moduleDone: []
495 };
496
497 // Load paramaters
498 (function() {
499         var location = window.location || { search: "", protocol: "file:" },
500                 params = location.search.slice( 1 ).split( "&" ),
501                 length = params.length,
502                 urlParams = {},
503                 current;
504
505         if ( params[ 0 ] ) {
506                 for ( var i = 0; i < length; i++ ) {
507                         current = params[ i ].split( "=" );
508                         current[ 0 ] = decodeURIComponent( current[ 0 ] );
509                         // allow just a key to turn on a flag, e.g., test.html?noglobals
510                         current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
511                         urlParams[ current[ 0 ] ] = current[ 1 ];
512                 }
513         }
514
515         QUnit.urlParams = urlParams;
516         config.filter = urlParams.filter;
517
518         // Figure out if we're running the tests from a server or not
519         QUnit.isLocal = !!(location.protocol === 'file:');
520 })();
521
522 // Expose the API as global variables, unless an 'exports'
523 // object exists, in that case we assume we're in CommonJS
524 if ( typeof exports === "undefined" || typeof require === "undefined" ) {
525         extend(window, QUnit);
526         window.QUnit = QUnit;
527 } else {
528         extend(exports, QUnit);
529         exports.QUnit = QUnit;
530 }
531
532 // define these after exposing globals to keep them in these QUnit namespace only
533 extend(QUnit, {
534         config: config,
535
536         // Initialize the configuration options
537         init: function() {
538                 extend(config, {
539                         stats: { all: 0, bad: 0 },
540                         moduleStats: { all: 0, bad: 0 },
541                         started: +new Date,
542                         updateRate: 1000,
543                         blocking: false,
544                         autostart: true,
545                         autorun: false,
546                         filter: "",
547                         queue: [],
548                         semaphore: 0
549                 });
550
551                 var tests = id( "qunit-tests" ),
552                         banner = id( "qunit-banner" ),
553                         result = id( "qunit-testresult" );
554
555                 if ( tests ) {
556                         tests.innerHTML = "";
557                 }
558
559                 if ( banner ) {
560                         banner.className = "";
561                 }
562
563                 if ( result ) {
564                         result.parentNode.removeChild( result );
565                 }
566
567                 if ( tests ) {
568                         result = document.createElement( "p" );
569                         result.id = "qunit-testresult";
570                         result.className = "result";
571                         tests.parentNode.insertBefore( result, tests );
572                         result.innerHTML = 'Running...<br/>&nbsp;';
573                 }
574         },
575
576         /**
577          * Resets the test setup. Useful for tests that modify the DOM.
578          *
579          * If jQuery is available, uses jQuery's replaceWith(), otherwise use replaceChild
580          */
581         reset: function() {
582                 if ( window.jQuery ) {
583                         jQuery( "#qunit-fixture" ).replaceWith( config.fixture.cloneNode(true) );
584                 } else {
585                         var main = id( 'qunit-fixture' );
586                         if ( main ) {
587                                 main.parentNode.replaceChild(config.fixture.cloneNode(true), main);
588                         }
589                 }
590         },
591
592         /**
593          * Trigger an event on an element.
594          *
595          * @example triggerEvent( document.body, "click" );
596          *
597          * @param DOMElement elem
598          * @param String type
599          */
600         triggerEvent: function( elem, type, event ) {
601                 if ( document.createEvent ) {
602                         event = document.createEvent("MouseEvents");
603                         event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
604                                 0, 0, 0, 0, 0, false, false, false, false, 0, null);
605                         elem.dispatchEvent( event );
606
607                 } else if ( elem.fireEvent ) {
608                         elem.fireEvent("on"+type);
609                 }
610         },
611
612         // Safe object type checking
613         is: function( type, obj ) {
614                 return QUnit.objectType( obj ) == type;
615         },
616
617         objectType: function( obj ) {
618                 if (typeof obj === "undefined") {
619                                 return "undefined";
620
621                 // consider: typeof null === object
622                 }
623                 if (obj === null) {
624                                 return "null";
625                 }
626
627                 var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
628
629                 switch (type) {
630                                 case 'Number':
631                                                 if (isNaN(obj)) {
632                                                                 return "nan";
633                                                 } else {
634                                                                 return "number";
635                                                 }
636                                 case 'String':
637                                 case 'Boolean':
638                                 case 'Array':
639                                 case 'Date':
640                                 case 'RegExp':
641                                 case 'Function':
642                                                 return type.toLowerCase();
643                 }
644                 if (typeof obj === "object") {
645                                 return "object";
646                 }
647                 return undefined;
648         },
649
650         push: function(result, actual, expected, message) {
651                 var details = {
652                         result: result,
653                         message: message,
654                         actual: actual,
655                         expected: expected
656                 };
657
658                 message = escapeInnerText(message) || (result ? "okay" : "failed");
659                 message = '<span class="test-message">' + message + "</span>";
660                 expected = escapeInnerText(QUnit.jsDump.parse(expected));
661                 actual = escapeInnerText(QUnit.jsDump.parse(actual));
662                 var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
663                 if (actual != expected) {
664                         output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
665                         output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
666                 }
667                 if (!result) {
668                         var source = sourceFromStacktrace();
669                         if (source) {
670                                 details.source = source;
671                                 output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
672                         }
673                 }
674                 output += "</table>";
675
676                 runLoggingCallbacks( 'log', QUnit, details );
677
678                 config.current.assertions.push({
679                         result: !!result,
680                         message: output
681                 });
682         },
683
684         url: function( params ) {
685                 params = extend( extend( {}, QUnit.urlParams ), params );
686                 var querystring = "?",
687                         key;
688                 for ( key in params ) {
689                         if ( !hasOwn.call( params, key ) ) {
690                                 continue;
691                         }
692                         querystring += encodeURIComponent( key ) + "=" +
693                                 encodeURIComponent( params[ key ] ) + "&";
694                 }
695                 return window.location.pathname + querystring.slice( 0, -1 );
696         },
697
698         extend: extend,
699         id: id,
700         addEvent: addEvent
701 });
702
703 //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
704 //Doing this allows us to tell if the following methods have been overwritten on the actual
705 //QUnit object, which is a deprecated way of using the callbacks.
706 extend(QUnit.constructor.prototype, {
707         // Logging callbacks; all receive a single argument with the listed properties
708         // run test/logs.html for any related changes
709         begin: registerLoggingCallback('begin'),
710         // done: { failed, passed, total, runtime }
711         done: registerLoggingCallback('done'),
712         // log: { result, actual, expected, message }
713         log: registerLoggingCallback('log'),
714         // testStart: { name }
715         testStart: registerLoggingCallback('testStart'),
716         // testDone: { name, failed, passed, total }
717         testDone: registerLoggingCallback('testDone'),
718         // moduleStart: { name }
719         moduleStart: registerLoggingCallback('moduleStart'),
720         // moduleDone: { name, failed, passed, total }
721         moduleDone: registerLoggingCallback('moduleDone')
722 });
723
724 if ( typeof document === "undefined" || document.readyState === "complete" ) {
725         config.autorun = true;
726 }
727
728 QUnit.load = function() {
729         runLoggingCallbacks( 'begin', QUnit, {} );
730
731         // Initialize the config, saving the execution queue
732         var oldconfig = extend({}, config);
733         QUnit.init();
734         extend(config, oldconfig);
735
736         config.blocking = false;
737
738         var urlConfigHtml = '', len = config.urlConfig.length;
739         for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
740                 config[val] = QUnit.urlParams[val];
741                 urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
742         }
743
744         var userAgent = id("qunit-userAgent");
745         if ( userAgent ) {
746                 userAgent.innerHTML = navigator.userAgent;
747         }
748         var banner = id("qunit-header");
749         if ( banner ) {
750                 banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
751                 addEvent( banner, "change", function( event ) {
752                         var params = {};
753                         params[ event.target.name ] = event.target.checked ? true : undefined;
754                         window.location = QUnit.url( params );
755                 });
756         }
757
758         var toolbar = id("qunit-testrunner-toolbar");
759         if ( toolbar ) {
760                 var filter = document.createElement("input");
761                 filter.type = "checkbox";
762                 filter.id = "qunit-filter-pass";
763                 addEvent( filter, "click", function() {
764                         var ol = document.getElementById("qunit-tests");
765                         if ( filter.checked ) {
766                                 ol.className = ol.className + " hidepass";
767                         } else {
768                                 var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
769                                 ol.className = tmp.replace(/ hidepass /, " ");
770                         }
771                         if ( defined.sessionStorage ) {
772                                 if (filter.checked) {
773                                         sessionStorage.setItem("qunit-filter-passed-tests", "true");
774                                 } else {
775                                         sessionStorage.removeItem("qunit-filter-passed-tests");
776                                 }
777                         }
778                 });
779                 if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
780                         filter.checked = true;
781                         var ol = document.getElementById("qunit-tests");
782                         ol.className = ol.className + " hidepass";
783                 }
784                 toolbar.appendChild( filter );
785
786                 var label = document.createElement("label");
787                 label.setAttribute("for", "qunit-filter-pass");
788                 label.innerHTML = "Hide passed tests";
789                 toolbar.appendChild( label );
790         }
791
792         var main = id('qunit-fixture');
793         if ( main ) {
794                 config.fixture = main.cloneNode(true);
795         }
796
797         if (config.autostart) {
798                 QUnit.start();
799         }
800 };
801
802 addEvent(window, "load", QUnit.load);
803
804 // addEvent(window, "error") gives us a useless event object
805 window.onerror = function( message, file, line ) {
806         if ( QUnit.config.current ) {
807                 ok( false, message + ", " + file + ":" + line );
808         } else {
809                 test( "global failure", function() {
810                         ok( false, message + ", " + file + ":" + line );
811                 });
812         }
813 };
814
815 function done() {
816         config.autorun = true;
817
818         // Log the last module results
819         if ( config.currentModule ) {
820                 runLoggingCallbacks( 'moduleDone', QUnit, {
821                         name: config.currentModule,
822                         failed: config.moduleStats.bad,
823                         passed: config.moduleStats.all - config.moduleStats.bad,
824                         total: config.moduleStats.all
825                 } );
826         }
827
828         var banner = id("qunit-banner"),
829                 tests = id("qunit-tests"),
830                 runtime = +new Date - config.started,
831                 passed = config.stats.all - config.stats.bad,
832                 html = [
833                         'Tests completed in ',
834                         runtime,
835                         ' milliseconds.<br/>',
836                         '<span class="passed">',
837                         passed,
838                         '</span> tests of <span class="total">',
839                         config.stats.all,
840                         '</span> passed, <span class="failed">',
841                         config.stats.bad,
842                         '</span> failed.'
843                 ].join('');
844
845         if ( banner ) {
846                 banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
847         }
848
849         if ( tests ) {
850                 id( "qunit-testresult" ).innerHTML = html;
851         }
852
853         if ( config.altertitle && typeof document !== "undefined" && document.title ) {
854                 // show ✖ for good, ✔ for bad suite result in title
855                 // use escape sequences in case file gets loaded with non-utf-8-charset
856                 document.title = [
857                         (config.stats.bad ? "\u2716" : "\u2714"),
858                         document.title.replace(/^[\u2714\u2716] /i, "")
859                 ].join(" ");
860         }
861
862         runLoggingCallbacks( 'done', QUnit, {
863                 failed: config.stats.bad,
864                 passed: passed,
865                 total: config.stats.all,
866                 runtime: runtime
867         } );
868 }
869
870 function validTest( name ) {
871         var filter = config.filter,
872                 run = false;
873
874         if ( !filter ) {
875                 return true;
876         }
877
878         var not = filter.charAt( 0 ) === "!";
879         if ( not ) {
880                 filter = filter.slice( 1 );
881         }
882
883         if ( name.indexOf( filter ) !== -1 ) {
884                 return !not;
885         }
886
887         if ( not ) {
888                 run = true;
889         }
890
891         return run;
892 }
893
894 // so far supports only Firefox, Chrome and Opera (buggy)
895 // could be extended in the future to use something like https://github.com/csnover/TraceKit
896 function sourceFromStacktrace() {
897         try {
898                 throw new Error();
899         } catch ( e ) {
900                 if (e.stacktrace) {
901                         // Opera
902                         return e.stacktrace.split("\n")[6];
903                 } else if (e.stack) {
904                         // Firefox, Chrome
905                         return e.stack.split("\n")[4];
906                 } else if (e.sourceURL) {
907                         // Safari, PhantomJS
908                         // TODO sourceURL points at the 'throw new Error' line above, useless
909                         //return e.sourceURL + ":" + e.line;
910                 }
911         }
912 }
913
914 function escapeInnerText(s) {
915         if (!s) {
916                 return "";
917         }
918         s = s + "";
919         return s.replace(/[\&<>]/g, function(s) {
920                 switch(s) {
921                         case "&": return "&amp;";
922                         case "<": return "&lt;";
923                         case ">": return "&gt;";
924                         default: return s;
925                 }
926         });
927 }
928
929 function synchronize( callback, last ) {
930         config.queue.push( callback );
931
932         if ( config.autorun && !config.blocking ) {
933                 process(last);
934         }
935 }
936
937 function process( last ) {
938         var start = new Date().getTime();
939         config.depth = config.depth ? config.depth + 1 : 1;
940
941         while ( config.queue.length && !config.blocking ) {
942                 if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
943                         config.queue.shift()();
944                 } else {
945                         window.setTimeout( function(){
946                                 process( last );
947                         }, 13 );
948                         break;
949                 }
950         }
951         config.depth--;
952         if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
953                 done();
954         }
955 }
956
957 function saveGlobal() {
958         config.pollution = [];
959
960         if ( config.noglobals ) {
961                 for ( var key in window ) {
962                         if ( !hasOwn.call( window, key ) ) {
963                                 continue;
964                         }
965                         config.pollution.push( key );
966                 }
967         }
968 }
969
970 function checkPollution( name ) {
971         var old = config.pollution;
972         saveGlobal();
973
974         var newGlobals = diff( config.pollution, old );
975         if ( newGlobals.length > 0 ) {
976                 ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
977         }
978
979         var deletedGlobals = diff( old, config.pollution );
980         if ( deletedGlobals.length > 0 ) {
981                 ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
982         }
983 }
984
985 // returns a new Array with the elements that are in a but not in b
986 function diff( a, b ) {
987         var result = a.slice();
988         for ( var i = 0; i < result.length; i++ ) {
989                 for ( var j = 0; j < b.length; j++ ) {
990                         if ( result[i] === b[j] ) {
991                                 result.splice(i, 1);
992                                 i--;
993                                 break;
994                         }
995                 }
996         }
997         return result;
998 }
999
1000 function fail(message, exception, callback) {
1001         if ( typeof console !== "undefined" && console.error && console.warn ) {
1002                 console.error(message);
1003                 console.error(exception);
1004                 console.error(exception.stack);
1005                 console.warn(callback.toString());
1006
1007         } else if ( window.opera && opera.postError ) {
1008                 opera.postError(message, exception, callback.toString);
1009         }
1010 }
1011
1012 function extend(a, b) {
1013         for ( var prop in b ) {
1014                 if ( b[prop] === undefined ) {
1015                         delete a[prop];
1016
1017                 // Avoid "Member not found" error in IE8 caused by setting window.constructor
1018                 } else if ( prop !== "constructor" || a !== window ) {
1019                         a[prop] = b[prop];
1020                 }
1021         }
1022
1023         return a;
1024 }
1025
1026 function addEvent(elem, type, fn) {
1027         if ( elem.addEventListener ) {
1028                 elem.addEventListener( type, fn, false );
1029         } else if ( elem.attachEvent ) {
1030                 elem.attachEvent( "on" + type, fn );
1031         } else {
1032                 fn();
1033         }
1034 }
1035
1036 function id(name) {
1037         return !!(typeof document !== "undefined" && document && document.getElementById) &&
1038                 document.getElementById( name );
1039 }
1040
1041 function registerLoggingCallback(key){
1042         return function(callback){
1043                 config[key].push( callback );
1044         };
1045 }
1046
1047 // Supports deprecated method of completely overwriting logging callbacks
1048 function runLoggingCallbacks(key, scope, args) {
1049         //debugger;
1050         var callbacks;
1051         if ( QUnit.hasOwnProperty(key) ) {
1052                 QUnit[key].call(scope, args);
1053         } else {
1054                 callbacks = config[key];
1055                 for( var i = 0; i < callbacks.length; i++ ) {
1056                         callbacks[i].call( scope, args );
1057                 }
1058         }
1059 }
1060
1061 // Test for equality any JavaScript type.
1062 // Author: Philippe Rathé <prathe@gmail.com>
1063 QUnit.equiv = function () {
1064
1065         var innerEquiv; // the real equiv function
1066         var callers = []; // stack to decide between skip/abort functions
1067         var parents = []; // stack to avoiding loops from circular referencing
1068
1069         // Call the o related callback with the given arguments.
1070         function bindCallbacks(o, callbacks, args) {
1071                 var prop = QUnit.objectType(o);
1072                 if (prop) {
1073                         if (QUnit.objectType(callbacks[prop]) === "function") {
1074                                 return callbacks[prop].apply(callbacks, args);
1075                         } else {
1076                                 return callbacks[prop]; // or undefined
1077                         }
1078                 }
1079         }
1080
1081         var getProto = Object.getPrototypeOf || function (obj) {
1082                 return obj.__proto__;
1083         };
1084
1085         var callbacks = function () {
1086
1087                 // for string, boolean, number and null
1088                 function useStrictEquality(b, a) {
1089                         if (b instanceof a.constructor || a instanceof b.constructor) {
1090                                 // to catch short annotaion VS 'new' annotation of a
1091                                 // declaration
1092                                 // e.g. var i = 1;
1093                                 // var j = new Number(1);
1094                                 return a == b;
1095                         } else {
1096                                 return a === b;
1097                         }
1098                 }
1099
1100                 return {
1101                         "string" : useStrictEquality,
1102                         "boolean" : useStrictEquality,
1103                         "number" : useStrictEquality,
1104                         "null" : useStrictEquality,
1105                         "undefined" : useStrictEquality,
1106
1107                         "nan" : function(b) {
1108                                 return isNaN(b);
1109                         },
1110
1111                         "date" : function(b, a) {
1112                                 return QUnit.objectType(b) === "date"
1113                                                 && a.valueOf() === b.valueOf();
1114                         },
1115
1116                         "regexp" : function(b, a) {
1117                                 return QUnit.objectType(b) === "regexp"
1118                                                 && a.source === b.source && // the regex itself
1119                                                 a.global === b.global && // and its modifers
1120                                                                                                         // (gmi) ...
1121                                                 a.ignoreCase === b.ignoreCase
1122                                                 && a.multiline === b.multiline;
1123                         },
1124
1125                         // - skip when the property is a method of an instance (OOP)
1126                         // - abort otherwise,
1127                         // initial === would have catch identical references anyway
1128                         "function" : function() {
1129                                 var caller = callers[callers.length - 1];
1130                                 return caller !== Object && typeof caller !== "undefined";
1131                         },
1132
1133                         "array" : function(b, a) {
1134                                 var i, j, loop;
1135                                 var len;
1136
1137                                 // b could be an object literal here
1138                                 if (!(QUnit.objectType(b) === "array")) {
1139                                         return false;
1140                                 }
1141
1142                                 len = a.length;
1143                                 if (len !== b.length) { // safe and faster
1144                                         return false;
1145                                 }
1146
1147                                 // track reference to avoid circular references
1148                                 parents.push(a);
1149                                 for (i = 0; i < len; i++) {
1150                                         loop = false;
1151                                         for (j = 0; j < parents.length; j++) {
1152                                                 if (parents[j] === a[i]) {
1153                                                         loop = true;// dont rewalk array
1154                                                 }
1155                                         }
1156                                         if (!loop && !innerEquiv(a[i], b[i])) {
1157                                                 parents.pop();
1158                                                 return false;
1159                                         }
1160                                 }
1161                                 parents.pop();
1162                                 return true;
1163                         },
1164
1165                         "object" : function(b, a) {
1166                                 var i, j, loop;
1167                                 var eq = true; // unless we can proove it
1168                                 var aProperties = [], bProperties = []; // collection of
1169                                                                                                                 // strings
1170
1171                                 // comparing constructors is more strict than using
1172                                 // instanceof
1173                                 if (a.constructor !== b.constructor) {
1174                                         // Allow objects with no prototype to be equivalent to
1175                                         // objects with Object as their constructor.
1176                                         if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
1177                                                   (getProto(b) === null && getProto(a) === Object.prototype)))
1178                                         {
1179                                                 return false;
1180                                         }
1181                                 }
1182
1183                                 // stack constructor before traversing properties
1184                                 callers.push(a.constructor);
1185                                 // track reference to avoid circular references
1186                                 parents.push(a);
1187
1188                                 for (i in a) { // be strict: don't ensures hasOwnProperty
1189                                                                 // and go deep
1190                                         loop = false;
1191                                         for (j = 0; j < parents.length; j++) {
1192                                                 if (parents[j] === a[i])
1193                                                         loop = true; // don't go down the same path
1194                                                                                         // twice
1195                                         }
1196                                         aProperties.push(i); // collect a's properties
1197
1198                                         if (!loop && !innerEquiv(a[i], b[i])) {
1199                                                 eq = false;
1200                                                 break;
1201                                         }
1202                                 }
1203
1204                                 callers.pop(); // unstack, we are done
1205                                 parents.pop();
1206
1207                                 for (i in b) {
1208                                         bProperties.push(i); // collect b's properties
1209                                 }
1210
1211                                 // Ensures identical properties name
1212                                 return eq
1213                                                 && innerEquiv(aProperties.sort(), bProperties
1214                                                                 .sort());
1215                         }
1216                 };
1217         }();
1218
1219         innerEquiv = function() { // can take multiple arguments
1220                 var args = Array.prototype.slice.apply(arguments);
1221                 if (args.length < 2) {
1222                         return true; // end transition
1223                 }
1224
1225                 return (function(a, b) {
1226                         if (a === b) {
1227                                 return true; // catch the most you can
1228                         } else if (a === null || b === null || typeof a === "undefined"
1229                                         || typeof b === "undefined"
1230                                         || QUnit.objectType(a) !== QUnit.objectType(b)) {
1231                                 return false; // don't lose time with error prone cases
1232                         } else {
1233                                 return bindCallbacks(a, callbacks, [ b, a ]);
1234                         }
1235
1236                         // apply transition with (1..n) arguments
1237                 })(args[0], args[1])
1238                                 && arguments.callee.apply(this, args.splice(1,
1239                                                 args.length - 1));
1240         };
1241
1242         return innerEquiv;
1243
1244 }();
1245
1246 /**
1247  * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
1248  * http://flesler.blogspot.com Licensed under BSD
1249  * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
1250  *
1251  * @projectDescription Advanced and extensible data dumping for Javascript.
1252  * @version 1.0.0
1253  * @author Ariel Flesler
1254  * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
1255  */
1256 QUnit.jsDump = (function() {
1257         function quote( str ) {
1258                 return '"' + str.toString().replace(/"/g, '\\"') + '"';
1259         };
1260         function literal( o ) {
1261                 return o + '';
1262         };
1263         function join( pre, arr, post ) {
1264                 var s = jsDump.separator(),
1265                         base = jsDump.indent(),
1266                         inner = jsDump.indent(1);
1267                 if ( arr.join )
1268                         arr = arr.join( ',' + s + inner );
1269                 if ( !arr )
1270                         return pre + post;
1271                 return [ pre, inner + arr, base + post ].join(s);
1272         };
1273         function array( arr, stack ) {
1274                 var i = arr.length, ret = Array(i);
1275                 this.up();
1276                 while ( i-- )
1277                         ret[i] = this.parse( arr[i] , undefined , stack);
1278                 this.down();
1279                 return join( '[', ret, ']' );
1280         };
1281
1282         var reName = /^function (\w+)/;
1283
1284         var jsDump = {
1285                 parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
1286                         stack = stack || [ ];
1287                         var parser = this.parsers[ type || this.typeOf(obj) ];
1288                         type = typeof parser;
1289                         var inStack = inArray(obj, stack);
1290                         if (inStack != -1) {
1291                                 return 'recursion('+(inStack - stack.length)+')';
1292                         }
1293                         //else
1294                         if (type == 'function')  {
1295                                         stack.push(obj);
1296                                         var res = parser.call( this, obj, stack );
1297                                         stack.pop();
1298                                         return res;
1299                         }
1300                         // else
1301                         return (type == 'string') ? parser : this.parsers.error;
1302                 },
1303                 typeOf:function( obj ) {
1304                         var type;
1305                         if ( obj === null ) {
1306                                 type = "null";
1307                         } else if (typeof obj === "undefined") {
1308                                 type = "undefined";
1309                         } else if (QUnit.is("RegExp", obj)) {
1310                                 type = "regexp";
1311                         } else if (QUnit.is("Date", obj)) {
1312                                 type = "date";
1313                         } else if (QUnit.is("Function", obj)) {
1314                                 type = "function";
1315                         } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
1316                                 type = "window";
1317                         } else if (obj.nodeType === 9) {
1318                                 type = "document";
1319                         } else if (obj.nodeType) {
1320                                 type = "node";
1321                         } else if (
1322                                 // native arrays
1323                                 toString.call( obj ) === "[object Array]" ||
1324                                 // NodeList objects
1325                                 ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
1326                         ) {
1327                                 type = "array";
1328                         } else {
1329                                 type = typeof obj;
1330                         }
1331                         return type;
1332                 },
1333                 separator:function() {
1334                         return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' ';
1335                 },
1336                 indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
1337                         if ( !this.multiline )
1338                                 return '';
1339                         var chr = this.indentChar;
1340                         if ( this.HTML )
1341                                 chr = chr.replace(/\t/g,'   ').replace(/ /g,'&nbsp;');
1342                         return Array( this._depth_ + (extra||0) ).join(chr);
1343                 },
1344                 up:function( a ) {
1345                         this._depth_ += a || 1;
1346                 },
1347                 down:function( a ) {
1348                         this._depth_ -= a || 1;
1349                 },
1350                 setParser:function( name, parser ) {
1351                         this.parsers[name] = parser;
1352                 },
1353                 // The next 3 are exposed so you can use them
1354                 quote:quote,
1355                 literal:literal,
1356                 join:join,
1357                 //
1358                 _depth_: 1,
1359                 // This is the list of parsers, to modify them, use jsDump.setParser
1360                 parsers:{
1361                         window: '[Window]',
1362                         document: '[Document]',
1363                         error:'[ERROR]', //when no parser is found, shouldn't happen
1364                         unknown: '[Unknown]',
1365                         'null':'null',
1366                         'undefined':'undefined',
1367                         'function':function( fn ) {
1368                                 var ret = 'function',
1369                                         name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
1370                                 if ( name )
1371                                         ret += ' ' + name;
1372                                 ret += '(';
1373
1374                                 ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
1375                                 return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
1376                         },
1377                         array: array,
1378                         nodelist: array,
1379                         arguments: array,
1380                         object:function( map, stack ) {
1381                                 var ret = [ ];
1382                                 QUnit.jsDump.up();
1383                                 for ( var key in map ) {
1384                                         var val = map[key];
1385                                         ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
1386                                 }
1387                                 QUnit.jsDump.down();
1388                                 return join( '{', ret, '}' );
1389                         },
1390                         node:function( node ) {
1391                                 var open = QUnit.jsDump.HTML ? '&lt;' : '<',
1392                                         close = QUnit.jsDump.HTML ? '&gt;' : '>';
1393
1394                                 var tag = node.nodeName.toLowerCase(),
1395                                         ret = open + tag;
1396
1397                                 for ( var a in QUnit.jsDump.DOMAttrs ) {
1398                                         var val = node[QUnit.jsDump.DOMAttrs[a]];
1399                                         if ( val )
1400                                                 ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
1401                                 }
1402                                 return ret + close + open + '/' + tag + close;
1403                         },
1404                         functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
1405                                 var l = fn.length;
1406                                 if ( !l ) return '';
1407
1408                                 var args = Array(l);
1409                                 while ( l-- )
1410                                         args[l] = String.fromCharCode(97+l);//97 is 'a'
1411                                 return ' ' + args.join(', ') + ' ';
1412                         },
1413                         key:quote, //object calls it internally, the key part of an item in a map
1414                         functionCode:'[code]', //function calls it internally, it's the content of the function
1415                         attribute:quote, //node calls it internally, it's an html attribute value
1416                         string:quote,
1417                         date:quote,
1418                         regexp:literal, //regex
1419                         number:literal,
1420                         'boolean':literal
1421                 },
1422                 DOMAttrs:{//attributes to dump from nodes, name=>realName
1423                         id:'id',
1424                         name:'name',
1425                         'class':'className'
1426                 },
1427                 HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
1428                 indentChar:'  ',//indentation unit
1429                 multiline:true //if true, items in a collection, are separated by a \n, else just a space.
1430         };
1431
1432         return jsDump;
1433 })();
1434
1435 // from Sizzle.js
1436 function getText( elems ) {
1437         var ret = "", elem;
1438
1439         for ( var i = 0; elems[i]; i++ ) {
1440                 elem = elems[i];
1441
1442                 // Get the text from text nodes and CDATA nodes
1443                 if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
1444                         ret += elem.nodeValue;
1445
1446                 // Traverse everything else, except comment nodes
1447                 } else if ( elem.nodeType !== 8 ) {
1448                         ret += getText( elem.childNodes );
1449                 }
1450         }
1451
1452         return ret;
1453 };
1454
1455 //from jquery.js
1456 function inArray( elem, array ) {
1457         if ( array.indexOf ) {
1458                 return array.indexOf( elem );
1459         }
1460
1461         for ( var i = 0, length = array.length; i < length; i++ ) {
1462                 if ( array[ i ] === elem ) {
1463                         return i;
1464                 }
1465         }
1466
1467         return -1;
1468 }
1469
1470 /*
1471  * Javascript Diff Algorithm
1472  *  By John Resig (http://ejohn.org/)
1473  *  Modified by Chu Alan "sprite"
1474  *
1475  * Released under the MIT license.
1476  *
1477  * More Info:
1478  *  http://ejohn.org/projects/javascript-diff-algorithm/
1479  *
1480  * Usage: QUnit.diff(expected, actual)
1481  *
1482  * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the  quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
1483  */
1484 QUnit.diff = (function() {
1485         function diff(o, n) {
1486                 var ns = {};
1487                 var os = {};
1488
1489                 for (var i = 0; i < n.length; i++) {
1490                         if (ns[n[i]] == null)
1491                                 ns[n[i]] = {
1492                                         rows: [],
1493                                         o: null
1494                                 };
1495                         ns[n[i]].rows.push(i);
1496                 }
1497
1498                 for (var i = 0; i < o.length; i++) {
1499                         if (os[o[i]] == null)
1500                                 os[o[i]] = {
1501                                         rows: [],
1502                                         n: null
1503                                 };
1504                         os[o[i]].rows.push(i);
1505                 }
1506
1507                 for (var i in ns) {
1508                         if ( !hasOwn.call( ns, i ) ) {
1509                                 continue;
1510                         }
1511                         if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
1512                                 n[ns[i].rows[0]] = {
1513                                         text: n[ns[i].rows[0]],
1514                                         row: os[i].rows[0]
1515                                 };
1516                                 o[os[i].rows[0]] = {
1517                                         text: o[os[i].rows[0]],
1518                                         row: ns[i].rows[0]
1519                                 };
1520                         }
1521                 }
1522
1523                 for (var i = 0; i < n.length - 1; i++) {
1524                         if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
1525                         n[i + 1] == o[n[i].row + 1]) {
1526                                 n[i + 1] = {
1527                                         text: n[i + 1],
1528                                         row: n[i].row + 1
1529                                 };
1530                                 o[n[i].row + 1] = {
1531                                         text: o[n[i].row + 1],
1532                                         row: i + 1
1533                                 };
1534                         }
1535                 }
1536
1537                 for (var i = n.length - 1; i > 0; i--) {
1538                         if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
1539                         n[i - 1] == o[n[i].row - 1]) {
1540                                 n[i - 1] = {
1541                                         text: n[i - 1],
1542                                         row: n[i].row - 1
1543                                 };
1544                                 o[n[i].row - 1] = {
1545                                         text: o[n[i].row - 1],
1546                                         row: i - 1
1547                                 };
1548                         }
1549                 }
1550
1551                 return {
1552                         o: o,
1553                         n: n
1554                 };
1555         }
1556
1557         return function(o, n) {
1558                 o = o.replace(/\s+$/, '');
1559                 n = n.replace(/\s+$/, '');
1560                 var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
1561
1562                 var str = "";
1563
1564                 var oSpace = o.match(/\s+/g);
1565                 if (oSpace == null) {
1566                         oSpace = [" "];
1567                 }
1568                 else {
1569                         oSpace.push(" ");
1570                 }
1571                 var nSpace = n.match(/\s+/g);
1572                 if (nSpace == null) {
1573                         nSpace = [" "];
1574                 }
1575                 else {
1576                         nSpace.push(" ");
1577                 }
1578
1579                 if (out.n.length == 0) {
1580                         for (var i = 0; i < out.o.length; i++) {
1581                                 str += '<del>' + out.o[i] + oSpace[i] + "</del>";
1582                         }
1583                 }
1584                 else {
1585                         if (out.n[0].text == null) {
1586                                 for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
1587                                         str += '<del>' + out.o[n] + oSpace[n] + "</del>";
1588                                 }
1589                         }
1590
1591                         for (var i = 0; i < out.n.length; i++) {
1592                                 if (out.n[i].text == null) {
1593                                         str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
1594                                 }
1595                                 else {
1596                                         var pre = "";
1597
1598                                         for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
1599                                                 pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
1600                                         }
1601                                         str += " " + out.n[i].text + nSpace[i] + pre;
1602                                 }
1603                         }
1604                 }
1605
1606                 return str;
1607         };
1608 })();
1609
1610 })(this);

Hosting is provided AltSPAHow to use Git
Please direct any questions on jabber alex.wolf@jabber.ru

Valid HTML 4.0 Transitional Valid CSS!

Designer Alexander Wolf