<commit_before>/*
 * QUnit - jQuery unit testrunner
 * 
 * http://docs.jquery.com/QUnit
 *
 * Copyright (c) 2008 <NAME>, <NAME>
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */

// NOTE: This version of Qunit has been tweaked slightly to use a private 
// version of jQuery (called Q$).  You should be able to merge this file with
// changes from the main Qunit though with only minor effort.
sc_require('jquery');


(function($) {

// Tests for equality any JavaScript type and structure without unexpected results.
// Discussions and reference: http://philrathe.com/articles/equiv
// Test suites: http://philrathe.com/tests/equiv
// Author: <NAME> <<EMAIL>>
var equiv = function () {

    var innerEquiv; // the real equiv function
    var callers = []; // stack to decide between skip/abort functions

    // Determine what is o.
    function hoozit(o) {
        if (typeof o === "string") {
            return "string";

        } else if (typeof o === "boolean") {
            return "boolean";

        } else if (typeof o === "number") {

            if (isNaN(o)) {
                return "nan";
            } else {
                return "number";
            }

        } else if (typeof o === "undefined") {
            return "undefined";

        // consider: typeof null === object
        } else if (o === null) {
            return "null";

        // consider: typeof [] === object
        } else if (o instanceof Array) {
            return "array";
        
        // consider: typeof new Date() === object
        } else if (o instanceof Date) {
            return "date";

        // consider: /./ instanceof Object;
        //           /./ instanceof RegExp;
        //          typeof /./ === "function"; // => false in IE and Opera,
        //                                          true in FF and Safari
        } else if (o instanceof RegExp) {
            return "regexp";

        } else if (typeof o === "object") {
            return "object";

        } else if (o instanceof Function) {
            return "function";
        }
    }

    // Call the o related callback with the given arguments.
    function bindCallbacks(o, callbacks, args) {
        var prop = hoozit(o);
        if (prop) {
            if (hoozit(callbacks[prop]) === "function") {
                return callbacks[prop].apply(callbacks, args);
            } else {
                return callbacks[prop]; // or undefined
            }
        }
    }

    var callbacks = function () {

        // for string, boolean, number and null
        function useStrictEquality(b, a) {
            return a === b;
        }

        return {
            "string": useStrictEquality,
            "boolean": useStrictEquality,
            "number": useStrictEquality,
            "null": useStrictEquality,
            "undefined": useStrictEquality,

            "nan": function (b) {
                return isNaN(b);
            },

            "date": function (b, a) {
                return hoozit(b) === "date" && a.valueOf() === b.valueOf();
            },

            "regexp": function (b, a) {
                return hoozit(b) === "regexp" &&
                    a.source === b.source && // the regex itself
                    a.global === b.global && // and its modifers (gmi) ...
                    a.ignoreCase === b.ignoreCase &&
                    a.multiline === b.multiline;
            },

            // - skip when the property is a method of an instance (OOP)
            // - abort otherwise,
            //   initial === would have catch identical references anyway
            "function": function () {
                var caller = callers[callers.length - 1];
                return caller !== Object &&
                        typeof caller !== "undefined";
            },

            "array": function (b, a) {
                var i;
                var len;

                // b could be an object literal here
                if ( ! (hoozit(b) === "array")) {
                    return false;
                }

                len = a.length;
                if (len !== b.length) { // safe and faster
                    return false;
                }
                for (i = 0; i < len; i++) {
                    if( ! innerEquiv(a[i], b[i])) {
                        return false;
                    }
                }
                return true;
            },

            "object": function (b, a) {
                var i;
                var eq = true; // unless we can proove it
                var aProperties = [], bProperties = []; // collection of strings

                // comparing constructors is more strict than using instanceof
                if ( a.constructor !== b.constructor) {
                    return false;
                }

                // stack constructor before traversing properties
                callers.push(a.constructor);

                for (i in a) { // be strict: don't ensures hasOwnProperty and go deep

                    aProperties.push(i); // collect a's properties

                    if ( ! innerEquiv(a[i], b[i])) {
                        eq = false;
                    }
                }

                callers.pop(); // unstack, we are done

                for (i in b) {
                    bProperties.push(i); // collect b's properties
                }

                // Ensures identical properties name
                return eq && innerEquiv(aProperties.sort(), bProperties.sort());
            }
        };
    }();

    innerEquiv = function () { // can take multiple arguments
        var args = Array.prototype.slice.apply(arguments);
        if (args.length < 2) {
            return true; // end transition
        }

        return (function (a, b) {
            if (a === b) {
                return true; // catch the most you can

            } else if (typeof a !== typeof b || a === null || b === null || typeof a === "undefined" || typeof b === "undefined") {
                return false; // don't lose time with error prone cases

            } else {
                return bindCallbacks(a, callbacks, [b, a]);
            }

        // apply transition with (1..n) arguments
        })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
    };

    return innerEquiv;
}(); // equiv

var GETParams = $.map( location.search.slice(1).split('&'), decodeURIComponent ),
	ngindex = $.inArray("noglobals", GETParams),
	noglobals = ngindex !== -1;

if( noglobals )
	GETParams.splice( ngindex, 1 );
	
var config = {
	stats: {
		all: 0,
		bad: 0
	},
	queue: [],
	// block until document ready
	blocking: true,
	//restrict modules/tests by get parameters
	filters: GETParams,
	isLocal: !!(window.location.protocol == 'file:')
};

// public API as global methods
$.extend(window, {
	test: test,
	module: module,
	expect: expect,
	ok: ok,
	equals: equals,
	start: start,
	stop: stop,
	reset: reset,
	synchronize: synchronize,
	isLocal: config.isLocal,
	same: function(a, b, message) {
		push(equiv(a, b), a, b, message);
	},
	QUnit: {
		equiv: equiv
	},
	// legacy methods below
	isSet: isSet,
	isObj: isObj,
	compare: function() {
		throw "compare is deprecated - use same() instead";
	},
	compare2: function() {
		throw "compare2 is deprecated - use same() instead";
	},
	serialArray: function() {
		throw "serialArray is deprecated - use jsDump.parse() instead";
	},
	q: q,
	t: t,
	url: url,
	triggerEvent: triggerEvent
});

$(window).load(function() {
  if($('#userAgent').length == 0) {
    $('body').append($('<div id="userAgent"></div>'));
  }

  if ($('#tests').length == 0) {
    $('body').append($('<ol id="tests"></ol>')) ;
  }
  
	$('#userAgent').html(navigator.userAgent);
	var head = $('<div class="testrunner-toolbar"><label for="filter">Hide passed tests</label></div>').insertAfter("#userAgent");
	$('<input type="checkbox" id="filter" />').attr("disabled", true).prependTo(head).click(function() {
		$('li.pass')[this.checked ? 'hide' : 'show']();
	});
	runTest();	
});

function synchronize(callback) {
	config.queue.push(callback);
	if(!config.blocking) {
		process();
	}
}

function process() {
  window.config = config ;
	while(config.queue.length && !config.blocking) {
		config.queue.shift()();
	}
}

function stop(timeout) {
	config.blocking = true;
	if (timeout)
		config.timeout = setTimeout(function() {
			ok( false, "Test timed out" );
			start();
		}, timeout);
}
function start() {
	// A slight delay, to avoid any current callbacks
	setTimeout(function() {
		if(config.timeout)
			clearTimeout(config.timeout);
		config.blocking = false;
		process();
	}, 13);
}

function validTest( name ) {
	var i = config.filters.length,
		run = false;

	if( !i )
		return true;
	
	while( i-- ){
		var filter = config.filters[i],
			not = filter.charAt(0) == '!';
		if( not ) 
			filter = filter.slice(1);
		if( name.indexOf(filter) != -1 )
			return !not;
		if( not )
			run = true;
	}
	return run;
}

function runTest() {
	config.blocking = false;
	var started = +new Date;
	
	config.ajaxSettings = $.ajaxSettings;
	synchronize(function() {
		$('<p id="testresult" class="result"/>').html(['Tests completed in ',
			+new Date - started, ' milliseconds.<br/>',
			'<span class="bad">', config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> failed.']
			.join(''))
			.appendTo("body");
		$("#banner").addClass(config.stats.bad ? "fail" : "pass");
	});
}

var pollution;

function saveGlobal(){
	pollution = [ ];
	
	if( noglobals )
		for( var key in window )
			pollution.push(key);
}
function checkPollution( name ){
	var old = pollution;
	saveGlobal();
	
	if( pollution.length > old.length ){
		ok( false, "Introduced global variable(s): " + diff(old, pollution).join(", ") );
		config.expected++;
	}
}

function diff( clean, dirty ){
	return $.grep( dirty, function(name){
		return $.inArray( name, clean ) == -1;
	});
}

function test(name, callback) {
	if(config.currentModule)
		name = config.currentModule + " module: " + name;
	var lifecycle = $.extend({
		setup: function() {},
		teardown: function() {}
	}, config.moduleLifecycle);
	
	if ( !validTest(name) )
		return;
	
	synchronize(function() {
	  
	  // save main fixture...
	  var mainEl = document.getElementById('main');
  	config.fixture = mainEl ? mainEl.innerHTML : '';
  	mainEl = null;
  	
		config.assertions = [];
		config.expected = null;
		try {
			if( !pollution )
				saveGlobal();
			lifecycle.setup();
		} catch(e) {
			config.assertions.push( {
				result: false,
				message: "Setup failed on " + name + ": " + e.message
			});
		}
	})
	synchronize(function() {
		try {
			callback();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("Test " + name + " died, exception and test follows");
				console.error(e);
				console.warn(callback.toString());
			}
			config.assertions.push( {
				result: false,
				message: "Died on test #" + (config.assertions.length + 1) + ": " + e.message
			});
			// else next test will carry the responsibility
			saveGlobal();
		}
	});
	synchronize(function() {
		try {
			checkPollution();
			lifecycle.teardown();
		} catch(e) {
			config.assertions.push( {
				result: false,
				message: "Teardown failed on " + name + ": " + e.message
			});
		}
	})
	synchronize(function() {
		try {
			reset();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("reset() failed, following Test " + name + ", exception and reset fn follows");
				console.error(e);
				console.warn(reset.toString());
			}
		}
		
		if(config.expected && config.expected != config.assertions.length) {
			config.assertions.push({
				result: false,
				message: "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run"
			});
		}
		
		var good = 0, bad = 0;
		var ol  = $("<ol/>").hide();
		config.stats.all += config.assertions.length;
		for ( var i = 0; i < config.assertions.length; i++ ) {
			var assertion = config.assertions[i];
			$("<li/>").addClass(assertion.result ? "pass" : "fail").text(assertion.message || "(no message)").appendTo(ol);
			assertion.result ? good++ : bad++;
		}
		config.stats.bad += bad;
	
		var b = $("<strong/>").html(name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>")
		.click(function(){
			$(this).next().toggle();
		})
		.dblclick(function(event) {
			var target = $(event.target).filter("strong").clone();
			if ( target.length ) {
				target.children().remove();
				location.href = location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent($.trim(target.text()));
			}
		});
		
		$("<li/>").addClass(bad ? "fail" : "pass").append(b).append(ol).appendTo("#tests");
	
		if(bad) {
			$("#filter").attr("disabled", null);
		}
	});
}

// call on start of module test to prepend name to all tests
function module(name, lifecycle) {
	config.currentModule = name;
	config.moduleLifecycle = lifecycle;
}

/**
 * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
 */
function expect(asserts) {
	config.expected = asserts;
}

/**
 * Resets the test setup. Useful for tests that modify the DOM.
 */
function reset() {
	$("#main").html( config.fixture );
	$.event.global = {};
	$.ajaxSettings = $.extend({}, config.ajaxSettings);
}

/**
 * Asserts true.
 * @example ok( $("a").size() > 5, "There must be at least 5 anchors" );
 */
function ok(a, msg) {
	config.assertions.push({
		result: !!a,
		message: msg
	});
}

/**
 * Asserts that two arrays are the same
 */
function isSet(a, b, msg) {
	function serialArray( a ) {
		var r = [];
		
		if ( a && a.length )
	        for ( var i = 0; i < a.length; i++ ) {
	            var str = a[i].nodeName;
	            if ( str ) {
	                str = str.toLowerCase();
	                if ( a[i].id )
	                    str += "#" + a[i].id;
	            } else
	                str = a[i];
	            r.push( str );
	        }
	
		return "[ " + r.join(", ") + " ]";
	}
	var ret = true;
	if ( a && b && a.length != undefined && a.length == b.length ) {
		for ( var i = 0; i < a.length; i++ )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;
	config.assertions.push({
		result: ret,
		message: !ret ? (msg + " expected: " + serialArray(b) + " result: " + serialArray(a)) : msg
	});
}

/**
 * Asserts that two objects are equivalent
 */
function isObj(a, b, msg) {
	var ret = true;
	
	if ( a && b ) {
		for ( var i in a )
			if ( a[i] != b[i] )
				ret = false;

		for ( i in b )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;

    config.assertions.push({
		result: ret,
		message: msg
	});
}

/**
 * Returns an array of elements with the given IDs, eg.
 * @example q("main", "foo", "bar")
 * @result [<div id="main">, <span id="foo">, <input id="bar">]
 */
function q() {
	var r = [];
	for ( var i = 0; i < arguments.length; i++ )
		r.push( document.getElementById( arguments[i] ) );
	return r;
}

/**
 * Asserts that a select matches the given IDs
 * @example t("Check for something", "//[a]", ["foo", "baar"]);
 * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
 */
function t(a,b,c) {
	var f = $(b);
	var s = "";
	for ( var i = 0; i < f.length; i++ )
		s += (s && ",") + '"' + f[i].id + '"';
	isSet(f, q.apply(q,c), a + " (" + b + ")");
}

/**
 * Add random number to url to stop IE from caching
 *
 * @example url("data/test.html")
 * @result "data/test.html?10538358428943"
 *
 * @example url("data/test.php?foo=bar")
 * @result "data/test.php?foo=bar&10538358345554"
 */
function url(value) {
	return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
}

/**
 * Checks that the first two arguments are equal, with an optional message.
 * Prints out both actual and expected values.
 *
 * Prefered to ok( actual == expected, message )
 *
 * @example equals( $.format("Received {0} bytes.", 2), "Received 2 bytes." );
 *
 * @param Object actual
 * @param Object expected
 * @param String message (optional)
 */
function equals(actual, expected, message) {
	push(expected == actual, actual, expected, message);
}

function push(result, actual, expected, message) {
	message = message || (result ? "okay" : "failed");
	config.assertions.push({
		result: result,
		message: result ? message + ": " + expected : message + ", expected: " + jsDump.parse(expected) + " result: " + jsDump.parse(actual)
	});
}

/**
 * Trigger an event on an element.
 *
 * @example triggerEvent( document.body, "click" );
 *
 * @param DOMElement elem
 * @param String type
 */
function triggerEvent( elem, type, event ) {
	if ( $.browser.mozilla || $.browser.opera ) {
		event = document.createEvent("MouseEvents");
		event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,<commit_msg>show full parses during "expected" generation in qunit<commit_after>/*
 * QUnit - jQuery unit testrunner
 * 
 * http://docs.jquery.com/QUnit
 *
 * Copyright (c) 2008 <NAME>, <NAME>
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */

// NOTE: This version of Qunit has been tweaked slightly to use a private 
// version of jQuery (called Q$).  You should be able to merge this file with
// changes from the main Qunit though with only minor effort.
sc_require('jquery');


(function($) {

// Tests for equality any JavaScript type and structure without unexpected results.
// Discussions and reference: http://philrathe.com/articles/equiv
// Test suites: http://philrathe.com/tests/equiv
// Author: <NAME> <<EMAIL>>
var equiv = function () {

    var innerEquiv; // the real equiv function
    var callers = []; // stack to decide between skip/abort functions

    // Determine what is o.
    function hoozit(o) {
        if (typeof o === "string") {
            return "string";

        } else if (typeof o === "boolean") {
            return "boolean";

        } else if (typeof o === "number") {

            if (isNaN(o)) {
                return "nan";
            } else {
                return "number";
            }

        } else if (typeof o === "undefined") {
            return "undefined";

        // consider: typeof null === object
        } else if (o === null) {
            return "null";

        // consider: typeof [] === object
        } else if (o instanceof Array) {
            return "array";
        
        // consider: typeof new Date() === object
        } else if (o instanceof Date) {
            return "date";

        // consider: /./ instanceof Object;
        //           /./ instanceof RegExp;
        //          typeof /./ === "function"; // => false in IE and Opera,
        //                                          true in FF and Safari
        } else if (o instanceof RegExp) {
            return "regexp";

        } else if (typeof o === "object") {
            return "object";

        } else if (o instanceof Function) {
            return "function";
        }
    }

    // Call the o related callback with the given arguments.
    function bindCallbacks(o, callbacks, args) {
        var prop = hoozit(o);
        if (prop) {
            if (hoozit(callbacks[prop]) === "function") {
                return callbacks[prop].apply(callbacks, args);
            } else {
                return callbacks[prop]; // or undefined
            }
        }
    }

    var callbacks = function () {

        // for string, boolean, number and null
        function useStrictEquality(b, a) {
            return a === b;
        }

        return {
            "string": useStrictEquality,
            "boolean": useStrictEquality,
            "number": useStrictEquality,
            "null": useStrictEquality,
            "undefined": useStrictEquality,

            "nan": function (b) {
                return isNaN(b);
            },

            "date": function (b, a) {
                return hoozit(b) === "date" && a.valueOf() === b.valueOf();
            },

            "regexp": function (b, a) {
                return hoozit(b) === "regexp" &&
                    a.source === b.source && // the regex itself
                    a.global === b.global && // and its modifers (gmi) ...
                    a.ignoreCase === b.ignoreCase &&
                    a.multiline === b.multiline;
            },

            // - skip when the property is a method of an instance (OOP)
            // - abort otherwise,
            //   initial === would have catch identical references anyway
            "function": function () {
                var caller = callers[callers.length - 1];
                return caller !== Object &&
                        typeof caller !== "undefined";
            },

            "array": function (b, a) {
                var i;
                var len;

                // b could be an object literal here
                if ( ! (hoozit(b) === "array")) {
                    return false;
                }

                len = a.length;
                if (len !== b.length) { // safe and faster
                    return false;
                }
                for (i = 0; i < len; i++) {
                    if( ! innerEquiv(a[i], b[i])) {
                        return false;
                    }
                }
                return true;
            },

            "object": function (b, a) {
                var i;
                var eq = true; // unless we can proove it
                var aProperties = [], bProperties = []; // collection of strings

                // comparing constructors is more strict than using instanceof
                if ( a.constructor !== b.constructor) {
                    return false;
                }

                // stack constructor before traversing properties
                callers.push(a.constructor);

                for (i in a) { // be strict: don't ensures hasOwnProperty and go deep

                    aProperties.push(i); // collect a's properties

                    if ( ! innerEquiv(a[i], b[i])) {
                        eq = false;
                    }
                }

                callers.pop(); // unstack, we are done

                for (i in b) {
                    bProperties.push(i); // collect b's properties
                }

                // Ensures identical properties name
                return eq && innerEquiv(aProperties.sort(), bProperties.sort());
            }
        };
    }();

    innerEquiv = function () { // can take multiple arguments
        var args = Array.prototype.slice.apply(arguments);
        if (args.length < 2) {
            return true; // end transition
        }

        return (function (a, b) {
            if (a === b) {
                return true; // catch the most you can

            } else if (typeof a !== typeof b || a === null || b === null || typeof a === "undefined" || typeof b === "undefined") {
                return false; // don't lose time with error prone cases

            } else {
                return bindCallbacks(a, callbacks, [b, a]);
            }

        // apply transition with (1..n) arguments
        })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
    };

    return innerEquiv;
}(); // equiv

var GETParams = $.map( location.search.slice(1).split('&'), decodeURIComponent ),
	ngindex = $.inArray("noglobals", GETParams),
	noglobals = ngindex !== -1;

if( noglobals )
	GETParams.splice( ngindex, 1 );
	
var config = {
	stats: {
		all: 0,
		bad: 0
	},
	queue: [],
	// block until document ready
	blocking: true,
	//restrict modules/tests by get parameters
	filters: GETParams,
	isLocal: !!(window.location.protocol == 'file:')
};

// public API as global methods
$.extend(window, {
	test: test,
	module: module,
	expect: expect,
	ok: ok,
	equals: equals,
	start: start,
	stop: stop,
	reset: reset,
	synchronize: synchronize,
	isLocal: config.isLocal,
	same: function(a, b, message) {
		push(equiv(a, b), a, b, message);
	},
	QUnit: {
		equiv: equiv
	},
	// legacy methods below
	isSet: isSet,
	isObj: isObj,
	compare: function() {
		throw "compare is deprecated - use same() instead";
	},
	compare2: function() {
		throw "compare2 is deprecated - use same() instead";
	},
	serialArray: function() {
		throw "serialArray is deprecated - use jsDump.parse() instead";
	},
	q: q,
	t: t,
	url: url,
	triggerEvent: triggerEvent
});

$(window).load(function() {
  if($('#userAgent').length == 0) {
    $('body').append($('<div id="userAgent"></div>'));
  }

  if ($('#tests').length == 0) {
    $('body').append($('<ol id="tests"></ol>')) ;
  }
  
	$('#userAgent').html(navigator.userAgent);
	var head = $('<div class="testrunner-toolbar"><label for="filter">Hide passed tests</label></div>').insertAfter("#userAgent");
	$('<input type="checkbox" id="filter" />').attr("disabled", true).prependTo(head).click(function() {
		$('li.pass')[this.checked ? 'hide' : 'show']();
	});
	runTest();	
});

function synchronize(callback) {
	config.queue.push(callback);
	if(!config.blocking) {
		process();
	}
}

function process() {
  window.config = config ;
	while(config.queue.length && !config.blocking) {
		config.queue.shift()();
	}
}

function stop(timeout) {
	config.blocking = true;
	if (timeout)
		config.timeout = setTimeout(function() {
			ok( false, "Test timed out" );
			start();
		}, timeout);
}
function start() {
	// A slight delay, to avoid any current callbacks
	setTimeout(function() {
		if(config.timeout)
			clearTimeout(config.timeout);
		config.blocking = false;
		process();
	}, 13);
}

function validTest( name ) {
	var i = config.filters.length,
		run = false;

	if( !i )
		return true;
	
	while( i-- ){
		var filter = config.filters[i],
			not = filter.charAt(0) == '!';
		if( not ) 
			filter = filter.slice(1);
		if( name.indexOf(filter) != -1 )
			return !not;
		if( not )
			run = true;
	}
	return run;
}

function runTest() {
	config.blocking = false;
	var started = +new Date;
	
	config.ajaxSettings = $.ajaxSettings;
	synchronize(function() {
		$('<p id="testresult" class="result"/>').html(['Tests completed in ',
			+new Date - started, ' milliseconds.<br/>',
			'<span class="bad">', config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> failed.']
			.join(''))
			.appendTo("body");
		$("#banner").addClass(config.stats.bad ? "fail" : "pass");
	});
}

var pollution;

function saveGlobal(){
	pollution = [ ];
	
	if( noglobals )
		for( var key in window )
			pollution.push(key);
}
function checkPollution( name ){
	var old = pollution;
	saveGlobal();
	
	if( pollution.length > old.length ){
		ok( false, "Introduced global variable(s): " + diff(old, pollution).join(", ") );
		config.expected++;
	}
}

function diff( clean, dirty ){
	return $.grep( dirty, function(name){
		return $.inArray( name, clean ) == -1;
	});
}

function test(name, callback) {
	if(config.currentModule)
		name = config.currentModule + " module: " + name;
	var lifecycle = $.extend({
		setup: function() {},
		teardown: function() {}
	}, config.moduleLifecycle);
	
	if ( !validTest(name) )
		return;
	
	synchronize(function() {
	  
	  // save main fixture...
	  var mainEl = document.getElementById('main');
  	config.fixture = mainEl ? mainEl.innerHTML : '';
  	mainEl = null;
  	
		config.assertions = [];
		config.expected = null;
		try {
			if( !pollution )
				saveGlobal();
			lifecycle.setup();
		} catch(e) {
			config.assertions.push( {
				result: false,
				message: "Setup failed on " + name + ": " + e.message
			});
		}
	})
	synchronize(function() {
		try {
			callback();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("Test " + name + " died, exception and test follows");
				console.error(e);
				console.warn(callback.toString());
			}
			config.assertions.push( {
				result: false,
				message: "Died on test #" + (config.assertions.length + 1) + ": " + e.message
			});
			// else next test will carry the responsibility
			saveGlobal();
		}
	});
	synchronize(function() {
		try {
			checkPollution();
			lifecycle.teardown();
		} catch(e) {
			config.assertions.push( {
				result: false,
				message: "Teardown failed on " + name + ": " + e.message
			});
		}
	})
	synchronize(function() {
		try {
			reset();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("reset() failed, following Test " + name + ", exception and reset fn follows");
				console.error(e);
				console.warn(reset.toString());
			}
		}
		
		if(config.expected && config.expected != config.assertions.length) {
			config.assertions.push({
				result: false,
				message: "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run"
			});
		}
		
		var good = 0, bad = 0;
		var ol  = $("<ol/>").hide();
		config.stats.all += config.assertions.length;
		for ( var i = 0; i < config.assertions.length; i++ ) {
			var assertion = config.assertions[i];
			$("<li/>").addClass(assertion.result ? "pass" : "fail").text(assertion.message || "(no message)").appendTo(ol);
			assertion.result ? good++ : bad++;
		}
		config.stats.bad += bad;
	
		var b = $("<strong/>").html(name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>")
		.click(function(){
			$(this).next().toggle();
		})
		.dblclick(function(event) {
			var target = $(event.target).filter("strong").clone();
			if ( target.length ) {
				target.children().remove();
				location.href = location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent($.trim(target.text()));
			}
		});
		
		$("<li/>").addClass(bad ? "fail" : "pass").append(b).append(ol).appendTo("#tests");
	
		if(bad) {
			$("#filter").attr("disabled", null);
		}
	});
}

// call on start of module test to prepend name to all tests
function module(name, lifecycle) {
	config.currentModule = name;
	config.moduleLifecycle = lifecycle;
}

/**
 * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
 */
function expect(asserts) {
	config.expected = asserts;
}

/**
 * Resets the test setup. Useful for tests that modify the DOM.
 */
function reset() {
	$("#main").html( config.fixture );
	$.event.global = {};
	$.ajaxSettings = $.extend({}, config.ajaxSettings);
}

/**
 * Asserts true.
 * @example ok( $("a").size() > 5, "There must be at least 5 anchors" );
 */
function ok(a, msg) {
	config.assertions.push({
		result: !!a,
		message: msg
	});
}

/**
 * Asserts that two arrays are the same
 */
function isSet(a, b, msg) {
	function serialArray( a ) {
		var r = [];
		
		if ( a && a.length )
	        for ( var i = 0; i < a.length; i++ ) {
	            var str = a[i].nodeName;
	            if ( str ) {
	                str = str.toLowerCase();
	                if ( a[i].id )
	                    str += "#" + a[i].id;
	            } else
	                str = a[i];
	            r.push( str );
	        }
	
		return "[ " + r.join(", ") + " ]";
	}
	var ret = true;
	if ( a && b && a.length != undefined && a.length == b.length ) {
		for ( var i = 0; i < a.length; i++ )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;
	config.assertions.push({
		result: ret,
		message: !ret ? (msg + " expected: " + serialArray(b) + " result: " + serialArray(a)) : msg
	});
}

/**
 * Asserts that two objects are equivalent
 */
function isObj(a, b, msg) {
	var ret = true;
	
	if ( a && b ) {
		for ( var i in a )
			if ( a[i] != b[i] )
				ret = false;

		for ( i in b )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;

    config.assertions.push({
		result: ret,
		message: msg
	});
}

/**
 * Returns an array of elements with the given IDs, eg.
 * @example q("main", "foo", "bar")
 * @result [<div id="main">, <span id="foo">, <input id="bar">]
 */
function q() {
	var r = [];
	for ( var i = 0; i < arguments.length; i++ )
		r.push( document.getElementById( arguments[i] ) );
	return r;
}

/**
 * Asserts that a select matches the given IDs
 * @example t("Check for something", "//[a]", ["foo", "baar"]);
 * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
 */
function t(a,b,c) {
	var f = $(b);
	var s = "";
	for ( var i = 0; i < f.length; i++ )
		s += (s && ",") + '"' + f[i].id + '"';
	isSet(f, q.apply(q,c), a + " (" + b + ")");
}

/**
 * Add random number to url to stop IE from caching
 *
 * @example url("data/test.html")
 * @result "data/test.html?10538358428943"
 *
 * @example url("data/test.php?foo=bar")
 * @result "data/test.php?foo=bar&10538358345554"
 */
function url(value) {
	return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
}

/**
 * Checks that the first two arguments are equal, with an optional message.
 * Prints out both actual and expected values.
 *
 * Prefered to ok( actual == expected, message )
 *
 * @example equals( $.format("Received {0} bytes.", 2), "Received 2 bytes." );
 *
 * @param Object actual
 * @param Object expected
 * @param String message (optional)
 */
function equals(actual, expected, message) {
	push(expected == actual, actual, expected, message);
}

function push(result, actual, expected, message) {
	message = message || (result ? "okay" : "failed");
	config.assertions.push({
		result: result,
		message: result ? message + ": " + jsDump.parse(expected) : message + ", expected: " + jsDump.parse(expected) + " result: " + jsDump.parse(actual)
	});
}

/**
 * Trigger an event on an element.
 *
 * @example triggerEvent( document.body, "click" );
 *
 * @param DOMElement elem
 * @param String type
 */
function triggerEvent( elem, type, event ) {
	if ( $.browser.mozilla || $.browser.opera ) {
		event = document.createEvent("MouseEvents");
		event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
{'fraction_non_alphanumeric': 0.16634911329327276, 'fraction_numerical': 0.004396892862377253, 'mean_word_length': 2.222442618305469, 'pattern_counts': {'":': 30, '<': 83, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6583453', 'n_tokens_mistral': 11405, 'n_tokens_neox': 10494, 'n_words': 2916}