diff options
35 files changed, 16919 insertions, 0 deletions
| diff --git a/.bowerrc b/.bowerrc new file mode 100644 index 0000000..70f2b61 --- /dev/null +++ b/.bowerrc @@ -0,0 +1,3 @@ +{ +	"directory": "lib" +} diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..ca247bd --- /dev/null +++ b/bower.json @@ -0,0 +1,6 @@ +{ +	"name": "Peniquitous", +	"dependencies": { +		"mousetrap": "~1.5.2" +	} +} diff --git a/lib/mousetrap/.bower.json b/lib/mousetrap/.bower.json new file mode 100644 index 0000000..bde083a --- /dev/null +++ b/lib/mousetrap/.bower.json @@ -0,0 +1,15 @@ +{ +  "name": "mousetrap", +  "homepage": "https://github.com/ccampbell/mousetrap", +  "version": "1.5.2", +  "_release": "1.5.2", +  "_resolution": { +    "type": "version", +    "tag": "1.5.2", +    "commit": "1087ddde951a55aceec163fa402dbccdc9949e40" +  }, +  "_source": "git://github.com/ccampbell/mousetrap.git", +  "_target": "~1.5.2", +  "_originalSource": "mousetrap", +  "_direct": true +}
\ No newline at end of file diff --git a/lib/mousetrap/.gitignore b/lib/mousetrap/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/lib/mousetrap/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/lib/mousetrap/Gruntfile.js b/lib/mousetrap/Gruntfile.js new file mode 100644 index 0000000..859ec6b --- /dev/null +++ b/lib/mousetrap/Gruntfile.js @@ -0,0 +1,47 @@ +/*jshint node:true */ +module.exports = function(grunt) { +    'use strict'; + +    grunt.initConfig({ +        pkg: grunt.file.readJSON('package.json'), + +        mocha: { +            options: { +                reporter: 'Nyan', +                run: true +            }, +            mousetrap: { +                src: ['tests/mousetrap.html'] +            } +        }, + +        complexity: { +            options: { +                errorsOnly: false, +                cyclomatic: 10, +                halstead: 30, +                maintainability: 85 +            }, +            generic: { +                src: [ +                    'mousetrap.js' +                ] +            }, +            plugins: { +                src: [ +                    'plugins/**/*.js', +                    '!plugins/**/tests/**', +                    '!plugins/**/*.min.js' +                ] +            } +        } +    }); + +    grunt.loadNpmTasks('grunt-complexity'); +    grunt.loadNpmTasks('grunt-mocha'); + +    grunt.registerTask('default', [ +        'complexity', +        'mocha' +    ]); +}; diff --git a/lib/mousetrap/README.md b/lib/mousetrap/README.md new file mode 100644 index 0000000..67c1321 --- /dev/null +++ b/lib/mousetrap/README.md @@ -0,0 +1,102 @@ +# Mousetrap + +Mousetrap is a simple library for handling keyboard shortcuts in Javascript. + +It is licensed under the Apache 2.0 license. + +It is around **2kb** minified and gzipped and **4.5kb** minified, has no external dependencies, and has been tested in the following browsers: + +- Internet Explorer 6+ +- Safari +- Firefox +- Chrome + +It has support for ``keypress``, ``keydown``, and ``keyup`` events on specific keys, keyboard combinations, or key sequences. + +If you would like to donate to help support Mousetrap development use [Gittip](https://www.gittip.com/ccampbell). + +## Getting started + +1.  Include mousetrap on your page before the closing ``</body>`` tag + +    ```html +    <script src="/path/to/mousetrap.min.js"></script> +    ``` + +2.  Add some keyboard events to listen for + +    ```html +    <script> +        // single keys +        Mousetrap.bind('4', function() { console.log('4'); }); +        Mousetrap.bind("?", function() { console.log('show shortcuts!'); }); +        Mousetrap.bind('esc', function() { console.log('escape'); }, 'keyup'); + +        // combinations +        Mousetrap.bind('command+shift+k', function() { console.log('command shift k'); }); + +        // map multiple combinations to the same callback +        Mousetrap.bind(['command+k', 'ctrl+k'], function() { +            console.log('command k or control k'); + +            // return false to prevent default browser behavior +            // and stop event from bubbling +            return false; +        }); + +        // gmail style sequences +        Mousetrap.bind('g i', function() { console.log('go to inbox'); }); +        Mousetrap.bind('* a', function() { console.log('select all'); }); + +        // konami code! +        Mousetrap.bind('up up down down left right left right b a enter', function() { +            console.log('konami code'); +        }); +    </script> +    ``` + +## Why Mousetrap? + +There are a number of other similar libraries out there so what makes this one different? + +- There are no external dependencies, no framework is required +- You are not limited to ``keydown`` events (You can specify ``keypress``, ``keydown``, or ``keyup`` or let Mousetrap choose for you). +- You can bind key events directly to special keys such as ``?`` or ``*`` without having to specify ``shift+/`` or ``shift+8`` which are not consistent across all keyboards +- It works with international keyboard layouts +- You can bind Gmail like key sequences in addition to regular keys and key combinations +- You can programatically trigger key events with the ``trigger()`` method +- It works with the numeric keypad on your keyboard +- The code is well documented/commented + +## Tests + +Unit tests run via <a href="http://mochajs.org/" target="_blank">mocha</a>. + +### Running in browser + +Download the repo and go to `tests/mousetrap.html` in your browser. + +### Running with Grunt and PhantomJS + +1.  Install grunt-cli + +    ```bash +    npm install -g grunt-cli +    ``` + +2.  Install npm packages + +    ```bash +    cd /path/to/repo +    npm install +    ``` + +3.  Run tests + +    ```bash +    grunt mocha +    ``` + +## Documentation + +Full documentation can be found at https://craig.is/killing/mice diff --git a/lib/mousetrap/mousetrap.js b/lib/mousetrap/mousetrap.js new file mode 100644 index 0000000..deb141e --- /dev/null +++ b/lib/mousetrap/mousetrap.js @@ -0,0 +1,1021 @@ +/*global define:false */ +/** + * Copyright 2015 Craig Campbell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Mousetrap is a simple keyboard shortcut library for Javascript with + * no external dependencies + * + * @version 1.5.2 + * @url craig.is/killing/mice + */ +(function(window, document, undefined) { + +    /** +     * mapping of special keycodes to their corresponding keys +     * +     * everything in this dictionary cannot use keypress events +     * so it has to be here to map to the correct keycodes for +     * keyup/keydown events +     * +     * @type {Object} +     */ +    var _MAP = { +        8: 'backspace', +        9: 'tab', +        13: 'enter', +        16: 'shift', +        17: 'ctrl', +        18: 'alt', +        20: 'capslock', +        27: 'esc', +        32: 'space', +        33: 'pageup', +        34: 'pagedown', +        35: 'end', +        36: 'home', +        37: 'left', +        38: 'up', +        39: 'right', +        40: 'down', +        45: 'ins', +        46: 'del', +        91: 'meta', +        93: 'meta', +        224: 'meta' +    }; + +    /** +     * mapping for special characters so they can support +     * +     * this dictionary is only used incase you want to bind a +     * keyup or keydown event to one of these keys +     * +     * @type {Object} +     */ +    var _KEYCODE_MAP = { +        106: '*', +        107: '+', +        109: '-', +        110: '.', +        111 : '/', +        186: ';', +        187: '=', +        188: ',', +        189: '-', +        190: '.', +        191: '/', +        192: '`', +        219: '[', +        220: '\\', +        221: ']', +        222: '\'' +    }; + +    /** +     * this is a mapping of keys that require shift on a US keypad +     * back to the non shift equivelents +     * +     * this is so you can use keyup events with these keys +     * +     * note that this will only work reliably on US keyboards +     * +     * @type {Object} +     */ +    var _SHIFT_MAP = { +        '~': '`', +        '!': '1', +        '@': '2', +        '#': '3', +        '$': '4', +        '%': '5', +        '^': '6', +        '&': '7', +        '*': '8', +        '(': '9', +        ')': '0', +        '_': '-', +        '+': '=', +        ':': ';', +        '\"': '\'', +        '<': ',', +        '>': '.', +        '?': '/', +        '|': '\\' +    }; + +    /** +     * this is a list of special strings you can use to map +     * to modifier keys when you specify your keyboard shortcuts +     * +     * @type {Object} +     */ +    var _SPECIAL_ALIASES = { +        'option': 'alt', +        'command': 'meta', +        'return': 'enter', +        'escape': 'esc', +        'plus': '+', +        'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl' +    }; + +    /** +     * variable to store the flipped version of _MAP from above +     * needed to check if we should use keypress or not when no action +     * is specified +     * +     * @type {Object|undefined} +     */ +    var _REVERSE_MAP; + +    /** +     * loop through the f keys, f1 to f19 and add them to the map +     * programatically +     */ +    for (var i = 1; i < 20; ++i) { +        _MAP[111 + i] = 'f' + i; +    } + +    /** +     * loop through to map numbers on the numeric keypad +     */ +    for (i = 0; i <= 9; ++i) { +        _MAP[i + 96] = i; +    } + +    /** +     * cross browser add event method +     * +     * @param {Element|HTMLDocument} object +     * @param {string} type +     * @param {Function} callback +     * @returns void +     */ +    function _addEvent(object, type, callback) { +        if (object.addEventListener) { +            object.addEventListener(type, callback, false); +            return; +        } + +        object.attachEvent('on' + type, callback); +    } + +    /** +     * takes the event and returns the key character +     * +     * @param {Event} e +     * @return {string} +     */ +    function _characterFromEvent(e) { + +        // for keypress events we should return the character as is +        if (e.type == 'keypress') { +            var character = String.fromCharCode(e.which); + +            // if the shift key is not pressed then it is safe to assume +            // that we want the character to be lowercase.  this means if +            // you accidentally have caps lock on then your key bindings +            // will continue to work +            // +            // the only side effect that might not be desired is if you +            // bind something like 'A' cause you want to trigger an +            // event when capital A is pressed caps lock will no longer +            // trigger the event.  shift+a will though. +            if (!e.shiftKey) { +                character = character.toLowerCase(); +            } + +            return character; +        } + +        // for non keypress events the special maps are needed +        if (_MAP[e.which]) { +            return _MAP[e.which]; +        } + +        if (_KEYCODE_MAP[e.which]) { +            return _KEYCODE_MAP[e.which]; +        } + +        // if it is not in the special map + +        // with keydown and keyup events the character seems to always +        // come in as an uppercase character whether you are pressing shift +        // or not.  we should make sure it is always lowercase for comparisons +        return String.fromCharCode(e.which).toLowerCase(); +    } + +    /** +     * checks if two arrays are equal +     * +     * @param {Array} modifiers1 +     * @param {Array} modifiers2 +     * @returns {boolean} +     */ +    function _modifiersMatch(modifiers1, modifiers2) { +        return modifiers1.sort().join(',') === modifiers2.sort().join(','); +    } + +    /** +     * takes a key event and figures out what the modifiers are +     * +     * @param {Event} e +     * @returns {Array} +     */ +    function _eventModifiers(e) { +        var modifiers = []; + +        if (e.shiftKey) { +            modifiers.push('shift'); +        } + +        if (e.altKey) { +            modifiers.push('alt'); +        } + +        if (e.ctrlKey) { +            modifiers.push('ctrl'); +        } + +        if (e.metaKey) { +            modifiers.push('meta'); +        } + +        return modifiers; +    } + +    /** +     * prevents default for this event +     * +     * @param {Event} e +     * @returns void +     */ +    function _preventDefault(e) { +        if (e.preventDefault) { +            e.preventDefault(); +            return; +        } + +        e.returnValue = false; +    } + +    /** +     * stops propogation for this event +     * +     * @param {Event} e +     * @returns void +     */ +    function _stopPropagation(e) { +        if (e.stopPropagation) { +            e.stopPropagation(); +            return; +        } + +        e.cancelBubble = true; +    } + +    /** +     * determines if the keycode specified is a modifier key or not +     * +     * @param {string} key +     * @returns {boolean} +     */ +    function _isModifier(key) { +        return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; +    } + +    /** +     * reverses the map lookup so that we can look for specific keys +     * to see what can and can't use keypress +     * +     * @return {Object} +     */ +    function _getReverseMap() { +        if (!_REVERSE_MAP) { +            _REVERSE_MAP = {}; +            for (var key in _MAP) { + +                // pull out the numeric keypad from here cause keypress should +                // be able to detect the keys from the character +                if (key > 95 && key < 112) { +                    continue; +                } + +                if (_MAP.hasOwnProperty(key)) { +                    _REVERSE_MAP[_MAP[key]] = key; +                } +            } +        } +        return _REVERSE_MAP; +    } + +    /** +     * picks the best action based on the key combination +     * +     * @param {string} key - character for key +     * @param {Array} modifiers +     * @param {string=} action passed in +     */ +    function _pickBestAction(key, modifiers, action) { + +        // if no action was picked in we should try to pick the one +        // that we think would work best for this key +        if (!action) { +            action = _getReverseMap()[key] ? 'keydown' : 'keypress'; +        } + +        // modifier keys don't work as expected with keypress, +        // switch to keydown +        if (action == 'keypress' && modifiers.length) { +            action = 'keydown'; +        } + +        return action; +    } + +    /** +     * Converts from a string key combination to an array +     * +     * @param  {string} combination like "command+shift+l" +     * @return {Array} +     */ +    function _keysFromString(combination) { +        if (combination === '+') { +            return ['+']; +        } + +        combination = combination.replace(/\+{2}/g, '+plus'); +        return combination.split('+'); +    } + +    /** +     * Gets info for a specific key combination +     * +     * @param  {string} combination key combination ("command+s" or "a" or "*") +     * @param  {string=} action +     * @returns {Object} +     */ +    function _getKeyInfo(combination, action) { +        var keys; +        var key; +        var i; +        var modifiers = []; + +        // take the keys from this pattern and figure out what the actual +        // pattern is all about +        keys = _keysFromString(combination); + +        for (i = 0; i < keys.length; ++i) { +            key = keys[i]; + +            // normalize key names +            if (_SPECIAL_ALIASES[key]) { +                key = _SPECIAL_ALIASES[key]; +            } + +            // if this is not a keypress event then we should +            // be smart about using shift keys +            // this will only work for US keyboards however +            if (action && action != 'keypress' && _SHIFT_MAP[key]) { +                key = _SHIFT_MAP[key]; +                modifiers.push('shift'); +            } + +            // if this key is a modifier then add it to the list of modifiers +            if (_isModifier(key)) { +                modifiers.push(key); +            } +        } + +        // depending on what the key combination is +        // we will try to pick the best event for it +        action = _pickBestAction(key, modifiers, action); + +        return { +            key: key, +            modifiers: modifiers, +            action: action +        }; +    } + +    function _belongsTo(element, ancestor) { +        if (element === document) { +            return false; +        } + +        if (element === ancestor) { +            return true; +        } + +        return _belongsTo(element.parentNode, ancestor); +    } + +    function Mousetrap(targetElement) { +        var self = this; + +        targetElement = targetElement || document; + +        if (!(self instanceof Mousetrap)) { +            return new Mousetrap(targetElement); +        } + +        /** +         * element to attach key events to +         * +         * @type {Element} +         */ +        self.target = targetElement; + +        /** +         * a list of all the callbacks setup via Mousetrap.bind() +         * +         * @type {Object} +         */ +        self._callbacks = {}; + +        /** +         * direct map of string combinations to callbacks used for trigger() +         * +         * @type {Object} +         */ +        self._directMap = {}; + +        /** +         * keeps track of what level each sequence is at since multiple +         * sequences can start out with the same sequence +         * +         * @type {Object} +         */ +        var _sequenceLevels = {}; + +        /** +         * variable to store the setTimeout call +         * +         * @type {null|number} +         */ +        var _resetTimer; + +        /** +         * temporary state where we will ignore the next keyup +         * +         * @type {boolean|string} +         */ +        var _ignoreNextKeyup = false; + +        /** +         * temporary state where we will ignore the next keypress +         * +         * @type {boolean} +         */ +        var _ignoreNextKeypress = false; + +        /** +         * are we currently inside of a sequence? +         * type of action ("keyup" or "keydown" or "keypress") or false +         * +         * @type {boolean|string} +         */ +        var _nextExpectedAction = false; + +        /** +         * resets all sequence counters except for the ones passed in +         * +         * @param {Object} doNotReset +         * @returns void +         */ +        function _resetSequences(doNotReset) { +            doNotReset = doNotReset || {}; + +            var activeSequences = false, +                key; + +            for (key in _sequenceLevels) { +                if (doNotReset[key]) { +                    activeSequences = true; +                    continue; +                } +                _sequenceLevels[key] = 0; +            } + +            if (!activeSequences) { +                _nextExpectedAction = false; +            } +        } + +        /** +         * finds all callbacks that match based on the keycode, modifiers, +         * and action +         * +         * @param {string} character +         * @param {Array} modifiers +         * @param {Event|Object} e +         * @param {string=} sequenceName - name of the sequence we are looking for +         * @param {string=} combination +         * @param {number=} level +         * @returns {Array} +         */ +        function _getMatches(character, modifiers, e, sequenceName, combination, level) { +            var i; +            var callback; +            var matches = []; +            var action = e.type; + +            // if there are no events related to this keycode +            if (!self._callbacks[character]) { +                return []; +            } + +            // if a modifier key is coming up on its own we should allow it +            if (action == 'keyup' && _isModifier(character)) { +                modifiers = [character]; +            } + +            // loop through all callbacks for the key that was pressed +            // and see if any of them match +            for (i = 0; i < self._callbacks[character].length; ++i) { +                callback = self._callbacks[character][i]; + +                // if a sequence name is not specified, but this is a sequence at +                // the wrong level then move onto the next match +                if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) { +                    continue; +                } + +                // if the action we are looking for doesn't match the action we got +                // then we should keep going +                if (action != callback.action) { +                    continue; +                } + +                // if this is a keypress event and the meta key and control key +                // are not pressed that means that we need to only look at the +                // character, otherwise check the modifiers as well +                // +                // chrome will not fire a keypress if meta or control is down +                // safari will fire a keypress if meta or meta+shift is down +                // firefox will fire a keypress if meta or control is down +                if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { + +                    // when you bind a combination or sequence a second time it +                    // should overwrite the first one.  if a sequenceName or +                    // combination is specified in this call it does just that +                    // +                    // @todo make deleting its own method? +                    var deleteCombo = !sequenceName && callback.combo == combination; +                    var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level; +                    if (deleteCombo || deleteSequence) { +                        self._callbacks[character].splice(i, 1); +                    } + +                    matches.push(callback); +                } +            } + +            return matches; +        } + +        /** +         * actually calls the callback function +         * +         * if your callback function returns false this will use the jquery +         * convention - prevent default and stop propogation on the event +         * +         * @param {Function} callback +         * @param {Event} e +         * @returns void +         */ +        function _fireCallback(callback, e, combo, sequence) { + +            // if this event should not happen stop here +            if (self.stopCallback(e, e.target || e.srcElement, combo, sequence)) { +                return; +            } + +            if (callback(e, combo) === false) { +                _preventDefault(e); +                _stopPropagation(e); +            } +        } + +        /** +         * handles a character key event +         * +         * @param {string} character +         * @param {Array} modifiers +         * @param {Event} e +         * @returns void +         */ +        self._handleKey = function(character, modifiers, e) { +            var callbacks = _getMatches(character, modifiers, e); +            var i; +            var doNotReset = {}; +            var maxLevel = 0; +            var processedSequenceCallback = false; + +            // Calculate the maxLevel for sequences so we can only execute the longest callback sequence +            for (i = 0; i < callbacks.length; ++i) { +                if (callbacks[i].seq) { +                    maxLevel = Math.max(maxLevel, callbacks[i].level); +                } +            } + +            // loop through matching callbacks for this key event +            for (i = 0; i < callbacks.length; ++i) { + +                // fire for all sequence callbacks +                // this is because if for example you have multiple sequences +                // bound such as "g i" and "g t" they both need to fire the +                // callback for matching g cause otherwise you can only ever +                // match the first one +                if (callbacks[i].seq) { + +                    // only fire callbacks for the maxLevel to prevent +                    // subsequences from also firing +                    // +                    // for example 'a option b' should not cause 'option b' to fire +                    // even though 'option b' is part of the other sequence +                    // +                    // any sequences that do not match here will be discarded +                    // below by the _resetSequences call +                    if (callbacks[i].level != maxLevel) { +                        continue; +                    } + +                    processedSequenceCallback = true; + +                    // keep a list of which sequences were matches for later +                    doNotReset[callbacks[i].seq] = 1; +                    _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq); +                    continue; +                } + +                // if there were no sequence matches but we are still here +                // that means this is a regular match so we should fire that +                if (!processedSequenceCallback) { +                    _fireCallback(callbacks[i].callback, e, callbacks[i].combo); +                } +            } + +            // if the key you pressed matches the type of sequence without +            // being a modifier (ie "keyup" or "keypress") then we should +            // reset all sequences that were not matched by this event +            // +            // this is so, for example, if you have the sequence "h a t" and you +            // type "h e a r t" it does not match.  in this case the "e" will +            // cause the sequence to reset +            // +            // modifier keys are ignored because you can have a sequence +            // that contains modifiers such as "enter ctrl+space" and in most +            // cases the modifier key will be pressed before the next key +            // +            // also if you have a sequence such as "ctrl+b a" then pressing the +            // "b" key will trigger a "keypress" and a "keydown" +            // +            // the "keydown" is expected when there is a modifier, but the +            // "keypress" ends up matching the _nextExpectedAction since it occurs +            // after and that causes the sequence to reset +            // +            // we ignore keypresses in a sequence that directly follow a keydown +            // for the same character +            var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress; +            if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) { +                _resetSequences(doNotReset); +            } + +            _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown'; +        }; + +        /** +         * handles a keydown event +         * +         * @param {Event} e +         * @returns void +         */ +        function _handleKeyEvent(e) { + +            // normalize e.which for key events +            // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion +            if (typeof e.which !== 'number') { +                e.which = e.keyCode; +            } + +            var character = _characterFromEvent(e); + +            // no character found then stop +            if (!character) { +                return; +            } + +            // need to use === for the character check because the character can be 0 +            if (e.type == 'keyup' && _ignoreNextKeyup === character) { +                _ignoreNextKeyup = false; +                return; +            } + +            self.handleKey(character, _eventModifiers(e), e); +        } + +        /** +         * called to set a 1 second timeout on the specified sequence +         * +         * this is so after each key press in the sequence you have 1 second +         * to press the next key before you have to start over +         * +         * @returns void +         */ +        function _resetSequenceTimer() { +            clearTimeout(_resetTimer); +            _resetTimer = setTimeout(_resetSequences, 1000); +        } + +        /** +         * binds a key sequence to an event +         * +         * @param {string} combo - combo specified in bind call +         * @param {Array} keys +         * @param {Function} callback +         * @param {string=} action +         * @returns void +         */ +        function _bindSequence(combo, keys, callback, action) { + +            // start off by adding a sequence level record for this combination +            // and setting the level to 0 +            _sequenceLevels[combo] = 0; + +            /** +             * callback to increase the sequence level for this sequence and reset +             * all other sequences that were active +             * +             * @param {string} nextAction +             * @returns {Function} +             */ +            function _increaseSequence(nextAction) { +                return function() { +                    _nextExpectedAction = nextAction; +                    ++_sequenceLevels[combo]; +                    _resetSequenceTimer(); +                }; +            } + +            /** +             * wraps the specified callback inside of another function in order +             * to reset all sequence counters as soon as this sequence is done +             * +             * @param {Event} e +             * @returns void +             */ +            function _callbackAndReset(e) { +                _fireCallback(callback, e, combo); + +                // we should ignore the next key up if the action is key down +                // or keypress.  this is so if you finish a sequence and +                // release the key the final key will not trigger a keyup +                if (action !== 'keyup') { +                    _ignoreNextKeyup = _characterFromEvent(e); +                } + +                // weird race condition if a sequence ends with the key +                // another sequence begins with +                setTimeout(_resetSequences, 10); +            } + +            // loop through keys one at a time and bind the appropriate callback +            // function.  for any key leading up to the final one it should +            // increase the sequence. after the final, it should reset all sequences +            // +            // if an action is specified in the original bind call then that will +            // be used throughout.  otherwise we will pass the action that the +            // next key in the sequence should match.  this allows a sequence +            // to mix and match keypress and keydown events depending on which +            // ones are better suited to the key provided +            for (var i = 0; i < keys.length; ++i) { +                var isFinal = i + 1 === keys.length; +                var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action); +                _bindSingle(keys[i], wrappedCallback, action, combo, i); +            } +        } + +        /** +         * binds a single keyboard combination +         * +         * @param {string} combination +         * @param {Function} callback +         * @param {string=} action +         * @param {string=} sequenceName - name of sequence if part of sequence +         * @param {number=} level - what part of the sequence the command is +         * @returns void +         */ +        function _bindSingle(combination, callback, action, sequenceName, level) { + +            // store a direct mapped reference for use with Mousetrap.trigger +            self._directMap[combination + ':' + action] = callback; + +            // make sure multiple spaces in a row become a single space +            combination = combination.replace(/\s+/g, ' '); + +            var sequence = combination.split(' '); +            var info; + +            // if this pattern is a sequence of keys then run through this method +            // to reprocess each pattern one key at a time +            if (sequence.length > 1) { +                _bindSequence(combination, sequence, callback, action); +                return; +            } + +            info = _getKeyInfo(combination, action); + +            // make sure to initialize array if this is the first time +            // a callback is added for this key +            self._callbacks[info.key] = self._callbacks[info.key] || []; + +            // remove an existing match if there is one +            _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level); + +            // add this call back to the array +            // if it is a sequence put it at the beginning +            // if not put it at the end +            // +            // this is important because the way these are processed expects +            // the sequence ones to come first +            self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({ +                callback: callback, +                modifiers: info.modifiers, +                action: info.action, +                seq: sequenceName, +                level: level, +                combo: combination +            }); +        } + +        /** +         * binds multiple combinations to the same callback +         * +         * @param {Array} combinations +         * @param {Function} callback +         * @param {string|undefined} action +         * @returns void +         */ +        self._bindMultiple = function(combinations, callback, action) { +            for (var i = 0; i < combinations.length; ++i) { +                _bindSingle(combinations[i], callback, action); +            } +        }; + +        // start! +        _addEvent(targetElement, 'keypress', _handleKeyEvent); +        _addEvent(targetElement, 'keydown', _handleKeyEvent); +        _addEvent(targetElement, 'keyup', _handleKeyEvent); +    } + +    /** +     * binds an event to mousetrap +     * +     * can be a single key, a combination of keys separated with +, +     * an array of keys, or a sequence of keys separated by spaces +     * +     * be sure to list the modifier keys first to make sure that the +     * correct key ends up getting bound (the last key in the pattern) +     * +     * @param {string|Array} keys +     * @param {Function} callback +     * @param {string=} action - 'keypress', 'keydown', or 'keyup' +     * @returns void +     */ +    Mousetrap.prototype.bind = function(keys, callback, action) { +        var self = this; +        keys = keys instanceof Array ? keys : [keys]; +        self._bindMultiple.call(self, keys, callback, action); +        return self; +    }; + +    /** +     * unbinds an event to mousetrap +     * +     * the unbinding sets the callback function of the specified key combo +     * to an empty function and deletes the corresponding key in the +     * _directMap dict. +     * +     * TODO: actually remove this from the _callbacks dictionary instead +     * of binding an empty function +     * +     * the keycombo+action has to be exactly the same as +     * it was defined in the bind method +     * +     * @param {string|Array} keys +     * @param {string} action +     * @returns void +     */ +    Mousetrap.prototype.unbind = function(keys, action) { +        var self = this; +        return self.bind.call(self, keys, function() {}, action); +    }; + +    /** +     * triggers an event that has already been bound +     * +     * @param {string} keys +     * @param {string=} action +     * @returns void +     */ +    Mousetrap.prototype.trigger = function(keys, action) { +        var self = this; +        if (self._directMap[keys + ':' + action]) { +            self._directMap[keys + ':' + action]({}, keys); +        } +        return self; +    }; + +    /** +     * resets the library back to its initial state.  this is useful +     * if you want to clear out the current keyboard shortcuts and bind +     * new ones - for example if you switch to another page +     * +     * @returns void +     */ +    Mousetrap.prototype.reset = function() { +        var self = this; +        self._callbacks = {}; +        self._directMap = {}; +        return self; +    }; + +    /** +     * should we stop this event before firing off callbacks +     * +     * @param {Event} e +     * @param {Element} element +     * @return {boolean} +     */ +    Mousetrap.prototype.stopCallback = function(e, element) { +        var self = this; + +        // if the element has the class "mousetrap" then no need to stop +        if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { +            return false; +        } + +        if (_belongsTo(element, self.target)) { +            return false; +        } + +        // stop for input, select, and textarea +        return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable; +    }; + +    /** +     * exposes _handleKey publicly so it can be overwritten by extensions +     */ +    Mousetrap.prototype.handleKey = function() { +        var self = this; +        return self._handleKey.apply(self, arguments); +    }; + +    /** +     * Init the global mousetrap functions +     * +     * This method is needed to allow the global mousetrap functions to work +     * now that mousetrap is a constructor function. +     */ +    Mousetrap.init = function() { +        var documentMousetrap = Mousetrap(document); +        for (var method in documentMousetrap) { +            if (method.charAt(0) !== '_') { +                Mousetrap[method] = (function(method) { +                    return function() { +                        return documentMousetrap[method].apply(documentMousetrap, arguments); +                    }; +                } (method)); +            } +        } +    }; + +    Mousetrap.init(); + +    // expose mousetrap to the global object +    window.Mousetrap = Mousetrap; + +    // expose as a common js module +    if (typeof module !== 'undefined' && module.exports) { +        module.exports = Mousetrap; +    } + +    // expose mousetrap as an AMD module +    if (typeof define === 'function' && define.amd) { +        define(function() { +            return Mousetrap; +        }); +    } +}) (window, document); diff --git a/lib/mousetrap/mousetrap.min.js b/lib/mousetrap/mousetrap.min.js new file mode 100644 index 0000000..7467e2d --- /dev/null +++ b/lib/mousetrap/mousetrap.min.js @@ -0,0 +1,11 @@ +/* mousetrap v1.5.2 craig.is/killing/mice */ +(function(C,r,g){function t(a,b,h){a.addEventListener?a.addEventListener(b,h,!1):a.attachEvent("on"+b,h)}function x(a){if("keypress"==a.type){var b=String.fromCharCode(a.which);a.shiftKey||(b=b.toLowerCase());return b}return l[a.which]?l[a.which]:p[a.which]?p[a.which]:String.fromCharCode(a.which).toLowerCase()}function D(a){var b=[];a.shiftKey&&b.push("shift");a.altKey&&b.push("alt");a.ctrlKey&&b.push("ctrl");a.metaKey&&b.push("meta");return b}function u(a){return"shift"==a||"ctrl"==a||"alt"==a|| +"meta"==a}function y(a,b){var h,c,e,g=[];h=a;"+"===h?h=["+"]:(h=h.replace(/\+{2}/g,"+plus"),h=h.split("+"));for(e=0;e<h.length;++e)c=h[e],z[c]&&(c=z[c]),b&&"keypress"!=b&&A[c]&&(c=A[c],g.push("shift")),u(c)&&g.push(c);h=c;e=b;if(!e){if(!k){k={};for(var m in l)95<m&&112>m||l.hasOwnProperty(m)&&(k[l[m]]=m)}e=k[h]?"keydown":"keypress"}"keypress"==e&&g.length&&(e="keydown");return{key:c,modifiers:g,action:e}}function B(a,b){return a===r?!1:a===b?!0:B(a.parentNode,b)}function c(a){function b(a){a=a||{}; +var b=!1,n;for(n in q)a[n]?b=!0:q[n]=0;b||(v=!1)}function h(a,b,n,f,c,h){var g,e,l=[],m=n.type;if(!d._callbacks[a])return[];"keyup"==m&&u(a)&&(b=[a]);for(g=0;g<d._callbacks[a].length;++g)if(e=d._callbacks[a][g],(f||!e.seq||q[e.seq]==e.level)&&m==e.action){var k;(k="keypress"==m&&!n.metaKey&&!n.ctrlKey)||(k=e.modifiers,k=b.sort().join(",")===k.sort().join(","));k&&(k=f&&e.seq==f&&e.level==h,(!f&&e.combo==c||k)&&d._callbacks[a].splice(g,1),l.push(e))}return l}function g(a,b,n,f){d.stopCallback(b,b.target|| +b.srcElement,n,f)||!1!==a(b,n)||(b.preventDefault?b.preventDefault():b.returnValue=!1,b.stopPropagation?b.stopPropagation():b.cancelBubble=!0)}function e(a){"number"!==typeof a.which&&(a.which=a.keyCode);var b=x(a);b&&("keyup"==a.type&&w===b?w=!1:d.handleKey(b,D(a),a))}function l(a,c,n,f){function e(c){return function(){v=c;++q[a];clearTimeout(k);k=setTimeout(b,1E3)}}function h(c){g(n,c,a);"keyup"!==f&&(w=x(c));setTimeout(b,10)}for(var d=q[a]=0;d<c.length;++d){var p=d+1===c.length?h:e(f||y(c[d+1]).action); +m(c[d],p,f,a,d)}}function m(a,b,c,f,e){d._directMap[a+":"+c]=b;a=a.replace(/\s+/g," ");var g=a.split(" ");1<g.length?l(a,g,b,c):(c=y(a,c),d._callbacks[c.key]=d._callbacks[c.key]||[],h(c.key,c.modifiers,{type:c.action},f,a,e),d._callbacks[c.key][f?"unshift":"push"]({callback:b,modifiers:c.modifiers,action:c.action,seq:f,level:e,combo:a}))}var d=this;a=a||r;if(!(d instanceof c))return new c(a);d.target=a;d._callbacks={};d._directMap={};var q={},k,w=!1,p=!1,v=!1;d._handleKey=function(a,c,e){var f=h(a, +c,e),d;c={};var k=0,l=!1;for(d=0;d<f.length;++d)f[d].seq&&(k=Math.max(k,f[d].level));for(d=0;d<f.length;++d)f[d].seq?f[d].level==k&&(l=!0,c[f[d].seq]=1,g(f[d].callback,e,f[d].combo,f[d].seq)):l||g(f[d].callback,e,f[d].combo);f="keypress"==e.type&&p;e.type!=v||u(a)||f||b(c);p=l&&"keydown"==e.type};d._bindMultiple=function(a,b,c){for(var d=0;d<a.length;++d)m(a[d],b,c)};t(a,"keypress",e);t(a,"keydown",e);t(a,"keyup",e)}var l={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",20:"capslock", +27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"ins",46:"del",91:"meta",93:"meta",224:"meta"},p={106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},A={"~":"`","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=",":":";",'"':"'","<":",",">":".","?":"/","|":"\\"},z={option:"alt",command:"meta","return":"enter",escape:"esc", +plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},k;for(g=1;20>g;++g)l[111+g]="f"+g;for(g=0;9>=g;++g)l[g+96]=g;c.prototype.bind=function(a,b,c){a=a instanceof Array?a:[a];this._bindMultiple.call(this,a,b,c);return this};c.prototype.unbind=function(a,b){return this.bind.call(this,a,function(){},b)};c.prototype.trigger=function(a,b){if(this._directMap[a+":"+b])this._directMap[a+":"+b]({},a);return this};c.prototype.reset=function(){this._callbacks={};this._directMap={};return this}; +c.prototype.stopCallback=function(a,b){return-1<(" "+b.className+" ").indexOf(" mousetrap ")||B(b,this.target)?!1:"INPUT"==b.tagName||"SELECT"==b.tagName||"TEXTAREA"==b.tagName||b.isContentEditable};c.prototype.handleKey=function(){return this._handleKey.apply(this,arguments)};c.init=function(){var a=c(r),b;for(b in a)"_"!==b.charAt(0)&&(c[b]=function(b){return function(){return a[b].apply(a,arguments)}}(b))};c.init();C.Mousetrap=c;"undefined"!==typeof module&&module.exports&&(module.exports=c);"function"=== +typeof define&&define.amd&&define(function(){return c})})(window,document); diff --git a/lib/mousetrap/package.json b/lib/mousetrap/package.json new file mode 100644 index 0000000..60fccc1 --- /dev/null +++ b/lib/mousetrap/package.json @@ -0,0 +1,30 @@ +{ +  "name": "mousetrap", +  "version": "1.5.2", +  "description": "Simple library for handling keyboard shortcuts", +  "main": "mousetrap.js", +  "directories": { +    "test": "tests" +  }, +  "scripts": { +    "test": "grunt mocha" +  }, +  "repository": { +    "type": "git", +    "url": "git://github.com/ccampbell/mousetrap.git" +  }, +  "keywords": [ +    "keyboard", +    "shortcuts", +    "events" +  ], +  "author": "Craig Campbell", +  "license": "Apache 2.0", +  "gitHead": "c202a0bd4967d5a3064f9cb376db51dec9345336", +  "readmeFilename": "README.md", +  "devDependencies": { +    "grunt": "~0.4.1", +    "grunt-complexity": "~0.1.2", +    "grunt-mocha": "~0.3.1" +  } +} diff --git a/lib/mousetrap/plugins/README.md b/lib/mousetrap/plugins/README.md new file mode 100644 index 0000000..704cf04 --- /dev/null +++ b/lib/mousetrap/plugins/README.md @@ -0,0 +1,24 @@ +# Plugins + +Plugins extend the functionality of Mousetrap.  To use a plugin just include the plugin after mousetrap. + +```html +<script src="mousetrap.js"></script> +<script src="mousetrap-record.js"></script> +``` + +## Bind dictionary + +Allows you to make multiple bindings in a single ``Mousetrap.bind`` call. + +## Global bind + +Allows you to set global bindings that work even inside of input fields. + +## Pause/unpause + +Allows you to temporarily prevent Mousetrap events from firing. + +## Record + +Allows you to capture a keyboard shortcut or sequence defined by a user. diff --git a/lib/mousetrap/plugins/bind-dictionary/README.md b/lib/mousetrap/plugins/bind-dictionary/README.md new file mode 100644 index 0000000..6f956b6 --- /dev/null +++ b/lib/mousetrap/plugins/bind-dictionary/README.md @@ -0,0 +1,16 @@ +# Bind Dictionary + +This extension overwrites the default bind behavior and allows you to bind multiple combinations in a single bind call. + +Usage looks like: + +```javascript +Mousetrap.bind({ +    'a': function() { console.log('a'); }, +    'b': function() { console.log('b'); } +}); +``` + +You can optionally pass in ``keypress``, ``keydown`` or ``keyup`` as a second argument. + +Other bind calls work the same way as they do by default. diff --git a/lib/mousetrap/plugins/bind-dictionary/mousetrap-bind-dictionary.js b/lib/mousetrap/plugins/bind-dictionary/mousetrap-bind-dictionary.js new file mode 100644 index 0000000..523fc86 --- /dev/null +++ b/lib/mousetrap/plugins/bind-dictionary/mousetrap-bind-dictionary.js @@ -0,0 +1,39 @@ +/** + * Overwrites default Mousetrap.bind method to optionally accept + * an object to bind multiple key events in a single call + * + * You can pass it in like: + * + * Mousetrap.bind({ + *     'a': function() { console.log('a'); }, + *     'b': function() { console.log('b'); } + * }); + * + * And can optionally pass in 'keypress', 'keydown', or 'keyup' + * as a second argument + * + */ +/* global Mousetrap:true */ +(function(Mousetrap) { +    var _oldBind = Mousetrap.prototype.bind; +    var args; + +    Mousetrap.prototype.bind = function() { +        var self = this; +        args = arguments; + +        // normal call +        if (typeof args[0] == 'string' || args[0] instanceof Array) { +            return _oldBind.call(self, args[0], args[1], args[2]); +        } + +        // object passed in +        for (var key in args[0]) { +            if (args[0].hasOwnProperty(key)) { +                _oldBind.call(self, key, args[0][key], args[1]); +            } +        } +    }; + +    Mousetrap.init(); +}) (Mousetrap); diff --git a/lib/mousetrap/plugins/bind-dictionary/mousetrap-bind-dictionary.min.js b/lib/mousetrap/plugins/bind-dictionary/mousetrap-bind-dictionary.min.js new file mode 100644 index 0000000..bf9d8d0 --- /dev/null +++ b/lib/mousetrap/plugins/bind-dictionary/mousetrap-bind-dictionary.min.js @@ -0,0 +1 @@ +(function(b){var c=b.prototype.bind,a;b.prototype.bind=function(){a=arguments;if("string"==typeof a[0]||a[0]instanceof Array)return c.call(this,a[0],a[1],a[2]);for(var b in a[0])a[0].hasOwnProperty(b)&&c.call(this,b,a[0][b],a[1])};b.init()})(Mousetrap); diff --git a/lib/mousetrap/plugins/global-bind/README.md b/lib/mousetrap/plugins/global-bind/README.md new file mode 100644 index 0000000..a37a219 --- /dev/null +++ b/lib/mousetrap/plugins/global-bind/README.md @@ -0,0 +1,15 @@ +# Global Bind + +This extension allows you to specify keyboard events that will work anywhere including inside textarea/input fields. + +Usage looks like: + +```javascript +Mousetrap.bindGlobal('ctrl+s', function() { +    _save(); +}); +``` + +This means that a keyboard event bound using ``Mousetrap.bind`` will only work outside of form input fields, but using ``Moustrap.bindGlobal`` will work in both places. + +If you wanted to create keyboard shortcuts that only work when you are inside a specific textarea you can do that too by creating your own extension. diff --git a/lib/mousetrap/plugins/global-bind/mousetrap-global-bind.js b/lib/mousetrap/plugins/global-bind/mousetrap-global-bind.js new file mode 100644 index 0000000..1c4ac14 --- /dev/null +++ b/lib/mousetrap/plugins/global-bind/mousetrap-global-bind.js @@ -0,0 +1,43 @@ +/** + * adds a bindGlobal method to Mousetrap that allows you to + * bind specific keyboard shortcuts that will still work + * inside a text input field + * + * usage: + * Mousetrap.bindGlobal('ctrl+s', _saveChanges); + */ +/* global Mousetrap:true */ +(function(Mousetrap) { +    var _globalCallbacks = {}; +    var _originalStopCallback = Mousetrap.prototype.stopCallback; + +    Mousetrap.prototype.stopCallback = function(e, element, combo, sequence) { +        var self = this; + +        if (self.paused) { +            return true; +        } + +        if (_globalCallbacks[combo] || _globalCallbacks[sequence]) { +            return false; +        } + +        return _originalStopCallback.call(self, e, element, combo); +    }; + +    Mousetrap.prototype.bindGlobal = function(keys, callback, action) { +        var self = this; +        self.bind(keys, callback, action); + +        if (keys instanceof Array) { +            for (var i = 0; i < keys.length; i++) { +                _globalCallbacks[keys[i]] = true; +            } +            return; +        } + +        _globalCallbacks[keys] = true; +    }; + +    Mousetrap.init(); +}) (Mousetrap); diff --git a/lib/mousetrap/plugins/global-bind/mousetrap-global-bind.min.js b/lib/mousetrap/plugins/global-bind/mousetrap-global-bind.min.js new file mode 100644 index 0000000..073ce67 --- /dev/null +++ b/lib/mousetrap/plugins/global-bind/mousetrap-global-bind.min.js @@ -0,0 +1 @@ +(function(a){var c={},d=a.prototype.stopCallback;a.prototype.stopCallback=function(e,b,a,f){return this.paused?!0:c[a]||c[f]?!1:d.call(this,e,b,a)};a.prototype.bindGlobal=function(a,b,d){this.bind(a,b,d);if(a instanceof Array)for(b=0;b<a.length;b++)c[a[b]]=!0;else c[a]=!0};a.init()})(Mousetrap); diff --git a/lib/mousetrap/plugins/pause/README.md b/lib/mousetrap/plugins/pause/README.md new file mode 100644 index 0000000..0b3b3bd --- /dev/null +++ b/lib/mousetrap/plugins/pause/README.md @@ -0,0 +1,13 @@ +# Pause/unpause + +This extension allows Mousetrap to be paused and unpaused without having to reset keyboard shortcuts and rebind them. + +Usage looks like: + +```javascript +// stop Mousetrap events from firing +Mousetrap.pause(); + +// allow Mousetrap events to fire again +Mousetrap.unpause(); +``` diff --git a/lib/mousetrap/plugins/pause/mousetrap-pause.js b/lib/mousetrap/plugins/pause/mousetrap-pause.js new file mode 100644 index 0000000..0138b8a --- /dev/null +++ b/lib/mousetrap/plugins/pause/mousetrap-pause.js @@ -0,0 +1,31 @@ +/** + * adds a pause and unpause method to Mousetrap + * this allows you to enable or disable keyboard shortcuts + * without having to reset Mousetrap and rebind everything + */ +/* global Mousetrap:true */ +(function(Mousetrap) { +    var _originalStopCallback = Mousetrap.prototype.stopCallback; + +    Mousetrap.prototype.stopCallback = function(e, element, combo) { +        var self = this; + +        if (self.paused) { +            return true; +        } + +        return _originalStopCallback.call(self, e, element, combo); +    }; + +    Mousetrap.prototype.pause = function() { +        var self = this; +        self.paused = true; +    }; + +    Mousetrap.prototype.unpause = function() { +        var self = this; +        self.paused = false; +    }; + +    Mousetrap.init(); +}) (Mousetrap); diff --git a/lib/mousetrap/plugins/pause/mousetrap-pause.min.js b/lib/mousetrap/plugins/pause/mousetrap-pause.min.js new file mode 100644 index 0000000..d3df296 --- /dev/null +++ b/lib/mousetrap/plugins/pause/mousetrap-pause.min.js @@ -0,0 +1 @@ +(function(a){var b=a.prototype.stopCallback;a.prototype.stopCallback=function(a,c,d){return this.paused?!0:b.call(this,a,c,d)};a.prototype.pause=function(){this.paused=!0};a.prototype.unpause=function(){this.paused=!1};a.init()})(Mousetrap); diff --git a/lib/mousetrap/plugins/record/README.md b/lib/mousetrap/plugins/record/README.md new file mode 100644 index 0000000..903f605 --- /dev/null +++ b/lib/mousetrap/plugins/record/README.md @@ -0,0 +1,16 @@ +# Record + +This extension lets you use Mousetrap to record keyboard sequences and play them back: + +```html +<button onclick="recordSequence()">Record</button> + +<script> +    function recordSequence() { +        Mousetrap.record(function(sequence) { +            // sequence is an array like ['ctrl+k', 'c'] +            alert('You pressed: ' + sequence.join(' ')); +        }); +    } +</script> +``` diff --git a/lib/mousetrap/plugins/record/mousetrap-record.js b/lib/mousetrap/plugins/record/mousetrap-record.js new file mode 100644 index 0000000..b7d364d --- /dev/null +++ b/lib/mousetrap/plugins/record/mousetrap-record.js @@ -0,0 +1,205 @@ +/** + * This extension allows you to record a sequence using Mousetrap. + * + * @author Dan Tao <daniel.tao@gmail.com> + */ +(function(Mousetrap) { +    /** +     * the sequence currently being recorded +     * +     * @type {Array} +     */ +    var _recordedSequence = [], + +        /** +         * a callback to invoke after recording a sequence +         * +         * @type {Function|null} +         */ +        _recordedSequenceCallback = null, + +        /** +         * a list of all of the keys currently held down +         * +         * @type {Array} +         */ +        _currentRecordedKeys = [], + +        /** +         * temporary state where we remember if we've already captured a +         * character key in the current combo +         * +         * @type {boolean} +         */ +        _recordedCharacterKey = false, + +        /** +         * a handle for the timer of the current recording +         * +         * @type {null|number} +         */ +        _recordTimer = null, + +        /** +         * the original handleKey method to override when Mousetrap.record() is +         * called +         * +         * @type {Function} +         */ +        _origHandleKey = Mousetrap.prototype.handleKey; + +    /** +     * handles a character key event +     * +     * @param {string} character +     * @param {Array} modifiers +     * @param {Event} e +     * @returns void +     */ +    function _handleKey(character, modifiers, e) { +        var self = this; + +        if (!self.recording) { +            _origHandleKey.apply(self, arguments); +            return; +        } + +        // remember this character if we're currently recording a sequence +        if (e.type == 'keydown') { +            if (character.length === 1 && _recordedCharacterKey) { +                _recordCurrentCombo(); +            } + +            for (i = 0; i < modifiers.length; ++i) { +                _recordKey(modifiers[i]); +            } +            _recordKey(character); + +        // once a key is released, all keys that were held down at the time +        // count as a keypress +        } else if (e.type == 'keyup' && _currentRecordedKeys.length > 0) { +            _recordCurrentCombo(); +        } +    } + +    /** +     * marks a character key as held down while recording a sequence +     * +     * @param {string} key +     * @returns void +     */ +    function _recordKey(key) { +        var i; + +        // one-off implementation of Array.indexOf, since IE6-9 don't support it +        for (i = 0; i < _currentRecordedKeys.length; ++i) { +            if (_currentRecordedKeys[i] === key) { +                return; +            } +        } + +        _currentRecordedKeys.push(key); + +        if (key.length === 1) { +            _recordedCharacterKey = true; +        } +    } + +    /** +     * marks whatever key combination that's been recorded so far as finished +     * and gets ready for the next combo +     * +     * @returns void +     */ +    function _recordCurrentCombo() { +        _recordedSequence.push(_currentRecordedKeys); +        _currentRecordedKeys = []; +        _recordedCharacterKey = false; +        _restartRecordTimer(); +    } + +    /** +     * ensures each combo in a sequence is in a predictable order and formats +     * key combos to be '+'-delimited +     * +     * modifies the sequence in-place +     * +     * @param {Array} sequence +     * @returns void +     */ +    function _normalizeSequence(sequence) { +        var i; + +        for (i = 0; i < sequence.length; ++i) { +            sequence[i].sort(function(x, y) { +                // modifier keys always come first, in alphabetical order +                if (x.length > 1 && y.length === 1) { +                    return -1; +                } else if (x.length === 1 && y.length > 1) { +                    return 1; +                } + +                // character keys come next (list should contain no duplicates, +                // so no need for equality check) +                return x > y ? 1 : -1; +            }); + +            sequence[i] = sequence[i].join('+'); +        } +    } + +    /** +     * finishes the current recording, passes the recorded sequence to the stored +     * callback, and sets Mousetrap.handleKey back to its original function +     * +     * @returns void +     */ +    function _finishRecording() { +        if (_recordedSequenceCallback) { +            _normalizeSequence(_recordedSequence); +            _recordedSequenceCallback(_recordedSequence); +        } + +        // reset all recorded state +        _recordedSequence = []; +        _recordedSequenceCallback = null; +        _currentRecordedKeys = []; +    } + +    /** +     * called to set a 1 second timeout on the current recording +     * +     * this is so after each key press in the sequence the recording will wait for +     * 1 more second before executing the callback +     * +     * @returns void +     */ +    function _restartRecordTimer() { +        clearTimeout(_recordTimer); +        _recordTimer = setTimeout(_finishRecording, 1000); +    } + +    /** +     * records the next sequence and passes it to a callback once it's +     * completed +     * +     * @param {Function} callback +     * @returns void +     */ +    Mousetrap.prototype.record = function(callback) { +        var self = this; +        self.recording = true; +        _recordedSequenceCallback = function() { +            self.recording = false; +            callback.apply(self, arguments); +        }; +    }; + +    Mousetrap.prototype.handleKey = function() { +        var self = this; +        _handleKey.apply(self, arguments); +    }; + +    Mousetrap.init(); + +})(Mousetrap); diff --git a/lib/mousetrap/plugins/record/mousetrap-record.min.js b/lib/mousetrap/plugins/record/mousetrap-record.min.js new file mode 100644 index 0000000..25f3e71 --- /dev/null +++ b/lib/mousetrap/plugins/record/mousetrap-record.min.js @@ -0,0 +1,2 @@ +(function(d){function n(b,a,h){if(this.recording)if("keydown"==h.type){1===b.length&&g&&k();for(i=0;i<a.length;++i)l(a[i]);l(b)}else"keyup"==h.type&&0<c.length&&k();else p.apply(this,arguments)}function l(b){var a;for(a=0;a<c.length;++a)if(c[a]===b)return;c.push(b);1===b.length&&(g=!0)}function k(){e.push(c);c=[];g=!1;clearTimeout(m);m=setTimeout(q,1E3)}function r(b){var a;for(a=0;a<b.length;++a)b[a].sort(function(a,b){return 1<a.length&&1===b.length?-1:1===a.length&&1<b.length?1:a>b?1:-1}),b[a]= +b[a].join("+")}function q(){f&&(r(e),f(e));e=[];f=null;c=[]}var e=[],f=null,c=[],g=!1,m=null,p=d.prototype.handleKey;d.prototype.record=function(b){var a=this;a.recording=!0;f=function(){a.recording=!1;b.apply(a,arguments)}};d.prototype.handleKey=function(){n.apply(this,arguments)};d.init()})(Mousetrap); diff --git a/lib/mousetrap/plugins/record/tests/index.html b/lib/mousetrap/plugins/record/tests/index.html new file mode 100644 index 0000000..5608f09 --- /dev/null +++ b/lib/mousetrap/plugins/record/tests/index.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html> + +    <head> +        <title>Jelly</title> +        <meta charset=utf-8> +        <link href="jelly.css" rel="stylesheet"> +    </head> + +    <body> +        <h1>Jelly</h1> + +        <h2>For testing the <strong>record</strong> extension</h2> + +        <p>Click "Record" to test recording a sequence.</p> +        <button class="test-record">Record</button> +        <div class="test-record-result"></div> + +        <script type="text/javascript" src="../../../tests/libs/jquery-1.7.2.min.js"></script> +        <script type="text/javascript" src="../../../mousetrap.js"></script> +        <script type="text/javascript" src="../mousetrap-record.js"></script> +        <script type="text/javascript" src="jelly.js"></script> + +        <script type="text/javascript"> +            Jelly.spread(); +        </script> +    </body> + +</html> diff --git a/lib/mousetrap/plugins/record/tests/jelly.css b/lib/mousetrap/plugins/record/tests/jelly.css new file mode 100644 index 0000000..a071c77 --- /dev/null +++ b/lib/mousetrap/plugins/record/tests/jelly.css @@ -0,0 +1,18 @@ +body { +    font-family: helvetica, arial, sans-serif; +    line-height: 20px; +} + +kbd { +    background-color: #ccc; +    display: inline-block; +    padding: 0.5ex 1em; +} + +.test-record-result { +  margin-top: 20px; +} + +.test-record-result span:nth-child(n+2) { +    margin-left: 10px; +} diff --git a/lib/mousetrap/plugins/record/tests/jelly.js b/lib/mousetrap/plugins/record/tests/jelly.js new file mode 100644 index 0000000..57ff01a --- /dev/null +++ b/lib/mousetrap/plugins/record/tests/jelly.js @@ -0,0 +1,53 @@ +/** + * Peanut butter goes great with jelly. + * + * @author Dan Tao <daniel.tao@gmail.com> + */ +var Jelly = (function() { +    var recordButton = $("button.test-record"), +        recordResult = $("div.test-record-result"); + +    function _formatSequenceAsHtml(sequence) { +        var combos = [], +            i; + +        for (i = 0; i < sequence.length; ++i) { +            combos.push('<span>' + _formatKeysAsHtml(sequence[i].split('+')) + '</span>'); +        } + +        return combos.join(' '); +    } + +    function _formatKeysAsHtml(keys) { +        var htmlKeys = [], +            i; + +        for (i = 0; i < keys.length; ++i) { +            htmlKeys.push('<kbd>' + keys[i] + '</kbd>'); +        } + +        return htmlKeys.join('+'); +    } + +    function _prepareRecordTest() { +        recordButton.prop('disabled', true); +        recordButton.text('Recording'); + +        Mousetrap.record(function(sequence) { +            recordResult.html(_formatSequenceAsHtml(sequence)); +            recordButton.prop('disabled', false); +            recordButton.text('Record'); +        }); + +        // take focus away from the button so that Mousetrap will actually +        // capture keystrokes +        recordButton.blur(); +    } + +    return { +        spread: function() { +            recordButton.click(_prepareRecordTest); +        } +    }; + +})(); diff --git a/lib/mousetrap/tests/libs/chai-1.6.0.js b/lib/mousetrap/tests/libs/chai-1.6.0.js new file mode 100644 index 0000000..629e199 --- /dev/null +++ b/lib/mousetrap/tests/libs/chai-1.6.0.js @@ -0,0 +1,4251 @@ +;(function(){ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { +  var resolved = require.resolve(path); + +  // lookup failed +  if (null == resolved) { +    orig = orig || path; +    parent = parent || 'root'; +    var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); +    err.path = orig; +    err.parent = parent; +    err.require = true; +    throw err; +  } + +  var module = require.modules[resolved]; + +  // perform real require() +  // by invoking the module's +  // registered function +  if (!module.exports) { +    module.exports = {}; +    module.client = module.component = true; +    module.call(this, module.exports, require.relative(resolved), module); +  } + +  return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + *   - PATH/index.js + *   - PATH.js + *   - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { +  if (path.charAt(0) === '/') path = path.slice(1); +  var index = path + '/index.js'; + +  var paths = [ +    path, +    path + '.js', +    path + '.json', +    path + '/index.js', +    path + '/index.json' +  ]; + +  for (var i = 0; i < paths.length; i++) { +    var path = paths[i]; +    if (require.modules.hasOwnProperty(path)) return path; +  } + +  if (require.aliases.hasOwnProperty(index)) { +    return require.aliases[index]; +  } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { +  var segs = []; + +  if ('.' != path.charAt(0)) return path; + +  curr = curr.split('/'); +  path = path.split('/'); + +  for (var i = 0; i < path.length; ++i) { +    if ('..' == path[i]) { +      curr.pop(); +    } else if ('.' != path[i] && '' != path[i]) { +      segs.push(path[i]); +    } +  } + +  return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { +  require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { +  if (!require.modules.hasOwnProperty(from)) { +    throw new Error('Failed to alias "' + from + '", it does not exist'); +  } +  require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { +  var p = require.normalize(parent, '..'); + +  /** +   * lastIndexOf helper. +   */ + +  function lastIndexOf(arr, obj) { +    var i = arr.length; +    while (i--) { +      if (arr[i] === obj) return i; +    } +    return -1; +  } + +  /** +   * The relative require() itself. +   */ + +  function localRequire(path) { +    var resolved = localRequire.resolve(path); +    return require(resolved, parent, path); +  } + +  /** +   * Resolve relative to the parent. +   */ + +  localRequire.resolve = function(path) { +    var c = path.charAt(0); +    if ('/' == c) return path.slice(1); +    if ('.' == c) return require.normalize(p, path); + +    // resolve deps by returning +    // the dep in the nearest "deps" +    // directory +    var segs = parent.split('/'); +    var i = lastIndexOf(segs, 'deps') + 1; +    if (!i) i = 0; +    path = segs.slice(0, i + 1).join('/') + '/deps/' + path; +    return path; +  }; + +  /** +   * Check if module is defined at `path`. +   */ + +  localRequire.exists = function(path) { +    return require.modules.hasOwnProperty(localRequire.resolve(path)); +  }; + +  return localRequire; +}; +require.register("chai/index.js", function(exports, require, module){ +module.exports = require('./lib/chai'); + +}); +require.register("chai/lib/chai.js", function(exports, require, module){ +/*! + * chai + * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +var used = [] +  , exports = module.exports = {}; + +/*! + * Chai version + */ + +exports.version = '1.6.0'; + +/*! + * Primary `Assertion` prototype + */ + +exports.Assertion = require('./chai/assertion'); + +/*! + * Assertion Error + */ + +exports.AssertionError = require('./chai/error'); + +/*! + * Utils for plugins (not exported) + */ + +var util = require('./chai/utils'); + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai + * + * @param {Function} + * @returns {this} for chaining + * @api public + */ + +exports.use = function (fn) { +  if (!~used.indexOf(fn)) { +    fn(this, util); +    used.push(fn); +  } + +  return this; +}; + +/*! + * Core Assertions + */ + +var core = require('./chai/core/assertions'); +exports.use(core); + +/*! + * Expect interface + */ + +var expect = require('./chai/interface/expect'); +exports.use(expect); + +/*! + * Should interface + */ + +var should = require('./chai/interface/should'); +exports.use(should); + +/*! + * Assert interface + */ + +var assert = require('./chai/interface/assert'); +exports.use(assert); + +}); +require.register("chai/lib/chai/assertion.js", function(exports, require, module){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Module dependencies. + */ + +var AssertionError = require('./error') +  , util = require('./utils') +  , flag = util.flag; + +/*! + * Module export. + */ + +module.exports = Assertion; + + +/*! + * Assertion Constructor + * + * Creates object for chaining. + * + * @api private + */ + +function Assertion (obj, msg, stack) { +  flag(this, 'ssfi', stack || arguments.callee); +  flag(this, 'object', obj); +  flag(this, 'message', msg); +} + +/*! +  * ### Assertion.includeStack +  * +  * User configurable property, influences whether stack trace +  * is included in Assertion error message. Default of false +  * suppresses stack trace in the error message +  * +  *     Assertion.includeStack = true;  // enable stack on error +  * +  * @api public +  */ + +Assertion.includeStack = false; + +/*! + * ### Assertion.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @api public + */ + +Assertion.showDiff = true; + +Assertion.addProperty = function (name, fn) { +  util.addProperty(this.prototype, name, fn); +}; + +Assertion.addMethod = function (name, fn) { +  util.addMethod(this.prototype, name, fn); +}; + +Assertion.addChainableMethod = function (name, fn, chainingBehavior) { +  util.addChainableMethod(this.prototype, name, fn, chainingBehavior); +}; + +Assertion.overwriteProperty = function (name, fn) { +  util.overwriteProperty(this.prototype, name, fn); +}; + +Assertion.overwriteMethod = function (name, fn) { +  util.overwriteMethod(this.prototype, name, fn); +}; + +/*! + * ### .assert(expression, message, negateMessage, expected, actual) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {Philosophical} expression to be tested + * @param {String} message to display if fails + * @param {String} negatedMessage to display if negated expression fails + * @param {Mixed} expected value (remember to check for negation) + * @param {Mixed} actual (optional) will default to `this.obj` + * @api private + */ + +Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { +  var ok = util.test(this, arguments); +  if (true !== showDiff) showDiff = false; +  if (true !== Assertion.showDiff) showDiff = false; + +  if (!ok) { +    var msg = util.getMessage(this, arguments) +      , actual = util.getActual(this, arguments); +    throw new AssertionError({ +        message: msg +      , actual: actual +      , expected: expected +      , stackStartFunction: (Assertion.includeStack) ? this.assert : flag(this, 'ssfi') +      , showDiff: showDiff +    }); +  } +}; + +/*! + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @api private + */ + +Object.defineProperty(Assertion.prototype, '_obj', +  { get: function () { +      return flag(this, 'object'); +    } +  , set: function (val) { +      flag(this, 'object', val); +    } +}); + +}); +require.register("chai/lib/chai/error.js", function(exports, require, module){ +/*! + * chai + * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Main export + */ + +module.exports = AssertionError; + +/** + * # AssertionError (constructor) + * + * Create a new assertion error based on the Javascript + * `Error` prototype. + * + * **Options** + * - message + * - actual + * - expected + * - operator + * - startStackFunction + * + * @param {Object} options + * @api public + */ + +function AssertionError (options) { +  options = options || {}; +  this.message = options.message; +  this.actual = options.actual; +  this.expected = options.expected; +  this.operator = options.operator; +  this.showDiff = options.showDiff; + +  if (options.stackStartFunction && Error.captureStackTrace) { +    var stackStartFunction = options.stackStartFunction; +    Error.captureStackTrace(this, stackStartFunction); +  } +} + +/*! + * Inherit from Error + */ + +AssertionError.prototype = Object.create(Error.prototype); +AssertionError.prototype.name = 'AssertionError'; +AssertionError.prototype.constructor = AssertionError; + +/** + * # toString() + * + * Override default to string method + */ + +AssertionError.prototype.toString = function() { +  return this.message; +}; + +}); +require.register("chai/lib/chai/core/assertions.js", function(exports, require, module){ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +module.exports = function (chai, _) { +  var Assertion = chai.Assertion +    , toString = Object.prototype.toString +    , flag = _.flag; + +  /** +   * ### Language Chains +   * +   * The following are provide as chainable getters to +   * improve the readability of your assertions. They +   * do not provide an testing capability unless they +   * have been overwritten by a plugin. +   * +   * **Chains** +   * +   * - to +   * - be +   * - been +   * - is +   * - that +   * - and +   * - have +   * - with +   * - at +   * - of +   * - same +   * +   * @name language chains +   * @api public +   */ + +  [ 'to', 'be', 'been' +  , 'is', 'and', 'have' +  , 'with', 'that', 'at' +  , 'of', 'same' ].forEach(function (chain) { +    Assertion.addProperty(chain, function () { +      return this; +    }); +  }); + +  /** +   * ### .not +   * +   * Negates any of assertions following in the chain. +   * +   *     expect(foo).to.not.equal('bar'); +   *     expect(goodFn).to.not.throw(Error); +   *     expect({ foo: 'baz' }).to.have.property('foo') +   *       .and.not.equal('bar'); +   * +   * @name not +   * @api public +   */ + +  Assertion.addProperty('not', function () { +    flag(this, 'negate', true); +  }); + +  /** +   * ### .deep +   * +   * Sets the `deep` flag, later used by the `equal` and +   * `property` assertions. +   * +   *     expect(foo).to.deep.equal({ bar: 'baz' }); +   *     expect({ foo: { bar: { baz: 'quux' } } }) +   *       .to.have.deep.property('foo.bar.baz', 'quux'); +   * +   * @name deep +   * @api public +   */ + +  Assertion.addProperty('deep', function () { +    flag(this, 'deep', true); +  }); + +  /** +   * ### .a(type) +   * +   * The `a` and `an` assertions are aliases that can be +   * used either as language chains or to assert a value's +   * type. +   * +   *     // typeof +   *     expect('test').to.be.a('string'); +   *     expect({ foo: 'bar' }).to.be.an('object'); +   *     expect(null).to.be.a('null'); +   *     expect(undefined).to.be.an('undefined'); +   * +   *     // language chain +   *     expect(foo).to.be.an.instanceof(Foo); +   * +   * @name a +   * @alias an +   * @param {String} type +   * @param {String} message _optional_ +   * @api public +   */ + +  function an (type, msg) { +    if (msg) flag(this, 'message', msg); +    type = type.toLowerCase(); +    var obj = flag(this, 'object') +      , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + +    this.assert( +        type === _.type(obj) +      , 'expected #{this} to be ' + article + type +      , 'expected #{this} not to be ' + article + type +    ); +  } + +  Assertion.addChainableMethod('an', an); +  Assertion.addChainableMethod('a', an); + +  /** +   * ### .include(value) +   * +   * The `include` and `contain` assertions can be used as either property +   * based language chains or as methods to assert the inclusion of an object +   * in an array or a substring in a string. When used as language chains, +   * they toggle the `contain` flag for the `keys` assertion. +   * +   *     expect([1,2,3]).to.include(2); +   *     expect('foobar').to.contain('foo'); +   *     expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); +   * +   * @name include +   * @alias contain +   * @param {Object|String|Number} obj +   * @param {String} message _optional_ +   * @api public +   */ + +  function includeChainingBehavior () { +    flag(this, 'contains', true); +  } + +  function include (val, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object') +    this.assert( +        ~obj.indexOf(val) +      , 'expected #{this} to include ' + _.inspect(val) +      , 'expected #{this} to not include ' + _.inspect(val)); +  } + +  Assertion.addChainableMethod('include', include, includeChainingBehavior); +  Assertion.addChainableMethod('contain', include, includeChainingBehavior); + +  /** +   * ### .ok +   * +   * Asserts that the target is truthy. +   * +   *     expect('everthing').to.be.ok; +   *     expect(1).to.be.ok; +   *     expect(false).to.not.be.ok; +   *     expect(undefined).to.not.be.ok; +   *     expect(null).to.not.be.ok; +   * +   * @name ok +   * @api public +   */ + +  Assertion.addProperty('ok', function () { +    this.assert( +        flag(this, 'object') +      , 'expected #{this} to be truthy' +      , 'expected #{this} to be falsy'); +  }); + +  /** +   * ### .true +   * +   * Asserts that the target is `true`. +   * +   *     expect(true).to.be.true; +   *     expect(1).to.not.be.true; +   * +   * @name true +   * @api public +   */ + +  Assertion.addProperty('true', function () { +    this.assert( +        true === flag(this, 'object') +      , 'expected #{this} to be true' +      , 'expected #{this} to be false' +      , this.negate ? false : true +    ); +  }); + +  /** +   * ### .false +   * +   * Asserts that the target is `false`. +   * +   *     expect(false).to.be.false; +   *     expect(0).to.not.be.false; +   * +   * @name false +   * @api public +   */ + +  Assertion.addProperty('false', function () { +    this.assert( +        false === flag(this, 'object') +      , 'expected #{this} to be false' +      , 'expected #{this} to be true' +      , this.negate ? true : false +    ); +  }); + +  /** +   * ### .null +   * +   * Asserts that the target is `null`. +   * +   *     expect(null).to.be.null; +   *     expect(undefined).not.to.be.null; +   * +   * @name null +   * @api public +   */ + +  Assertion.addProperty('null', function () { +    this.assert( +        null === flag(this, 'object') +      , 'expected #{this} to be null' +      , 'expected #{this} not to be null' +    ); +  }); + +  /** +   * ### .undefined +   * +   * Asserts that the target is `undefined`. +   * +   *      expect(undefined).to.be.undefined; +   *      expect(null).to.not.be.undefined; +   * +   * @name undefined +   * @api public +   */ + +  Assertion.addProperty('undefined', function () { +    this.assert( +        undefined === flag(this, 'object') +      , 'expected #{this} to be undefined' +      , 'expected #{this} not to be undefined' +    ); +  }); + +  /** +   * ### .exist +   * +   * Asserts that the target is neither `null` nor `undefined`. +   * +   *     var foo = 'hi' +   *       , bar = null +   *       , baz; +   * +   *     expect(foo).to.exist; +   *     expect(bar).to.not.exist; +   *     expect(baz).to.not.exist; +   * +   * @name exist +   * @api public +   */ + +  Assertion.addProperty('exist', function () { +    this.assert( +        null != flag(this, 'object') +      , 'expected #{this} to exist' +      , 'expected #{this} to not exist' +    ); +  }); + + +  /** +   * ### .empty +   * +   * Asserts that the target's length is `0`. For arrays, it checks +   * the `length` property. For objects, it gets the count of +   * enumerable keys. +   * +   *     expect([]).to.be.empty; +   *     expect('').to.be.empty; +   *     expect({}).to.be.empty; +   * +   * @name empty +   * @api public +   */ + +  Assertion.addProperty('empty', function () { +    var obj = flag(this, 'object') +      , expected = obj; + +    if (Array.isArray(obj) || 'string' === typeof object) { +      expected = obj.length; +    } else if (typeof obj === 'object') { +      expected = Object.keys(obj).length; +    } + +    this.assert( +        !expected +      , 'expected #{this} to be empty' +      , 'expected #{this} not to be empty' +    ); +  }); + +  /** +   * ### .arguments +   * +   * Asserts that the target is an arguments object. +   * +   *     function test () { +   *       expect(arguments).to.be.arguments; +   *     } +   * +   * @name arguments +   * @alias Arguments +   * @api public +   */ + +  function checkArguments () { +    var obj = flag(this, 'object') +      , type = Object.prototype.toString.call(obj); +    this.assert( +        '[object Arguments]' === type +      , 'expected #{this} to be arguments but got ' + type +      , 'expected #{this} to not be arguments' +    ); +  } + +  Assertion.addProperty('arguments', checkArguments); +  Assertion.addProperty('Arguments', checkArguments); + +  /** +   * ### .equal(value) +   * +   * Asserts that the target is strictly equal (`===`) to `value`. +   * Alternately, if the `deep` flag is set, asserts that +   * the target is deeply equal to `value`. +   * +   *     expect('hello').to.equal('hello'); +   *     expect(42).to.equal(42); +   *     expect(1).to.not.equal(true); +   *     expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); +   *     expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); +   * +   * @name equal +   * @alias equals +   * @alias eq +   * @alias deep.equal +   * @param {Mixed} value +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertEqual (val, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    if (flag(this, 'deep')) { +      return this.eql(val); +    } else { +      this.assert( +          val === obj +        , 'expected #{this} to equal #{exp}' +        , 'expected #{this} to not equal #{exp}' +        , val +        , this._obj +        , true +      ); +    } +  } + +  Assertion.addMethod('equal', assertEqual); +  Assertion.addMethod('equals', assertEqual); +  Assertion.addMethod('eq', assertEqual); + +  /** +   * ### .eql(value) +   * +   * Asserts that the target is deeply equal to `value`. +   * +   *     expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); +   *     expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); +   * +   * @name eql +   * @alias eqls +   * @param {Mixed} value +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertEql(obj, msg) { +    if (msg) flag(this, 'message', msg); +    this.assert( +        _.eql(obj, flag(this, 'object')) +      , 'expected #{this} to deeply equal #{exp}' +      , 'expected #{this} to not deeply equal #{exp}' +      , obj +      , this._obj +      , true +    ); +  } + +  Assertion.addMethod('eql', assertEql); +  Assertion.addMethod('eqls', assertEql); + +  /** +   * ### .above(value) +   * +   * Asserts that the target is greater than `value`. +   * +   *     expect(10).to.be.above(5); +   * +   * Can also be used in conjunction with `length` to +   * assert a minimum length. The benefit being a +   * more informative error message than if the length +   * was supplied directly. +   * +   *     expect('foo').to.have.length.above(2); +   *     expect([ 1, 2, 3 ]).to.have.length.above(2); +   * +   * @name above +   * @alias gt +   * @alias greaterThan +   * @param {Number} value +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertAbove (n, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    if (flag(this, 'doLength')) { +      new Assertion(obj, msg).to.have.property('length'); +      var len = obj.length; +      this.assert( +          len > n +        , 'expected #{this} to have a length above #{exp} but got #{act}' +        , 'expected #{this} to not have a length above #{exp}' +        , n +        , len +      ); +    } else { +      this.assert( +          obj > n +        , 'expected #{this} to be above ' + n +        , 'expected #{this} to be at most ' + n +      ); +    } +  } + +  Assertion.addMethod('above', assertAbove); +  Assertion.addMethod('gt', assertAbove); +  Assertion.addMethod('greaterThan', assertAbove); + +  /** +   * ### .least(value) +   * +   * Asserts that the target is greater than or equal to `value`. +   * +   *     expect(10).to.be.at.least(10); +   * +   * Can also be used in conjunction with `length` to +   * assert a minimum length. The benefit being a +   * more informative error message than if the length +   * was supplied directly. +   * +   *     expect('foo').to.have.length.of.at.least(2); +   *     expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); +   * +   * @name least +   * @alias gte +   * @param {Number} value +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertLeast (n, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    if (flag(this, 'doLength')) { +      new Assertion(obj, msg).to.have.property('length'); +      var len = obj.length; +      this.assert( +          len >= n +        , 'expected #{this} to have a length at least #{exp} but got #{act}' +        , 'expected #{this} to have a length below #{exp}' +        , n +        , len +      ); +    } else { +      this.assert( +          obj >= n +        , 'expected #{this} to be at least ' + n +        , 'expected #{this} to be below ' + n +      ); +    } +  } + +  Assertion.addMethod('least', assertLeast); +  Assertion.addMethod('gte', assertLeast); + +  /** +   * ### .below(value) +   * +   * Asserts that the target is less than `value`. +   * +   *     expect(5).to.be.below(10); +   * +   * Can also be used in conjunction with `length` to +   * assert a maximum length. The benefit being a +   * more informative error message than if the length +   * was supplied directly. +   * +   *     expect('foo').to.have.length.below(4); +   *     expect([ 1, 2, 3 ]).to.have.length.below(4); +   * +   * @name below +   * @alias lt +   * @alias lessThan +   * @param {Number} value +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertBelow (n, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    if (flag(this, 'doLength')) { +      new Assertion(obj, msg).to.have.property('length'); +      var len = obj.length; +      this.assert( +          len < n +        , 'expected #{this} to have a length below #{exp} but got #{act}' +        , 'expected #{this} to not have a length below #{exp}' +        , n +        , len +      ); +    } else { +      this.assert( +          obj < n +        , 'expected #{this} to be below ' + n +        , 'expected #{this} to be at least ' + n +      ); +    } +  } + +  Assertion.addMethod('below', assertBelow); +  Assertion.addMethod('lt', assertBelow); +  Assertion.addMethod('lessThan', assertBelow); + +  /** +   * ### .most(value) +   * +   * Asserts that the target is less than or equal to `value`. +   * +   *     expect(5).to.be.at.most(5); +   * +   * Can also be used in conjunction with `length` to +   * assert a maximum length. The benefit being a +   * more informative error message than if the length +   * was supplied directly. +   * +   *     expect('foo').to.have.length.of.at.most(4); +   *     expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); +   * +   * @name most +   * @alias lte +   * @param {Number} value +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertMost (n, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    if (flag(this, 'doLength')) { +      new Assertion(obj, msg).to.have.property('length'); +      var len = obj.length; +      this.assert( +          len <= n +        , 'expected #{this} to have a length at most #{exp} but got #{act}' +        , 'expected #{this} to have a length above #{exp}' +        , n +        , len +      ); +    } else { +      this.assert( +          obj <= n +        , 'expected #{this} to be at most ' + n +        , 'expected #{this} to be above ' + n +      ); +    } +  } + +  Assertion.addMethod('most', assertMost); +  Assertion.addMethod('lte', assertMost); + +  /** +   * ### .within(start, finish) +   * +   * Asserts that the target is within a range. +   * +   *     expect(7).to.be.within(5,10); +   * +   * Can also be used in conjunction with `length` to +   * assert a length range. The benefit being a +   * more informative error message than if the length +   * was supplied directly. +   * +   *     expect('foo').to.have.length.within(2,4); +   *     expect([ 1, 2, 3 ]).to.have.length.within(2,4); +   * +   * @name within +   * @param {Number} start lowerbound inclusive +   * @param {Number} finish upperbound inclusive +   * @param {String} message _optional_ +   * @api public +   */ + +  Assertion.addMethod('within', function (start, finish, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object') +      , range = start + '..' + finish; +    if (flag(this, 'doLength')) { +      new Assertion(obj, msg).to.have.property('length'); +      var len = obj.length; +      this.assert( +          len >= start && len <= finish +        , 'expected #{this} to have a length within ' + range +        , 'expected #{this} to not have a length within ' + range +      ); +    } else { +      this.assert( +          obj >= start && obj <= finish +        , 'expected #{this} to be within ' + range +        , 'expected #{this} to not be within ' + range +      ); +    } +  }); + +  /** +   * ### .instanceof(constructor) +   * +   * Asserts that the target is an instance of `constructor`. +   * +   *     var Tea = function (name) { this.name = name; } +   *       , Chai = new Tea('chai'); +   * +   *     expect(Chai).to.be.an.instanceof(Tea); +   *     expect([ 1, 2, 3 ]).to.be.instanceof(Array); +   * +   * @name instanceof +   * @param {Constructor} constructor +   * @param {String} message _optional_ +   * @alias instanceOf +   * @api public +   */ + +  function assertInstanceOf (constructor, msg) { +    if (msg) flag(this, 'message', msg); +    var name = _.getName(constructor); +    this.assert( +        flag(this, 'object') instanceof constructor +      , 'expected #{this} to be an instance of ' + name +      , 'expected #{this} to not be an instance of ' + name +    ); +  }; + +  Assertion.addMethod('instanceof', assertInstanceOf); +  Assertion.addMethod('instanceOf', assertInstanceOf); + +  /** +   * ### .property(name, [value]) +   * +   * Asserts that the target has a property `name`, optionally asserting that +   * the value of that property is strictly equal to  `value`. +   * If the `deep` flag is set, you can use dot- and bracket-notation for deep +   * references into objects and arrays. +   * +   *     // simple referencing +   *     var obj = { foo: 'bar' }; +   *     expect(obj).to.have.property('foo'); +   *     expect(obj).to.have.property('foo', 'bar'); +   * +   *     // deep referencing +   *     var deepObj = { +   *         green: { tea: 'matcha' } +   *       , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] +   *     }; + +   *     expect(deepObj).to.have.deep.property('green.tea', 'matcha'); +   *     expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); +   *     expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); +   * +   * You can also use an array as the starting point of a `deep.property` +   * assertion, or traverse nested arrays. +   * +   *     var arr = [ +   *         [ 'chai', 'matcha', 'konacha' ] +   *       , [ { tea: 'chai' } +   *         , { tea: 'matcha' } +   *         , { tea: 'konacha' } ] +   *     ]; +   * +   *     expect(arr).to.have.deep.property('[0][1]', 'matcha'); +   *     expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); +   * +   * Furthermore, `property` changes the subject of the assertion +   * to be the value of that property from the original object. This +   * permits for further chainable assertions on that property. +   * +   *     expect(obj).to.have.property('foo') +   *       .that.is.a('string'); +   *     expect(deepObj).to.have.property('green') +   *       .that.is.an('object') +   *       .that.deep.equals({ tea: 'matcha' }); +   *     expect(deepObj).to.have.property('teas') +   *       .that.is.an('array') +   *       .with.deep.property('[2]') +   *         .that.deep.equals({ tea: 'konacha' }); +   * +   * @name property +   * @alias deep.property +   * @param {String} name +   * @param {Mixed} value (optional) +   * @param {String} message _optional_ +   * @returns value of property for chaining +   * @api public +   */ + +  Assertion.addMethod('property', function (name, val, msg) { +    if (msg) flag(this, 'message', msg); + +    var descriptor = flag(this, 'deep') ? 'deep property ' : 'property ' +      , negate = flag(this, 'negate') +      , obj = flag(this, 'object') +      , value = flag(this, 'deep') +        ? _.getPathValue(name, obj) +        : obj[name]; + +    if (negate && undefined !== val) { +      if (undefined === value) { +        msg = (msg != null) ? msg + ': ' : ''; +        throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); +      } +    } else { +      this.assert( +          undefined !== value +        , 'expected #{this} to have a ' + descriptor + _.inspect(name) +        , 'expected #{this} to not have ' + descriptor + _.inspect(name)); +    } + +    if (undefined !== val) { +      this.assert( +          val === value +        , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' +        , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' +        , val +        , value +      ); +    } + +    flag(this, 'object', value); +  }); + + +  /** +   * ### .ownProperty(name) +   * +   * Asserts that the target has an own property `name`. +   * +   *     expect('test').to.have.ownProperty('length'); +   * +   * @name ownProperty +   * @alias haveOwnProperty +   * @param {String} name +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertOwnProperty (name, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    this.assert( +        obj.hasOwnProperty(name) +      , 'expected #{this} to have own property ' + _.inspect(name) +      , 'expected #{this} to not have own property ' + _.inspect(name) +    ); +  } + +  Assertion.addMethod('ownProperty', assertOwnProperty); +  Assertion.addMethod('haveOwnProperty', assertOwnProperty); + +  /** +   * ### .length(value) +   * +   * Asserts that the target's `length` property has +   * the expected value. +   * +   *     expect([ 1, 2, 3]).to.have.length(3); +   *     expect('foobar').to.have.length(6); +   * +   * Can also be used as a chain precursor to a value +   * comparison for the length property. +   * +   *     expect('foo').to.have.length.above(2); +   *     expect([ 1, 2, 3 ]).to.have.length.above(2); +   *     expect('foo').to.have.length.below(4); +   *     expect([ 1, 2, 3 ]).to.have.length.below(4); +   *     expect('foo').to.have.length.within(2,4); +   *     expect([ 1, 2, 3 ]).to.have.length.within(2,4); +   * +   * @name length +   * @alias lengthOf +   * @param {Number} length +   * @param {String} message _optional_ +   * @api public +   */ + +  function assertLengthChain () { +    flag(this, 'doLength', true); +  } + +  function assertLength (n, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    new Assertion(obj, msg).to.have.property('length'); +    var len = obj.length; + +    this.assert( +        len == n +      , 'expected #{this} to have a length of #{exp} but got #{act}' +      , 'expected #{this} to not have a length of #{act}' +      , n +      , len +    ); +  } + +  Assertion.addChainableMethod('length', assertLength, assertLengthChain); +  Assertion.addMethod('lengthOf', assertLength, assertLengthChain); + +  /** +   * ### .match(regexp) +   * +   * Asserts that the target matches a regular expression. +   * +   *     expect('foobar').to.match(/^foo/); +   * +   * @name match +   * @param {RegExp} RegularExpression +   * @param {String} message _optional_ +   * @api public +   */ + +  Assertion.addMethod('match', function (re, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    this.assert( +        re.exec(obj) +      , 'expected #{this} to match ' + re +      , 'expected #{this} not to match ' + re +    ); +  }); + +  /** +   * ### .string(string) +   * +   * Asserts that the string target contains another string. +   * +   *     expect('foobar').to.have.string('bar'); +   * +   * @name string +   * @param {String} string +   * @param {String} message _optional_ +   * @api public +   */ + +  Assertion.addMethod('string', function (str, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    new Assertion(obj, msg).is.a('string'); + +    this.assert( +        ~obj.indexOf(str) +      , 'expected #{this} to contain ' + _.inspect(str) +      , 'expected #{this} to not contain ' + _.inspect(str) +    ); +  }); + + +  /** +   * ### .keys(key1, [key2], [...]) +   * +   * Asserts that the target has exactly the given keys, or +   * asserts the inclusion of some keys when using the +   * `include` or `contain` modifiers. +   * +   *     expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']); +   *     expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar'); +   * +   * @name keys +   * @alias key +   * @param {String...|Array} keys +   * @api public +   */ + +  function assertKeys (keys) { +    var obj = flag(this, 'object') +      , str +      , ok = true; + +    keys = keys instanceof Array +      ? keys +      : Array.prototype.slice.call(arguments); + +    if (!keys.length) throw new Error('keys required'); + +    var actual = Object.keys(obj) +      , len = keys.length; + +    // Inclusion +    ok = keys.every(function(key){ +      return ~actual.indexOf(key); +    }); + +    // Strict +    if (!flag(this, 'negate') && !flag(this, 'contains')) { +      ok = ok && keys.length == actual.length; +    } + +    // Key string +    if (len > 1) { +      keys = keys.map(function(key){ +        return _.inspect(key); +      }); +      var last = keys.pop(); +      str = keys.join(', ') + ', and ' + last; +    } else { +      str = _.inspect(keys[0]); +    } + +    // Form +    str = (len > 1 ? 'keys ' : 'key ') + str; + +    // Have / include +    str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; + +    // Assertion +    this.assert( +        ok +      , 'expected #{this} to ' + str +      , 'expected #{this} to not ' + str +    ); +  } + +  Assertion.addMethod('keys', assertKeys); +  Assertion.addMethod('key', assertKeys); + +  /** +   * ### .throw(constructor) +   * +   * Asserts that the function target will throw a specific error, or specific type of error +   * (as determined using `instanceof`), optionally with a RegExp or string inclusion test +   * for the error's message. +   * +   *     var err = new ReferenceError('This is a bad function.'); +   *     var fn = function () { throw err; } +   *     expect(fn).to.throw(ReferenceError); +   *     expect(fn).to.throw(Error); +   *     expect(fn).to.throw(/bad function/); +   *     expect(fn).to.not.throw('good function'); +   *     expect(fn).to.throw(ReferenceError, /bad function/); +   *     expect(fn).to.throw(err); +   *     expect(fn).to.not.throw(new RangeError('Out of range.')); +   * +   * Please note that when a throw expectation is negated, it will check each +   * parameter independently, starting with error constructor type. The appropriate way +   * to check for the existence of a type of error but for a message that does not match +   * is to use `and`. +   * +   *     expect(fn).to.throw(ReferenceError) +   *        .and.not.throw(/good function/); +   * +   * @name throw +   * @alias throws +   * @alias Throw +   * @param {ErrorConstructor} constructor +   * @param {String|RegExp} expected error message +   * @param {String} message _optional_ +   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types +   * @api public +   */ + +  function assertThrows (constructor, errMsg, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    new Assertion(obj, msg).is.a('function'); + +    var thrown = false +      , desiredError = null +      , name = null +      , thrownError = null; + +    if (arguments.length === 0) { +      errMsg = null; +      constructor = null; +    } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) { +      errMsg = constructor; +      constructor = null; +    } else if (constructor && constructor instanceof Error) { +      desiredError = constructor; +      constructor = null; +      errMsg = null; +    } else if (typeof constructor === 'function') { +      name = (new constructor()).name; +    } else { +      constructor = null; +    } + +    try { +      obj(); +    } catch (err) { +      // first, check desired error +      if (desiredError) { +        this.assert( +            err === desiredError +          , 'expected #{this} to throw #{exp} but #{act} was thrown' +          , 'expected #{this} to not throw #{exp}' +          , desiredError +          , err +        ); + +        return this; +      } +      // next, check constructor +      if (constructor) { +        this.assert( +            err instanceof constructor +          , 'expected #{this} to throw #{exp} but #{act} was thrown' +          , 'expected #{this} to not throw #{exp} but #{act} was thrown' +          , name +          , err +        ); + +        if (!errMsg) return this; +      } +      // next, check message +      var message = 'object' === _.type(err) && "message" in err +        ? err.message +        : '' + err; + +      if ((message != null) && errMsg && errMsg instanceof RegExp) { +        this.assert( +            errMsg.exec(message) +          , 'expected #{this} to throw error matching #{exp} but got #{act}' +          , 'expected #{this} to throw error not matching #{exp}' +          , errMsg +          , message +        ); + +        return this; +      } else if ((message != null) && errMsg && 'string' === typeof errMsg) { +        this.assert( +            ~message.indexOf(errMsg) +          , 'expected #{this} to throw error including #{exp} but got #{act}' +          , 'expected #{this} to throw error not including #{act}' +          , errMsg +          , message +        ); + +        return this; +      } else { +        thrown = true; +        thrownError = err; +      } +    } + +    var actuallyGot = '' +      , expectedThrown = name !== null +        ? name +        : desiredError +          ? '#{exp}' //_.inspect(desiredError) +          : 'an error'; + +    if (thrown) { +      actuallyGot = ' but #{act} was thrown' +    } + +    this.assert( +        thrown === true +      , 'expected #{this} to throw ' + expectedThrown + actuallyGot +      , 'expected #{this} to not throw ' + expectedThrown + actuallyGot +      , desiredError +      , thrownError +    ); +  }; + +  Assertion.addMethod('throw', assertThrows); +  Assertion.addMethod('throws', assertThrows); +  Assertion.addMethod('Throw', assertThrows); + +  /** +   * ### .respondTo(method) +   * +   * Asserts that the object or class target will respond to a method. +   * +   *     Klass.prototype.bar = function(){}; +   *     expect(Klass).to.respondTo('bar'); +   *     expect(obj).to.respondTo('bar'); +   * +   * To check if a constructor will respond to a static function, +   * set the `itself` flag. +   * +   *    Klass.baz = function(){}; +   *    expect(Klass).itself.to.respondTo('baz'); +   * +   * @name respondTo +   * @param {String} method +   * @param {String} message _optional_ +   * @api public +   */ + +  Assertion.addMethod('respondTo', function (method, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object') +      , itself = flag(this, 'itself') +      , context = ('function' === _.type(obj) && !itself) +        ? obj.prototype[method] +        : obj[method]; + +    this.assert( +        'function' === typeof context +      , 'expected #{this} to respond to ' + _.inspect(method) +      , 'expected #{this} to not respond to ' + _.inspect(method) +    ); +  }); + +  /** +   * ### .itself +   * +   * Sets the `itself` flag, later used by the `respondTo` assertion. +   * +   *    function Foo() {} +   *    Foo.bar = function() {} +   *    Foo.prototype.baz = function() {} +   * +   *    expect(Foo).itself.to.respondTo('bar'); +   *    expect(Foo).itself.not.to.respondTo('baz'); +   * +   * @name itself +   * @api public +   */ + +  Assertion.addProperty('itself', function () { +    flag(this, 'itself', true); +  }); + +  /** +   * ### .satisfy(method) +   * +   * Asserts that the target passes a given truth test. +   * +   *     expect(1).to.satisfy(function(num) { return num > 0; }); +   * +   * @name satisfy +   * @param {Function} matcher +   * @param {String} message _optional_ +   * @api public +   */ + +  Assertion.addMethod('satisfy', function (matcher, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    this.assert( +        matcher(obj) +      , 'expected #{this} to satisfy ' + _.objDisplay(matcher) +      , 'expected #{this} to not satisfy' + _.objDisplay(matcher) +      , this.negate ? false : true +      , matcher(obj) +    ); +  }); + +  /** +   * ### .closeTo(expected, delta) +   * +   * Asserts that the target is equal `expected`, to within a +/- `delta` range. +   * +   *     expect(1.5).to.be.closeTo(1, 0.5); +   * +   * @name closeTo +   * @param {Number} expected +   * @param {Number} delta +   * @param {String} message _optional_ +   * @api public +   */ + +  Assertion.addMethod('closeTo', function (expected, delta, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); +    this.assert( +        Math.abs(obj - expected) <= delta +      , 'expected #{this} to be close to ' + expected + ' +/- ' + delta +      , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta +    ); +  }); + +  function isSubsetOf(subset, superset) { +    return subset.every(function(elem) { +      return superset.indexOf(elem) !== -1; +    }) +  } + +  /** +   * ### .members +   * +   * Asserts that the target is a superset of `set`, +   * or that the target and `set` have the same members. +   * +   *    expect([1, 2, 3]).to.include.members([3, 2]); +   *    expect([1, 2, 3]).to.not.include.members([3, 2, 8]); +   * +   *    expect([4, 2]).to.have.members([2, 4]); +   *    expect([5, 2]).to.not.have.members([5, 2, 1]); +   * +   * @name members +   * @param {Array} set +   * @param {String} message _optional_ +   * @api public +   */ + +  Assertion.addMethod('members', function (subset, msg) { +    if (msg) flag(this, 'message', msg); +    var obj = flag(this, 'object'); + +    new Assertion(obj).to.be.an('array'); +    new Assertion(subset).to.be.an('array'); + +    if (flag(this, 'contains')) { +      return this.assert( +          isSubsetOf(subset, obj) +        , 'expected #{this} to be a superset of #{act}' +        , 'expected #{this} to not be a superset of #{act}' +        , obj +        , subset +      ); +    } + +    this.assert( +        isSubsetOf(obj, subset) && isSubsetOf(subset, obj) +        , 'expected #{this} to have the same members as #{act}' +        , 'expected #{this} to not have the same members as #{act}' +        , obj +        , subset +    ); +  }); +}; + +}); +require.register("chai/lib/chai/interface/assert.js", function(exports, require, module){ +/*! + * chai + * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + + +module.exports = function (chai, util) { + +  /*! +   * Chai dependencies. +   */ + +  var Assertion = chai.Assertion +    , flag = util.flag; + +  /*! +   * Module export. +   */ + +  /** +   * ### assert(expression, message) +   * +   * Write your own test expressions. +   * +   *     assert('foo' !== 'bar', 'foo is not bar'); +   *     assert(Array.isArray([]), 'empty arrays are arrays'); +   * +   * @param {Mixed} expression to test for truthiness +   * @param {String} message to display on error +   * @name assert +   * @api public +   */ + +  var assert = chai.assert = function (express, errmsg) { +    var test = new Assertion(null); +    test.assert( +        express +      , errmsg +      , '[ negation message unavailable ]' +    ); +  }; + +  /** +   * ### .fail(actual, expected, [message], [operator]) +   * +   * Throw a failure. Node.js `assert` module-compatible. +   * +   * @name fail +   * @param {Mixed} actual +   * @param {Mixed} expected +   * @param {String} message +   * @param {String} operator +   * @api public +   */ + +  assert.fail = function (actual, expected, message, operator) { +    throw new chai.AssertionError({ +        actual: actual +      , expected: expected +      , message: message +      , operator: operator +      , stackStartFunction: assert.fail +    }); +  }; + +  /** +   * ### .ok(object, [message]) +   * +   * Asserts that `object` is truthy. +   * +   *     assert.ok('everything', 'everything is ok'); +   *     assert.ok(false, 'this will fail'); +   * +   * @name ok +   * @param {Mixed} object to test +   * @param {String} message +   * @api public +   */ + +  assert.ok = function (val, msg) { +    new Assertion(val, msg).is.ok; +  }; + +  /** +   * ### .equal(actual, expected, [message]) +   * +   * Asserts non-strict equality (`==`) of `actual` and `expected`. +   * +   *     assert.equal(3, '3', '== coerces values to strings'); +   * +   * @name equal +   * @param {Mixed} actual +   * @param {Mixed} expected +   * @param {String} message +   * @api public +   */ + +  assert.equal = function (act, exp, msg) { +    var test = new Assertion(act, msg); + +    test.assert( +        exp == flag(test, 'object') +      , 'expected #{this} to equal #{exp}' +      , 'expected #{this} to not equal #{act}' +      , exp +      , act +    ); +  }; + +  /** +   * ### .notEqual(actual, expected, [message]) +   * +   * Asserts non-strict inequality (`!=`) of `actual` and `expected`. +   * +   *     assert.notEqual(3, 4, 'these numbers are not equal'); +   * +   * @name notEqual +   * @param {Mixed} actual +   * @param {Mixed} expected +   * @param {String} message +   * @api public +   */ + +  assert.notEqual = function (act, exp, msg) { +    var test = new Assertion(act, msg); + +    test.assert( +        exp != flag(test, 'object') +      , 'expected #{this} to not equal #{exp}' +      , 'expected #{this} to equal #{act}' +      , exp +      , act +    ); +  }; + +  /** +   * ### .strictEqual(actual, expected, [message]) +   * +   * Asserts strict equality (`===`) of `actual` and `expected`. +   * +   *     assert.strictEqual(true, true, 'these booleans are strictly equal'); +   * +   * @name strictEqual +   * @param {Mixed} actual +   * @param {Mixed} expected +   * @param {String} message +   * @api public +   */ + +  assert.strictEqual = function (act, exp, msg) { +    new Assertion(act, msg).to.equal(exp); +  }; + +  /** +   * ### .notStrictEqual(actual, expected, [message]) +   * +   * Asserts strict inequality (`!==`) of `actual` and `expected`. +   * +   *     assert.notStrictEqual(3, '3', 'no coercion for strict equality'); +   * +   * @name notStrictEqual +   * @param {Mixed} actual +   * @param {Mixed} expected +   * @param {String} message +   * @api public +   */ + +  assert.notStrictEqual = function (act, exp, msg) { +    new Assertion(act, msg).to.not.equal(exp); +  }; + +  /** +   * ### .deepEqual(actual, expected, [message]) +   * +   * Asserts that `actual` is deeply equal to `expected`. +   * +   *     assert.deepEqual({ tea: 'green' }, { tea: 'green' }); +   * +   * @name deepEqual +   * @param {Mixed} actual +   * @param {Mixed} expected +   * @param {String} message +   * @api public +   */ + +  assert.deepEqual = function (act, exp, msg) { +    new Assertion(act, msg).to.eql(exp); +  }; + +  /** +   * ### .notDeepEqual(actual, expected, [message]) +   * +   * Assert that `actual` is not deeply equal to `expected`. +   * +   *     assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); +   * +   * @name notDeepEqual +   * @param {Mixed} actual +   * @param {Mixed} expected +   * @param {String} message +   * @api public +   */ + +  assert.notDeepEqual = function (act, exp, msg) { +    new Assertion(act, msg).to.not.eql(exp); +  }; + +  /** +   * ### .isTrue(value, [message]) +   * +   * Asserts that `value` is true. +   * +   *     var teaServed = true; +   *     assert.isTrue(teaServed, 'the tea has been served'); +   * +   * @name isTrue +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isTrue = function (val, msg) { +    new Assertion(val, msg).is['true']; +  }; + +  /** +   * ### .isFalse(value, [message]) +   * +   * Asserts that `value` is false. +   * +   *     var teaServed = false; +   *     assert.isFalse(teaServed, 'no tea yet? hmm...'); +   * +   * @name isFalse +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isFalse = function (val, msg) { +    new Assertion(val, msg).is['false']; +  }; + +  /** +   * ### .isNull(value, [message]) +   * +   * Asserts that `value` is null. +   * +   *     assert.isNull(err, 'there was no error'); +   * +   * @name isNull +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNull = function (val, msg) { +    new Assertion(val, msg).to.equal(null); +  }; + +  /** +   * ### .isNotNull(value, [message]) +   * +   * Asserts that `value` is not null. +   * +   *     var tea = 'tasty chai'; +   *     assert.isNotNull(tea, 'great, time for tea!'); +   * +   * @name isNotNull +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNotNull = function (val, msg) { +    new Assertion(val, msg).to.not.equal(null); +  }; + +  /** +   * ### .isUndefined(value, [message]) +   * +   * Asserts that `value` is `undefined`. +   * +   *     var tea; +   *     assert.isUndefined(tea, 'no tea defined'); +   * +   * @name isUndefined +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isUndefined = function (val, msg) { +    new Assertion(val, msg).to.equal(undefined); +  }; + +  /** +   * ### .isDefined(value, [message]) +   * +   * Asserts that `value` is not `undefined`. +   * +   *     var tea = 'cup of chai'; +   *     assert.isDefined(tea, 'tea has been defined'); +   * +   * @name isUndefined +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isDefined = function (val, msg) { +    new Assertion(val, msg).to.not.equal(undefined); +  }; + +  /** +   * ### .isFunction(value, [message]) +   * +   * Asserts that `value` is a function. +   * +   *     function serveTea() { return 'cup of tea'; }; +   *     assert.isFunction(serveTea, 'great, we can have tea now'); +   * +   * @name isFunction +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isFunction = function (val, msg) { +    new Assertion(val, msg).to.be.a('function'); +  }; + +  /** +   * ### .isNotFunction(value, [message]) +   * +   * Asserts that `value` is _not_ a function. +   * +   *     var serveTea = [ 'heat', 'pour', 'sip' ]; +   *     assert.isNotFunction(serveTea, 'great, we have listed the steps'); +   * +   * @name isNotFunction +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNotFunction = function (val, msg) { +    new Assertion(val, msg).to.not.be.a('function'); +  }; + +  /** +   * ### .isObject(value, [message]) +   * +   * Asserts that `value` is an object (as revealed by +   * `Object.prototype.toString`). +   * +   *     var selection = { name: 'Chai', serve: 'with spices' }; +   *     assert.isObject(selection, 'tea selection is an object'); +   * +   * @name isObject +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isObject = function (val, msg) { +    new Assertion(val, msg).to.be.a('object'); +  }; + +  /** +   * ### .isNotObject(value, [message]) +   * +   * Asserts that `value` is _not_ an object. +   * +   *     var selection = 'chai' +   *     assert.isObject(selection, 'tea selection is not an object'); +   *     assert.isObject(null, 'null is not an object'); +   * +   * @name isNotObject +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNotObject = function (val, msg) { +    new Assertion(val, msg).to.not.be.a('object'); +  }; + +  /** +   * ### .isArray(value, [message]) +   * +   * Asserts that `value` is an array. +   * +   *     var menu = [ 'green', 'chai', 'oolong' ]; +   *     assert.isArray(menu, 'what kind of tea do we want?'); +   * +   * @name isArray +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isArray = function (val, msg) { +    new Assertion(val, msg).to.be.an('array'); +  }; + +  /** +   * ### .isNotArray(value, [message]) +   * +   * Asserts that `value` is _not_ an array. +   * +   *     var menu = 'green|chai|oolong'; +   *     assert.isNotArray(menu, 'what kind of tea do we want?'); +   * +   * @name isNotArray +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNotArray = function (val, msg) { +    new Assertion(val, msg).to.not.be.an('array'); +  }; + +  /** +   * ### .isString(value, [message]) +   * +   * Asserts that `value` is a string. +   * +   *     var teaOrder = 'chai'; +   *     assert.isString(teaOrder, 'order placed'); +   * +   * @name isString +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isString = function (val, msg) { +    new Assertion(val, msg).to.be.a('string'); +  }; + +  /** +   * ### .isNotString(value, [message]) +   * +   * Asserts that `value` is _not_ a string. +   * +   *     var teaOrder = 4; +   *     assert.isNotString(teaOrder, 'order placed'); +   * +   * @name isNotString +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNotString = function (val, msg) { +    new Assertion(val, msg).to.not.be.a('string'); +  }; + +  /** +   * ### .isNumber(value, [message]) +   * +   * Asserts that `value` is a number. +   * +   *     var cups = 2; +   *     assert.isNumber(cups, 'how many cups'); +   * +   * @name isNumber +   * @param {Number} value +   * @param {String} message +   * @api public +   */ + +  assert.isNumber = function (val, msg) { +    new Assertion(val, msg).to.be.a('number'); +  }; + +  /** +   * ### .isNotNumber(value, [message]) +   * +   * Asserts that `value` is _not_ a number. +   * +   *     var cups = '2 cups please'; +   *     assert.isNotNumber(cups, 'how many cups'); +   * +   * @name isNotNumber +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNotNumber = function (val, msg) { +    new Assertion(val, msg).to.not.be.a('number'); +  }; + +  /** +   * ### .isBoolean(value, [message]) +   * +   * Asserts that `value` is a boolean. +   * +   *     var teaReady = true +   *       , teaServed = false; +   * +   *     assert.isBoolean(teaReady, 'is the tea ready'); +   *     assert.isBoolean(teaServed, 'has tea been served'); +   * +   * @name isBoolean +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isBoolean = function (val, msg) { +    new Assertion(val, msg).to.be.a('boolean'); +  }; + +  /** +   * ### .isNotBoolean(value, [message]) +   * +   * Asserts that `value` is _not_ a boolean. +   * +   *     var teaReady = 'yep' +   *       , teaServed = 'nope'; +   * +   *     assert.isNotBoolean(teaReady, 'is the tea ready'); +   *     assert.isNotBoolean(teaServed, 'has tea been served'); +   * +   * @name isNotBoolean +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.isNotBoolean = function (val, msg) { +    new Assertion(val, msg).to.not.be.a('boolean'); +  }; + +  /** +   * ### .typeOf(value, name, [message]) +   * +   * Asserts that `value`'s type is `name`, as determined by +   * `Object.prototype.toString`. +   * +   *     assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); +   *     assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); +   *     assert.typeOf('tea', 'string', 'we have a string'); +   *     assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); +   *     assert.typeOf(null, 'null', 'we have a null'); +   *     assert.typeOf(undefined, 'undefined', 'we have an undefined'); +   * +   * @name typeOf +   * @param {Mixed} value +   * @param {String} name +   * @param {String} message +   * @api public +   */ + +  assert.typeOf = function (val, type, msg) { +    new Assertion(val, msg).to.be.a(type); +  }; + +  /** +   * ### .notTypeOf(value, name, [message]) +   * +   * Asserts that `value`'s type is _not_ `name`, as determined by +   * `Object.prototype.toString`. +   * +   *     assert.notTypeOf('tea', 'number', 'strings are not numbers'); +   * +   * @name notTypeOf +   * @param {Mixed} value +   * @param {String} typeof name +   * @param {String} message +   * @api public +   */ + +  assert.notTypeOf = function (val, type, msg) { +    new Assertion(val, msg).to.not.be.a(type); +  }; + +  /** +   * ### .instanceOf(object, constructor, [message]) +   * +   * Asserts that `value` is an instance of `constructor`. +   * +   *     var Tea = function (name) { this.name = name; } +   *       , chai = new Tea('chai'); +   * +   *     assert.instanceOf(chai, Tea, 'chai is an instance of tea'); +   * +   * @name instanceOf +   * @param {Object} object +   * @param {Constructor} constructor +   * @param {String} message +   * @api public +   */ + +  assert.instanceOf = function (val, type, msg) { +    new Assertion(val, msg).to.be.instanceOf(type); +  }; + +  /** +   * ### .notInstanceOf(object, constructor, [message]) +   * +   * Asserts `value` is not an instance of `constructor`. +   * +   *     var Tea = function (name) { this.name = name; } +   *       , chai = new String('chai'); +   * +   *     assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); +   * +   * @name notInstanceOf +   * @param {Object} object +   * @param {Constructor} constructor +   * @param {String} message +   * @api public +   */ + +  assert.notInstanceOf = function (val, type, msg) { +    new Assertion(val, msg).to.not.be.instanceOf(type); +  }; + +  /** +   * ### .include(haystack, needle, [message]) +   * +   * Asserts that `haystack` includes `needle`. Works +   * for strings and arrays. +   * +   *     assert.include('foobar', 'bar', 'foobar contains string "bar"'); +   *     assert.include([ 1, 2, 3 ], 3, 'array contains value'); +   * +   * @name include +   * @param {Array|String} haystack +   * @param {Mixed} needle +   * @param {String} message +   * @api public +   */ + +  assert.include = function (exp, inc, msg) { +    var obj = new Assertion(exp, msg); + +    if (Array.isArray(exp)) { +      obj.to.include(inc); +    } else if ('string' === typeof exp) { +      obj.to.contain.string(inc); +    } else { +      throw new chai.AssertionError({ +          message: 'expected an array or string' +        , stackStartFunction: assert.include +      }); +    } +  }; + +  /** +   * ### .notInclude(haystack, needle, [message]) +   * +   * Asserts that `haystack` does not include `needle`. Works +   * for strings and arrays. +   *i +   *     assert.notInclude('foobar', 'baz', 'string not include substring'); +   *     assert.notInclude([ 1, 2, 3 ], 4, 'array not include contain value'); +   * +   * @name notInclude +   * @param {Array|String} haystack +   * @param {Mixed} needle +   * @param {String} message +   * @api public +   */ + +  assert.notInclude = function (exp, inc, msg) { +    var obj = new Assertion(exp, msg); + +    if (Array.isArray(exp)) { +      obj.to.not.include(inc); +    } else if ('string' === typeof exp) { +      obj.to.not.contain.string(inc); +    } else { +      throw new chai.AssertionError({ +          message: 'expected an array or string' +        , stackStartFunction: assert.include +      }); +    } +  }; + +  /** +   * ### .match(value, regexp, [message]) +   * +   * Asserts that `value` matches the regular expression `regexp`. +   * +   *     assert.match('foobar', /^foo/, 'regexp matches'); +   * +   * @name match +   * @param {Mixed} value +   * @param {RegExp} regexp +   * @param {String} message +   * @api public +   */ + +  assert.match = function (exp, re, msg) { +    new Assertion(exp, msg).to.match(re); +  }; + +  /** +   * ### .notMatch(value, regexp, [message]) +   * +   * Asserts that `value` does not match the regular expression `regexp`. +   * +   *     assert.notMatch('foobar', /^foo/, 'regexp does not match'); +   * +   * @name notMatch +   * @param {Mixed} value +   * @param {RegExp} regexp +   * @param {String} message +   * @api public +   */ + +  assert.notMatch = function (exp, re, msg) { +    new Assertion(exp, msg).to.not.match(re); +  }; + +  /** +   * ### .property(object, property, [message]) +   * +   * Asserts that `object` has a property named by `property`. +   * +   *     assert.property({ tea: { green: 'matcha' }}, 'tea'); +   * +   * @name property +   * @param {Object} object +   * @param {String} property +   * @param {String} message +   * @api public +   */ + +  assert.property = function (obj, prop, msg) { +    new Assertion(obj, msg).to.have.property(prop); +  }; + +  /** +   * ### .notProperty(object, property, [message]) +   * +   * Asserts that `object` does _not_ have a property named by `property`. +   * +   *     assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); +   * +   * @name notProperty +   * @param {Object} object +   * @param {String} property +   * @param {String} message +   * @api public +   */ + +  assert.notProperty = function (obj, prop, msg) { +    new Assertion(obj, msg).to.not.have.property(prop); +  }; + +  /** +   * ### .deepProperty(object, property, [message]) +   * +   * Asserts that `object` has a property named by `property`, which can be a +   * string using dot- and bracket-notation for deep reference. +   * +   *     assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green'); +   * +   * @name deepProperty +   * @param {Object} object +   * @param {String} property +   * @param {String} message +   * @api public +   */ + +  assert.deepProperty = function (obj, prop, msg) { +    new Assertion(obj, msg).to.have.deep.property(prop); +  }; + +  /** +   * ### .notDeepProperty(object, property, [message]) +   * +   * Asserts that `object` does _not_ have a property named by `property`, which +   * can be a string using dot- and bracket-notation for deep reference. +   * +   *     assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); +   * +   * @name notDeepProperty +   * @param {Object} object +   * @param {String} property +   * @param {String} message +   * @api public +   */ + +  assert.notDeepProperty = function (obj, prop, msg) { +    new Assertion(obj, msg).to.not.have.deep.property(prop); +  }; + +  /** +   * ### .propertyVal(object, property, value, [message]) +   * +   * Asserts that `object` has a property named by `property` with value given +   * by `value`. +   * +   *     assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); +   * +   * @name propertyVal +   * @param {Object} object +   * @param {String} property +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.propertyVal = function (obj, prop, val, msg) { +    new Assertion(obj, msg).to.have.property(prop, val); +  }; + +  /** +   * ### .propertyNotVal(object, property, value, [message]) +   * +   * Asserts that `object` has a property named by `property`, but with a value +   * different from that given by `value`. +   * +   *     assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad'); +   * +   * @name propertyNotVal +   * @param {Object} object +   * @param {String} property +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.propertyNotVal = function (obj, prop, val, msg) { +    new Assertion(obj, msg).to.not.have.property(prop, val); +  }; + +  /** +   * ### .deepPropertyVal(object, property, value, [message]) +   * +   * Asserts that `object` has a property named by `property` with value given +   * by `value`. `property` can use dot- and bracket-notation for deep +   * reference. +   * +   *     assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); +   * +   * @name deepPropertyVal +   * @param {Object} object +   * @param {String} property +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.deepPropertyVal = function (obj, prop, val, msg) { +    new Assertion(obj, msg).to.have.deep.property(prop, val); +  }; + +  /** +   * ### .deepPropertyNotVal(object, property, value, [message]) +   * +   * Asserts that `object` has a property named by `property`, but with a value +   * different from that given by `value`. `property` can use dot- and +   * bracket-notation for deep reference. +   * +   *     assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); +   * +   * @name deepPropertyNotVal +   * @param {Object} object +   * @param {String} property +   * @param {Mixed} value +   * @param {String} message +   * @api public +   */ + +  assert.deepPropertyNotVal = function (obj, prop, val, msg) { +    new Assertion(obj, msg).to.not.have.deep.property(prop, val); +  }; + +  /** +   * ### .lengthOf(object, length, [message]) +   * +   * Asserts that `object` has a `length` property with the expected value. +   * +   *     assert.lengthOf([1,2,3], 3, 'array has length of 3'); +   *     assert.lengthOf('foobar', 5, 'string has length of 6'); +   * +   * @name lengthOf +   * @param {Mixed} object +   * @param {Number} length +   * @param {String} message +   * @api public +   */ + +  assert.lengthOf = function (exp, len, msg) { +    new Assertion(exp, msg).to.have.length(len); +  }; + +  /** +   * ### .throws(function, [constructor/string/regexp], [string/regexp], [message]) +   * +   * Asserts that `function` will throw an error that is an instance of +   * `constructor`, or alternately that it will throw an error with message +   * matching `regexp`. +   * +   *     assert.throw(fn, 'function throws a reference error'); +   *     assert.throw(fn, /function throws a reference error/); +   *     assert.throw(fn, ReferenceError); +   *     assert.throw(fn, ReferenceError, 'function throws a reference error'); +   *     assert.throw(fn, ReferenceError, /function throws a reference error/); +   * +   * @name throws +   * @alias throw +   * @alias Throw +   * @param {Function} function +   * @param {ErrorConstructor} constructor +   * @param {RegExp} regexp +   * @param {String} message +   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types +   * @api public +   */ + +  assert.Throw = function (fn, errt, errs, msg) { +    if ('string' === typeof errt || errt instanceof RegExp) { +      errs = errt; +      errt = null; +    } + +    new Assertion(fn, msg).to.Throw(errt, errs); +  }; + +  /** +   * ### .doesNotThrow(function, [constructor/regexp], [message]) +   * +   * Asserts that `function` will _not_ throw an error that is an instance of +   * `constructor`, or alternately that it will not throw an error with message +   * matching `regexp`. +   * +   *     assert.doesNotThrow(fn, Error, 'function does not throw'); +   * +   * @name doesNotThrow +   * @param {Function} function +   * @param {ErrorConstructor} constructor +   * @param {RegExp} regexp +   * @param {String} message +   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types +   * @api public +   */ + +  assert.doesNotThrow = function (fn, type, msg) { +    if ('string' === typeof type) { +      msg = type; +      type = null; +    } + +    new Assertion(fn, msg).to.not.Throw(type); +  }; + +  /** +   * ### .operator(val1, operator, val2, [message]) +   * +   * Compares two values using `operator`. +   * +   *     assert.operator(1, '<', 2, 'everything is ok'); +   *     assert.operator(1, '>', 2, 'this will fail'); +   * +   * @name operator +   * @param {Mixed} val1 +   * @param {String} operator +   * @param {Mixed} val2 +   * @param {String} message +   * @api public +   */ + +  assert.operator = function (val, operator, val2, msg) { +    if (!~['==', '===', '>', '>=', '<', '<=', '!=', '!=='].indexOf(operator)) { +      throw new Error('Invalid operator "' + operator + '"'); +    } +    var test = new Assertion(eval(val + operator + val2), msg); +    test.assert( +        true === flag(test, 'object') +      , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) +      , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); +  }; + +  /** +   * ### .closeTo(actual, expected, delta, [message]) +   * +   * Asserts that the target is equal `expected`, to within a +/- `delta` range. +   * +   *     assert.closeTo(1.5, 1, 0.5, 'numbers are close'); +   * +   * @name closeTo +   * @param {Number} actual +   * @param {Number} expected +   * @param {Number} delta +   * @param {String} message +   * @api public +   */ + +  assert.closeTo = function (act, exp, delta, msg) { +    new Assertion(act, msg).to.be.closeTo(exp, delta); +  }; + +  /** +   * ### .sameMembers(set1, set2, [message]) +   * +   * Asserts that `set1` and `set2` have the same members. +   * Order is not taken into account. +   * +   *     assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); +   * +   * @name sameMembers +   * @param {Array} superset +   * @param {Array} subset +   * @param {String} message +   * @api public +   */ + +  assert.sameMembers = function (set1, set2, msg) { +    new Assertion(set1, msg).to.have.same.members(set2); +  } + +  /** +   * ### .includeMembers(superset, subset, [message]) +   * +   * Asserts that `subset` is included in `superset`. +   * Order is not taken into account. +   * +   *     assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members'); +   * +   * @name includeMembers +   * @param {Array} superset +   * @param {Array} subset +   * @param {String} message +   * @api public +   */ + +  assert.includeMembers = function (superset, subset, msg) { +    new Assertion(superset, msg).to.include.members(subset); +  } + +  /*! +   * Undocumented / untested +   */ + +  assert.ifError = function (val, msg) { +    new Assertion(val, msg).to.not.be.ok; +  }; + +  /*! +   * Aliases. +   */ + +  (function alias(name, as){ +    assert[as] = assert[name]; +    return alias; +  }) +  ('Throw', 'throw') +  ('Throw', 'throws'); +}; + +}); +require.register("chai/lib/chai/interface/expect.js", function(exports, require, module){ +/*! + * chai + * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +module.exports = function (chai, util) { +  chai.expect = function (val, message) { +    return new chai.Assertion(val, message); +  }; +}; + + +}); +require.register("chai/lib/chai/interface/should.js", function(exports, require, module){ +/*! + * chai + * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +module.exports = function (chai, util) { +  var Assertion = chai.Assertion; + +  function loadShould () { +    // modify Object.prototype to have `should` +    Object.defineProperty(Object.prototype, 'should', +      { +        set: function (value) { +          // See https://github.com/chaijs/chai/issues/86: this makes +          // `whatever.should = someValue` actually set `someValue`, which is +          // especially useful for `global.should = require('chai').should()`. +          // +          // Note that we have to use [[DefineProperty]] instead of [[Put]] +          // since otherwise we would trigger this very setter! +          Object.defineProperty(this, 'should', { +            value: value, +            enumerable: true, +            configurable: true, +            writable: true +          }); +        } +      , get: function(){ +          if (this instanceof String || this instanceof Number) { +            return new Assertion(this.constructor(this)); +          } else if (this instanceof Boolean) { +            return new Assertion(this == true); +          } +          return new Assertion(this); +        } +      , configurable: true +    }); + +    var should = {}; + +    should.equal = function (val1, val2, msg) { +      new Assertion(val1, msg).to.equal(val2); +    }; + +    should.Throw = function (fn, errt, errs, msg) { +      new Assertion(fn, msg).to.Throw(errt, errs); +    }; + +    should.exist = function (val, msg) { +      new Assertion(val, msg).to.exist; +    } + +    // negation +    should.not = {} + +    should.not.equal = function (val1, val2, msg) { +      new Assertion(val1, msg).to.not.equal(val2); +    }; + +    should.not.Throw = function (fn, errt, errs, msg) { +      new Assertion(fn, msg).to.not.Throw(errt, errs); +    }; + +    should.not.exist = function (val, msg) { +      new Assertion(val, msg).to.not.exist; +    } + +    should['throw'] = should['Throw']; +    should.not['throw'] = should.not['Throw']; + +    return should; +  }; + +  chai.should = loadShould; +  chai.Should = loadShould; +}; + +}); +require.register("chai/lib/chai/utils/addChainableMethod.js", function(exports, require, module){ +/*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Module dependencies + */ + +var transferFlags = require('./transferFlags'); + +/*! + * Module variables + */ + +// Check whether `__proto__` is supported +var hasProtoSupport = '__proto__' in Object; + +// Without `__proto__` support, this module will need to add properties to a function. +// However, some Function.prototype methods cannot be overwritten, +// and there seems no easy cross-platform way to detect them (@see chaijs/chai/issues/69). +var excludeNames = /^(?:length|name|arguments|caller)$/; + +// Cache `Function` properties +var call  = Function.prototype.call, +    apply = Function.prototype.apply; + +/** + * ### addChainableMethod (ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + *     utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + *       var obj = utils.flag(this, 'object'); + *       new chai.Assertion(obj).to.be.equal(str); + *     }); + * + * Can also be accessed directly from `chai.Assertion`. + * + *     chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + *     expect(fooStr).to.be.foo('bar'); + *     expect(fooStr).to.be.foo.equal('foo'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @name addChainableMethod + * @api public + */ + +module.exports = function (ctx, name, method, chainingBehavior) { +  if (typeof chainingBehavior !== 'function') +    chainingBehavior = function () { }; + +  Object.defineProperty(ctx, name, +    { get: function () { +        chainingBehavior.call(this); + +        var assert = function () { +          var result = method.apply(this, arguments); +          return result === undefined ? this : result; +        }; + +        // Use `__proto__` if available +        if (hasProtoSupport) { +          // Inherit all properties from the object by replacing the `Function` prototype +          var prototype = assert.__proto__ = Object.create(this); +          // Restore the `call` and `apply` methods from `Function` +          prototype.call = call; +          prototype.apply = apply; +        } +        // Otherwise, redefine all properties (slow!) +        else { +          var asserterNames = Object.getOwnPropertyNames(ctx); +          asserterNames.forEach(function (asserterName) { +            if (!excludeNames.test(asserterName)) { +              var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); +              Object.defineProperty(assert, asserterName, pd); +            } +          }); +        } + +        transferFlags(this, assert); +        return assert; +      } +    , configurable: true +  }); +}; + +}); +require.register("chai/lib/chai/utils/addMethod.js", function(exports, require, module){ +/*! + * Chai - addMethod utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### .addMethod (ctx, name, method) + * + * Adds a method to the prototype of an object. + * + *     utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { + *       var obj = utils.flag(this, 'object'); + *       new chai.Assertion(obj).to.be.equal(str); + *     }); + * + * Can also be accessed directly from `chai.Assertion`. + * + *     chai.Assertion.addMethod('foo', fn); + * + * Then can be used as any other assertion. + * + *     expect(fooStr).to.be.foo('bar'); + * + * @param {Object} ctx object to which the method is added + * @param {String} name of method to add + * @param {Function} method function to be used for name + * @name addMethod + * @api public + */ + +module.exports = function (ctx, name, method) { +  ctx[name] = function () { +    var result = method.apply(this, arguments); +    return result === undefined ? this : result; +  }; +}; + +}); +require.register("chai/lib/chai/utils/addProperty.js", function(exports, require, module){ +/*! + * Chai - addProperty utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### addProperty (ctx, name, getter) + * + * Adds a property to the prototype of an object. + * + *     utils.addProperty(chai.Assertion.prototype, 'foo', function () { + *       var obj = utils.flag(this, 'object'); + *       new chai.Assertion(obj).to.be.instanceof(Foo); + *     }); + * + * Can also be accessed directly from `chai.Assertion`. + * + *     chai.Assertion.addProperty('foo', fn); + * + * Then can be used as any other assertion. + * + *     expect(myFoo).to.be.foo; + * + * @param {Object} ctx object to which the property is added + * @param {String} name of property to add + * @param {Function} getter function to be used for name + * @name addProperty + * @api public + */ + +module.exports = function (ctx, name, getter) { +  Object.defineProperty(ctx, name, +    { get: function () { +        var result = getter.call(this); +        return result === undefined ? this : result; +      } +    , configurable: true +  }); +}; + +}); +require.register("chai/lib/chai/utils/eql.js", function(exports, require, module){ +// This is (almost) directly from Node.js assert +// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/assert.js + +module.exports = _deepEqual; + +var getEnumerableProperties = require('./getEnumerableProperties'); + +// for the browser +var Buffer; +try { +  Buffer = require('buffer').Buffer; +} catch (ex) { +  Buffer = { +    isBuffer: function () { return false; } +  }; +} + +function _deepEqual(actual, expected, memos) { + +  // 7.1. All identical values are equivalent, as determined by ===. +  if (actual === expected) { +    return true; + +  } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { +    if (actual.length != expected.length) return false; + +    for (var i = 0; i < actual.length; i++) { +      if (actual[i] !== expected[i]) return false; +    } + +    return true; + +  // 7.2. If the expected value is a Date object, the actual value is +  // equivalent if it is also a Date object that refers to the same time. +  } else if (actual instanceof Date && expected instanceof Date) { +    return actual.getTime() === expected.getTime(); + +  // 7.3. Other pairs that do not both pass typeof value == 'object', +  // equivalence is determined by ==. +  } else if (typeof actual != 'object' && typeof expected != 'object') { +    return actual === expected; + +  // 7.4. For all other Object pairs, including Array objects, equivalence is +  // determined by having the same number of owned properties (as verified +  // with Object.prototype.hasOwnProperty.call), the same set of keys +  // (although not necessarily the same order), equivalent values for every +  // corresponding key, and an identical 'prototype' property. Note: this +  // accounts for both named and indexed properties on Arrays. +  } else { +    return objEquiv(actual, expected, memos); +  } +} + +function isUndefinedOrNull(value) { +  return value === null || value === undefined; +} + +function isArguments(object) { +  return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b, memos) { +  if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) +    return false; + +  // an identical 'prototype' property. +  if (a.prototype !== b.prototype) return false; + +  // check if we have already compared a and b +  var i; +  if (memos) { +    for(i = 0; i < memos.length; i++) { +      if ((memos[i][0] === a && memos[i][1] === b) || +          (memos[i][0] === b && memos[i][1] === a)) +        return true; +    } +  } else { +    memos = []; +  } + +  //~~~I've managed to break Object.keys through screwy arguments passing. +  //   Converting to array solves the problem. +  if (isArguments(a)) { +    if (!isArguments(b)) { +      return false; +    } +    a = pSlice.call(a); +    b = pSlice.call(b); +    return _deepEqual(a, b, memos); +  } +  try { +    var ka = getEnumerableProperties(a), +        kb = getEnumerableProperties(b), +        key; +  } catch (e) {//happens when one is a string literal and the other isn't +    return false; +  } + +  // having the same number of owned properties (keys incorporates +  // hasOwnProperty) +  if (ka.length != kb.length) +    return false; + +  //the same set of keys (although not necessarily the same order), +  ka.sort(); +  kb.sort(); +  //~~~cheap key test +  for (i = ka.length - 1; i >= 0; i--) { +    if (ka[i] != kb[i]) +      return false; +  } + +  // remember objects we have compared to guard against circular references +  memos.push([ a, b ]); + +  //equivalent values for every corresponding key, and +  //~~~possibly expensive deep test +  for (i = ka.length - 1; i >= 0; i--) { +    key = ka[i]; +    if (!_deepEqual(a[key], b[key], memos)) return false; +  } + +  return true; +} + +}); +require.register("chai/lib/chai/utils/flag.js", function(exports, require, module){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### flag(object ,key, [value]) + * + * Get or set a flag value on an object. If a + * value is provided it will be set, else it will + * return the currently set value or `undefined` if + * the value is not set. + * + *     utils.flag(this, 'foo', 'bar'); // setter + *     utils.flag(this, 'foo'); // getter, returns `bar` + * + * @param {Object} object (constructed Assertion + * @param {String} key + * @param {Mixed} value (optional) + * @name flag + * @api private + */ + +module.exports = function (obj, key, value) { +  var flags = obj.__flags || (obj.__flags = Object.create(null)); +  if (arguments.length === 3) { +    flags[key] = value; +  } else { +    return flags[key]; +  } +}; + +}); +require.register("chai/lib/chai/utils/getActual.js", function(exports, require, module){ +/*! + * Chai - getActual utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * # getActual(object, [actual]) + * + * Returns the `actual` value for an Assertion + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + */ + +module.exports = function (obj, args) { +  var actual = args[4]; +  return 'undefined' !== typeof actual ? actual : obj._obj; +}; + +}); +require.register("chai/lib/chai/utils/getEnumerableProperties.js", function(exports, require, module){ +/*! + * Chai - getEnumerableProperties utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### .getEnumerableProperties(object) + * + * This allows the retrieval of enumerable property names of an object, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @name getEnumerableProperties + * @api public + */ + +module.exports = function getEnumerableProperties(object) { +  var result = []; +  for (var name in object) { +    result.push(name); +  } +  return result; +}; + +}); +require.register("chai/lib/chai/utils/getMessage.js", function(exports, require, module){ +/*! + * Chai - message composition utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Module dependancies + */ + +var flag = require('./flag') +  , getActual = require('./getActual') +  , inspect = require('./inspect') +  , objDisplay = require('./objDisplay'); + +/** + * ### .getMessage(object, message, negateMessage) + * + * Construct the error message based on flags + * and template tags. Template tags will return + * a stringified inspection of the object referenced. + * + * Messsage template tags: + * - `#{this}` current asserted object + * - `#{act}` actual value + * - `#{exp}` expected value + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + * @name getMessage + * @api public + */ + +module.exports = function (obj, args) { +  var negate = flag(obj, 'negate') +    , val = flag(obj, 'object') +    , expected = args[3] +    , actual = getActual(obj, args) +    , msg = negate ? args[2] : args[1] +    , flagMsg = flag(obj, 'message'); + +  msg = msg || ''; +  msg = msg +    .replace(/#{this}/g, objDisplay(val)) +    .replace(/#{act}/g, objDisplay(actual)) +    .replace(/#{exp}/g, objDisplay(expected)); + +  return flagMsg ? flagMsg + ': ' + msg : msg; +}; + +}); +require.register("chai/lib/chai/utils/getName.js", function(exports, require, module){ +/*! + * Chai - getName utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * # getName(func) + * + * Gets the name of a function, in a cross-browser way. + * + * @param {Function} a function (usually a constructor) + */ + +module.exports = function (func) { +  if (func.name) return func.name; + +  var match = /^\s?function ([^(]*)\(/.exec(func); +  return match && match[1] ? match[1] : ""; +}; + +}); +require.register("chai/lib/chai/utils/getPathValue.js", function(exports, require, module){ +/*! + * Chai - getPathValue utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * @see https://github.com/logicalparadox/filtr + * MIT Licensed + */ + +/** + * ### .getPathValue(path, object) + * + * This allows the retrieval of values in an + * object given a string path. + * + *     var obj = { + *         prop1: { + *             arr: ['a', 'b', 'c'] + *           , str: 'Hello' + *         } + *       , prop2: { + *             arr: [ { nested: 'Universe' } ] + *           , str: 'Hello again!' + *         } + *     } + * + * The following would be the results. + * + *     getPathValue('prop1.str', obj); // Hello + *     getPathValue('prop1.att[2]', obj); // b + *     getPathValue('prop2.arr[0].nested', obj); // Universe + * + * @param {String} path + * @param {Object} object + * @returns {Object} value or `undefined` + * @name getPathValue + * @api public + */ + +var getPathValue = module.exports = function (path, obj) { +  var parsed = parsePath(path); +  return _getPathValue(parsed, obj); +}; + +/*! + * ## parsePath(path) + * + * Helper function used to parse string object + * paths. Use in conjunction with `_getPathValue`. + * + *      var parsed = parsePath('myobject.property.subprop'); + * + * ### Paths: + * + * * Can be as near infinitely deep and nested + * * Arrays are also valid using the formal `myobject.document[3].property`. + * + * @param {String} path + * @returns {Object} parsed + * @api private + */ + +function parsePath (path) { +  var str = path.replace(/\[/g, '.[') +    , parts = str.match(/(\\\.|[^.]+?)+/g); +  return parts.map(function (value) { +    var re = /\[(\d+)\]$/ +      , mArr = re.exec(value) +    if (mArr) return { i: parseFloat(mArr[1]) }; +    else return { p: value }; +  }); +}; + +/*! + * ## _getPathValue(parsed, obj) + * + * Helper companion function for `.parsePath` that returns + * the value located at the parsed address. + * + *      var value = getPathValue(parsed, obj); + * + * @param {Object} parsed definition from `parsePath`. + * @param {Object} object to search against + * @returns {Object|Undefined} value + * @api private + */ + +function _getPathValue (parsed, obj) { +  var tmp = obj +    , res; +  for (var i = 0, l = parsed.length; i < l; i++) { +    var part = parsed[i]; +    if (tmp) { +      if ('undefined' !== typeof part.p) +        tmp = tmp[part.p]; +      else if ('undefined' !== typeof part.i) +        tmp = tmp[part.i]; +      if (i == (l - 1)) res = tmp; +    } else { +      res = undefined; +    } +  } +  return res; +}; + +}); +require.register("chai/lib/chai/utils/getProperties.js", function(exports, require, module){ +/*! + * Chai - getProperties utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### .getProperties(object) + * + * This allows the retrieval of property names of an object, enumerable or not, + * inherited or not. + * + * @param {Object} object + * @returns {Array} + * @name getProperties + * @api public + */ + +module.exports = function getProperties(object) { +  var result = Object.getOwnPropertyNames(subject); + +  function addProperty(property) { +    if (result.indexOf(property) === -1) { +      result.push(property); +    } +  } + +  var proto = Object.getPrototypeOf(subject); +  while (proto !== null) { +    Object.getOwnPropertyNames(proto).forEach(addProperty); +    proto = Object.getPrototypeOf(proto); +  } + +  return result; +}; + +}); +require.register("chai/lib/chai/utils/index.js", function(exports, require, module){ +/*! + * chai + * Copyright(c) 2011 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Main exports + */ + +var exports = module.exports = {}; + +/*! + * test utility + */ + +exports.test = require('./test'); + +/*! + * type utility + */ + +exports.type = require('./type'); + +/*! + * message utility + */ + +exports.getMessage = require('./getMessage'); + +/*! + * actual utility + */ + +exports.getActual = require('./getActual'); + +/*! + * Inspect util + */ + +exports.inspect = require('./inspect'); + +/*! + * Object Display util + */ + +exports.objDisplay = require('./objDisplay'); + +/*! + * Flag utility + */ + +exports.flag = require('./flag'); + +/*! + * Flag transferring utility + */ + +exports.transferFlags = require('./transferFlags'); + +/*! + * Deep equal utility + */ + +exports.eql = require('./eql'); + +/*! + * Deep path value + */ + +exports.getPathValue = require('./getPathValue'); + +/*! + * Function name + */ + +exports.getName = require('./getName'); + +/*! + * add Property + */ + +exports.addProperty = require('./addProperty'); + +/*! + * add Method + */ + +exports.addMethod = require('./addMethod'); + +/*! + * overwrite Property + */ + +exports.overwriteProperty = require('./overwriteProperty'); + +/*! + * overwrite Method + */ + +exports.overwriteMethod = require('./overwriteMethod'); + +/*! + * Add a chainable method + */ + +exports.addChainableMethod = require('./addChainableMethod'); + + +}); +require.register("chai/lib/chai/utils/inspect.js", function(exports, require, module){ +// This is (almost) directly from Node.js utils +// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js + +var getName = require('./getName'); +var getProperties = require('./getProperties'); +var getEnumerableProperties = require('./getEnumerableProperties'); + +module.exports = inspect; + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Boolean} showHidden Flag that shows hidden (not enumerable) + *    properties of objects. + * @param {Number} depth Depth in which to descend in object. Default is 2. + * @param {Boolean} colors Flag to turn on ANSI escape codes to color the + *    output. Default is false (no coloring). + */ +function inspect(obj, showHidden, depth, colors) { +  var ctx = { +    showHidden: showHidden, +    seen: [], +    stylize: function (str) { return str; } +  }; +  return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); +} + +// https://gist.github.com/1044128/ +var getOuterHTML = function(element) { +  if ('outerHTML' in element) return element.outerHTML; +  var ns = "http://www.w3.org/1999/xhtml"; +  var container = document.createElementNS(ns, '_'); +  var elemProto = (window.HTMLElement || window.Element).prototype; +  var xmlSerializer = new XMLSerializer(); +  var html; +  if (document.xmlVersion) { +    return xmlSerializer.serializeToString(element); +  } else { +    container.appendChild(element.cloneNode(false)); +    html = container.innerHTML.replace('><', '>' + element.innerHTML + '<'); +    container.innerHTML = ''; +    return html; +  } +}; + +// Returns true if object is a DOM element. +var isDOMElement = function (object) { +  if (typeof HTMLElement === 'object') { +    return object instanceof HTMLElement; +  } else { +    return object && +      typeof object === 'object' && +      object.nodeType === 1 && +      typeof object.nodeName === 'string'; +  } +}; + +function formatValue(ctx, value, recurseTimes) { +  // Provide a hook for user-specified inspect functions. +  // Check that value is an object with an inspect function on it +  if (value && typeof value.inspect === 'function' && +      // Filter out the util module, it's inspect function is special +      value.inspect !== exports.inspect && +      // Also filter out any prototype objects using the circular check. +      !(value.constructor && value.constructor.prototype === value)) { +    return value.inspect(recurseTimes); +  } + +  // Primitive types cannot have properties +  var primitive = formatPrimitive(ctx, value); +  if (primitive) { +    return primitive; +  } + +  // If it's DOM elem, get outer HTML. +  if (isDOMElement(value)) { +    return getOuterHTML(value); +  } + +  // Look up the keys of the object. +  var visibleKeys = getEnumerableProperties(value); +  var keys = ctx.showHidden ? getProperties(value) : visibleKeys; + +  // Some type of object without properties can be shortcutted. +  // In IE, errors have a single `stack` property, or if they are vanilla `Error`, +  // a `stack` plus `description` property; ignore those for consistency. +  if (keys.length === 0 || (isError(value) && ( +      (keys.length === 1 && keys[0] === 'stack') || +      (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') +     ))) { +    if (typeof value === 'function') { +      var name = getName(value); +      var nameSuffix = name ? ': ' + name : ''; +      return ctx.stylize('[Function' + nameSuffix + ']', 'special'); +    } +    if (isRegExp(value)) { +      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +    } +    if (isDate(value)) { +      return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); +    } +    if (isError(value)) { +      return formatError(value); +    } +  } + +  var base = '', array = false, braces = ['{', '}']; + +  // Make Array say that they are Array +  if (isArray(value)) { +    array = true; +    braces = ['[', ']']; +  } + +  // Make functions say that they are functions +  if (typeof value === 'function') { +    var name = getName(value); +    var nameSuffix = name ? ': ' + name : ''; +    base = ' [Function' + nameSuffix + ']'; +  } + +  // Make RegExps say that they are RegExps +  if (isRegExp(value)) { +    base = ' ' + RegExp.prototype.toString.call(value); +  } + +  // Make dates with properties first say the date +  if (isDate(value)) { +    base = ' ' + Date.prototype.toUTCString.call(value); +  } + +  // Make error with message first say the error +  if (isError(value)) { +    return formatError(value); +  } + +  if (keys.length === 0 && (!array || value.length == 0)) { +    return braces[0] + base + braces[1]; +  } + +  if (recurseTimes < 0) { +    if (isRegExp(value)) { +      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +    } else { +      return ctx.stylize('[Object]', 'special'); +    } +  } + +  ctx.seen.push(value); + +  var output; +  if (array) { +    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +  } else { +    output = keys.map(function(key) { +      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +    }); +  } + +  ctx.seen.pop(); + +  return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { +  switch (typeof value) { +    case 'undefined': +      return ctx.stylize('undefined', 'undefined'); + +    case 'string': +      var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +                                               .replace(/'/g, "\\'") +                                               .replace(/\\"/g, '"') + '\''; +      return ctx.stylize(simple, 'string'); + +    case 'number': +      return ctx.stylize('' + value, 'number'); + +    case 'boolean': +      return ctx.stylize('' + value, 'boolean'); +  } +  // For some reason typeof null is "object", so special case here. +  if (value === null) { +    return ctx.stylize('null', 'null'); +  } +} + + +function formatError(value) { +  return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +  var output = []; +  for (var i = 0, l = value.length; i < l; ++i) { +    if (Object.prototype.hasOwnProperty.call(value, String(i))) { +      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +          String(i), true)); +    } else { +      output.push(''); +    } +  } +  keys.forEach(function(key) { +    if (!key.match(/^\d+$/)) { +      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +          key, true)); +    } +  }); +  return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +  var name, str; +  if (value.__lookupGetter__) { +    if (value.__lookupGetter__(key)) { +      if (value.__lookupSetter__(key)) { +        str = ctx.stylize('[Getter/Setter]', 'special'); +      } else { +        str = ctx.stylize('[Getter]', 'special'); +      } +    } else { +      if (value.__lookupSetter__(key)) { +        str = ctx.stylize('[Setter]', 'special'); +      } +    } +  } +  if (visibleKeys.indexOf(key) < 0) { +    name = '[' + key + ']'; +  } +  if (!str) { +    if (ctx.seen.indexOf(value[key]) < 0) { +      if (recurseTimes === null) { +        str = formatValue(ctx, value[key], null); +      } else { +        str = formatValue(ctx, value[key], recurseTimes - 1); +      } +      if (str.indexOf('\n') > -1) { +        if (array) { +          str = str.split('\n').map(function(line) { +            return '  ' + line; +          }).join('\n').substr(2); +        } else { +          str = '\n' + str.split('\n').map(function(line) { +            return '   ' + line; +          }).join('\n'); +        } +      } +    } else { +      str = ctx.stylize('[Circular]', 'special'); +    } +  } +  if (typeof name === 'undefined') { +    if (array && key.match(/^\d+$/)) { +      return str; +    } +    name = JSON.stringify('' + key); +    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +      name = name.substr(1, name.length - 2); +      name = ctx.stylize(name, 'name'); +    } else { +      name = name.replace(/'/g, "\\'") +                 .replace(/\\"/g, '"') +                 .replace(/(^"|"$)/g, "'"); +      name = ctx.stylize(name, 'string'); +    } +  } + +  return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { +  var numLinesEst = 0; +  var length = output.reduce(function(prev, cur) { +    numLinesEst++; +    if (cur.indexOf('\n') >= 0) numLinesEst++; +    return prev + cur.length + 1; +  }, 0); + +  if (length > 60) { +    return braces[0] + +           (base === '' ? '' : base + '\n ') + +           ' ' + +           output.join(',\n  ') + +           ' ' + +           braces[1]; +  } + +  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + +function isArray(ar) { +  return Array.isArray(ar) || +         (typeof ar === 'object' && objectToString(ar) === '[object Array]'); +} + +function isRegExp(re) { +  return typeof re === 'object' && objectToString(re) === '[object RegExp]'; +} + +function isDate(d) { +  return typeof d === 'object' && objectToString(d) === '[object Date]'; +} + +function isError(e) { +  return typeof e === 'object' && objectToString(e) === '[object Error]'; +} + +function objectToString(o) { +  return Object.prototype.toString.call(o); +} + +}); +require.register("chai/lib/chai/utils/objDisplay.js", function(exports, require, module){ +/*! + * Chai - flag utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Module dependancies + */ + +var inspect = require('./inspect'); + +/** + * ### .objDisplay (object) + * + * Determines if an object or an array matches + * criteria to be inspected in-line for error + * messages or should be truncated. + * + * @param {Mixed} javascript object to inspect + * @name objDisplay + * @api public + */ + +module.exports = function (obj) { +  var str = inspect(obj) +    , type = Object.prototype.toString.call(obj); + +  if (str.length >= 40) { +    if (type === '[object Function]') { +      return !obj.name || obj.name === '' +        ? '[Function]' +        : '[Function: ' + obj.name + ']'; +    } else if (type === '[object Array]') { +      return '[ Array(' + obj.length + ') ]'; +    } else if (type === '[object Object]') { +      var keys = Object.keys(obj) +        , kstr = keys.length > 2 +          ? keys.splice(0, 2).join(', ') + ', ...' +          : keys.join(', '); +      return '{ Object (' + kstr + ') }'; +    } else { +      return str; +    } +  } else { +    return str; +  } +}; + +}); +require.register("chai/lib/chai/utils/overwriteMethod.js", function(exports, require, module){ +/*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### overwriteMethod (ctx, name, fn) + * + * Overwites an already existing method and provides + * access to previous function. Must return function + * to be used for name. + * + *     utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { + *       return function (str) { + *         var obj = utils.flag(this, 'object'); + *         if (obj instanceof Foo) { + *           new chai.Assertion(obj.value).to.equal(str); + *         } else { + *           _super.apply(this, arguments); + *         } + *       } + *     }); + * + * Can also be accessed directly from `chai.Assertion`. + * + *     chai.Assertion.overwriteMethod('foo', fn); + * + * Then can be used as any other assertion. + * + *     expect(myFoo).to.equal('bar'); + * + * @param {Object} ctx object whose method is to be overwritten + * @param {String} name of method to overwrite + * @param {Function} method function that returns a function to be used for name + * @name overwriteMethod + * @api public + */ + +module.exports = function (ctx, name, method) { +  var _method = ctx[name] +    , _super = function () { return this; }; + +  if (_method && 'function' === typeof _method) +    _super = _method; + +  ctx[name] = function () { +    var result = method(_super).apply(this, arguments); +    return result === undefined ? this : result; +  } +}; + +}); +require.register("chai/lib/chai/utils/overwriteProperty.js", function(exports, require, module){ +/*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### overwriteProperty (ctx, name, fn) + * + * Overwites an already existing property getter and provides + * access to previous value. Must return function to use as getter. + * + *     utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { + *       return function () { + *         var obj = utils.flag(this, 'object'); + *         if (obj instanceof Foo) { + *           new chai.Assertion(obj.name).to.equal('bar'); + *         } else { + *           _super.call(this); + *         } + *       } + *     }); + * + * + * Can also be accessed directly from `chai.Assertion`. + * + *     chai.Assertion.overwriteProperty('foo', fn); + * + * Then can be used as any other assertion. + * + *     expect(myFoo).to.be.ok; + * + * @param {Object} ctx object whose property is to be overwritten + * @param {String} name of property to overwrite + * @param {Function} getter function that returns a getter function to be used for name + * @name overwriteProperty + * @api public + */ + +module.exports = function (ctx, name, getter) { +  var _get = Object.getOwnPropertyDescriptor(ctx, name) +    , _super = function () {}; + +  if (_get && 'function' === typeof _get.get) +    _super = _get.get + +  Object.defineProperty(ctx, name, +    { get: function () { +        var result = getter(_super).call(this); +        return result === undefined ? this : result; +      } +    , configurable: true +  }); +}; + +}); +require.register("chai/lib/chai/utils/test.js", function(exports, require, module){ +/*! + * Chai - test utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Module dependancies + */ + +var flag = require('./flag'); + +/** + * # test(object, expression) + * + * Test and object for expression. + * + * @param {Object} object (constructed Assertion) + * @param {Arguments} chai.Assertion.prototype.assert arguments + */ + +module.exports = function (obj, args) { +  var negate = flag(obj, 'negate') +    , expr = args[0]; +  return negate ? !expr : expr; +}; + +}); +require.register("chai/lib/chai/utils/transferFlags.js", function(exports, require, module){ +/*! + * Chai - transferFlags utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/** + * ### transferFlags(assertion, object, includeAll = true) + * + * Transfer all the flags for `assertion` to `object`. If + * `includeAll` is set to `false`, then the base Chai + * assertion flags (namely `object`, `ssfi`, and `message`) + * will not be transferred. + * + * + *     var newAssertion = new Assertion(); + *     utils.transferFlags(assertion, newAssertion); + * + *     var anotherAsseriton = new Assertion(myObj); + *     utils.transferFlags(assertion, anotherAssertion, false); + * + * @param {Assertion} assertion the assertion to transfer the flags from + * @param {Object} object the object to transfer the flags too; usually a new assertion + * @param {Boolean} includeAll + * @name getAllFlags + * @api private + */ + +module.exports = function (assertion, object, includeAll) { +  var flags = assertion.__flags || (assertion.__flags = Object.create(null)); + +  if (!object.__flags) { +    object.__flags = Object.create(null); +  } + +  includeAll = arguments.length === 3 ? includeAll : true; + +  for (var flag in flags) { +    if (includeAll || +        (flag !== 'object' && flag !== 'ssfi' && flag != 'message')) { +      object.__flags[flag] = flags[flag]; +    } +  } +}; + +}); +require.register("chai/lib/chai/utils/type.js", function(exports, require, module){ +/*! + * Chai - type utility + * Copyright(c) 2012-2013 Jake Luer <jake@alogicalparadox.com> + * MIT Licensed + */ + +/*! + * Detectable javascript natives + */ + +var natives = { +    '[object Arguments]': 'arguments' +  , '[object Array]': 'array' +  , '[object Date]': 'date' +  , '[object Function]': 'function' +  , '[object Number]': 'number' +  , '[object RegExp]': 'regexp' +  , '[object String]': 'string' +}; + +/** + * ### type(object) + * + * Better implementation of `typeof` detection that can + * be used cross-browser. Handles the inconsistencies of + * Array, `null`, and `undefined` detection. + * + *     utils.type({}) // 'object' + *     utils.type(null) // `null' + *     utils.type(undefined) // `undefined` + *     utils.type([]) // `array` + * + * @param {Mixed} object to detect type of + * @name type + * @api private + */ + +module.exports = function (obj) { +  var str = Object.prototype.toString.call(obj); +  if (natives[str]) return natives[str]; +  if (obj === null) return 'null'; +  if (obj === undefined) return 'undefined'; +  if (obj === Object(obj)) return 'object'; +  return typeof obj; +}; + +}); +require.alias("chai/index.js", "chai/index.js"); + +if (typeof exports == "object") { +  module.exports = require("chai"); +} else if (typeof define == "function" && define.amd) { +  define(function(){ return require("chai"); }); +} else { +  this["chai"] = require("chai"); +}})(); diff --git a/lib/mousetrap/tests/libs/jquery-1.7.2.min.js b/lib/mousetrap/tests/libs/jquery-1.7.2.min.js new file mode 100644 index 0000000..5627896 --- /dev/null +++ b/lib/mousetrap/tests/libs/jquery-1.7.2.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7.2 jquery.com | jquery.org/license */ +(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( +a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f +.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); diff --git a/lib/mousetrap/tests/libs/key-event.js b/lib/mousetrap/tests/libs/key-event.js new file mode 100644 index 0000000..44cee7c --- /dev/null +++ b/lib/mousetrap/tests/libs/key-event.js @@ -0,0 +1,129 @@ +(function() { +    var KeyEvent = function(data, type) { +        this.keyCode = 'keyCode' in data ? data.keyCode : 0; +        this.charCode = 'charCode' in data ? data.charCode : 0; + +        var modifiers = 'modifiers' in data ? data.modifiers : []; + +        this.ctrlKey = false; +        this.metaKey = false; +        this.altKey = false; +        this.shiftKey = false; + +        for (var i = 0; i < modifiers.length; i++) { +            this[modifiers[i] + 'Key'] = true; +        } + +        this.type = type || 'keypress'; +    }; + +    KeyEvent.prototype.toNative = function() { +        var event = document.createEventObject ? document.createEventObject() : document.createEvent('Events'); + +        if (event.initEvent) { +            event.initEvent(this.type, true, true); +        } + +        event.keyCode = this.keyCode; +        event.which = this.charCode || this.keyCode; +        event.shiftKey = this.shiftKey; +        event.metaKey = this.metaKey; +        event.altKey = this.altKey; +        event.ctrlKey = this.ctrlKey; + +        return event; +    }; + +    KeyEvent.prototype.fire = function(element) { +        var event = this.toNative(); +        if (element.dispatchEvent) { +            element.dispatchEvent(event); +            return; +        } + +        element.fireEvent('on' + this.type, event); +    }; + +    // simulates complete key event as if the user pressed the key in the browser +    // triggers a keydown, then a keypress, then a keyup +    KeyEvent.simulate = function(charCode, keyCode, modifiers, element, repeat) { +        if (modifiers === undefined) { +            modifiers = []; +        } + +        if (element === undefined) { +            element = document; +        } + +        if (repeat === undefined) { +            repeat = 1; +        } + +        var modifierToKeyCode = { +            'shift': 16, +            'ctrl': 17, +            'alt': 18, +            'meta': 91 +        }; + +        // if the key is a modifier then take it out of the regular +        // keypress/keydown +        if (keyCode == 16 || keyCode == 17 || keyCode == 18 || keyCode == 91) { +            repeat = 0; +        } + +        var modifiersToInclude = []; +        var keyEvents = []; + +        // modifiers would go down first +        for (var i = 0; i < modifiers.length; i++) { +            modifiersToInclude.push(modifiers[i]); +            keyEvents.push(new KeyEvent({ +                charCode: 0, +                keyCode: modifierToKeyCode[modifiers[i]], +                modifiers: modifiersToInclude +            }, 'keydown')); +        } + +        // @todo factor in duration for these +        while (repeat > 0) { +            keyEvents.push(new KeyEvent({ +                charCode: 0, +                keyCode: keyCode, +                modifiers: modifiersToInclude +            }, 'keydown')); + +            keyEvents.push(new KeyEvent({ +                charCode: charCode, +                keyCode: charCode, +                modifiers: modifiersToInclude +            }, 'keypress')); + +            repeat--; +        } + +        keyEvents.push(new KeyEvent({ +            charCode: 0, +            keyCode: keyCode, +            modifiers: modifiersToInclude +        }, 'keyup')); + +        // now lift up the modifier keys +        for (i = 0; i < modifiersToInclude.length; i++) { +            var modifierKeyCode = modifierToKeyCode[modifiersToInclude[i]]; +            modifiersToInclude.splice(i, 1); +            keyEvents.push(new KeyEvent({ +                charCode: 0, +                keyCode: modifierKeyCode, +                modifiers: modifiersToInclude +            }, 'keyup')); +        } + +        for (i = 0; i < keyEvents.length; i++) { +            // console.log('firing', keyEvents[i].type, keyEvents[i].keyCode, keyEvents[i].charCode); +            keyEvents[i].fire(element); +        } +    }; + +    window.KeyEvent = KeyEvent; +}) (); diff --git a/lib/mousetrap/tests/libs/mocha-1.9.0.css b/lib/mousetrap/tests/libs/mocha-1.9.0.css new file mode 100644 index 0000000..883d44b --- /dev/null +++ b/lib/mousetrap/tests/libs/mocha-1.9.0.css @@ -0,0 +1,246 @@ +@charset "utf-8"; + +body { +  font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; +  padding: 60px 50px; +} + +#mocha ul, #mocha li { +  margin: 0; +  padding: 0; +} + +#mocha ul { +  list-style: none; +} + +#mocha h1, #mocha h2 { +  margin: 0; +} + +#mocha h1 { +  margin-top: 15px; +  font-size: 1em; +  font-weight: 200; +} + +#mocha h1 a { +  text-decoration: none; +  color: inherit; +} + +#mocha h1 a:hover { +  text-decoration: underline; +} + +#mocha .suite .suite h1 { +  margin-top: 0; +  font-size: .8em; +} + +.hidden { +  display: none; +} + +#mocha h2 { +  font-size: 12px; +  font-weight: normal; +  cursor: pointer; +} + +#mocha .suite { +  margin-left: 15px; +} + +#mocha .test { +  margin-left: 15px; +  overflow: hidden; +} + +#mocha .test.pending:hover h2::after { +  content: '(pending)'; +  font-family: arial; +} + +#mocha .test.pass.medium .duration { +  background: #C09853; +} + +#mocha .test.pass.slow .duration { +  background: #B94A48; +} + +#mocha .test.pass::before { +  content: '✓'; +  font-size: 12px; +  display: block; +  float: left; +  margin-right: 5px; +  color: #00d6b2; +} + +#mocha .test.pass .duration { +  font-size: 9px; +  margin-left: 5px; +  padding: 2px 5px; +  color: white; +  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); +  -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); +  box-shadow: inset 0 1px 1px rgba(0,0,0,.2); +  -webkit-border-radius: 5px; +  -moz-border-radius: 5px; +  -ms-border-radius: 5px; +  -o-border-radius: 5px; +  border-radius: 5px; +} + +#mocha .test.pass.fast .duration { +  display: none; +} + +#mocha .test.pending { +  color: #0b97c4; +} + +#mocha .test.pending::before { +  content: '◦'; +  color: #0b97c4; +} + +#mocha .test.fail { +  color: #c00; +} + +#mocha .test.fail pre { +  color: black; +} + +#mocha .test.fail::before { +  content: '✖'; +  font-size: 12px; +  display: block; +  float: left; +  margin-right: 5px; +  color: #c00; +} + +#mocha .test pre.error { +  color: #c00; +  max-height: 300px; +  overflow: auto; +} + +#mocha .test pre { +  display: block; +  float: left; +  clear: left; +  font: 12px/1.5 monaco, monospace; +  margin: 5px; +  padding: 15px; +  border: 1px solid #eee; +  border-bottom-color: #ddd; +  -webkit-border-radius: 3px; +  -webkit-box-shadow: 0 1px 3px #eee; +  -moz-border-radius: 3px; +  -moz-box-shadow: 0 1px 3px #eee; +} + +#mocha .test h2 { +  position: relative; +} + +#mocha .test a.replay { +  position: absolute; +  top: 3px; +  right: 0; +  text-decoration: none; +  vertical-align: middle; +  display: block; +  width: 15px; +  height: 15px; +  line-height: 15px; +  text-align: center; +  background: #eee; +  font-size: 15px; +  -moz-border-radius: 15px; +  border-radius: 15px; +  -webkit-transition: opacity 200ms; +  -moz-transition: opacity 200ms; +  transition: opacity 200ms; +  opacity: 0.3; +  color: #888; +} + +#mocha .test:hover a.replay { +  opacity: 1; +} + +#mocha-report.pass .test.fail { +  display: none; +} + +#mocha-report.fail .test.pass { +  display: none; +} + +#mocha-error { +  color: #c00; +  font-size: 1.5  em; +  font-weight: 100; +  letter-spacing: 1px; +} + +#mocha-stats { +  position: fixed; +  top: 15px; +  right: 10px; +  font-size: 12px; +  margin: 0; +  color: #888; +} + +#mocha-stats .progress { +  float: right; +  padding-top: 0; +} + +#mocha-stats em { +  color: black; +} + +#mocha-stats a { +  text-decoration: none; +  color: inherit; +} + +#mocha-stats a:hover { +  border-bottom: 1px solid #eee; +} + +#mocha-stats li { +  display: inline-block; +  margin: 0 5px; +  list-style: none; +  padding-top: 11px; +} + +#mocha-stats canvas { +  width: 40px; +  height: 40px; +} + +code .comment { color: #ddd } +code .init { color: #2F6FAD } +code .string { color: #5890AD } +code .keyword { color: #8A6343 } +code .number { color: #2F6FAD } + +@media screen and (max-device-width: 480px) { +  body { +    padding: 60px 0px; +  } + +  #stats { +    position: absolute; +  } +} diff --git a/lib/mousetrap/tests/libs/mocha-1.9.0.js b/lib/mousetrap/tests/libs/mocha-1.9.0.js new file mode 100644 index 0000000..aed04d9 --- /dev/null +++ b/lib/mousetrap/tests/libs/mocha-1.9.0.js @@ -0,0 +1,5338 @@ +;(function(){ + +// CommonJS require() + +function require(p){ +    var path = require.resolve(p) +      , mod = require.modules[path]; +    if (!mod) throw new Error('failed to require "' + p + '"'); +    if (!mod.exports) { +      mod.exports = {}; +      mod.call(mod.exports, mod, mod.exports, require.relative(path)); +    } +    return mod.exports; +  } + +require.modules = {}; + +require.resolve = function (path){ +    var orig = path +      , reg = path + '.js' +      , index = path + '/index.js'; +    return require.modules[reg] && reg +      || require.modules[index] && index +      || orig; +  }; + +require.register = function (path, fn){ +    require.modules[path] = fn; +  }; + +require.relative = function (parent) { +    return function(p){ +      if ('.' != p.charAt(0)) return require(p); + +      var path = parent.split('/') +        , segs = p.split('/'); +      path.pop(); + +      for (var i = 0; i < segs.length; i++) { +        var seg = segs[i]; +        if ('..' == seg) path.pop(); +        else if ('.' != seg) path.push(seg); +      } + +      return require(path.join('/')); +    }; +  }; + + +require.register("browser/debug.js", function(module, exports, require){ + +module.exports = function(type){ +  return function(){ +  } +}; + +}); // module: browser/debug.js + +require.register("browser/diff.js", function(module, exports, require){ +/* See license.txt for terms of usage */ + +/* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +var JsDiff = (function() { +  function clonePath(path) { +    return { newPos: path.newPos, components: path.components.slice(0) }; +  } +  function removeEmpty(array) { +    var ret = []; +    for (var i = 0; i < array.length; i++) { +      if (array[i]) { +        ret.push(array[i]); +      } +    } +    return ret; +  } +  function escapeHTML(s) { +    var n = s; +    n = n.replace(/&/g, "&"); +    n = n.replace(/</g, "<"); +    n = n.replace(/>/g, ">"); +    n = n.replace(/"/g, """); + +    return n; +  } + + +  var fbDiff = function(ignoreWhitespace) { +    this.ignoreWhitespace = ignoreWhitespace; +  }; +  fbDiff.prototype = { +      diff: function(oldString, newString) { +        // Handle the identity case (this is due to unrolling editLength == 0 +        if (newString == oldString) { +          return [{ value: newString }]; +        } +        if (!newString) { +          return [{ value: oldString, removed: true }]; +        } +        if (!oldString) { +          return [{ value: newString, added: true }]; +        } + +        newString = this.tokenize(newString); +        oldString = this.tokenize(oldString); + +        var newLen = newString.length, oldLen = oldString.length; +        var maxEditLength = newLen + oldLen; +        var bestPath = [{ newPos: -1, components: [] }]; + +        // Seed editLength = 0 +        var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); +        if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { +          return bestPath[0].components; +        } + +        for (var editLength = 1; editLength <= maxEditLength; editLength++) { +          for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { +            var basePath; +            var addPath = bestPath[diagonalPath-1], +                removePath = bestPath[diagonalPath+1]; +            oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; +            if (addPath) { +              // No one else is going to attempt to use this value, clear it +              bestPath[diagonalPath-1] = undefined; +            } + +            var canAdd = addPath && addPath.newPos+1 < newLen; +            var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; +            if (!canAdd && !canRemove) { +              bestPath[diagonalPath] = undefined; +              continue; +            } + +            // Select the diagonal that we want to branch from. We select the prior +            // path whose position in the new string is the farthest from the origin +            // and does not pass the bounds of the diff graph +            if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { +              basePath = clonePath(removePath); +              this.pushComponent(basePath.components, oldString[oldPos], undefined, true); +            } else { +              basePath = clonePath(addPath); +              basePath.newPos++; +              this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); +            } + +            var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); + +            if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { +              return basePath.components; +            } else { +              bestPath[diagonalPath] = basePath; +            } +          } +        } +      }, + +      pushComponent: function(components, value, added, removed) { +        var last = components[components.length-1]; +        if (last && last.added === added && last.removed === removed) { +          // We need to clone here as the component clone operation is just +          // as shallow array clone +          components[components.length-1] = +            {value: this.join(last.value, value), added: added, removed: removed }; +        } else { +          components.push({value: value, added: added, removed: removed }); +        } +      }, +      extractCommon: function(basePath, newString, oldString, diagonalPath) { +        var newLen = newString.length, +            oldLen = oldString.length, +            newPos = basePath.newPos, +            oldPos = newPos - diagonalPath; +        while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { +          newPos++; +          oldPos++; + +          this.pushComponent(basePath.components, newString[newPos], undefined, undefined); +        } +        basePath.newPos = newPos; +        return oldPos; +      }, + +      equals: function(left, right) { +        var reWhitespace = /\S/; +        if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { +          return true; +        } else { +          return left == right; +        } +      }, +      join: function(left, right) { +        return left + right; +      }, +      tokenize: function(value) { +        return value; +      } +  }; + +  var CharDiff = new fbDiff(); + +  var WordDiff = new fbDiff(true); +  WordDiff.tokenize = function(value) { +    return removeEmpty(value.split(/(\s+|\b)/)); +  }; + +  var CssDiff = new fbDiff(true); +  CssDiff.tokenize = function(value) { +    return removeEmpty(value.split(/([{}:;,]|\s+)/)); +  }; + +  var LineDiff = new fbDiff(); +  LineDiff.tokenize = function(value) { +    return value.split(/^/m); +  }; + +  return { +    diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, +    diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, +    diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, + +    diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, + +    createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { +      var ret = []; + +      ret.push("Index: " + fileName); +      ret.push("==================================================================="); +      ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader)); +      ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader)); + +      var diff = LineDiff.diff(oldStr, newStr); +      if (!diff[diff.length-1].value) { +        diff.pop();   // Remove trailing newline add +      } +      diff.push({value: "", lines: []});   // Append an empty value to make cleanup easier + +      function contextLines(lines) { +        return lines.map(function(entry) { return ' ' + entry; }); +      } +      function eofNL(curRange, i, current) { +        var last = diff[diff.length-2], +            isLast = i === diff.length-2, +            isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed); + +        // Figure out if this is the last line for the given file and missing NL +        if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { +          curRange.push('\\ No newline at end of file'); +        } +      } + +      var oldRangeStart = 0, newRangeStart = 0, curRange = [], +          oldLine = 1, newLine = 1; +      for (var i = 0; i < diff.length; i++) { +        var current = diff[i], +            lines = current.lines || current.value.replace(/\n$/, "").split("\n"); +        current.lines = lines; + +        if (current.added || current.removed) { +          if (!oldRangeStart) { +            var prev = diff[i-1]; +            oldRangeStart = oldLine; +            newRangeStart = newLine; + +            if (prev) { +              curRange = contextLines(prev.lines.slice(-4)); +              oldRangeStart -= curRange.length; +              newRangeStart -= curRange.length; +            } +          } +          curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; })); +          eofNL(curRange, i, current); + +          if (current.added) { +            newLine += lines.length; +          } else { +            oldLine += lines.length; +          } +        } else { +          if (oldRangeStart) { +            // Close out any changes that have been output (or join overlapping) +            if (lines.length <= 8 && i < diff.length-2) { +              // Overlapping +              curRange.push.apply(curRange, contextLines(lines)); +            } else { +              // end the range and output +              var contextSize = Math.min(lines.length, 4); +              ret.push( +                  "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize) +                  + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize) +                  + " @@"); +              ret.push.apply(ret, curRange); +              ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); +              if (lines.length <= 4) { +                eofNL(ret, i, current); +              } + +              oldRangeStart = 0;  newRangeStart = 0; curRange = []; +            } +          } +          oldLine += lines.length; +          newLine += lines.length; +        } +      } + +      return ret.join('\n') + '\n'; +    }, + +    convertChangesToXML: function(changes){ +      var ret = []; +      for ( var i = 0; i < changes.length; i++) { +        var change = changes[i]; +        if (change.added) { +          ret.push("<ins>"); +        } else if (change.removed) { +          ret.push("<del>"); +        } + +        ret.push(escapeHTML(change.value)); + +        if (change.added) { +          ret.push("</ins>"); +        } else if (change.removed) { +          ret.push("</del>"); +        } +      } +      return ret.join(""); +    } +  }; +})(); + +if (typeof module !== "undefined") { +    module.exports = JsDiff; +} + +}); // module: browser/diff.js + +require.register("browser/events.js", function(module, exports, require){ + +/** + * Module exports. + */ + +exports.EventEmitter = EventEmitter; + +/** + * Check if `obj` is an array. + */ + +function isArray(obj) { +  return '[object Array]' == {}.toString.call(obj); +} + +/** + * Event emitter constructor. + * + * @api public + */ + +function EventEmitter(){}; + +/** + * Adds a listener. + * + * @api public + */ + +EventEmitter.prototype.on = function (name, fn) { +  if (!this.$events) { +    this.$events = {}; +  } + +  if (!this.$events[name]) { +    this.$events[name] = fn; +  } else if (isArray(this.$events[name])) { +    this.$events[name].push(fn); +  } else { +    this.$events[name] = [this.$events[name], fn]; +  } + +  return this; +}; + +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +/** + * Adds a volatile listener. + * + * @api public + */ + +EventEmitter.prototype.once = function (name, fn) { +  var self = this; + +  function on () { +    self.removeListener(name, on); +    fn.apply(this, arguments); +  }; + +  on.listener = fn; +  this.on(name, on); + +  return this; +}; + +/** + * Removes a listener. + * + * @api public + */ + +EventEmitter.prototype.removeListener = function (name, fn) { +  if (this.$events && this.$events[name]) { +    var list = this.$events[name]; + +    if (isArray(list)) { +      var pos = -1; + +      for (var i = 0, l = list.length; i < l; i++) { +        if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { +          pos = i; +          break; +        } +      } + +      if (pos < 0) { +        return this; +      } + +      list.splice(pos, 1); + +      if (!list.length) { +        delete this.$events[name]; +      } +    } else if (list === fn || (list.listener && list.listener === fn)) { +      delete this.$events[name]; +    } +  } + +  return this; +}; + +/** + * Removes all listeners for an event. + * + * @api public + */ + +EventEmitter.prototype.removeAllListeners = function (name) { +  if (name === undefined) { +    this.$events = {}; +    return this; +  } + +  if (this.$events && this.$events[name]) { +    this.$events[name] = null; +  } + +  return this; +}; + +/** + * Gets all listeners for a certain event. + * + * @api public + */ + +EventEmitter.prototype.listeners = function (name) { +  if (!this.$events) { +    this.$events = {}; +  } + +  if (!this.$events[name]) { +    this.$events[name] = []; +  } + +  if (!isArray(this.$events[name])) { +    this.$events[name] = [this.$events[name]]; +  } + +  return this.$events[name]; +}; + +/** + * Emits an event. + * + * @api public + */ + +EventEmitter.prototype.emit = function (name) { +  if (!this.$events) { +    return false; +  } + +  var handler = this.$events[name]; + +  if (!handler) { +    return false; +  } + +  var args = [].slice.call(arguments, 1); + +  if ('function' == typeof handler) { +    handler.apply(this, args); +  } else if (isArray(handler)) { +    var listeners = handler.slice(); + +    for (var i = 0, l = listeners.length; i < l; i++) { +      listeners[i].apply(this, args); +    } +  } else { +    return false; +  } + +  return true; +}; +}); // module: browser/events.js + +require.register("browser/fs.js", function(module, exports, require){ + +}); // module: browser/fs.js + +require.register("browser/path.js", function(module, exports, require){ + +}); // module: browser/path.js + +require.register("browser/progress.js", function(module, exports, require){ + +/** + * Expose `Progress`. + */ + +module.exports = Progress; + +/** + * Initialize a new `Progress` indicator. + */ + +function Progress() { +  this.percent = 0; +  this.size(0); +  this.fontSize(11); +  this.font('helvetica, arial, sans-serif'); +} + +/** + * Set progress size to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.size = function(n){ +  this._size = n; +  return this; +}; + +/** + * Set text to `str`. + * + * @param {String} str + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.text = function(str){ +  this._text = str; +  return this; +}; + +/** + * Set font size to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.fontSize = function(n){ +  this._fontSize = n; +  return this; +}; + +/** + * Set font `family`. + * + * @param {String} family + * @return {Progress} for chaining + */ + +Progress.prototype.font = function(family){ +  this._font = family; +  return this; +}; + +/** + * Update percentage to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + */ + +Progress.prototype.update = function(n){ +  this.percent = n; +  return this; +}; + +/** + * Draw on `ctx`. + * + * @param {CanvasRenderingContext2d} ctx + * @return {Progress} for chaining + */ + +Progress.prototype.draw = function(ctx){ +  var percent = Math.min(this.percent, 100) +    , size = this._size +    , half = size / 2 +    , x = half +    , y = half +    , rad = half - 1 +    , fontSize = this._fontSize; + +  ctx.font = fontSize + 'px ' + this._font; + +  var angle = Math.PI * 2 * (percent / 100); +  ctx.clearRect(0, 0, size, size); + +  // outer circle +  ctx.strokeStyle = '#9f9f9f'; +  ctx.beginPath(); +  ctx.arc(x, y, rad, 0, angle, false); +  ctx.stroke(); + +  // inner circle +  ctx.strokeStyle = '#eee'; +  ctx.beginPath(); +  ctx.arc(x, y, rad - 1, 0, angle, true); +  ctx.stroke(); + +  // text +  var text = this._text || (percent | 0) + '%' +    , w = ctx.measureText(text).width; + +  ctx.fillText( +      text +    , x - w / 2 + 1 +    , y + fontSize / 2 - 1); + +  return this; +}; + +}); // module: browser/progress.js + +require.register("browser/tty.js", function(module, exports, require){ + +exports.isatty = function(){ +  return true; +}; + +exports.getWindowSize = function(){ +  return [window.innerHeight, window.innerWidth]; +}; +}); // module: browser/tty.js + +require.register("context.js", function(module, exports, require){ + +/** + * Expose `Context`. + */ + +module.exports = Context; + +/** + * Initialize a new `Context`. + * + * @api private + */ + +function Context(){} + +/** + * Set or get the context `Runnable` to `runnable`. + * + * @param {Runnable} runnable + * @return {Context} + * @api private + */ + +Context.prototype.runnable = function(runnable){ +  if (0 == arguments.length) return this._runnable; +  this.test = this._runnable = runnable; +  return this; +}; + +/** + * Set test timeout `ms`. + * + * @param {Number} ms + * @return {Context} self + * @api private + */ + +Context.prototype.timeout = function(ms){ +  this.runnable().timeout(ms); +  return this; +}; + +/** + * Set test slowness threshold `ms`. + * + * @param {Number} ms + * @return {Context} self + * @api private + */ + +Context.prototype.slow = function(ms){ +  this.runnable().slow(ms); +  return this; +}; + +/** + * Inspect the context void of `._runnable`. + * + * @return {String} + * @api private + */ + +Context.prototype.inspect = function(){ +  return JSON.stringify(this, function(key, val){ +    if ('_runnable' == key) return; +    if ('test' == key) return; +    return val; +  }, 2); +}; + +}); // module: context.js + +require.register("hook.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Runnable = require('./runnable'); + +/** + * Expose `Hook`. + */ + +module.exports = Hook; + +/** + * Initialize a new `Hook` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Hook(title, fn) { +  Runnable.call(this, title, fn); +  this.type = 'hook'; +} + +/** + * Inherit from `Runnable.prototype`. + */ + +function F(){}; +F.prototype = Runnable.prototype; +Hook.prototype = new F; +Hook.prototype.constructor = Hook; + + +/** + * Get or set the test `err`. + * + * @param {Error} err + * @return {Error} + * @api public + */ + +Hook.prototype.error = function(err){ +  if (0 == arguments.length) { +    var err = this._error; +    this._error = null; +    return err; +  } + +  this._error = err; +}; + +}); // module: hook.js + +require.register("interfaces/bdd.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') +  , Test = require('../test'); + +/** + * BDD-style interface: + * + *      describe('Array', function(){ + *        describe('#indexOf()', function(){ + *          it('should return -1 when not present', function(){ + * + *          }); + * + *          it('should return the index when present', function(){ + * + *          }); + *        }); + *      }); + * + */ + +module.exports = function(suite){ +  var suites = [suite]; + +  suite.on('pre-require', function(context, file, mocha){ + +    /** +     * Execute before running tests. +     */ + +    context.before = function(fn){ +      suites[0].beforeAll(fn); +    }; + +    /** +     * Execute after running tests. +     */ + +    context.after = function(fn){ +      suites[0].afterAll(fn); +    }; + +    /** +     * Execute before each test case. +     */ + +    context.beforeEach = function(fn){ +      suites[0].beforeEach(fn); +    }; + +    /** +     * Execute after each test case. +     */ + +    context.afterEach = function(fn){ +      suites[0].afterEach(fn); +    }; + +    /** +     * Describe a "suite" with the given `title` +     * and callback `fn` containing nested suites +     * and/or tests. +     */ + +    context.describe = context.context = function(title, fn){ +      var suite = Suite.create(suites[0], title); +      suites.unshift(suite); +      fn.call(suite); +      suites.shift(); +      return suite; +    }; + +    /** +     * Pending describe. +     */ + +    context.xdescribe = +    context.xcontext = +    context.describe.skip = function(title, fn){ +      var suite = Suite.create(suites[0], title); +      suite.pending = true; +      suites.unshift(suite); +      fn.call(suite); +      suites.shift(); +    }; + +    /** +     * Exclusive suite. +     */ + +    context.describe.only = function(title, fn){ +      var suite = context.describe(title, fn); +      mocha.grep(suite.fullTitle()); +    }; + +    /** +     * Describe a specification or test-case +     * with the given `title` and callback `fn` +     * acting as a thunk. +     */ + +    context.it = context.specify = function(title, fn){ +      var suite = suites[0]; +      if (suite.pending) var fn = null; +      var test = new Test(title, fn); +      suite.addTest(test); +      return test; +    }; + +    /** +     * Exclusive test-case. +     */ + +    context.it.only = function(title, fn){ +      var test = context.it(title, fn); +      mocha.grep(test.fullTitle()); +    }; + +    /** +     * Pending test case. +     */ + +    context.xit = +    context.xspecify = +    context.it.skip = function(title){ +      context.it(title); +    }; +  }); +}; + +}); // module: interfaces/bdd.js + +require.register("interfaces/exports.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') +  , Test = require('../test'); + +/** + * TDD-style interface: + * + *     exports.Array = { + *       '#indexOf()': { + *         'should return -1 when the value is not present': function(){ + * + *         }, + * + *         'should return the correct index when the value is present': function(){ + * + *         } + *       } + *     }; + * + */ + +module.exports = function(suite){ +  var suites = [suite]; + +  suite.on('require', visit); + +  function visit(obj) { +    var suite; +    for (var key in obj) { +      if ('function' == typeof obj[key]) { +        var fn = obj[key]; +        switch (key) { +          case 'before': +            suites[0].beforeAll(fn); +            break; +          case 'after': +            suites[0].afterAll(fn); +            break; +          case 'beforeEach': +            suites[0].beforeEach(fn); +            break; +          case 'afterEach': +            suites[0].afterEach(fn); +            break; +          default: +            suites[0].addTest(new Test(key, fn)); +        } +      } else { +        var suite = Suite.create(suites[0], key); +        suites.unshift(suite); +        visit(obj[key]); +        suites.shift(); +      } +    } +  } +}; + +}); // module: interfaces/exports.js + +require.register("interfaces/index.js", function(module, exports, require){ + +exports.bdd = require('./bdd'); +exports.tdd = require('./tdd'); +exports.qunit = require('./qunit'); +exports.exports = require('./exports'); + +}); // module: interfaces/index.js + +require.register("interfaces/qunit.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') +  , Test = require('../test'); + +/** + * QUnit-style interface: + * + *     suite('Array'); + * + *     test('#length', function(){ + *       var arr = [1,2,3]; + *       ok(arr.length == 3); + *     }); + * + *     test('#indexOf()', function(){ + *       var arr = [1,2,3]; + *       ok(arr.indexOf(1) == 0); + *       ok(arr.indexOf(2) == 1); + *       ok(arr.indexOf(3) == 2); + *     }); + * + *     suite('String'); + * + *     test('#length', function(){ + *       ok('foo'.length == 3); + *     }); + * + */ + +module.exports = function(suite){ +  var suites = [suite]; + +  suite.on('pre-require', function(context){ + +    /** +     * Execute before running tests. +     */ + +    context.before = function(fn){ +      suites[0].beforeAll(fn); +    }; + +    /** +     * Execute after running tests. +     */ + +    context.after = function(fn){ +      suites[0].afterAll(fn); +    }; + +    /** +     * Execute before each test case. +     */ + +    context.beforeEach = function(fn){ +      suites[0].beforeEach(fn); +    }; + +    /** +     * Execute after each test case. +     */ + +    context.afterEach = function(fn){ +      suites[0].afterEach(fn); +    }; + +    /** +     * Describe a "suite" with the given `title`. +     */ + +    context.suite = function(title){ +      if (suites.length > 1) suites.shift(); +      var suite = Suite.create(suites[0], title); +      suites.unshift(suite); +    }; + +    /** +     * Describe a specification or test-case +     * with the given `title` and callback `fn` +     * acting as a thunk. +     */ + +    context.test = function(title, fn){ +      suites[0].addTest(new Test(title, fn)); +    }; +  }); +}; + +}); // module: interfaces/qunit.js + +require.register("interfaces/tdd.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') +  , Test = require('../test'); + +/** + * TDD-style interface: + * + *      suite('Array', function(){ + *        suite('#indexOf()', function(){ + *          suiteSetup(function(){ + * + *          }); + * + *          test('should return -1 when not present', function(){ + * + *          }); + * + *          test('should return the index when present', function(){ + * + *          }); + * + *          suiteTeardown(function(){ + * + *          }); + *        }); + *      }); + * + */ + +module.exports = function(suite){ +  var suites = [suite]; + +  suite.on('pre-require', function(context, file, mocha){ + +    /** +     * Execute before each test case. +     */ + +    context.setup = function(fn){ +      suites[0].beforeEach(fn); +    }; + +    /** +     * Execute after each test case. +     */ + +    context.teardown = function(fn){ +      suites[0].afterEach(fn); +    }; + +    /** +     * Execute before the suite. +     */ + +    context.suiteSetup = function(fn){ +      suites[0].beforeAll(fn); +    }; + +    /** +     * Execute after the suite. +     */ + +    context.suiteTeardown = function(fn){ +      suites[0].afterAll(fn); +    }; + +    /** +     * Describe a "suite" with the given `title` +     * and callback `fn` containing nested suites +     * and/or tests. +     */ + +    context.suite = function(title, fn){ +      var suite = Suite.create(suites[0], title); +      suites.unshift(suite); +      fn.call(suite); +      suites.shift(); +      return suite; +    }; + +    /** +     * Exclusive test-case. +     */ + +    context.suite.only = function(title, fn){ +      var suite = context.suite(title, fn); +      mocha.grep(suite.fullTitle()); +    }; + +    /** +     * Describe a specification or test-case +     * with the given `title` and callback `fn` +     * acting as a thunk. +     */ + +    context.test = function(title, fn){ +      var test = new Test(title, fn); +      suites[0].addTest(test); +      return test; +    }; + +    /** +     * Exclusive test-case. +     */ + +    context.test.only = function(title, fn){ +      var test = context.test(title, fn); +      mocha.grep(test.fullTitle()); +    }; + +    /** +     * Pending test case. +     */ + +    context.test.skip = function(title){ +      context.test(title); +    }; +  }); +}; + +}); // module: interfaces/tdd.js + +require.register("mocha.js", function(module, exports, require){ +/*! + * mocha + * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca> + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var path = require('browser/path') +  , utils = require('./utils'); + +/** + * Expose `Mocha`. + */ + +exports = module.exports = Mocha; + +/** + * Expose internals. + */ + +exports.utils = utils; +exports.interfaces = require('./interfaces'); +exports.reporters = require('./reporters'); +exports.Runnable = require('./runnable'); +exports.Context = require('./context'); +exports.Runner = require('./runner'); +exports.Suite = require('./suite'); +exports.Hook = require('./hook'); +exports.Test = require('./test'); + +/** + * Return image `name` path. + * + * @param {String} name + * @return {String} + * @api private + */ + +function image(name) { +  return __dirname + '/../images/' + name + '.png'; +} + +/** + * Setup mocha with `options`. + * + * Options: + * + *   - `ui` name "bdd", "tdd", "exports" etc + *   - `reporter` reporter instance, defaults to `mocha.reporters.Dot` + *   - `globals` array of accepted globals + *   - `timeout` timeout in milliseconds + *   - `bail` bail on the first test failure + *   - `slow` milliseconds to wait before considering a test slow + *   - `ignoreLeaks` ignore global leaks + *   - `grep` string or regexp to filter tests with + * + * @param {Object} options + * @api public + */ + +function Mocha(options) { +  options = options || {}; +  this.files = []; +  this.options = options; +  this.grep(options.grep); +  this.suite = new exports.Suite('', new exports.Context); +  this.ui(options.ui); +  this.bail(options.bail); +  this.reporter(options.reporter); +  if (options.timeout) this.timeout(options.timeout); +  if (options.slow) this.slow(options.slow); +} + +/** + * Enable or disable bailing on the first failure. + * + * @param {Boolean} [bail] + * @api public + */ + +Mocha.prototype.bail = function(bail){ +  if (0 == arguments.length) bail = true; +  this.suite.bail(bail); +  return this; +}; + +/** + * Add test `file`. + * + * @param {String} file + * @api public + */ + +Mocha.prototype.addFile = function(file){ +  this.files.push(file); +  return this; +}; + +/** + * Set reporter to `reporter`, defaults to "dot". + * + * @param {String|Function} reporter name or constructor + * @api public + */ + +Mocha.prototype.reporter = function(reporter){ +  if ('function' == typeof reporter) { +    this._reporter = reporter; +  } else { +    reporter = reporter || 'dot'; +    try { +      this._reporter = require('./reporters/' + reporter); +    } catch (err) { +      this._reporter = require(reporter); +    } +    if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); +  } +  return this; +}; + +/** + * Set test UI `name`, defaults to "bdd". + * + * @param {String} bdd + * @api public + */ + +Mocha.prototype.ui = function(name){ +  name = name || 'bdd'; +  this._ui = exports.interfaces[name]; +  if (!this._ui) throw new Error('invalid interface "' + name + '"'); +  this._ui = this._ui(this.suite); +  return this; +}; + +/** + * Load registered files. + * + * @api private + */ + +Mocha.prototype.loadFiles = function(fn){ +  var self = this; +  var suite = this.suite; +  var pending = this.files.length; +  this.files.forEach(function(file){ +    file = path.resolve(file); +    suite.emit('pre-require', global, file, self); +    suite.emit('require', require(file), file, self); +    suite.emit('post-require', global, file, self); +    --pending || (fn && fn()); +  }); +}; + +/** + * Enable growl support. + * + * @api private + */ + +Mocha.prototype._growl = function(runner, reporter) { +  var notify = require('growl'); + +  runner.on('end', function(){ +    var stats = reporter.stats; +    if (stats.failures) { +      var msg = stats.failures + ' of ' + runner.total + ' tests failed'; +      notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); +    } else { +      notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { +          name: 'mocha' +        , title: 'Passed' +        , image: image('ok') +      }); +    } +  }); +}; + +/** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @param {RegExp|String} re + * @return {Mocha} + * @api public + */ + +Mocha.prototype.grep = function(re){ +  this.options.grep = 'string' == typeof re +    ? new RegExp(utils.escapeRegexp(re)) +    : re; +  return this; +}; + +/** + * Invert `.grep()` matches. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.invert = function(){ +  this.options.invert = true; +  return this; +}; + +/** + * Ignore global leaks. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.ignoreLeaks = function(){ +  this.options.ignoreLeaks = true; +  return this; +}; + +/** + * Enable global leak checking. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.checkLeaks = function(){ +  this.options.ignoreLeaks = false; +  return this; +}; + +/** + * Enable growl support. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.growl = function(){ +  this.options.growl = true; +  return this; +}; + +/** + * Ignore `globals` array or string. + * + * @param {Array|String} globals + * @return {Mocha} + * @api public + */ + +Mocha.prototype.globals = function(globals){ +  this.options.globals = (this.options.globals || []).concat(globals); +  return this; +}; + +/** + * Set the timeout in milliseconds. + * + * @param {Number} timeout + * @return {Mocha} + * @api public + */ + +Mocha.prototype.timeout = function(timeout){ +  this.suite.timeout(timeout); +  return this; +}; + +/** + * Set slowness threshold in milliseconds. + * + * @param {Number} slow + * @return {Mocha} + * @api public + */ + +Mocha.prototype.slow = function(slow){ +  this.suite.slow(slow); +  return this; +}; + +/** + * Makes all tests async (accepting a callback) + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.asyncOnly = function(){ +  this.options.asyncOnly = true; +  return this; +}; + +/** + * Run tests and invoke `fn()` when complete. + * + * @param {Function} fn + * @return {Runner} + * @api public + */ + +Mocha.prototype.run = function(fn){ +  if (this.files.length) this.loadFiles(); +  var suite = this.suite; +  var options = this.options; +  var runner = new exports.Runner(suite); +  var reporter = new this._reporter(runner); +  runner.ignoreLeaks = false !== options.ignoreLeaks; +  runner.asyncOnly = options.asyncOnly; +  if (options.grep) runner.grep(options.grep, options.invert); +  if (options.globals) runner.globals(options.globals); +  if (options.growl) this._growl(runner, reporter); +  return runner.run(fn); +}; + +}); // module: mocha.js + +require.register("ms.js", function(module, exports, require){ + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; + +/** + * Parse or format the given `val`. + * + * @param {String|Number} val + * @return {String|Number} + * @api public + */ + +module.exports = function(val){ +  if ('string' == typeof val) return parse(val); +  return format(val); +} + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { +  var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); +  if (!m) return; +  var n = parseFloat(m[1]); +  var type = (m[2] || 'ms').toLowerCase(); +  switch (type) { +    case 'years': +    case 'year': +    case 'y': +      return n * 31557600000; +    case 'days': +    case 'day': +    case 'd': +      return n * 86400000; +    case 'hours': +    case 'hour': +    case 'h': +      return n * 3600000; +    case 'minutes': +    case 'minute': +    case 'm': +      return n * 60000; +    case 'seconds': +    case 'second': +    case 's': +      return n * 1000; +    case 'ms': +      return n; +  } +} + +/** + * Format the given `ms`. + * + * @param {Number} ms + * @return {String} + * @api public + */ + +function format(ms) { +  if (ms == d) return Math.round(ms / d) + ' day'; +  if (ms > d) return Math.round(ms / d) + ' days'; +  if (ms == h) return Math.round(ms / h) + ' hour'; +  if (ms > h) return Math.round(ms / h) + ' hours'; +  if (ms == m) return Math.round(ms / m) + ' minute'; +  if (ms > m) return Math.round(ms / m) + ' minutes'; +  if (ms == s) return Math.round(ms / s) + ' second'; +  if (ms > s) return Math.round(ms / s) + ' seconds'; +  return ms + ' ms'; +} +}); // module: ms.js + +require.register("reporters/base.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var tty = require('browser/tty') +  , diff = require('browser/diff') +  , ms = require('../ms'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date +  , setTimeout = global.setTimeout +  , setInterval = global.setInterval +  , clearTimeout = global.clearTimeout +  , clearInterval = global.clearInterval; + +/** + * Check if both stdio streams are associated with a tty. + */ + +var isatty = tty.isatty(1) && tty.isatty(2); + +/** + * Expose `Base`. + */ + +exports = module.exports = Base; + +/** + * Enable coloring by default. + */ + +exports.useColors = isatty; + +/** + * Default color map. + */ + +exports.colors = { +    'pass': 90 +  , 'fail': 31 +  , 'bright pass': 92 +  , 'bright fail': 91 +  , 'bright yellow': 93 +  , 'pending': 36 +  , 'suite': 0 +  , 'error title': 0 +  , 'error message': 31 +  , 'error stack': 90 +  , 'checkmark': 32 +  , 'fast': 90 +  , 'medium': 33 +  , 'slow': 31 +  , 'green': 32 +  , 'light': 90 +  , 'diff gutter': 90 +  , 'diff added': 42 +  , 'diff removed': 41 +}; + +/** + * Default symbol map. + */ + +exports.symbols = { +  ok: '✓', +  err: '✖', +  dot: '․' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if ('win32' == process.platform) { +  exports.symbols.ok = '\u221A'; +  exports.symbols.err = '\u00D7'; +  exports.symbols.dot = '.'; +} + +/** + * Color `str` with the given `type`, + * allowing colors to be disabled, + * as well as user-defined color + * schemes. + * + * @param {String} type + * @param {String} str + * @return {String} + * @api private + */ + +var color = exports.color = function(type, str) { +  if (!exports.useColors) return str; +  return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; +}; + +/** + * Expose term window size, with some + * defaults for when stderr is not a tty. + */ + +exports.window = { +  width: isatty +    ? process.stdout.getWindowSize +      ? process.stdout.getWindowSize(1)[0] +      : tty.getWindowSize()[1] +    : 75 +}; + +/** + * Expose some basic cursor interactions + * that are common among reporters. + */ + +exports.cursor = { +  hide: function(){ +    process.stdout.write('\u001b[?25l'); +  }, + +  show: function(){ +    process.stdout.write('\u001b[?25h'); +  }, + +  deleteLine: function(){ +    process.stdout.write('\u001b[2K'); +  }, + +  beginningOfLine: function(){ +    process.stdout.write('\u001b[0G'); +  }, + +  CR: function(){ +    exports.cursor.deleteLine(); +    exports.cursor.beginningOfLine(); +  } +}; + +/** + * Outut the given `failures` as a list. + * + * @param {Array} failures + * @api public + */ + +exports.list = function(failures){ +  console.error(); +  failures.forEach(function(test, i){ +    // format +    var fmt = color('error title', '  %s) %s:\n') +      + color('error message', '     %s') +      + color('error stack', '\n%s\n'); + +    // msg +    var err = test.err +      , message = err.message || '' +      , stack = err.stack || message +      , index = stack.indexOf(message) + message.length +      , msg = stack.slice(0, index) +      , actual = err.actual +      , expected = err.expected +      , escape = true; + +    // explicitly show diff +    if (err.showDiff) { +      escape = false; +      err.actual = actual = JSON.stringify(actual, null, 2); +      err.expected = expected = JSON.stringify(expected, null, 2); +    } + +    // actual / expected diff +    if ('string' == typeof actual && 'string' == typeof expected) { +      var len = Math.max(actual.length, expected.length); + +      if (len < 20) msg = errorDiff(err, 'Chars', escape); +      else msg = errorDiff(err, 'Words', escape); + +      // linenos +      var lines = msg.split('\n'); +      if (lines.length > 4) { +        var width = String(lines.length).length; +        msg = lines.map(function(str, i){ +          return pad(++i, width) + ' |' + ' ' + str; +        }).join('\n'); +      } + +      // legend +      msg = '\n' +        + color('diff removed', 'actual') +        + ' ' +        + color('diff added', 'expected') +        + '\n\n' +        + msg +        + '\n'; + +      // indent +      msg = msg.replace(/^/gm, '      '); + +      fmt = color('error title', '  %s) %s:\n%s') +        + color('error stack', '\n%s\n'); +    } + +    // indent stack trace without msg +    stack = stack.slice(index ? index + 1 : index) +      .replace(/^/gm, '  '); + +    console.error(fmt, (i + 1), test.fullTitle(), msg, stack); +  }); +}; + +/** + * Initialize a new `Base` reporter. + * + * All other reporters generally + * inherit from this reporter, providing + * stats such as test duration, number + * of tests passed / failed etc. + * + * @param {Runner} runner + * @api public + */ + +function Base(runner) { +  var self = this +    , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } +    , failures = this.failures = []; + +  if (!runner) return; +  this.runner = runner; + +  runner.stats = stats; + +  runner.on('start', function(){ +    stats.start = new Date; +  }); + +  runner.on('suite', function(suite){ +    stats.suites = stats.suites || 0; +    suite.root || stats.suites++; +  }); + +  runner.on('test end', function(test){ +    stats.tests = stats.tests || 0; +    stats.tests++; +  }); + +  runner.on('pass', function(test){ +    stats.passes = stats.passes || 0; + +    var medium = test.slow() / 2; +    test.speed = test.duration > test.slow() +      ? 'slow' +      : test.duration > medium +        ? 'medium' +        : 'fast'; + +    stats.passes++; +  }); + +  runner.on('fail', function(test, err){ +    stats.failures = stats.failures || 0; +    stats.failures++; +    test.err = err; +    failures.push(test); +  }); + +  runner.on('end', function(){ +    stats.end = new Date; +    stats.duration = new Date - stats.start; +  }); + +  runner.on('pending', function(){ +    stats.pending++; +  }); +} + +/** + * Output common epilogue used by many of + * the bundled reporters. + * + * @api public + */ + +Base.prototype.epilogue = function(){ +  var stats = this.stats +    , fmt +    , tests; + +  console.log(); + +  function pluralize(n) { +    return 1 == n ? 'test' : 'tests'; +  } + +  // failure +  if (stats.failures) { +    fmt = color('bright fail', '  ' + exports.symbols.err) +      + color('fail', ' %d of %d %s failed') +      + color('light', ':') + +    console.error(fmt, +      stats.failures, +      this.runner.total, +      pluralize(this.runner.total)); + +    Base.list(this.failures); +    console.error(); +    return; +  } + +  // pass +  fmt = color('bright pass', ' ') +    + color('green', ' %d %s complete') +    + color('light', ' (%s)'); + +  console.log(fmt, +    stats.tests || 0, +    pluralize(stats.tests), +    ms(stats.duration)); + +  // pending +  if (stats.pending) { +    fmt = color('pending', ' ') +      + color('pending', ' %d %s pending'); + +    console.log(fmt, stats.pending, pluralize(stats.pending)); +  } + +  console.log(); +}; + +/** + * Pad the given `str` to `len`. + * + * @param {String} str + * @param {String} len + * @return {String} + * @api private + */ + +function pad(str, len) { +  str = String(str); +  return Array(len - str.length + 1).join(' ') + str; +} + +/** + * Return a character diff for `err`. + * + * @param {Error} err + * @return {String} + * @api private + */ + +function errorDiff(err, type, escape) { +  return diff['diff' + type](err.actual, err.expected).map(function(str){ +    if (escape) { +      str.value = str.value +        .replace(/\t/g, '<tab>') +        .replace(/\r/g, '<CR>') +        .replace(/\n/g, '<LF>\n'); +    } +    if (str.added) return colorLines('diff added', str.value); +    if (str.removed) return colorLines('diff removed', str.value); +    return str.value; +  }).join(''); +} + +/** + * Color lines for `str`, using the color `name`. + * + * @param {String} name + * @param {String} str + * @return {String} + * @api private + */ + +function colorLines(name, str) { +  return str.split('\n').map(function(str){ +    return color(name, str); +  }).join('\n'); +} + +}); // module: reporters/base.js + +require.register("reporters/doc.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , utils = require('../utils'); + +/** + * Expose `Doc`. + */ + +exports = module.exports = Doc; + +/** + * Initialize a new `Doc` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Doc(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , total = runner.total +    , indents = 2; + +  function indent() { +    return Array(indents).join('  '); +  } + +  runner.on('suite', function(suite){ +    if (suite.root) return; +    ++indents; +    console.log('%s<section class="suite">', indent()); +    ++indents; +    console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title)); +    console.log('%s<dl>', indent()); +  }); + +  runner.on('suite end', function(suite){ +    if (suite.root) return; +    console.log('%s</dl>', indent()); +    --indents; +    console.log('%s</section>', indent()); +    --indents; +  }); + +  runner.on('pass', function(test){ +    console.log('%s  <dt>%s</dt>', indent(), utils.escape(test.title)); +    var code = utils.escape(utils.clean(test.fn.toString())); +    console.log('%s  <dd><pre><code>%s</code></pre></dd>', indent(), code); +  }); +} + +}); // module: reporters/doc.js + +require.register("reporters/dot.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = Dot; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + */ + +function Dot(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , width = Base.window.width * .75 | 0 +    , n = 0; + +  runner.on('start', function(){ +    process.stdout.write('\n  '); +  }); + +  runner.on('pending', function(test){ +    process.stdout.write(color('pending', Base.symbols.dot)); +  }); + +  runner.on('pass', function(test){ +    if (++n % width == 0) process.stdout.write('\n  '); +    if ('slow' == test.speed) { +      process.stdout.write(color('bright yellow', Base.symbols.dot)); +    } else { +      process.stdout.write(color(test.speed, Base.symbols.dot)); +    } +  }); + +  runner.on('fail', function(test, err){ +    if (++n % width == 0) process.stdout.write('\n  '); +    process.stdout.write(color('fail', Base.symbols.dot)); +  }); + +  runner.on('end', function(){ +    console.log(); +    self.epilogue(); +  }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Dot.prototype = new F; +Dot.prototype.constructor = Dot; + +}); // module: reporters/dot.js + +require.register("reporters/html-cov.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var JSONCov = require('./json-cov') +  , fs = require('browser/fs'); + +/** + * Expose `HTMLCov`. + */ + +exports = module.exports = HTMLCov; + +/** + * Initialize a new `JsCoverage` reporter. + * + * @param {Runner} runner + * @api public + */ + +function HTMLCov(runner) { +  var jade = require('jade') +    , file = __dirname + '/templates/coverage.jade' +    , str = fs.readFileSync(file, 'utf8') +    , fn = jade.compile(str, { filename: file }) +    , self = this; + +  JSONCov.call(this, runner, false); + +  runner.on('end', function(){ +    process.stdout.write(fn({ +        cov: self.cov +      , coverageClass: coverageClass +    })); +  }); +} + +/** + * Return coverage class for `n`. + * + * @return {String} + * @api private + */ + +function coverageClass(n) { +  if (n >= 75) return 'high'; +  if (n >= 50) return 'medium'; +  if (n >= 25) return 'low'; +  return 'terrible'; +} +}); // module: reporters/html-cov.js + +require.register("reporters/html.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , utils = require('../utils') +  , Progress = require('../browser/progress') +  , escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date +  , setTimeout = global.setTimeout +  , setInterval = global.setInterval +  , clearTimeout = global.clearTimeout +  , clearInterval = global.clearInterval; + +/** + * Expose `Doc`. + */ + +exports = module.exports = HTML; + +/** + * Stats template. + */ + +var statsTemplate = '<ul id="mocha-stats">' +  + '<li class="progress"><canvas width="40" height="40"></canvas></li>' +  + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>' +  + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>' +  + '<li class="duration">duration: <em>0</em>s</li>' +  + '</ul>'; + +/** + * Initialize a new `Doc` reporter. + * + * @param {Runner} runner + * @api public + */ + +function HTML(runner, root) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , total = runner.total +    , stat = fragment(statsTemplate) +    , items = stat.getElementsByTagName('li') +    , passes = items[1].getElementsByTagName('em')[0] +    , passesLink = items[1].getElementsByTagName('a')[0] +    , failures = items[2].getElementsByTagName('em')[0] +    , failuresLink = items[2].getElementsByTagName('a')[0] +    , duration = items[3].getElementsByTagName('em')[0] +    , canvas = stat.getElementsByTagName('canvas')[0] +    , report = fragment('<ul id="mocha-report"></ul>') +    , stack = [report] +    , progress +    , ctx + +  root = root || document.getElementById('mocha'); + +  if (canvas.getContext) { +    var ratio = window.devicePixelRatio || 1; +    canvas.style.width = canvas.width; +    canvas.style.height = canvas.height; +    canvas.width *= ratio; +    canvas.height *= ratio; +    ctx = canvas.getContext('2d'); +    ctx.scale(ratio, ratio); +    progress = new Progress; +  } + +  if (!root) return error('#mocha div missing, add it to your document'); + +  // pass toggle +  on(passesLink, 'click', function(){ +    unhide(); +    var name = /pass/.test(report.className) ? '' : ' pass'; +    report.className = report.className.replace(/fail|pass/g, '') + name; +    if (report.className.trim()) hideSuitesWithout('test pass'); +  }); + +  // failure toggle +  on(failuresLink, 'click', function(){ +    unhide(); +    var name = /fail/.test(report.className) ? '' : ' fail'; +    report.className = report.className.replace(/fail|pass/g, '') + name; +    if (report.className.trim()) hideSuitesWithout('test fail'); +  }); + +  root.appendChild(stat); +  root.appendChild(report); + +  if (progress) progress.size(40); + +  runner.on('suite', function(suite){ +    if (suite.root) return; + +    // suite +    var url = '?grep=' + encodeURIComponent(suite.fullTitle()); +    var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title)); + +    // container +    stack[0].appendChild(el); +    stack.unshift(document.createElement('ul')); +    el.appendChild(stack[0]); +  }); + +  runner.on('suite end', function(suite){ +    if (suite.root) return; +    stack.shift(); +  }); + +  runner.on('fail', function(test, err){ +    if ('hook' == test.type) runner.emit('test end', test); +  }); + +  runner.on('test end', function(test){ +    // TODO: add to stats +    var percent = stats.tests / this.total * 100 | 0; +    if (progress) progress.update(percent).draw(ctx); + +    // update stats +    var ms = new Date - stats.start; +    text(passes, stats.passes); +    text(failures, stats.failures); +    text(duration, (ms / 1000).toFixed(2)); + +    // test +    if ('passed' == test.state) { +      var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="?grep=%e" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle())); +    } else if (test.pending) { +      var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title); +    } else { +      var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle())); +      var str = test.err.stack || test.err.toString(); + +      // FF / Opera do not add the message +      if (!~str.indexOf(test.err.message)) { +        str = test.err.message + '\n' + str; +      } + +      // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we +      // check for the result of the stringifying. +      if ('[object Error]' == str) str = test.err.message; + +      // Safari doesn't give you a stack. Let's at least provide a source line. +      if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { +        str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; +      } + +      el.appendChild(fragment('<pre class="error">%e</pre>', str)); +    } + +    // toggle code +    // TODO: defer +    if (!test.pending) { +      var h2 = el.getElementsByTagName('h2')[0]; + +      on(h2, 'click', function(){ +        pre.style.display = 'none' == pre.style.display +          ? 'block' +          : 'none'; +      }); + +      var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString())); +      el.appendChild(pre); +      pre.style.display = 'none'; +    } + +    // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. +    if (stack[0]) stack[0].appendChild(el); +  }); +} + +/** + * Display error `msg`. + */ + +function error(msg) { +  document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg)); +} + +/** + * Return a DOM fragment from `html`. + */ + +function fragment(html) { +  var args = arguments +    , div = document.createElement('div') +    , i = 1; + +  div.innerHTML = html.replace(/%([se])/g, function(_, type){ +    switch (type) { +      case 's': return String(args[i++]); +      case 'e': return escape(args[i++]); +    } +  }); + +  return div.firstChild; +} + +/** + * Check for suites that do not have elements + * with `classname`, and hide them. + */ + +function hideSuitesWithout(classname) { +  var suites = document.getElementsByClassName('suite'); +  for (var i = 0; i < suites.length; i++) { +    var els = suites[i].getElementsByClassName(classname); +    if (0 == els.length) suites[i].className += ' hidden'; +  } +} + +/** + * Unhide .hidden suites. + */ + +function unhide() { +  var els = document.getElementsByClassName('suite hidden'); +  for (var i = 0; i < els.length; ++i) { +    els[i].className = els[i].className.replace('suite hidden', 'suite'); +  } +} + +/** + * Set `el` text to `str`. + */ + +function text(el, str) { +  if (el.textContent) { +    el.textContent = str; +  } else { +    el.innerText = str; +  } +} + +/** + * Listen on `event` with callback `fn`. + */ + +function on(el, event, fn) { +  if (el.addEventListener) { +    el.addEventListener(event, fn, false); +  } else { +    el.attachEvent('on' + event, fn); +  } +} + +}); // module: reporters/html.js + +require.register("reporters/index.js", function(module, exports, require){ + +exports.Base = require('./base'); +exports.Dot = require('./dot'); +exports.Doc = require('./doc'); +exports.TAP = require('./tap'); +exports.JSON = require('./json'); +exports.HTML = require('./html'); +exports.List = require('./list'); +exports.Min = require('./min'); +exports.Spec = require('./spec'); +exports.Nyan = require('./nyan'); +exports.XUnit = require('./xunit'); +exports.Markdown = require('./markdown'); +exports.Progress = require('./progress'); +exports.Landing = require('./landing'); +exports.JSONCov = require('./json-cov'); +exports.HTMLCov = require('./html-cov'); +exports.JSONStream = require('./json-stream'); +exports.Teamcity = require('./teamcity'); + +}); // module: reporters/index.js + +require.register("reporters/json-cov.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `JSONCov`. + */ + +exports = module.exports = JSONCov; + +/** + * Initialize a new `JsCoverage` reporter. + * + * @param {Runner} runner + * @param {Boolean} output + * @api public + */ + +function JSONCov(runner, output) { +  var self = this +    , output = 1 == arguments.length ? true : output; + +  Base.call(this, runner); + +  var tests = [] +    , failures = [] +    , passes = []; + +  runner.on('test end', function(test){ +    tests.push(test); +  }); + +  runner.on('pass', function(test){ +    passes.push(test); +  }); + +  runner.on('fail', function(test){ +    failures.push(test); +  }); + +  runner.on('end', function(){ +    var cov = global._$jscoverage || {}; +    var result = self.cov = map(cov); +    result.stats = self.stats; +    result.tests = tests.map(clean); +    result.failures = failures.map(clean); +    result.passes = passes.map(clean); +    if (!output) return; +    process.stdout.write(JSON.stringify(result, null, 2 )); +  }); +} + +/** + * Map jscoverage data to a JSON structure + * suitable for reporting. + * + * @param {Object} cov + * @return {Object} + * @api private + */ + +function map(cov) { +  var ret = { +      instrumentation: 'node-jscoverage' +    , sloc: 0 +    , hits: 0 +    , misses: 0 +    , coverage: 0 +    , files: [] +  }; + +  for (var filename in cov) { +    var data = coverage(filename, cov[filename]); +    ret.files.push(data); +    ret.hits += data.hits; +    ret.misses += data.misses; +    ret.sloc += data.sloc; +  } + +  ret.files.sort(function(a, b) { +    return a.filename.localeCompare(b.filename); +  }); + +  if (ret.sloc > 0) { +    ret.coverage = (ret.hits / ret.sloc) * 100; +  } + +  return ret; +}; + +/** + * Map jscoverage data for a single source file + * to a JSON structure suitable for reporting. + * + * @param {String} filename name of the source file + * @param {Object} data jscoverage coverage data + * @return {Object} + * @api private + */ + +function coverage(filename, data) { +  var ret = { +    filename: filename, +    coverage: 0, +    hits: 0, +    misses: 0, +    sloc: 0, +    source: {} +  }; + +  data.source.forEach(function(line, num){ +    num++; + +    if (data[num] === 0) { +      ret.misses++; +      ret.sloc++; +    } else if (data[num] !== undefined) { +      ret.hits++; +      ret.sloc++; +    } + +    ret.source[num] = { +        source: line +      , coverage: data[num] === undefined +        ? '' +        : data[num] +    }; +  }); + +  ret.coverage = ret.hits / ret.sloc * 100; + +  return ret; +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { +  return { +      title: test.title +    , fullTitle: test.fullTitle() +    , duration: test.duration +  } +} + +}); // module: reporters/json-cov.js + +require.register("reporters/json-stream.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , color = Base.color; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function List(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , total = runner.total; + +  runner.on('start', function(){ +    console.log(JSON.stringify(['start', { total: total }])); +  }); + +  runner.on('pass', function(test){ +    console.log(JSON.stringify(['pass', clean(test)])); +  }); + +  runner.on('fail', function(test, err){ +    console.log(JSON.stringify(['fail', clean(test)])); +  }); + +  runner.on('end', function(){ +    process.stdout.write(JSON.stringify(['end', self.stats])); +  }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { +  return { +      title: test.title +    , fullTitle: test.fullTitle() +    , duration: test.duration +  } +} +}); // module: reporters/json-stream.js + +require.register("reporters/json.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , cursor = Base.cursor +  , color = Base.color; + +/** + * Expose `JSON`. + */ + +exports = module.exports = JSONReporter; + +/** + * Initialize a new `JSON` reporter. + * + * @param {Runner} runner + * @api public + */ + +function JSONReporter(runner) { +  var self = this; +  Base.call(this, runner); + +  var tests = [] +    , failures = [] +    , passes = []; + +  runner.on('test end', function(test){ +    tests.push(test); +  }); + +  runner.on('pass', function(test){ +    passes.push(test); +  }); + +  runner.on('fail', function(test){ +    failures.push(test); +  }); + +  runner.on('end', function(){ +    var obj = { +        stats: self.stats +      , tests: tests.map(clean) +      , failures: failures.map(clean) +      , passes: passes.map(clean) +    }; + +    process.stdout.write(JSON.stringify(obj, null, 2)); +  }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { +  return { +      title: test.title +    , fullTitle: test.fullTitle() +    , duration: test.duration +  } +} +}); // module: reporters/json.js + +require.register("reporters/landing.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , cursor = Base.cursor +  , color = Base.color; + +/** + * Expose `Landing`. + */ + +exports = module.exports = Landing; + +/** + * Airplane color. + */ + +Base.colors.plane = 0; + +/** + * Airplane crash color. + */ + +Base.colors['plane crash'] = 31; + +/** + * Runway color. + */ + +Base.colors.runway = 90; + +/** + * Initialize a new `Landing` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Landing(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , width = Base.window.width * .75 | 0 +    , total = runner.total +    , stream = process.stdout +    , plane = color('plane', '✈') +    , crashed = -1 +    , n = 0; + +  function runway() { +    var buf = Array(width).join('-'); +    return '  ' + color('runway', buf); +  } + +  runner.on('start', function(){ +    stream.write('\n  '); +    cursor.hide(); +  }); + +  runner.on('test end', function(test){ +    // check if the plane crashed +    var col = -1 == crashed +      ? width * ++n / total | 0 +      : crashed; + +    // show the crash +    if ('failed' == test.state) { +      plane = color('plane crash', '✈'); +      crashed = col; +    } + +    // render landing strip +    stream.write('\u001b[4F\n\n'); +    stream.write(runway()); +    stream.write('\n  '); +    stream.write(color('runway', Array(col).join('⋅'))); +    stream.write(plane) +    stream.write(color('runway', Array(width - col).join('⋅') + '\n')); +    stream.write(runway()); +    stream.write('\u001b[0m'); +  }); + +  runner.on('end', function(){ +    cursor.show(); +    console.log(); +    self.epilogue(); +  }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Landing.prototype = new F; +Landing.prototype.constructor = Landing; + +}); // module: reporters/landing.js + +require.register("reporters/list.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , cursor = Base.cursor +  , color = Base.color; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function List(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , n = 0; + +  runner.on('start', function(){ +    console.log(); +  }); + +  runner.on('test', function(test){ +    process.stdout.write(color('pass', '    ' + test.fullTitle() + ': ')); +  }); + +  runner.on('pending', function(test){ +    var fmt = color('checkmark', '  -') +      + color('pending', ' %s'); +    console.log(fmt, test.fullTitle()); +  }); + +  runner.on('pass', function(test){ +    var fmt = color('checkmark', '  '+Base.symbols.dot) +      + color('pass', ' %s: ') +      + color(test.speed, '%dms'); +    cursor.CR(); +    console.log(fmt, test.fullTitle(), test.duration); +  }); + +  runner.on('fail', function(test, err){ +    cursor.CR(); +    console.log(color('fail', '  %d) %s'), ++n, test.fullTitle()); +  }); + +  runner.on('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +List.prototype = new F; +List.prototype.constructor = List; + + +}); // module: reporters/list.js + +require.register("reporters/markdown.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') +  , utils = require('../utils'); + +/** + * Expose `Markdown`. + */ + +exports = module.exports = Markdown; + +/** + * Initialize a new `Markdown` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Markdown(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , level = 0 +    , buf = ''; + +  function title(str) { +    return Array(level).join('#') + ' ' + str; +  } + +  function indent() { +    return Array(level).join('  '); +  } + +  function mapTOC(suite, obj) { +    var ret = obj; +    obj = obj[suite.title] = obj[suite.title] || { suite: suite }; +    suite.suites.forEach(function(suite){ +      mapTOC(suite, obj); +    }); +    return ret; +  } + +  function stringifyTOC(obj, level) { +    ++level; +    var buf = ''; +    var link; +    for (var key in obj) { +      if ('suite' == key) continue; +      if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; +      if (key) buf += Array(level).join('  ') + link; +      buf += stringifyTOC(obj[key], level); +    } +    --level; +    return buf; +  } + +  function generateTOC(suite) { +    var obj = mapTOC(suite, {}); +    return stringifyTOC(obj, 0); +  } + +  generateTOC(runner.suite); + +  runner.on('suite', function(suite){ +    ++level; +    var slug = utils.slug(suite.fullTitle()); +    buf += '<a name="' + slug + '"></a>' + '\n'; +    buf += title(suite.title) + '\n'; +  }); + +  runner.on('suite end', function(suite){ +    --level; +  }); + +  runner.on('pass', function(test){ +    var code = utils.clean(test.fn.toString()); +    buf += test.title + '.\n'; +    buf += '\n```js\n'; +    buf += code + '\n'; +    buf += '```\n\n'; +  }); + +  runner.on('end', function(){ +    process.stdout.write('# TOC\n'); +    process.stdout.write(generateTOC(runner.suite)); +    process.stdout.write(buf); +  }); +} +}); // module: reporters/markdown.js + +require.register("reporters/min.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `Min`. + */ + +exports = module.exports = Min; + +/** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @param {Runner} runner + * @api public + */ + +function Min(runner) { +  Base.call(this, runner); + +  runner.on('start', function(){ +    // clear screen +    process.stdout.write('\u001b[2J'); +    // set cursor position +    process.stdout.write('\u001b[1;3H'); +  }); + +  runner.on('end', this.epilogue.bind(this)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Min.prototype = new F; +Min.prototype.constructor = Min; + + +}); // module: reporters/min.js + +require.register("reporters/nyan.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') +  , color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = NyanCat; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + */ + +function NyanCat(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , width = Base.window.width * .75 | 0 +    , rainbowColors = this.rainbowColors = self.generateColors() +    , colorIndex = this.colorIndex = 0 +    , numerOfLines = this.numberOfLines = 4 +    , trajectories = this.trajectories = [[], [], [], []] +    , nyanCatWidth = this.nyanCatWidth = 11 +    , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) +    , scoreboardWidth = this.scoreboardWidth = 5 +    , tick = this.tick = 0 +    , n = 0; + +  runner.on('start', function(){ +    Base.cursor.hide(); +    self.draw('start'); +  }); + +  runner.on('pending', function(test){ +    self.draw('pending'); +  }); + +  runner.on('pass', function(test){ +    self.draw('pass'); +  }); + +  runner.on('fail', function(test, err){ +    self.draw('fail'); +  }); + +  runner.on('end', function(){ +    Base.cursor.show(); +    for (var i = 0; i < self.numberOfLines; i++) write('\n'); +    self.epilogue(); +  }); +} + +/** + * Draw the nyan cat with runner `status`. + * + * @param {String} status + * @api private + */ + +NyanCat.prototype.draw = function(status){ +  this.appendRainbow(); +  this.drawScoreboard(); +  this.drawRainbow(); +  this.drawNyanCat(status); +  this.tick = !this.tick; +}; + +/** + * Draw the "scoreboard" showing the number + * of passes, failures and pending tests. + * + * @api private + */ + +NyanCat.prototype.drawScoreboard = function(){ +  var stats = this.stats; +  var colors = Base.colors; + +  function draw(color, n) { +    write(' '); +    write('\u001b[' + color + 'm' + n + '\u001b[0m'); +    write('\n'); +  } + +  draw(colors.green, stats.passes); +  draw(colors.fail, stats.failures); +  draw(colors.pending, stats.pending); +  write('\n'); + +  this.cursorUp(this.numberOfLines); +}; + +/** + * Append the rainbow. + * + * @api private + */ + +NyanCat.prototype.appendRainbow = function(){ +  var segment = this.tick ? '_' : '-'; +  var rainbowified = this.rainbowify(segment); + +  for (var index = 0; index < this.numberOfLines; index++) { +    var trajectory = this.trajectories[index]; +    if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); +    trajectory.push(rainbowified); +  } +}; + +/** + * Draw the rainbow. + * + * @api private + */ + +NyanCat.prototype.drawRainbow = function(){ +  var self = this; + +  this.trajectories.forEach(function(line, index) { +    write('\u001b[' + self.scoreboardWidth + 'C'); +    write(line.join('')); +    write('\n'); +  }); + +  this.cursorUp(this.numberOfLines); +}; + +/** + * Draw the nyan cat with `status`. + * + * @param {String} status + * @api private + */ + +NyanCat.prototype.drawNyanCat = function(status) { +  var self = this; +  var startWidth = this.scoreboardWidth + this.trajectories[0].length; +  var color = '\u001b[' + startWidth + 'C'; +  var padding = ''; + +  write(color); +  write('_,------,'); +  write('\n'); + +  write(color); +  padding = self.tick ? '  ' : '   '; +  write('_|' + padding + '/\\_/\\ '); +  write('\n'); + +  write(color); +  padding = self.tick ? '_' : '__'; +  var tail = self.tick ? '~' : '^'; +  var face; +  switch (status) { +    case 'pass': +      face = '( ^ .^)'; +      break; +    case 'fail': +      face = '( o .o)'; +      break; +    default: +      face = '( - .-)'; +  } +  write(tail + '|' + padding + face + ' '); +  write('\n'); + +  write(color); +  padding = self.tick ? ' ' : '  '; +  write(padding + '""  "" '); +  write('\n'); + +  this.cursorUp(this.numberOfLines); +}; + +/** + * Move cursor up `n`. + * + * @param {Number} n + * @api private + */ + +NyanCat.prototype.cursorUp = function(n) { +  write('\u001b[' + n + 'A'); +}; + +/** + * Move cursor down `n`. + * + * @param {Number} n + * @api private + */ + +NyanCat.prototype.cursorDown = function(n) { +  write('\u001b[' + n + 'B'); +}; + +/** + * Generate rainbow colors. + * + * @return {Array} + * @api private + */ + +NyanCat.prototype.generateColors = function(){ +  var colors = []; + +  for (var i = 0; i < (6 * 7); i++) { +    var pi3 = Math.floor(Math.PI / 3); +    var n = (i * (1.0 / 6)); +    var r = Math.floor(3 * Math.sin(n) + 3); +    var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); +    var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); +    colors.push(36 * r + 6 * g + b + 16); +  } + +  return colors; +}; + +/** + * Apply rainbow to the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +NyanCat.prototype.rainbowify = function(str){ +  var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; +  this.colorIndex += 1; +  return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; +}; + +/** + * Stdout helper. + */ + +function write(string) { +  process.stdout.write(string); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +NyanCat.prototype = new F; +NyanCat.prototype.constructor = NyanCat; + + +}); // module: reporters/nyan.js + +require.register("reporters/progress.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , cursor = Base.cursor +  , color = Base.color; + +/** + * Expose `Progress`. + */ + +exports = module.exports = Progress; + +/** + * General progress bar color. + */ + +Base.colors.progress = 90; + +/** + * Initialize a new `Progress` bar test reporter. + * + * @param {Runner} runner + * @param {Object} options + * @api public + */ + +function Progress(runner, options) { +  Base.call(this, runner); + +  var self = this +    , options = options || {} +    , stats = this.stats +    , width = Base.window.width * .50 | 0 +    , total = runner.total +    , complete = 0 +    , max = Math.max; + +  // default chars +  options.open = options.open || '['; +  options.complete = options.complete || '▬'; +  options.incomplete = options.incomplete || Base.symbols.dot; +  options.close = options.close || ']'; +  options.verbose = false; + +  // tests started +  runner.on('start', function(){ +    console.log(); +    cursor.hide(); +  }); + +  // tests complete +  runner.on('test end', function(){ +    complete++; +    var incomplete = total - complete +      , percent = complete / total +      , n = width * percent | 0 +      , i = width - n; + +    cursor.CR(); +    process.stdout.write('\u001b[J'); +    process.stdout.write(color('progress', '  ' + options.open)); +    process.stdout.write(Array(n).join(options.complete)); +    process.stdout.write(Array(i).join(options.incomplete)); +    process.stdout.write(color('progress', options.close)); +    if (options.verbose) { +      process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); +    } +  }); + +  // tests are complete, output some stats +  // and the failures if any +  runner.on('end', function(){ +    cursor.show(); +    console.log(); +    self.epilogue(); +  }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Progress.prototype = new F; +Progress.prototype.constructor = Progress; + + +}); // module: reporters/progress.js + +require.register("reporters/spec.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , cursor = Base.cursor +  , color = Base.color; + +/** + * Expose `Spec`. + */ + +exports = module.exports = Spec; + +/** + * Initialize a new `Spec` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function Spec(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , indents = 0 +    , n = 0; + +  function indent() { +    return Array(indents).join('  ') +  } + +  runner.on('start', function(){ +    console.log(); +  }); + +  runner.on('suite', function(suite){ +    ++indents; +    console.log(color('suite', '%s%s'), indent(), suite.title); +  }); + +  runner.on('suite end', function(suite){ +    --indents; +    if (1 == indents) console.log(); +  }); + +  runner.on('test', function(test){ +    process.stdout.write(indent() + color('pass', '  ◦ ' + test.title + ': ')); +  }); + +  runner.on('pending', function(test){ +    var fmt = indent() + color('pending', '  - %s'); +    console.log(fmt, test.title); +  }); + +  runner.on('pass', function(test){ +    if ('fast' == test.speed) { +      var fmt = indent() +        + color('checkmark', '  ' + Base.symbols.ok) +        + color('pass', ' %s '); +      cursor.CR(); +      console.log(fmt, test.title); +    } else { +      var fmt = indent() +        + color('checkmark', '  ' + Base.symbols.ok) +        + color('pass', ' %s ') +        + color(test.speed, '(%dms)'); +      cursor.CR(); +      console.log(fmt, test.title, test.duration); +    } +  }); + +  runner.on('fail', function(test, err){ +    cursor.CR(); +    console.log(indent() + color('fail', '  %d) %s'), ++n, test.title); +  }); + +  runner.on('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Spec.prototype = new F; +Spec.prototype.constructor = Spec; + + +}); // module: reporters/spec.js + +require.register("reporters/tap.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , cursor = Base.cursor +  , color = Base.color; + +/** + * Expose `TAP`. + */ + +exports = module.exports = TAP; + +/** + * Initialize a new `TAP` reporter. + * + * @param {Runner} runner + * @api public + */ + +function TAP(runner) { +  Base.call(this, runner); + +  var self = this +    , stats = this.stats +    , n = 1 +    , passes = 0 +    , failures = 0; + +  runner.on('start', function(){ +    var total = runner.grepTotal(runner.suite); +    console.log('%d..%d', 1, total); +  }); + +  runner.on('test end', function(){ +    ++n; +  }); + +  runner.on('pending', function(test){ +    console.log('ok %d %s # SKIP -', n, title(test)); +  }); + +  runner.on('pass', function(test){ +    passes++; +    console.log('ok %d %s', n, title(test)); +  }); + +  runner.on('fail', function(test, err){ +    failures++; +    console.log('not ok %d %s', n, title(test)); +    if (err.stack) console.log(err.stack.replace(/^/gm, '  ')); +  }); + +  runner.on('end', function(){ +    console.log('# tests ' + (passes + failures)); +    console.log('# pass ' + passes); +    console.log('# fail ' + failures); +  }); +} + +/** + * Return a TAP-safe title of `test` + * + * @param {Object} test + * @return {String} + * @api private + */ + +function title(test) { +  return test.fullTitle().replace(/#/g, ''); +} + +}); // module: reporters/tap.js + +require.register("reporters/teamcity.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `Teamcity`. + */ + +exports = module.exports = Teamcity; + +/** + * Initialize a new `Teamcity` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Teamcity(runner) { +  Base.call(this, runner); +  var stats = this.stats; + +  runner.on('start', function() { +    console.log("##teamcity[testSuiteStarted name='mocha.suite']"); +  }); + +  runner.on('test', function(test) { +    console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); +  }); + +  runner.on('fail', function(test, err) { +    console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); +  }); + +  runner.on('pending', function(test) { +    console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); +  }); + +  runner.on('test end', function(test) { +    console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); +  }); + +  runner.on('end', function() { +    console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); +  }); +} + +/** + * Escape the given `str`. + */ + +function escape(str) { +  return str +    .replace(/\|/g, "||") +    .replace(/\n/g, "|n") +    .replace(/\r/g, "|r") +    .replace(/\[/g, "|[") +    .replace(/\]/g, "|]") +    .replace(/\u0085/g, "|x") +    .replace(/\u2028/g, "|l") +    .replace(/\u2029/g, "|p") +    .replace(/'/g, "|'"); +} + +}); // module: reporters/teamcity.js + +require.register("reporters/xunit.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') +  , utils = require('../utils') +  , escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date +  , setTimeout = global.setTimeout +  , setInterval = global.setInterval +  , clearTimeout = global.clearTimeout +  , clearInterval = global.clearInterval; + +/** + * Expose `XUnit`. + */ + +exports = module.exports = XUnit; + +/** + * Initialize a new `XUnit` reporter. + * + * @param {Runner} runner + * @api public + */ + +function XUnit(runner) { +  Base.call(this, runner); +  var stats = this.stats +    , tests = [] +    , self = this; + +  runner.on('pass', function(test){ +    tests.push(test); +  }); + +  runner.on('fail', function(test){ +    tests.push(test); +  }); + +  runner.on('end', function(){ +    console.log(tag('testsuite', { +        name: 'Mocha Tests' +      , tests: stats.tests +      , failures: stats.failures +      , errors: stats.failures +      , skip: stats.tests - stats.failures - stats.passes +      , timestamp: (new Date).toUTCString() +      , time: stats.duration / 1000 +    }, false)); + +    tests.forEach(test); +    console.log('</testsuite>'); +  }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +XUnit.prototype = new F; +XUnit.prototype.constructor = XUnit; + + +/** + * Output tag for the given `test.` + */ + +function test(test) { +  var attrs = { +      classname: test.parent.fullTitle() +    , name: test.title +    , time: test.duration / 1000 +  }; + +  if ('failed' == test.state) { +    var err = test.err; +    attrs.message = escape(err.message); +    console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); +  } else if (test.pending) { +    console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); +  } else { +    console.log(tag('testcase', attrs, true) ); +  } +} + +/** + * HTML tag helper. + */ + +function tag(name, attrs, close, content) { +  var end = close ? '/>' : '>' +    , pairs = [] +    , tag; + +  for (var key in attrs) { +    pairs.push(key + '="' + escape(attrs[key]) + '"'); +  } + +  tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; +  if (content) tag += content + '</' + name + end; +  return tag; +} + +/** + * Return cdata escaped CDATA `str`. + */ + +function cdata(str) { +  return '<![CDATA[' + escape(str) + ']]>'; +} + +}); // module: reporters/xunit.js + +require.register("runnable.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter +  , debug = require('browser/debug')('mocha:runnable') +  , milliseconds = require('./ms'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date +  , setTimeout = global.setTimeout +  , setInterval = global.setInterval +  , clearTimeout = global.clearTimeout +  , clearInterval = global.clearInterval; + +/** + * Object#toString(). + */ + +var toString = Object.prototype.toString; + +/** + * Expose `Runnable`. + */ + +module.exports = Runnable; + +/** + * Initialize a new `Runnable` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Runnable(title, fn) { +  this.title = title; +  this.fn = fn; +  this.async = fn && fn.length; +  this.sync = ! this.async; +  this._timeout = 2000; +  this._slow = 75; +  this.timedOut = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Runnable.prototype = new F; +Runnable.prototype.constructor = Runnable; + + +/** + * Set & get timeout `ms`. + * + * @param {Number|String} ms + * @return {Runnable|Number} ms or self + * @api private + */ + +Runnable.prototype.timeout = function(ms){ +  if (0 == arguments.length) return this._timeout; +  if ('string' == typeof ms) ms = milliseconds(ms); +  debug('timeout %d', ms); +  this._timeout = ms; +  if (this.timer) this.resetTimeout(); +  return this; +}; + +/** + * Set & get slow `ms`. + * + * @param {Number|String} ms + * @return {Runnable|Number} ms or self + * @api private + */ + +Runnable.prototype.slow = function(ms){ +  if (0 === arguments.length) return this._slow; +  if ('string' == typeof ms) ms = milliseconds(ms); +  debug('timeout %d', ms); +  this._slow = ms; +  return this; +}; + +/** + * Return the full title generated by recursively + * concatenating the parent's full title. + * + * @return {String} + * @api public + */ + +Runnable.prototype.fullTitle = function(){ +  return this.parent.fullTitle() + ' ' + this.title; +}; + +/** + * Clear the timeout. + * + * @api private + */ + +Runnable.prototype.clearTimeout = function(){ +  clearTimeout(this.timer); +}; + +/** + * Inspect the runnable void of private properties. + * + * @return {String} + * @api private + */ + +Runnable.prototype.inspect = function(){ +  return JSON.stringify(this, function(key, val){ +    if ('_' == key[0]) return; +    if ('parent' == key) return '#<Suite>'; +    if ('ctx' == key) return '#<Context>'; +    return val; +  }, 2); +}; + +/** + * Reset the timeout. + * + * @api private + */ + +Runnable.prototype.resetTimeout = function(){ +  var self = this +    , ms = this.timeout(); + +  this.clearTimeout(); +  if (ms) { +    this.timer = setTimeout(function(){ +      self.callback(new Error('timeout of ' + ms + 'ms exceeded')); +      self.timedOut = true; +    }, ms); +  } +}; + +/** + * Run the test and invoke `fn(err)`. + * + * @param {Function} fn + * @api private + */ + +Runnable.prototype.run = function(fn){ +  var self = this +    , ms = this.timeout() +    , start = new Date +    , ctx = this.ctx +    , finished +    , emitted; + +  if (ctx) ctx.runnable(this); + +  // timeout +  if (this.async) { +    if (ms) { +      this.timer = setTimeout(function(){ +        done(new Error('timeout of ' + ms + 'ms exceeded')); +        self.timedOut = true; +      }, ms); +    } +  } + +  // called multiple times +  function multiple(err) { +    if (emitted) return; +    emitted = true; +    self.emit('error', err || new Error('done() called multiple times')); +  } + +  // finished +  function done(err) { +    if (self.timedOut) return; +    if (finished) return multiple(err); +    self.clearTimeout(); +    self.duration = new Date - start; +    finished = true; +    fn(err); +  } + +  // for .resetTimeout() +  this.callback = done; + +  // async +  if (this.async) { +    try { +      this.fn.call(ctx, function(err){ +        if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); +        if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); +        done(); +      }); +    } catch (err) { +      done(err); +    } +    return; +  } + +  if (this.asyncOnly) { +    return done(new Error('--async-only option in use without declaring `done()`')); +  } + +  // sync +  try { +    if (!this.pending) this.fn.call(ctx); +    this.duration = new Date - start; +    fn(); +  } catch (err) { +    fn(err); +  } +}; + +}); // module: runnable.js + +require.register("runner.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter +  , debug = require('browser/debug')('mocha:runner') +  , Test = require('./test') +  , utils = require('./utils') +  , filter = utils.filter +  , keys = utils.keys; + +/** + * Non-enumerable globals. + */ + +var globals = [ +  'setTimeout', +  'clearTimeout', +  'setInterval', +  'clearInterval', +  'XMLHttpRequest', +  'Date' +]; + +/** + * Expose `Runner`. + */ + +module.exports = Runner; + +/** + * Initialize a `Runner` for the given `suite`. + * + * Events: + * + *   - `start`  execution started + *   - `end`  execution complete + *   - `suite`  (suite) test suite execution started + *   - `suite end`  (suite) all tests (and sub-suites) have finished + *   - `test`  (test) test execution started + *   - `test end`  (test) test completed + *   - `hook`  (hook) hook execution started + *   - `hook end`  (hook) hook complete + *   - `pass`  (test) test passed + *   - `fail`  (test, err) test failed + * + * @api public + */ + +function Runner(suite) { +  var self = this; +  this._globals = []; +  this.suite = suite; +  this.total = suite.total(); +  this.failures = 0; +  this.on('test end', function(test){ self.checkGlobals(test); }); +  this.on('hook end', function(hook){ self.checkGlobals(hook); }); +  this.grep(/.*/); +  this.globals(this.globalProps().concat(['errno'])); +} + +/** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @api private + */ + +Runner.immediately = global.setImmediate || process.nextTick; + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Runner.prototype = new F; +Runner.prototype.constructor = Runner; + + +/** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @param {RegExp} re + * @param {Boolean} invert + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.grep = function(re, invert){ +  debug('grep %s', re); +  this._grep = re; +  this._invert = invert; +  this.total = this.grepTotal(this.suite); +  return this; +}; + +/** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @param {Suite} suite + * @return {Number} + * @api public + */ + +Runner.prototype.grepTotal = function(suite) { +  var self = this; +  var total = 0; + +  suite.eachTest(function(test){ +    var match = self._grep.test(test.fullTitle()); +    if (self._invert) match = !match; +    if (match) total++; +  }); + +  return total; +}; + +/** + * Return a list of global properties. + * + * @return {Array} + * @api private + */ + +Runner.prototype.globalProps = function() { +  var props = utils.keys(global); + +  // non-enumerables +  for (var i = 0; i < globals.length; ++i) { +    if (~utils.indexOf(props, globals[i])) continue; +    props.push(globals[i]); +  } + +  return props; +}; + +/** + * Allow the given `arr` of globals. + * + * @param {Array} arr + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.globals = function(arr){ +  if (0 == arguments.length) return this._globals; +  debug('globals %j', arr); +  utils.forEach(arr, function(arr){ +    this._globals.push(arr); +  }, this); +  return this; +}; + +/** + * Check for global variable leaks. + * + * @api private + */ + +Runner.prototype.checkGlobals = function(test){ +  if (this.ignoreLeaks) return; +  var ok = this._globals; +  var globals = this.globalProps(); +  var isNode = process.kill; +  var leaks; + +  // check length - 2 ('errno' and 'location' globals) +  if (isNode && 1 == ok.length - globals.length) return +  else if (2 == ok.length - globals.length) return; + +  leaks = filterLeaks(ok, globals); +  this._globals = this._globals.concat(leaks); + +  if (leaks.length > 1) { +    this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); +  } else if (leaks.length) { +    this.fail(test, new Error('global leak detected: ' + leaks[0])); +  } +}; + +/** + * Fail the given `test`. + * + * @param {Test} test + * @param {Error} err + * @api private + */ + +Runner.prototype.fail = function(test, err){ +  ++this.failures; +  test.state = 'failed'; + +  if ('string' == typeof err) { +    err = new Error('the string "' + err + '" was thrown, throw an Error :)'); +  } + +  this.emit('fail', test, err); +}; + +/** + * Fail the given `hook` with `err`. + * + * Hook failures (currently) hard-end due + * to that fact that a failing hook will + * surely cause subsequent tests to fail, + * causing jumbled reporting. + * + * @param {Hook} hook + * @param {Error} err + * @api private + */ + +Runner.prototype.failHook = function(hook, err){ +  this.fail(hook, err); +  this.emit('end'); +}; + +/** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @param {String} name + * @param {Function} function + * @api private + */ + +Runner.prototype.hook = function(name, fn){ +  var suite = this.suite +    , hooks = suite['_' + name] +    , self = this +    , timer; + +  function next(i) { +    var hook = hooks[i]; +    if (!hook) return fn(); +    self.currentRunnable = hook; + +    self.emit('hook', hook); + +    hook.on('error', function(err){ +      self.failHook(hook, err); +    }); + +    hook.run(function(err){ +      hook.removeAllListeners('error'); +      var testError = hook.error(); +      if (testError) self.fail(self.test, testError); +      if (err) return self.failHook(hook, err); +      self.emit('hook end', hook); +      next(++i); +    }); +  } + +  Runner.immediately(function(){ +    next(0); +  }); +}; + +/** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err)`. + * + * @param {String} name + * @param {Array} suites + * @param {Function} fn + * @api private + */ + +Runner.prototype.hooks = function(name, suites, fn){ +  var self = this +    , orig = this.suite; + +  function next(suite) { +    self.suite = suite; + +    if (!suite) { +      self.suite = orig; +      return fn(); +    } + +    self.hook(name, function(err){ +      if (err) { +        self.suite = orig; +        return fn(err); +      } + +      next(suites.pop()); +    }); +  } + +  next(suites.pop()); +}; + +/** + * Run hooks from the top level down. + * + * @param {String} name + * @param {Function} fn + * @api private + */ + +Runner.prototype.hookUp = function(name, fn){ +  var suites = [this.suite].concat(this.parents()).reverse(); +  this.hooks(name, suites, fn); +}; + +/** + * Run hooks from the bottom up. + * + * @param {String} name + * @param {Function} fn + * @api private + */ + +Runner.prototype.hookDown = function(name, fn){ +  var suites = [this.suite].concat(this.parents()); +  this.hooks(name, suites, fn); +}; + +/** + * Return an array of parent Suites from + * closest to furthest. + * + * @return {Array} + * @api private + */ + +Runner.prototype.parents = function(){ +  var suite = this.suite +    , suites = []; +  while (suite = suite.parent) suites.push(suite); +  return suites; +}; + +/** + * Run the current test and callback `fn(err)`. + * + * @param {Function} fn + * @api private + */ + +Runner.prototype.runTest = function(fn){ +  var test = this.test +    , self = this; + +  if (this.asyncOnly) test.asyncOnly = true; + +  try { +    test.on('error', function(err){ +      self.fail(test, err); +    }); +    test.run(fn); +  } catch (err) { +    fn(err); +  } +}; + +/** + * Run tests in the given `suite` and invoke + * the callback `fn()` when complete. + * + * @param {Suite} suite + * @param {Function} fn + * @api private + */ + +Runner.prototype.runTests = function(suite, fn){ +  var self = this +    , tests = suite.tests.slice() +    , test; + +  function next(err) { +    // if we bail after first err +    if (self.failures && suite._bail) return fn(); + +    // next test +    test = tests.shift(); + +    // all done +    if (!test) return fn(); + +    // grep +    var match = self._grep.test(test.fullTitle()); +    if (self._invert) match = !match; +    if (!match) return next(); + +    // pending +    if (test.pending) { +      self.emit('pending', test); +      self.emit('test end', test); +      return next(); +    } + +    // execute test and hook(s) +    self.emit('test', self.test = test); +    self.hookDown('beforeEach', function(){ +      self.currentRunnable = self.test; +      self.runTest(function(err){ +        test = self.test; + +        if (err) { +          self.fail(test, err); +          self.emit('test end', test); +          return self.hookUp('afterEach', next); +        } + +        test.state = 'passed'; +        self.emit('pass', test); +        self.emit('test end', test); +        self.hookUp('afterEach', next); +      }); +    }); +  } + +  this.next = next; +  next(); +}; + +/** + * Run the given `suite` and invoke the + * callback `fn()` when complete. + * + * @param {Suite} suite + * @param {Function} fn + * @api private + */ + +Runner.prototype.runSuite = function(suite, fn){ +  var total = this.grepTotal(suite) +    , self = this +    , i = 0; + +  debug('run suite %s', suite.fullTitle()); + +  if (!total) return fn(); + +  this.emit('suite', this.suite = suite); + +  function next() { +    var curr = suite.suites[i++]; +    if (!curr) return done(); +    self.runSuite(curr, next); +  } + +  function done() { +    self.suite = suite; +    self.hook('afterAll', function(){ +      self.emit('suite end', suite); +      fn(); +    }); +  } + +  this.hook('beforeAll', function(){ +    self.runTests(suite, next); +  }); +}; + +/** + * Handle uncaught exceptions. + * + * @param {Error} err + * @api private + */ + +Runner.prototype.uncaught = function(err){ +  debug('uncaught exception %s', err.message); +  var runnable = this.currentRunnable; +  if (!runnable || 'failed' == runnable.state) return; +  runnable.clearTimeout(); +  err.uncaught = true; +  this.fail(runnable, err); + +  // recover from test +  if ('test' == runnable.type) { +    this.emit('test end', runnable); +    this.hookUp('afterEach', this.next); +    return; +  } + +  // bail on hooks +  this.emit('end'); +}; + +/** + * Run the root suite and invoke `fn(failures)` + * on completion. + * + * @param {Function} fn + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.run = function(fn){ +  var self = this +    , fn = fn || function(){}; + +  function uncaught(err){ +    self.uncaught(err); +  } + +  debug('start'); + +  // callback +  this.on('end', function(){ +    debug('end'); +    process.removeListener('uncaughtException', uncaught); +    fn(self.failures); +  }); + +  // run suites +  this.emit('start'); +  this.runSuite(this.suite, function(){ +    debug('finished running'); +    self.emit('end'); +  }); + +  // uncaught exception +  process.on('uncaughtException', uncaught); + +  return this; +}; + +/** + * Filter leaks with the given globals flagged as `ok`. + * + * @param {Array} ok + * @param {Array} globals + * @return {Array} + * @api private + */ + +function filterLeaks(ok, globals) { +  return filter(globals, function(key){ +    var matched = filter(ok, function(ok){ +      if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); +      // Opera and IE expose global variables for HTML element IDs (issue #243) +      if (/^mocha-/.test(key)) return true; +      return key == ok; +    }); +    return matched.length == 0 && (!global.navigator || 'onerror' !== key); +  }); +} + +}); // module: runner.js + +require.register("suite.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter +  , debug = require('browser/debug')('mocha:suite') +  , milliseconds = require('./ms') +  , utils = require('./utils') +  , Hook = require('./hook'); + +/** + * Expose `Suite`. + */ + +exports = module.exports = Suite; + +/** + * Create a new `Suite` with the given `title` + * and parent `Suite`. When a suite with the + * same title is already present, that suite + * is returned to provide nicer reporter + * and more flexible meta-testing. + * + * @param {Suite} parent + * @param {String} title + * @return {Suite} + * @api public + */ + +exports.create = function(parent, title){ +  var suite = new Suite(title, parent.ctx); +  suite.parent = parent; +  if (parent.pending) suite.pending = true; +  title = suite.fullTitle(); +  parent.addSuite(suite); +  return suite; +}; + +/** + * Initialize a new `Suite` with the given + * `title` and `ctx`. + * + * @param {String} title + * @param {Context} ctx + * @api private + */ + +function Suite(title, ctx) { +  this.title = title; +  this.ctx = ctx; +  this.suites = []; +  this.tests = []; +  this.pending = false; +  this._beforeEach = []; +  this._beforeAll = []; +  this._afterEach = []; +  this._afterAll = []; +  this.root = !title; +  this._timeout = 2000; +  this._slow = 75; +  this._bail = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Suite.prototype = new F; +Suite.prototype.constructor = Suite; + + +/** + * Return a clone of this `Suite`. + * + * @return {Suite} + * @api private + */ + +Suite.prototype.clone = function(){ +  var suite = new Suite(this.title); +  debug('clone'); +  suite.ctx = this.ctx; +  suite.timeout(this.timeout()); +  suite.slow(this.slow()); +  suite.bail(this.bail()); +  return suite; +}; + +/** + * Set timeout `ms` or short-hand such as "2s". + * + * @param {Number|String} ms + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.timeout = function(ms){ +  if (0 == arguments.length) return this._timeout; +  if ('string' == typeof ms) ms = milliseconds(ms); +  debug('timeout %d', ms); +  this._timeout = parseInt(ms, 10); +  return this; +}; + +/** + * Set slow `ms` or short-hand such as "2s". + * + * @param {Number|String} ms + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.slow = function(ms){ +  if (0 === arguments.length) return this._slow; +  if ('string' == typeof ms) ms = milliseconds(ms); +  debug('slow %d', ms); +  this._slow = ms; +  return this; +}; + +/** + * Sets whether to bail after first error. + * + * @parma {Boolean} bail + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.bail = function(bail){ +  if (0 == arguments.length) return this._bail; +  debug('bail %s', bail); +  this._bail = bail; +  return this; +}; + +/** + * Run `fn(test[, done])` before running tests. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.beforeAll = function(fn){ +  if (this.pending) return this; +  var hook = new Hook('"before all" hook', fn); +  hook.parent = this; +  hook.timeout(this.timeout()); +  hook.slow(this.slow()); +  hook.ctx = this.ctx; +  this._beforeAll.push(hook); +  this.emit('beforeAll', hook); +  return this; +}; + +/** + * Run `fn(test[, done])` after running tests. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.afterAll = function(fn){ +  if (this.pending) return this; +  var hook = new Hook('"after all" hook', fn); +  hook.parent = this; +  hook.timeout(this.timeout()); +  hook.slow(this.slow()); +  hook.ctx = this.ctx; +  this._afterAll.push(hook); +  this.emit('afterAll', hook); +  return this; +}; + +/** + * Run `fn(test[, done])` before each test case. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.beforeEach = function(fn){ +  if (this.pending) return this; +  var hook = new Hook('"before each" hook', fn); +  hook.parent = this; +  hook.timeout(this.timeout()); +  hook.slow(this.slow()); +  hook.ctx = this.ctx; +  this._beforeEach.push(hook); +  this.emit('beforeEach', hook); +  return this; +}; + +/** + * Run `fn(test[, done])` after each test case. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.afterEach = function(fn){ +  if (this.pending) return this; +  var hook = new Hook('"after each" hook', fn); +  hook.parent = this; +  hook.timeout(this.timeout()); +  hook.slow(this.slow()); +  hook.ctx = this.ctx; +  this._afterEach.push(hook); +  this.emit('afterEach', hook); +  return this; +}; + +/** + * Add a test `suite`. + * + * @param {Suite} suite + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.addSuite = function(suite){ +  suite.parent = this; +  suite.timeout(this.timeout()); +  suite.slow(this.slow()); +  suite.bail(this.bail()); +  this.suites.push(suite); +  this.emit('suite', suite); +  return this; +}; + +/** + * Add a `test` to this suite. + * + * @param {Test} test + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.addTest = function(test){ +  test.parent = this; +  test.timeout(this.timeout()); +  test.slow(this.slow()); +  test.ctx = this.ctx; +  this.tests.push(test); +  this.emit('test', test); +  return this; +}; + +/** + * Return the full title generated by recursively + * concatenating the parent's full title. + * + * @return {String} + * @api public + */ + +Suite.prototype.fullTitle = function(){ +  if (this.parent) { +    var full = this.parent.fullTitle(); +    if (full) return full + ' ' + this.title; +  } +  return this.title; +}; + +/** + * Return the total number of tests. + * + * @return {Number} + * @api public + */ + +Suite.prototype.total = function(){ +  return utils.reduce(this.suites, function(sum, suite){ +    return sum + suite.total(); +  }, 0) + this.tests.length; +}; + +/** + * Iterates through each suite recursively to find + * all tests. Applies a function in the format + * `fn(test)`. + * + * @param {Function} fn + * @return {Suite} + * @api private + */ + +Suite.prototype.eachTest = function(fn){ +  utils.forEach(this.tests, fn); +  utils.forEach(this.suites, function(suite){ +    suite.eachTest(fn); +  }); +  return this; +}; + +}); // module: suite.js + +require.register("test.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Runnable = require('./runnable'); + +/** + * Expose `Test`. + */ + +module.exports = Test; + +/** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Test(title, fn) { +  Runnable.call(this, title, fn); +  this.pending = !fn; +  this.type = 'test'; +} + +/** + * Inherit from `Runnable.prototype`. + */ + +function F(){}; +F.prototype = Runnable.prototype; +Test.prototype = new F; +Test.prototype.constructor = Test; + + +}); // module: test.js + +require.register("utils.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var fs = require('browser/fs') +  , path = require('browser/path') +  , join = path.join +  , debug = require('browser/debug')('mocha:watch'); + +/** + * Ignored directories. + */ + +var ignore = ['node_modules', '.git']; + +/** + * Escape special characters in the given string of html. + * + * @param  {String} html + * @return {String} + * @api private + */ + +exports.escape = function(html){ +  return String(html) +    .replace(/&/g, '&') +    .replace(/"/g, '"') +    .replace(/</g, '<') +    .replace(/>/g, '>'); +}; + +/** + * Array#forEach (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} scope + * @api private + */ + +exports.forEach = function(arr, fn, scope){ +  for (var i = 0, l = arr.length; i < l; i++) +    fn.call(scope, arr[i], i); +}; + +/** + * Array#indexOf (<=IE8) + * + * @parma {Array} arr + * @param {Object} obj to find index of + * @param {Number} start + * @api private + */ + +exports.indexOf = function(arr, obj, start){ +  for (var i = start || 0, l = arr.length; i < l; i++) { +    if (arr[i] === obj) +      return i; +  } +  return -1; +}; + +/** + * Array#reduce (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} initial value + * @api private + */ + +exports.reduce = function(arr, fn, val){ +  var rval = val; + +  for (var i = 0, l = arr.length; i < l; i++) { +    rval = fn(rval, arr[i], i, arr); +  } + +  return rval; +}; + +/** + * Array#filter (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @api private + */ + +exports.filter = function(arr, fn){ +  var ret = []; + +  for (var i = 0, l = arr.length; i < l; i++) { +    var val = arr[i]; +    if (fn(val, i, arr)) ret.push(val); +  } + +  return ret; +}; + +/** + * Object.keys (<=IE8) + * + * @param {Object} obj + * @return {Array} keys + * @api private + */ + +exports.keys = Object.keys || function(obj) { +  var keys = [] +    , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 + +  for (var key in obj) { +    if (has.call(obj, key)) { +      keys.push(key); +    } +  } + +  return keys; +}; + +/** + * Watch the given `files` for changes + * and invoke `fn(file)` on modification. + * + * @param {Array} files + * @param {Function} fn + * @api private + */ + +exports.watch = function(files, fn){ +  var options = { interval: 100 }; +  files.forEach(function(file){ +    debug('file %s', file); +    fs.watchFile(file, options, function(curr, prev){ +      if (prev.mtime < curr.mtime) fn(file); +    }); +  }); +}; + +/** + * Ignored files. + */ + +function ignored(path){ +  return !~ignore.indexOf(path); +} + +/** + * Lookup files in the given `dir`. + * + * @return {Array} + * @api private + */ + +exports.files = function(dir, ret){ +  ret = ret || []; + +  fs.readdirSync(dir) +  .filter(ignored) +  .forEach(function(path){ +    path = join(dir, path); +    if (fs.statSync(path).isDirectory()) { +      exports.files(path, ret); +    } else if (path.match(/\.(js|coffee)$/)) { +      ret.push(path); +    } +  }); + +  return ret; +}; + +/** + * Compute a slug from the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.slug = function(str){ +  return str +    .toLowerCase() +    .replace(/ +/g, '-') +    .replace(/[^-\w]/g, ''); +}; + +/** + * Strip the function definition from `str`, + * and re-indent for pre whitespace. + */ + +exports.clean = function(str) { +  str = str +    .replace(/^function *\(.*\) *{/, '') +    .replace(/\s+\}$/, ''); + +  var spaces = str.match(/^\n?( *)/)[1].length +    , re = new RegExp('^ {' + spaces + '}', 'gm'); + +  str = str.replace(re, ''); + +  return exports.trim(str); +}; + +/** + * Escape regular expression characters in `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.escapeRegexp = function(str){ +  return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); +}; + +/** + * Trim the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.trim = function(str){ +  return str.replace(/^\s+|\s+$/g, ''); +}; + +/** + * Parse the given `qs`. + * + * @param {String} qs + * @return {Object} + * @api private + */ + +exports.parseQuery = function(qs){ +  return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ +    var i = pair.indexOf('=') +      , key = pair.slice(0, i) +      , val = pair.slice(++i); + +    obj[key] = decodeURIComponent(val); +    return obj; +  }, {}); +}; + +/** + * Highlight the given string of `js`. + * + * @param {String} js + * @return {String} + * @api private + */ + +function highlight(js) { +  return js +    .replace(/</g, '<') +    .replace(/>/g, '>') +    .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>') +    .replace(/('.*?')/gm, '<span class="string">$1</span>') +    .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') +    .replace(/(\d+)/gm, '<span class="number">$1</span>') +    .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>') +    .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>') +} + +/** + * Highlight the contents of tag `name`. + * + * @param {String} name + * @api private + */ + +exports.highlightTags = function(name) { +  var code = document.getElementsByTagName(name); +  for (var i = 0, len = code.length; i < len; ++i) { +    code[i].innerHTML = highlight(code[i].innerHTML); +  } +}; + +}); // module: utils.js +/** + * Node shims. + * + * These are meant only to allow + * mocha.js to run untouched, not + * to allow running node code in + * the browser. + */ + +process = {}; +process.exit = function(status){}; +process.stdout = {}; +global = window; + +/** + * Remove uncaughtException listener. + */ + +process.removeListener = function(e){ +  if ('uncaughtException' == e) { +    window.onerror = null; +  } +}; + +/** + * Implements uncaughtException listener. + */ + +process.on = function(e, fn){ +  if ('uncaughtException' == e) { +    window.onerror = function(err, url, line){ +      fn(new Error(err + ' (' + url + ':' + line + ')')); +    }; +  } +}; + +// boot +;(function(){ + +  /** +   * Expose mocha. +   */ + +  var Mocha = window.Mocha = require('mocha'), +      mocha = window.mocha = new Mocha({ reporter: 'html' }); + +  var immediateQueue = [] +    , immediateTimeout; + +  function timeslice() { +    var immediateStart = new Date().getTime(); +    while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { +      immediateQueue.shift()(); +    } +    if (immediateQueue.length) { +      immediateTimeout = setTimeout(timeslice, 0); +    } else { +      immediateTimeout = null; +    } +  } + +  /** +   * High-performance override of Runner.immediately. +   */ + +  Mocha.Runner.immediately = function(callback) { +    immediateQueue.push(callback); +    if (!immediateTimeout) { +      immediateTimeout = setTimeout(timeslice, 0); +    } +  }; + +  /** +   * Override ui to ensure that the ui functions are initialized. +   * Normally this would happen in Mocha.prototype.loadFiles. +   */ + +  mocha.ui = function(ui){ +    Mocha.prototype.ui.call(this, ui); +    this.suite.emit('pre-require', window, null, this); +    return this; +  }; + +  /** +   * Setup mocha with the given setting options. +   */ + +  mocha.setup = function(opts){ +    if ('string' == typeof opts) opts = { ui: opts }; +    for (var opt in opts) this[opt](opts[opt]); +    return this; +  }; + +  /** +   * Run mocha, returning the Runner. +   */ + +  mocha.run = function(fn){ +    var options = mocha.options; +    mocha.globals('location'); + +    var query = Mocha.utils.parseQuery(window.location.search || ''); +    if (query.grep) mocha.grep(query.grep); +    if (query.invert) mocha.invert(); + +    return Mocha.prototype.run.call(mocha, function(){ +      Mocha.utils.highlightTags('code'); +      if (fn) fn(); +    }); +  }; +})(); +})(); diff --git a/lib/mousetrap/tests/libs/sinon-1.7.1.js b/lib/mousetrap/tests/libs/sinon-1.7.1.js new file mode 100644 index 0000000..fe9529f --- /dev/null +++ b/lib/mousetrap/tests/libs/sinon-1.7.1.js @@ -0,0 +1,4299 @@ +/** + * Sinon.JS 1.7.1, 2013/05/07 + * + * @author Christian Johansen (christian@cjohansen.no) + * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS + * + * (The BSD License) + * + * Copyright (c) 2010-2013, Christian Johansen, christian@cjohansen.no + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + *     * Redistributions of source code must retain the above copyright notice, + *       this list of conditions and the following disclaimer. + *     * Redistributions in binary form must reproduce the above copyright notice, + *       this list of conditions and the following disclaimer in the documentation + *       and/or other materials provided with the distribution. + *     * Neither the name of Christian Johansen nor the names of his contributors + *       may be used to endorse or promote products derived from this software + *       without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +this.sinon = (function () { +var buster = (function (setTimeout, B) { +    var isNode = typeof require == "function" && typeof module == "object"; +    var div = typeof document != "undefined" && document.createElement("div"); +    var F = function () {}; + +    var buster = { +        bind: function bind(obj, methOrProp) { +            var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp; +            var args = Array.prototype.slice.call(arguments, 2); +            return function () { +                var allArgs = args.concat(Array.prototype.slice.call(arguments)); +                return method.apply(obj, allArgs); +            }; +        }, + +        partial: function partial(fn) { +            var args = [].slice.call(arguments, 1); +            return function () { +                return fn.apply(this, args.concat([].slice.call(arguments))); +            }; +        }, + +        create: function create(object) { +            F.prototype = object; +            return new F(); +        }, + +        extend: function extend(target) { +            if (!target) { return; } +            for (var i = 1, l = arguments.length, prop; i < l; ++i) { +                for (prop in arguments[i]) { +                    target[prop] = arguments[i][prop]; +                } +            } +            return target; +        }, + +        nextTick: function nextTick(callback) { +            if (typeof process != "undefined" && process.nextTick) { +                return process.nextTick(callback); +            } +            setTimeout(callback, 0); +        }, + +        functionName: function functionName(func) { +            if (!func) return ""; +            if (func.displayName) return func.displayName; +            if (func.name) return func.name; +            var matches = func.toString().match(/function\s+([^\(]+)/m); +            return matches && matches[1] || ""; +        }, + +        isNode: function isNode(obj) { +            if (!div) return false; +            try { +                obj.appendChild(div); +                obj.removeChild(div); +            } catch (e) { +                return false; +            } +            return true; +        }, + +        isElement: function isElement(obj) { +            return obj && obj.nodeType === 1 && buster.isNode(obj); +        }, + +        isArray: function isArray(arr) { +            return Object.prototype.toString.call(arr) == "[object Array]"; +        }, + +        flatten: function flatten(arr) { +            var result = [], arr = arr || []; +            for (var i = 0, l = arr.length; i < l; ++i) { +                result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]); +            } +            return result; +        }, + +        each: function each(arr, callback) { +            for (var i = 0, l = arr.length; i < l; ++i) { +                callback(arr[i]); +            } +        }, + +        map: function map(arr, callback) { +            var results = []; +            for (var i = 0, l = arr.length; i < l; ++i) { +                results.push(callback(arr[i])); +            } +            return results; +        }, + +        parallel: function parallel(fns, callback) { +            function cb(err, res) { +                if (typeof callback == "function") { +                    callback(err, res); +                    callback = null; +                } +            } +            if (fns.length == 0) { return cb(null, []); } +            var remaining = fns.length, results = []; +            function makeDone(num) { +                return function done(err, result) { +                    if (err) { return cb(err); } +                    results[num] = result; +                    if (--remaining == 0) { cb(null, results); } +                }; +            } +            for (var i = 0, l = fns.length; i < l; ++i) { +                fns[i](makeDone(i)); +            } +        }, + +        series: function series(fns, callback) { +            function cb(err, res) { +                if (typeof callback == "function") { +                    callback(err, res); +                } +            } +            var remaining = fns.slice(); +            var results = []; +            function callNext() { +                if (remaining.length == 0) return cb(null, results); +                var promise = remaining.shift()(next); +                if (promise && typeof promise.then == "function") { +                    promise.then(buster.partial(next, null), next); +                } +            } +            function next(err, result) { +                if (err) return cb(err); +                results.push(result); +                callNext(); +            } +            callNext(); +        }, + +        countdown: function countdown(num, done) { +            return function () { +                if (--num == 0) done(); +            }; +        } +    }; + +    if (typeof process === "object" && +        typeof require === "function" && typeof module === "object") { +        var crypto = require("crypto"); +        var path = require("path"); + +        buster.tmpFile = function (fileName) { +            var hashed = crypto.createHash("sha1"); +            hashed.update(fileName); +            var tmpfileName = hashed.digest("hex"); + +            if (process.platform == "win32") { +                return path.join(process.env["TEMP"], tmpfileName); +            } else { +                return path.join("/tmp", tmpfileName); +            } +        }; +    } + +    if (Array.prototype.some) { +        buster.some = function (arr, fn, thisp) { +            return arr.some(fn, thisp); +        }; +    } else { +        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some +        buster.some = function (arr, fun, thisp) { +                        if (arr == null) { throw new TypeError(); } +            arr = Object(arr); +            var len = arr.length >>> 0; +            if (typeof fun !== "function") { throw new TypeError(); } + +            for (var i = 0; i < len; i++) { +                if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) { +                    return true; +                } +            } + +            return false; +        }; +    } + +    if (Array.prototype.filter) { +        buster.filter = function (arr, fn, thisp) { +            return arr.filter(fn, thisp); +        }; +    } else { +        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter +        buster.filter = function (fn, thisp) { +                        if (this == null) { throw new TypeError(); } + +            var t = Object(this); +            var len = t.length >>> 0; +            if (typeof fn != "function") { throw new TypeError(); } + +            var res = []; +            for (var i = 0; i < len; i++) { +                if (i in t) { +                    var val = t[i]; // in case fun mutates this +                    if (fn.call(thisp, val, i, t)) { res.push(val); } +                } +            } + +            return res; +        }; +    } + +    if (isNode) { +        module.exports = buster; +        buster.eventEmitter = require("./buster-event-emitter"); +        Object.defineProperty(buster, "defineVersionGetter", { +            get: function () { +                return require("./define-version-getter"); +            } +        }); +    } + +    return buster.extend(B || {}, buster); +}(setTimeout, buster)); +if (typeof buster === "undefined") { +    var buster = {}; +} + +if (typeof module === "object" && typeof require === "function") { +    buster = require("buster-core"); +} + +buster.format = buster.format || {}; +buster.format.excludeConstructors = ["Object", /^.$/]; +buster.format.quoteStrings = true; + +buster.format.ascii = (function () { + +    var hasOwn = Object.prototype.hasOwnProperty; + +    var specialObjects = []; +    if (typeof global != "undefined") { +        specialObjects.push({ obj: global, value: "[object global]" }); +    } +    if (typeof document != "undefined") { +        specialObjects.push({ obj: document, value: "[object HTMLDocument]" }); +    } +    if (typeof window != "undefined") { +        specialObjects.push({ obj: window, value: "[object Window]" }); +    } + +    function keys(object) { +        var k = Object.keys && Object.keys(object) || []; + +        if (k.length == 0) { +            for (var prop in object) { +                if (hasOwn.call(object, prop)) { +                    k.push(prop); +                } +            } +        } + +        return k.sort(); +    } + +    function isCircular(object, objects) { +        if (typeof object != "object") { +            return false; +        } + +        for (var i = 0, l = objects.length; i < l; ++i) { +            if (objects[i] === object) { +                return true; +            } +        } + +        return false; +    } + +    function ascii(object, processed, indent) { +        if (typeof object == "string") { +            var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings; +            return processed || quote ? '"' + object + '"' : object; +        } + +        if (typeof object == "function" && !(object instanceof RegExp)) { +            return ascii.func(object); +        } + +        processed = processed || []; + +        if (isCircular(object, processed)) { +            return "[Circular]"; +        } + +        if (Object.prototype.toString.call(object) == "[object Array]") { +            return ascii.array.call(this, object, processed); +        } + +        if (!object) { +            return "" + object; +        } + +        if (buster.isElement(object)) { +            return ascii.element(object); +        } + +        if (typeof object.toString == "function" && +            object.toString !== Object.prototype.toString) { +            return object.toString(); +        } + +        for (var i = 0, l = specialObjects.length; i < l; i++) { +            if (object === specialObjects[i].obj) { +                return specialObjects[i].value; +            } +        } + +        return ascii.object.call(this, object, processed, indent); +    } + +    ascii.func = function (func) { +        return "function " + buster.functionName(func) + "() {}"; +    }; + +    ascii.array = function (array, processed) { +        processed = processed || []; +        processed.push(array); +        var pieces = []; + +        for (var i = 0, l = array.length; i < l; ++i) { +            pieces.push(ascii.call(this, array[i], processed)); +        } + +        return "[" + pieces.join(", ") + "]"; +    }; + +    ascii.object = function (object, processed, indent) { +        processed = processed || []; +        processed.push(object); +        indent = indent || 0; +        var pieces = [], properties = keys(object), prop, str, obj; +        var is = ""; +        var length = 3; + +        for (var i = 0, l = indent; i < l; ++i) { +            is += " "; +        } + +        for (i = 0, l = properties.length; i < l; ++i) { +            prop = properties[i]; +            obj = object[prop]; + +            if (isCircular(obj, processed)) { +                str = "[Circular]"; +            } else { +                str = ascii.call(this, obj, processed, indent + 2); +            } + +            str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; +            length += str.length; +            pieces.push(str); +        } + +        var cons = ascii.constructorName.call(this, object); +        var prefix = cons ? "[" + cons + "] " : "" + +        return (length + indent) > 80 ? +            prefix + "{\n  " + is + pieces.join(",\n  " + is) + "\n" + is + "}" : +            prefix + "{ " + pieces.join(", ") + " }"; +    }; + +    ascii.element = function (element) { +        var tagName = element.tagName.toLowerCase(); +        var attrs = element.attributes, attribute, pairs = [], attrName; + +        for (var i = 0, l = attrs.length; i < l; ++i) { +            attribute = attrs.item(i); +            attrName = attribute.nodeName.toLowerCase().replace("html:", ""); + +            if (attrName == "contenteditable" && attribute.nodeValue == "inherit") { +                continue; +            } + +            if (!!attribute.nodeValue) { +                pairs.push(attrName + "=\"" + attribute.nodeValue + "\""); +            } +        } + +        var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); +        var content = element.innerHTML; + +        if (content.length > 20) { +            content = content.substr(0, 20) + "[...]"; +        } + +        var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">"; + +        return res.replace(/ contentEditable="inherit"/, ""); +    }; + +    ascii.constructorName = function (object) { +        var name = buster.functionName(object && object.constructor); +        var excludes = this.excludeConstructors || buster.format.excludeConstructors || []; + +        for (var i = 0, l = excludes.length; i < l; ++i) { +            if (typeof excludes[i] == "string" && excludes[i] == name) { +                return ""; +            } else if (excludes[i].test && excludes[i].test(name)) { +                return ""; +            } +        } + +        return name; +    }; + +    return ascii; +}()); + +if (typeof module != "undefined") { +    module.exports = buster.format; +} +/*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/ +/*global module, require, __dirname, document*/ +/** + * Sinon core utilities. For internal use only. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +var sinon = (function (buster) { +    var div = typeof document != "undefined" && document.createElement("div"); +    var hasOwn = Object.prototype.hasOwnProperty; + +    function isDOMNode(obj) { +        var success = false; + +        try { +            obj.appendChild(div); +            success = div.parentNode == obj; +        } catch (e) { +            return false; +        } finally { +            try { +                obj.removeChild(div); +            } catch (e) { +                // Remove failed, not much we can do about that +            } +        } + +        return success; +    } + +    function isElement(obj) { +        return div && obj && obj.nodeType === 1 && isDOMNode(obj); +    } + +    function isFunction(obj) { +        return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); +    } + +    function mirrorProperties(target, source) { +        for (var prop in source) { +            if (!hasOwn.call(target, prop)) { +                target[prop] = source[prop]; +            } +        } +    } + +    function isRestorable (obj) { +        return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; +    } + +    var sinon = { +        wrapMethod: function wrapMethod(object, property, method) { +            if (!object) { +                throw new TypeError("Should wrap property of object"); +            } + +            if (typeof method != "function") { +                throw new TypeError("Method wrapper should be function"); +            } + +            var wrappedMethod = object[property]; + +            if (!isFunction(wrappedMethod)) { +                throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + +                                    property + " as function"); +            } + +            if (wrappedMethod.restore && wrappedMethod.restore.sinon) { +                throw new TypeError("Attempted to wrap " + property + " which is already wrapped"); +            } + +            if (wrappedMethod.calledBefore) { +                var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; +                throw new TypeError("Attempted to wrap " + property + " which is already " + verb); +            } + +            // IE 8 does not support hasOwnProperty on the window object. +            var owned = hasOwn.call(object, property); +            object[property] = method; +            method.displayName = property; + +            method.restore = function () { +                // For prototype properties try to reset by delete first. +                // If this fails (ex: localStorage on mobile safari) then force a reset +                // via direct assignment. +                if (!owned) { +                    delete object[property]; +                } +                if (object[property] === method) { +                    object[property] = wrappedMethod; +                } +            }; + +            method.restore.sinon = true; +            mirrorProperties(method, wrappedMethod); + +            return method; +        }, + +        extend: function extend(target) { +            for (var i = 1, l = arguments.length; i < l; i += 1) { +                for (var prop in arguments[i]) { +                    if (arguments[i].hasOwnProperty(prop)) { +                        target[prop] = arguments[i][prop]; +                    } + +                    // DONT ENUM bug, only care about toString +                    if (arguments[i].hasOwnProperty("toString") && +                        arguments[i].toString != target.toString) { +                        target.toString = arguments[i].toString; +                    } +                } +            } + +            return target; +        }, + +        create: function create(proto) { +            var F = function () {}; +            F.prototype = proto; +            return new F(); +        }, + +        deepEqual: function deepEqual(a, b) { +            if (sinon.match && sinon.match.isMatcher(a)) { +                return a.test(b); +            } +            if (typeof a != "object" || typeof b != "object") { +                return a === b; +            } + +            if (isElement(a) || isElement(b)) { +                return a === b; +            } + +            if (a === b) { +                return true; +            } + +            if ((a === null && b !== null) || (a !== null && b === null)) { +                return false; +            } + +            var aString = Object.prototype.toString.call(a); +            if (aString != Object.prototype.toString.call(b)) { +                return false; +            } + +            if (aString == "[object Array]") { +                if (a.length !== b.length) { +                    return false; +                } + +                for (var i = 0, l = a.length; i < l; i += 1) { +                    if (!deepEqual(a[i], b[i])) { +                        return false; +                    } +                } + +                return true; +            } + +            var prop, aLength = 0, bLength = 0; + +            for (prop in a) { +                aLength += 1; + +                if (!deepEqual(a[prop], b[prop])) { +                    return false; +                } +            } + +            for (prop in b) { +                bLength += 1; +            } + +            return aLength == bLength; +        }, + +        functionName: function functionName(func) { +            var name = func.displayName || func.name; + +            // Use function decomposition as a last resort to get function +            // name. Does not rely on function decomposition to work - if it +            // doesn't debugging will be slightly less informative +            // (i.e. toString will say 'spy' rather than 'myFunc'). +            if (!name) { +                var matches = func.toString().match(/function ([^\s\(]+)/); +                name = matches && matches[1]; +            } + +            return name; +        }, + +        functionToString: function toString() { +            if (this.getCall && this.callCount) { +                var thisValue, prop, i = this.callCount; + +                while (i--) { +                    thisValue = this.getCall(i).thisValue; + +                    for (prop in thisValue) { +                        if (thisValue[prop] === this) { +                            return prop; +                        } +                    } +                } +            } + +            return this.displayName || "sinon fake"; +        }, + +        getConfig: function (custom) { +            var config = {}; +            custom = custom || {}; +            var defaults = sinon.defaultConfig; + +            for (var prop in defaults) { +                if (defaults.hasOwnProperty(prop)) { +                    config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; +                } +            } + +            return config; +        }, + +        format: function (val) { +            return "" + val; +        }, + +        defaultConfig: { +            injectIntoThis: true, +            injectInto: null, +            properties: ["spy", "stub", "mock", "clock", "server", "requests"], +            useFakeTimers: true, +            useFakeServer: true +        }, + +        timesInWords: function timesInWords(count) { +            return count == 1 && "once" || +                count == 2 && "twice" || +                count == 3 && "thrice" || +                (count || 0) + " times"; +        }, + +        calledInOrder: function (spies) { +            for (var i = 1, l = spies.length; i < l; i++) { +                if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { +                    return false; +                } +            } + +            return true; +        }, + +        orderByFirstCall: function (spies) { +            return spies.sort(function (a, b) { +                // uuid, won't ever be equal +                var aCall = a.getCall(0); +                var bCall = b.getCall(0); +                var aId = aCall && aCall.callId || -1; +                var bId = bCall && bCall.callId || -1; + +                return aId < bId ? -1 : 1; +            }); +        }, + +        log: function () {}, + +        logError: function (label, err) { +            var msg = label + " threw exception: " +            sinon.log(msg + "[" + err.name + "] " + err.message); +            if (err.stack) { sinon.log(err.stack); } + +            setTimeout(function () { +                err.message = msg + err.message; +                throw err; +            }, 0); +        }, + +        typeOf: function (value) { +            if (value === null) { +                return "null"; +            } +            else if (value === undefined) { +                return "undefined"; +            } +            var string = Object.prototype.toString.call(value); +            return string.substring(8, string.length - 1).toLowerCase(); +        }, + +        createStubInstance: function (constructor) { +            if (typeof constructor !== "function") { +                throw new TypeError("The constructor should be a function."); +            } +            return sinon.stub(sinon.create(constructor.prototype)); +        }, + +        restore: function (object) { +            if (object !== null && typeof object === "object") { +                for (var prop in object) { +                    if (isRestorable(object[prop])) { +                        object[prop].restore(); +                    } +                } +            } +            else if (isRestorable(object)) { +                object.restore(); +            } +        } +    }; + +    var isNode = typeof module == "object" && typeof require == "function"; + +    if (isNode) { +        try { +            buster = { format: require("buster-format") }; +        } catch (e) {} +        module.exports = sinon; +        module.exports.spy = require("./sinon/spy"); +        module.exports.spyCall = require("./sinon/call"); +        module.exports.stub = require("./sinon/stub"); +        module.exports.mock = require("./sinon/mock"); +        module.exports.collection = require("./sinon/collection"); +        module.exports.assert = require("./sinon/assert"); +        module.exports.sandbox = require("./sinon/sandbox"); +        module.exports.test = require("./sinon/test"); +        module.exports.testCase = require("./sinon/test_case"); +        module.exports.assert = require("./sinon/assert"); +        module.exports.match = require("./sinon/match"); +    } + +    if (buster) { +        var formatter = sinon.create(buster.format); +        formatter.quoteStrings = false; +        sinon.format = function () { +            return formatter.ascii.apply(formatter, arguments); +        }; +    } else if (isNode) { +        try { +            var util = require("util"); +            sinon.format = function (value) { +                return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; +            }; +        } catch (e) { +            /* Node, but no util module - would be very old, but better safe than +             sorry */ +        } +    } + +    return sinon; +}(typeof buster == "object" && buster)); + +/* @depend ../sinon.js */ +/*jslint eqeqeq: false, onevar: false, plusplus: false*/ +/*global module, require, sinon*/ +/** + * Match functions + * + * @author Maximilian Antoni (mail@maxantoni.de) + * @license BSD + * + * Copyright (c) 2012 Maximilian Antoni + */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function assertType(value, type, name) { +        var actual = sinon.typeOf(value); +        if (actual !== type) { +            throw new TypeError("Expected type of " + name + " to be " + +                type + ", but was " + actual); +        } +    } + +    var matcher = { +        toString: function () { +            return this.message; +        } +    }; + +    function isMatcher(object) { +        return matcher.isPrototypeOf(object); +    } + +    function matchObject(expectation, actual) { +        if (actual === null || actual === undefined) { +            return false; +        } +        for (var key in expectation) { +            if (expectation.hasOwnProperty(key)) { +                var exp = expectation[key]; +                var act = actual[key]; +                if (match.isMatcher(exp)) { +                    if (!exp.test(act)) { +                        return false; +                    } +                } else if (sinon.typeOf(exp) === "object") { +                    if (!matchObject(exp, act)) { +                        return false; +                    } +                } else if (!sinon.deepEqual(exp, act)) { +                    return false; +                } +            } +        } +        return true; +    } + +    matcher.or = function (m2) { +        if (!isMatcher(m2)) { +            throw new TypeError("Matcher expected"); +        } +        var m1 = this; +        var or = sinon.create(matcher); +        or.test = function (actual) { +            return m1.test(actual) || m2.test(actual); +        }; +        or.message = m1.message + ".or(" + m2.message + ")"; +        return or; +    }; + +    matcher.and = function (m2) { +        if (!isMatcher(m2)) { +            throw new TypeError("Matcher expected"); +        } +        var m1 = this; +        var and = sinon.create(matcher); +        and.test = function (actual) { +            return m1.test(actual) && m2.test(actual); +        }; +        and.message = m1.message + ".and(" + m2.message + ")"; +        return and; +    }; + +    var match = function (expectation, message) { +        var m = sinon.create(matcher); +        var type = sinon.typeOf(expectation); +        switch (type) { +        case "object": +            if (typeof expectation.test === "function") { +                m.test = function (actual) { +                    return expectation.test(actual) === true; +                }; +                m.message = "match(" + sinon.functionName(expectation.test) + ")"; +                return m; +            } +            var str = []; +            for (var key in expectation) { +                if (expectation.hasOwnProperty(key)) { +                    str.push(key + ": " + expectation[key]); +                } +            } +            m.test = function (actual) { +                return matchObject(expectation, actual); +            }; +            m.message = "match(" + str.join(", ") + ")"; +            break; +        case "number": +            m.test = function (actual) { +                return expectation == actual; +            }; +            break; +        case "string": +            m.test = function (actual) { +                if (typeof actual !== "string") { +                    return false; +                } +                return actual.indexOf(expectation) !== -1; +            }; +            m.message = "match(\"" + expectation + "\")"; +            break; +        case "regexp": +            m.test = function (actual) { +                if (typeof actual !== "string") { +                    return false; +                } +                return expectation.test(actual); +            }; +            break; +        case "function": +            m.test = expectation; +            if (message) { +                m.message = message; +            } else { +                m.message = "match(" + sinon.functionName(expectation) + ")"; +            } +            break; +        default: +            m.test = function (actual) { +              return sinon.deepEqual(expectation, actual); +            }; +        } +        if (!m.message) { +            m.message = "match(" + expectation + ")"; +        } +        return m; +    }; + +    match.isMatcher = isMatcher; + +    match.any = match(function () { +        return true; +    }, "any"); + +    match.defined = match(function (actual) { +        return actual !== null && actual !== undefined; +    }, "defined"); + +    match.truthy = match(function (actual) { +        return !!actual; +    }, "truthy"); + +    match.falsy = match(function (actual) { +        return !actual; +    }, "falsy"); + +    match.same = function (expectation) { +        return match(function (actual) { +            return expectation === actual; +        }, "same(" + expectation + ")"); +    }; + +    match.typeOf = function (type) { +        assertType(type, "string", "type"); +        return match(function (actual) { +            return sinon.typeOf(actual) === type; +        }, "typeOf(\"" + type + "\")"); +    }; + +    match.instanceOf = function (type) { +        assertType(type, "function", "type"); +        return match(function (actual) { +            return actual instanceof type; +        }, "instanceOf(" + sinon.functionName(type) + ")"); +    }; + +    function createPropertyMatcher(propertyTest, messagePrefix) { +        return function (property, value) { +            assertType(property, "string", "property"); +            var onlyProperty = arguments.length === 1; +            var message = messagePrefix + "(\"" + property + "\""; +            if (!onlyProperty) { +                message += ", " + value; +            } +            message += ")"; +            return match(function (actual) { +                if (actual === undefined || actual === null || +                        !propertyTest(actual, property)) { +                    return false; +                } +                return onlyProperty || sinon.deepEqual(value, actual[property]); +            }, message); +        }; +    } + +    match.has = createPropertyMatcher(function (actual, property) { +        if (typeof actual === "object") { +            return property in actual; +        } +        return actual[property] !== undefined; +    }, "has"); + +    match.hasOwn = createPropertyMatcher(function (actual, property) { +        return actual.hasOwnProperty(property); +    }, "hasOwn"); + +    match.bool = match.typeOf("boolean"); +    match.number = match.typeOf("number"); +    match.string = match.typeOf("string"); +    match.object = match.typeOf("object"); +    match.func = match.typeOf("function"); +    match.array = match.typeOf("array"); +    match.regexp = match.typeOf("regexp"); +    match.date = match.typeOf("date"); + +    if (commonJSModule) { +        module.exports = match; +    } else { +        sinon.match = match; +    } +}(typeof sinon == "object" && sinon || null)); + +/** +  * @depend ../sinon.js +  * @depend match.js +  */ +/*jslint eqeqeq: false, onevar: false, plusplus: false*/ +/*global module, require, sinon*/ +/** +  * Spy calls +  * +  * @author Christian Johansen (christian@cjohansen.no) +  * @author Maximilian Antoni (mail@maxantoni.de) +  * @license BSD +  * +  * Copyright (c) 2010-2013 Christian Johansen +  * Copyright (c) 2013 Maximilian Antoni +  */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function throwYieldError(proxy, text, args) { +        var msg = sinon.functionName(proxy) + text; +        if (args.length) { +            msg += " Received [" + slice.call(args).join(", ") + "]"; +        } +        throw new Error(msg); +    } + +    var slice = Array.prototype.slice; + +    var callProto = { +        calledOn: function calledOn(thisValue) { +            if (sinon.match && sinon.match.isMatcher(thisValue)) { +                return thisValue.test(this.thisValue); +            } +            return this.thisValue === thisValue; +        }, + +        calledWith: function calledWith() { +            for (var i = 0, l = arguments.length; i < l; i += 1) { +                if (!sinon.deepEqual(arguments[i], this.args[i])) { +                    return false; +                } +            } + +            return true; +        }, + +        calledWithMatch: function calledWithMatch() { +            for (var i = 0, l = arguments.length; i < l; i += 1) { +                var actual = this.args[i]; +                var expectation = arguments[i]; +                if (!sinon.match || !sinon.match(expectation).test(actual)) { +                    return false; +                } +            } +            return true; +        }, + +        calledWithExactly: function calledWithExactly() { +            return arguments.length == this.args.length && +                this.calledWith.apply(this, arguments); +        }, + +        notCalledWith: function notCalledWith() { +            return !this.calledWith.apply(this, arguments); +        }, + +        notCalledWithMatch: function notCalledWithMatch() { +            return !this.calledWithMatch.apply(this, arguments); +        }, + +        returned: function returned(value) { +            return sinon.deepEqual(value, this.returnValue); +        }, + +        threw: function threw(error) { +            if (typeof error === "undefined" || !this.exception) { +                return !!this.exception; +            } + +            return this.exception === error || this.exception.name === error; +        }, + +        calledWithNew: function calledWithNew(thisValue) { +            return this.thisValue instanceof this.proxy; +        }, + +        calledBefore: function (other) { +            return this.callId < other.callId; +        }, + +        calledAfter: function (other) { +            return this.callId > other.callId; +        }, + +        callArg: function (pos) { +            this.args[pos](); +        }, + +        callArgOn: function (pos, thisValue) { +            this.args[pos].apply(thisValue); +        }, + +        callArgWith: function (pos) { +            this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); +        }, + +        callArgOnWith: function (pos, thisValue) { +            var args = slice.call(arguments, 2); +            this.args[pos].apply(thisValue, args); +        }, + +        "yield": function () { +            this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); +        }, + +        yieldOn: function (thisValue) { +            var args = this.args; +            for (var i = 0, l = args.length; i < l; ++i) { +                if (typeof args[i] === "function") { +                    args[i].apply(thisValue, slice.call(arguments, 1)); +                    return; +                } +            } +            throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); +        }, + +        yieldTo: function (prop) { +            this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); +        }, + +        yieldToOn: function (prop, thisValue) { +            var args = this.args; +            for (var i = 0, l = args.length; i < l; ++i) { +                if (args[i] && typeof args[i][prop] === "function") { +                    args[i][prop].apply(thisValue, slice.call(arguments, 2)); +                    return; +                } +            } +            throwYieldError(this.proxy, " cannot yield to '" + prop + +                "' since no callback was passed.", args); +        }, + +        toString: function () { +            var callStr = this.proxy.toString() + "("; +            var args = []; + +            for (var i = 0, l = this.args.length; i < l; ++i) { +                args.push(sinon.format(this.args[i])); +            } + +            callStr = callStr + args.join(", ") + ")"; + +            if (typeof this.returnValue != "undefined") { +                callStr += " => " + sinon.format(this.returnValue); +            } + +            if (this.exception) { +                callStr += " !" + this.exception.name; + +                if (this.exception.message) { +                    callStr += "(" + this.exception.message + ")"; +                } +            } + +            return callStr; +        } +    }; + +    callProto.invokeCallback = callProto.yield; + +    function createSpyCall(spy, thisValue, args, returnValue, exception, id) { +        if (typeof id !== "number") { +            throw new TypeError("Call id is not a number"); +        } +        var proxyCall = sinon.create(callProto); +        proxyCall.proxy = spy; +        proxyCall.thisValue = thisValue; +        proxyCall.args = args; +        proxyCall.returnValue = returnValue; +        proxyCall.exception = exception; +        proxyCall.callId = id; + +        return proxyCall; +    }; +    createSpyCall.toString = callProto.toString; // used by mocks + +    if (commonJSModule) { +        module.exports = createSpyCall; +    } else { +        sinon.spyCall = createSpyCall; +    } +}(typeof sinon == "object" && sinon || null)); + + +/** +  * @depend ../sinon.js +  * @depend call.js +  */ +/*jslint eqeqeq: false, onevar: false, plusplus: false*/ +/*global module, require, sinon*/ +/** +  * Spy functions +  * +  * @author Christian Johansen (christian@cjohansen.no) +  * @license BSD +  * +  * Copyright (c) 2010-2013 Christian Johansen +  */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; +    var push = Array.prototype.push; +    var slice = Array.prototype.slice; +    var callId = 0; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function spy(object, property) { +        if (!property && typeof object == "function") { +            return spy.create(object); +        } + +        if (!object && !property) { +            return spy.create(function () { }); +        } + +        var method = object[property]; +        return sinon.wrapMethod(object, property, spy.create(method)); +    } + +    function matchingFake(fakes, args, strict) { +        if (!fakes) { +            return; +        } + +        var alen = args.length; + +        for (var i = 0, l = fakes.length; i < l; i++) { +            if (fakes[i].matches(args, strict)) { +                return fakes[i]; +            } +        } +    } + +    function incrementCallCount() { +        this.called = true; +        this.callCount += 1; +        this.notCalled = false; +        this.calledOnce = this.callCount == 1; +        this.calledTwice = this.callCount == 2; +        this.calledThrice = this.callCount == 3; +    } + +    function createCallProperties() { +        this.firstCall = this.getCall(0); +        this.secondCall = this.getCall(1); +        this.thirdCall = this.getCall(2); +        this.lastCall = this.getCall(this.callCount - 1); +    } + +    var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; +    function createProxy(func) { +        // Retain the function length: +        var p; +        if (func.length) { +            eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) + +                ") { return p.invoke(func, this, slice.call(arguments)); });"); +        } +        else { +            p = function proxy() { +                return p.invoke(func, this, slice.call(arguments)); +            }; +        } +        return p; +    } + +    var uuid = 0; + +    // Public API +    var spyApi = { +        reset: function () { +            this.called = false; +            this.notCalled = true; +            this.calledOnce = false; +            this.calledTwice = false; +            this.calledThrice = false; +            this.callCount = 0; +            this.firstCall = null; +            this.secondCall = null; +            this.thirdCall = null; +            this.lastCall = null; +            this.args = []; +            this.returnValues = []; +            this.thisValues = []; +            this.exceptions = []; +            this.callIds = []; +            if (this.fakes) { +                for (var i = 0; i < this.fakes.length; i++) { +                    this.fakes[i].reset(); +                } +            } +        }, + +        create: function create(func) { +            var name; + +            if (typeof func != "function") { +                func = function () { }; +            } else { +                name = sinon.functionName(func); +            } + +            var proxy = createProxy(func); + +            sinon.extend(proxy, spy); +            delete proxy.create; +            sinon.extend(proxy, func); + +            proxy.reset(); +            proxy.prototype = func.prototype; +            proxy.displayName = name || "spy"; +            proxy.toString = sinon.functionToString; +            proxy._create = sinon.spy.create; +            proxy.id = "spy#" + uuid++; + +            return proxy; +        }, + +        invoke: function invoke(func, thisValue, args) { +            var matching = matchingFake(this.fakes, args); +            var exception, returnValue; + +            incrementCallCount.call(this); +            push.call(this.thisValues, thisValue); +            push.call(this.args, args); +            push.call(this.callIds, callId++); + +            try { +                if (matching) { +                    returnValue = matching.invoke(func, thisValue, args); +                } else { +                    returnValue = (this.func || func).apply(thisValue, args); +                } +            } catch (e) { +                push.call(this.returnValues, undefined); +                exception = e; +                throw e; +            } finally { +                push.call(this.exceptions, exception); +            } + +            push.call(this.returnValues, returnValue); + +            createCallProperties.call(this); + +            return returnValue; +        }, + +        getCall: function getCall(i) { +            if (i < 0 || i >= this.callCount) { +                return null; +            } + +            return sinon.spyCall(this, this.thisValues[i], this.args[i], +                                    this.returnValues[i], this.exceptions[i], +                                    this.callIds[i]); +        }, + +        calledBefore: function calledBefore(spyFn) { +            if (!this.called) { +                return false; +            } + +            if (!spyFn.called) { +                return true; +            } + +            return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; +        }, + +        calledAfter: function calledAfter(spyFn) { +            if (!this.called || !spyFn.called) { +                return false; +            } + +            return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; +        }, + +        withArgs: function () { +            var args = slice.call(arguments); + +            if (this.fakes) { +                var match = matchingFake(this.fakes, args, true); + +                if (match) { +                    return match; +                } +            } else { +                this.fakes = []; +            } + +            var original = this; +            var fake = this._create(); +            fake.matchingAguments = args; +            push.call(this.fakes, fake); + +            fake.withArgs = function () { +                return original.withArgs.apply(original, arguments); +            }; + +            for (var i = 0; i < this.args.length; i++) { +                if (fake.matches(this.args[i])) { +                    incrementCallCount.call(fake); +                    push.call(fake.thisValues, this.thisValues[i]); +                    push.call(fake.args, this.args[i]); +                    push.call(fake.returnValues, this.returnValues[i]); +                    push.call(fake.exceptions, this.exceptions[i]); +                    push.call(fake.callIds, this.callIds[i]); +                } +            } +            createCallProperties.call(fake); + +            return fake; +        }, + +        matches: function (args, strict) { +            var margs = this.matchingAguments; + +            if (margs.length <= args.length && +                sinon.deepEqual(margs, args.slice(0, margs.length))) { +                return !strict || margs.length == args.length; +            } +        }, + +        printf: function (format) { +            var spy = this; +            var args = slice.call(arguments, 1); +            var formatter; + +            return (format || "").replace(/%(.)/g, function (match, specifyer) { +                formatter = spyApi.formatters[specifyer]; + +                if (typeof formatter == "function") { +                    return formatter.call(null, spy, args); +                } else if (!isNaN(parseInt(specifyer), 10)) { +                    return sinon.format(args[specifyer - 1]); +                } + +                return "%" + specifyer; +            }); +        } +    }; + +    function delegateToCalls(method, matchAny, actual, notCalled) { +        spyApi[method] = function () { +            if (!this.called) { +                if (notCalled) { +                    return notCalled.apply(this, arguments); +                } +                return false; +            } + +            var currentCall; +            var matches = 0; + +            for (var i = 0, l = this.callCount; i < l; i += 1) { +                currentCall = this.getCall(i); + +                if (currentCall[actual || method].apply(currentCall, arguments)) { +                    matches += 1; + +                    if (matchAny) { +                        return true; +                    } +                } +            } + +            return matches === this.callCount; +        }; +    } + +    delegateToCalls("calledOn", true); +    delegateToCalls("alwaysCalledOn", false, "calledOn"); +    delegateToCalls("calledWith", true); +    delegateToCalls("calledWithMatch", true); +    delegateToCalls("alwaysCalledWith", false, "calledWith"); +    delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); +    delegateToCalls("calledWithExactly", true); +    delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); +    delegateToCalls("neverCalledWith", false, "notCalledWith", +        function () { return true; }); +    delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", +        function () { return true; }); +    delegateToCalls("threw", true); +    delegateToCalls("alwaysThrew", false, "threw"); +    delegateToCalls("returned", true); +    delegateToCalls("alwaysReturned", false, "returned"); +    delegateToCalls("calledWithNew", true); +    delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); +    delegateToCalls("callArg", false, "callArgWith", function () { +        throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); +    }); +    spyApi.callArgWith = spyApi.callArg; +    delegateToCalls("callArgOn", false, "callArgOnWith", function () { +        throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); +    }); +    spyApi.callArgOnWith = spyApi.callArgOn; +    delegateToCalls("yield", false, "yield", function () { +        throw new Error(this.toString() + " cannot yield since it was not yet invoked."); +    }); +    // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. +    spyApi.invokeCallback = spyApi.yield; +    delegateToCalls("yieldOn", false, "yieldOn", function () { +        throw new Error(this.toString() + " cannot yield since it was not yet invoked."); +    }); +    delegateToCalls("yieldTo", false, "yieldTo", function (property) { +        throw new Error(this.toString() + " cannot yield to '" + property + +            "' since it was not yet invoked."); +    }); +    delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { +        throw new Error(this.toString() + " cannot yield to '" + property + +            "' since it was not yet invoked."); +    }); + +    spyApi.formatters = { +        "c": function (spy) { +            return sinon.timesInWords(spy.callCount); +        }, + +        "n": function (spy) { +            return spy.toString(); +        }, + +        "C": function (spy) { +            var calls = []; + +            for (var i = 0, l = spy.callCount; i < l; ++i) { +                var stringifiedCall = "    " + spy.getCall(i).toString(); +                if (/\n/.test(calls[i - 1])) { +                    stringifiedCall = "\n" + stringifiedCall; +                } +                push.call(calls, stringifiedCall); +            } + +            return calls.length > 0 ? "\n" + calls.join("\n") : ""; +        }, + +        "t": function (spy) { +            var objects = []; + +            for (var i = 0, l = spy.callCount; i < l; ++i) { +                push.call(objects, sinon.format(spy.thisValues[i])); +            } + +            return objects.join(", "); +        }, + +        "*": function (spy, args) { +            var formatted = []; + +            for (var i = 0, l = args.length; i < l; ++i) { +                push.call(formatted, sinon.format(args[i])); +            } + +            return formatted.join(", "); +        } +    }; + +    sinon.extend(spy, spyApi); + +    spy.spyCall = sinon.spyCall; + +    if (commonJSModule) { +        module.exports = spy; +    } else { +        sinon.spy = spy; +    } +}(typeof sinon == "object" && sinon || null)); + +/** + * @depend ../sinon.js + * @depend spy.js + */ +/*jslint eqeqeq: false, onevar: false*/ +/*global module, require, sinon*/ +/** + * Stub functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function stub(object, property, func) { +        if (!!func && typeof func != "function") { +            throw new TypeError("Custom stub should be function"); +        } + +        var wrapper; + +        if (func) { +            wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; +        } else { +            wrapper = stub.create(); +        } + +        if (!object && !property) { +            return sinon.stub.create(); +        } + +        if (!property && !!object && typeof object == "object") { +            for (var prop in object) { +                if (typeof object[prop] === "function") { +                    stub(object, prop); +                } +            } + +            return object; +        } + +        return sinon.wrapMethod(object, property, wrapper); +    } + +    function getChangingValue(stub, property) { +        var index = stub.callCount - 1; +        var values = stub[property]; +        var prop = index in values ? values[index] : values[values.length - 1]; +        stub[property + "Last"] = prop; + +        return prop; +    } + +    function getCallback(stub, args) { +        var callArgAt = getChangingValue(stub, "callArgAts"); + +        if (callArgAt < 0) { +            var callArgProp = getChangingValue(stub, "callArgProps"); + +            for (var i = 0, l = args.length; i < l; ++i) { +                if (!callArgProp && typeof args[i] == "function") { +                    return args[i]; +                } + +                if (callArgProp && args[i] && +                    typeof args[i][callArgProp] == "function") { +                    return args[i][callArgProp]; +                } +            } + +            return null; +        } + +        return args[callArgAt]; +    } + +    var join = Array.prototype.join; + +    function getCallbackError(stub, func, args) { +        if (stub.callArgAtsLast < 0) { +            var msg; + +            if (stub.callArgPropsLast) { +                msg = sinon.functionName(stub) + +                    " expected to yield to '" + stub.callArgPropsLast + +                    "', but no object with such a property was passed." +            } else { +                msg = sinon.functionName(stub) + +                            " expected to yield, but no callback was passed." +            } + +            if (args.length > 0) { +                msg += " Received [" + join.call(args, ", ") + "]"; +            } + +            return msg; +        } + +        return "argument at index " + stub.callArgAtsLast + " is not a function: " + func; +    } + +    var nextTick = (function () { +        if (typeof process === "object" && typeof process.nextTick === "function") { +            return process.nextTick; +        } else if (typeof setImmediate === "function") { +            return setImmediate; +        } else { +            return function (callback) { +                setTimeout(callback, 0); +            }; +        } +    })(); + +    function callCallback(stub, args) { +        if (stub.callArgAts.length > 0) { +            var func = getCallback(stub, args); + +            if (typeof func != "function") { +                throw new TypeError(getCallbackError(stub, func, args)); +            } + +            var callbackArguments = getChangingValue(stub, "callbackArguments"); +            var callbackContext = getChangingValue(stub, "callbackContexts"); + +            if (stub.callbackAsync) { +                nextTick(function() { +                    func.apply(callbackContext, callbackArguments); +                }); +            } else { +                func.apply(callbackContext, callbackArguments); +            } +        } +    } + +    var uuid = 0; + +    sinon.extend(stub, (function () { +        var slice = Array.prototype.slice, proto; + +        function throwsException(error, message) { +            if (typeof error == "string") { +                this.exception = new Error(message || ""); +                this.exception.name = error; +            } else if (!error) { +                this.exception = new Error("Error"); +            } else { +                this.exception = error; +            } + +            return this; +        } + +        proto = { +            create: function create() { +                var functionStub = function () { + +                    callCallback(functionStub, arguments); + +                    if (functionStub.exception) { +                        throw functionStub.exception; +                    } else if (typeof functionStub.returnArgAt == 'number') { +                        return arguments[functionStub.returnArgAt]; +                    } else if (functionStub.returnThis) { +                        return this; +                    } +                    return functionStub.returnValue; +                }; + +                functionStub.id = "stub#" + uuid++; +                var orig = functionStub; +                functionStub = sinon.spy.create(functionStub); +                functionStub.func = orig; + +                functionStub.callArgAts = []; +                functionStub.callbackArguments = []; +                functionStub.callbackContexts = []; +                functionStub.callArgProps = []; + +                sinon.extend(functionStub, stub); +                functionStub._create = sinon.stub.create; +                functionStub.displayName = "stub"; +                functionStub.toString = sinon.functionToString; + +                return functionStub; +            }, + +            resetBehavior: function () { +                var i; + +                this.callArgAts = []; +                this.callbackArguments = []; +                this.callbackContexts = []; +                this.callArgProps = []; + +                delete this.returnValue; +                delete this.returnArgAt; +                this.returnThis = false; + +                if (this.fakes) { +                    for (i = 0; i < this.fakes.length; i++) { +                        this.fakes[i].resetBehavior(); +                    } +                } +            }, + +            returns: function returns(value) { +                this.returnValue = value; + +                return this; +            }, + +            returnsArg: function returnsArg(pos) { +                if (typeof pos != "number") { +                    throw new TypeError("argument index is not number"); +                } + +                this.returnArgAt = pos; + +                return this; +            }, + +            returnsThis: function returnsThis() { +                this.returnThis = true; + +                return this; +            }, + +            "throws": throwsException, +            throwsException: throwsException, + +            callsArg: function callsArg(pos) { +                if (typeof pos != "number") { +                    throw new TypeError("argument index is not number"); +                } + +                this.callArgAts.push(pos); +                this.callbackArguments.push([]); +                this.callbackContexts.push(undefined); +                this.callArgProps.push(undefined); + +                return this; +            }, + +            callsArgOn: function callsArgOn(pos, context) { +                if (typeof pos != "number") { +                    throw new TypeError("argument index is not number"); +                } +                if (typeof context != "object") { +                    throw new TypeError("argument context is not an object"); +                } + +                this.callArgAts.push(pos); +                this.callbackArguments.push([]); +                this.callbackContexts.push(context); +                this.callArgProps.push(undefined); + +                return this; +            }, + +            callsArgWith: function callsArgWith(pos) { +                if (typeof pos != "number") { +                    throw new TypeError("argument index is not number"); +                } + +                this.callArgAts.push(pos); +                this.callbackArguments.push(slice.call(arguments, 1)); +                this.callbackContexts.push(undefined); +                this.callArgProps.push(undefined); + +                return this; +            }, + +            callsArgOnWith: function callsArgWith(pos, context) { +                if (typeof pos != "number") { +                    throw new TypeError("argument index is not number"); +                } +                if (typeof context != "object") { +                    throw new TypeError("argument context is not an object"); +                } + +                this.callArgAts.push(pos); +                this.callbackArguments.push(slice.call(arguments, 2)); +                this.callbackContexts.push(context); +                this.callArgProps.push(undefined); + +                return this; +            }, + +            yields: function () { +                this.callArgAts.push(-1); +                this.callbackArguments.push(slice.call(arguments, 0)); +                this.callbackContexts.push(undefined); +                this.callArgProps.push(undefined); + +                return this; +            }, + +            yieldsOn: function (context) { +                if (typeof context != "object") { +                    throw new TypeError("argument context is not an object"); +                } + +                this.callArgAts.push(-1); +                this.callbackArguments.push(slice.call(arguments, 1)); +                this.callbackContexts.push(context); +                this.callArgProps.push(undefined); + +                return this; +            }, + +            yieldsTo: function (prop) { +                this.callArgAts.push(-1); +                this.callbackArguments.push(slice.call(arguments, 1)); +                this.callbackContexts.push(undefined); +                this.callArgProps.push(prop); + +                return this; +            }, + +            yieldsToOn: function (prop, context) { +                if (typeof context != "object") { +                    throw new TypeError("argument context is not an object"); +                } + +                this.callArgAts.push(-1); +                this.callbackArguments.push(slice.call(arguments, 2)); +                this.callbackContexts.push(context); +                this.callArgProps.push(prop); + +                return this; +            } +        }; + +        // create asynchronous versions of callsArg* and yields* methods +        for (var method in proto) { +            // need to avoid creating anotherasync versions of the newly added async methods +            if (proto.hasOwnProperty(method) && +                method.match(/^(callsArg|yields|thenYields$)/) && +                !method.match(/Async/)) { +                proto[method + 'Async'] = (function (syncFnName) { +                    return function () { +                        this.callbackAsync = true; +                        return this[syncFnName].apply(this, arguments); +                    }; +                })(method); +            } +        } + +        return proto; + +    }())); + +    if (commonJSModule) { +        module.exports = stub; +    } else { +        sinon.stub = stub; +    } +}(typeof sinon == "object" && sinon || null)); + +/** + * @depend ../sinon.js + * @depend stub.js + */ +/*jslint eqeqeq: false, onevar: false, nomen: false*/ +/*global module, require, sinon*/ +/** + * Mock functions. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; +    var push = [].push; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function mock(object) { +        if (!object) { +            return sinon.expectation.create("Anonymous mock"); +        } + +        return mock.create(object); +    } + +    sinon.mock = mock; + +    sinon.extend(mock, (function () { +        function each(collection, callback) { +            if (!collection) { +                return; +            } + +            for (var i = 0, l = collection.length; i < l; i += 1) { +                callback(collection[i]); +            } +        } + +        return { +            create: function create(object) { +                if (!object) { +                    throw new TypeError("object is null"); +                } + +                var mockObject = sinon.extend({}, mock); +                mockObject.object = object; +                delete mockObject.create; + +                return mockObject; +            }, + +            expects: function expects(method) { +                if (!method) { +                    throw new TypeError("method is falsy"); +                } + +                if (!this.expectations) { +                    this.expectations = {}; +                    this.proxies = []; +                } + +                if (!this.expectations[method]) { +                    this.expectations[method] = []; +                    var mockObject = this; + +                    sinon.wrapMethod(this.object, method, function () { +                        return mockObject.invokeMethod(method, this, arguments); +                    }); + +                    push.call(this.proxies, method); +                } + +                var expectation = sinon.expectation.create(method); +                push.call(this.expectations[method], expectation); + +                return expectation; +            }, + +            restore: function restore() { +                var object = this.object; + +                each(this.proxies, function (proxy) { +                    if (typeof object[proxy].restore == "function") { +                        object[proxy].restore(); +                    } +                }); +            }, + +            verify: function verify() { +                var expectations = this.expectations || {}; +                var messages = [], met = []; + +                each(this.proxies, function (proxy) { +                    each(expectations[proxy], function (expectation) { +                        if (!expectation.met()) { +                            push.call(messages, expectation.toString()); +                        } else { +                            push.call(met, expectation.toString()); +                        } +                    }); +                }); + +                this.restore(); + +                if (messages.length > 0) { +                    sinon.expectation.fail(messages.concat(met).join("\n")); +                } else { +                    sinon.expectation.pass(messages.concat(met).join("\n")); +                } + +                return true; +            }, + +            invokeMethod: function invokeMethod(method, thisValue, args) { +                var expectations = this.expectations && this.expectations[method]; +                var length = expectations && expectations.length || 0, i; + +                for (i = 0; i < length; i += 1) { +                    if (!expectations[i].met() && +                        expectations[i].allowsCall(thisValue, args)) { +                        return expectations[i].apply(thisValue, args); +                    } +                } + +                var messages = [], available, exhausted = 0; + +                for (i = 0; i < length; i += 1) { +                    if (expectations[i].allowsCall(thisValue, args)) { +                        available = available || expectations[i]; +                    } else { +                        exhausted += 1; +                    } +                    push.call(messages, "    " + expectations[i].toString()); +                } + +                if (exhausted === 0) { +                    return available.apply(thisValue, args); +                } + +                messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ +                    proxy: method, +                    args: args +                })); + +                sinon.expectation.fail(messages.join("\n")); +            } +        }; +    }())); + +    var times = sinon.timesInWords; + +    sinon.expectation = (function () { +        var slice = Array.prototype.slice; +        var _invoke = sinon.spy.invoke; + +        function callCountInWords(callCount) { +            if (callCount == 0) { +                return "never called"; +            } else { +                return "called " + times(callCount); +            } +        } + +        function expectedCallCountInWords(expectation) { +            var min = expectation.minCalls; +            var max = expectation.maxCalls; + +            if (typeof min == "number" && typeof max == "number") { +                var str = times(min); + +                if (min != max) { +                    str = "at least " + str + " and at most " + times(max); +                } + +                return str; +            } + +            if (typeof min == "number") { +                return "at least " + times(min); +            } + +            return "at most " + times(max); +        } + +        function receivedMinCalls(expectation) { +            var hasMinLimit = typeof expectation.minCalls == "number"; +            return !hasMinLimit || expectation.callCount >= expectation.minCalls; +        } + +        function receivedMaxCalls(expectation) { +            if (typeof expectation.maxCalls != "number") { +                return false; +            } + +            return expectation.callCount == expectation.maxCalls; +        } + +        return { +            minCalls: 1, +            maxCalls: 1, + +            create: function create(methodName) { +                var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); +                delete expectation.create; +                expectation.method = methodName; + +                return expectation; +            }, + +            invoke: function invoke(func, thisValue, args) { +                this.verifyCallAllowed(thisValue, args); + +                return _invoke.apply(this, arguments); +            }, + +            atLeast: function atLeast(num) { +                if (typeof num != "number") { +                    throw new TypeError("'" + num + "' is not number"); +                } + +                if (!this.limitsSet) { +                    this.maxCalls = null; +                    this.limitsSet = true; +                } + +                this.minCalls = num; + +                return this; +            }, + +            atMost: function atMost(num) { +                if (typeof num != "number") { +                    throw new TypeError("'" + num + "' is not number"); +                } + +                if (!this.limitsSet) { +                    this.minCalls = null; +                    this.limitsSet = true; +                } + +                this.maxCalls = num; + +                return this; +            }, + +            never: function never() { +                return this.exactly(0); +            }, + +            once: function once() { +                return this.exactly(1); +            }, + +            twice: function twice() { +                return this.exactly(2); +            }, + +            thrice: function thrice() { +                return this.exactly(3); +            }, + +            exactly: function exactly(num) { +                if (typeof num != "number") { +                    throw new TypeError("'" + num + "' is not a number"); +                } + +                this.atLeast(num); +                return this.atMost(num); +            }, + +            met: function met() { +                return !this.failed && receivedMinCalls(this); +            }, + +            verifyCallAllowed: function verifyCallAllowed(thisValue, args) { +                if (receivedMaxCalls(this)) { +                    this.failed = true; +                    sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); +                } + +                if ("expectedThis" in this && this.expectedThis !== thisValue) { +                    sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + +                        this.expectedThis); +                } + +                if (!("expectedArguments" in this)) { +                    return; +                } + +                if (!args) { +                    sinon.expectation.fail(this.method + " received no arguments, expected " + +                        sinon.format(this.expectedArguments)); +                } + +                if (args.length < this.expectedArguments.length) { +                    sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + +                        "), expected " + sinon.format(this.expectedArguments)); +                } + +                if (this.expectsExactArgCount && +                    args.length != this.expectedArguments.length) { +                    sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + +                        "), expected " + sinon.format(this.expectedArguments)); +                } + +                for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { +                    if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { +                        sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + +                            ", expected " + sinon.format(this.expectedArguments)); +                    } +                } +            }, + +            allowsCall: function allowsCall(thisValue, args) { +                if (this.met() && receivedMaxCalls(this)) { +                    return false; +                } + +                if ("expectedThis" in this && this.expectedThis !== thisValue) { +                    return false; +                } + +                if (!("expectedArguments" in this)) { +                    return true; +                } + +                args = args || []; + +                if (args.length < this.expectedArguments.length) { +                    return false; +                } + +                if (this.expectsExactArgCount && +                    args.length != this.expectedArguments.length) { +                    return false; +                } + +                for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { +                    if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { +                        return false; +                    } +                } + +                return true; +            }, + +            withArgs: function withArgs() { +                this.expectedArguments = slice.call(arguments); +                return this; +            }, + +            withExactArgs: function withExactArgs() { +                this.withArgs.apply(this, arguments); +                this.expectsExactArgCount = true; +                return this; +            }, + +            on: function on(thisValue) { +                this.expectedThis = thisValue; +                return this; +            }, + +            toString: function () { +                var args = (this.expectedArguments || []).slice(); + +                if (!this.expectsExactArgCount) { +                    push.call(args, "[...]"); +                } + +                var callStr = sinon.spyCall.toString.call({ +                    proxy: this.method || "anonymous mock expectation", +                    args: args +                }); + +                var message = callStr.replace(", [...", "[, ...") + " " + +                    expectedCallCountInWords(this); + +                if (this.met()) { +                    return "Expectation met: " + message; +                } + +                return "Expected " + message + " (" + +                    callCountInWords(this.callCount) + ")"; +            }, + +            verify: function verify() { +                if (!this.met()) { +                    sinon.expectation.fail(this.toString()); +                } else { +                    sinon.expectation.pass(this.toString()); +                } + +                return true; +            }, + +            pass: function(message) { +              sinon.assert.pass(message); +            }, +            fail: function (message) { +                var exception = new Error(message); +                exception.name = "ExpectationError"; + +                throw exception; +            } +        }; +    }()); + +    if (commonJSModule) { +        module.exports = mock; +    } else { +        sinon.mock = mock; +    } +}(typeof sinon == "object" && sinon || null)); + +/** + * @depend ../sinon.js + * @depend stub.js + * @depend mock.js + */ +/*jslint eqeqeq: false, onevar: false, forin: true*/ +/*global module, require, sinon*/ +/** + * Collections of stubs, spies and mocks. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; +    var push = [].push; +    var hasOwnProperty = Object.prototype.hasOwnProperty; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function getFakes(fakeCollection) { +        if (!fakeCollection.fakes) { +            fakeCollection.fakes = []; +        } + +        return fakeCollection.fakes; +    } + +    function each(fakeCollection, method) { +        var fakes = getFakes(fakeCollection); + +        for (var i = 0, l = fakes.length; i < l; i += 1) { +            if (typeof fakes[i][method] == "function") { +                fakes[i][method](); +            } +        } +    } + +    function compact(fakeCollection) { +        var fakes = getFakes(fakeCollection); +        var i = 0; +        while (i < fakes.length) { +          fakes.splice(i, 1); +        } +    } + +    var collection = { +        verify: function resolve() { +            each(this, "verify"); +        }, + +        restore: function restore() { +            each(this, "restore"); +            compact(this); +        }, + +        verifyAndRestore: function verifyAndRestore() { +            var exception; + +            try { +                this.verify(); +            } catch (e) { +                exception = e; +            } + +            this.restore(); + +            if (exception) { +                throw exception; +            } +        }, + +        add: function add(fake) { +            push.call(getFakes(this), fake); +            return fake; +        }, + +        spy: function spy() { +            return this.add(sinon.spy.apply(sinon, arguments)); +        }, + +        stub: function stub(object, property, value) { +            if (property) { +                var original = object[property]; + +                if (typeof original != "function") { +                    if (!hasOwnProperty.call(object, property)) { +                        throw new TypeError("Cannot stub non-existent own property " + property); +                    } + +                    object[property] = value; + +                    return this.add({ +                        restore: function () { +                            object[property] = original; +                        } +                    }); +                } +            } +            if (!property && !!object && typeof object == "object") { +                var stubbedObj = sinon.stub.apply(sinon, arguments); + +                for (var prop in stubbedObj) { +                    if (typeof stubbedObj[prop] === "function") { +                        this.add(stubbedObj[prop]); +                    } +                } + +                return stubbedObj; +            } + +            return this.add(sinon.stub.apply(sinon, arguments)); +        }, + +        mock: function mock() { +            return this.add(sinon.mock.apply(sinon, arguments)); +        }, + +        inject: function inject(obj) { +            var col = this; + +            obj.spy = function () { +                return col.spy.apply(col, arguments); +            }; + +            obj.stub = function () { +                return col.stub.apply(col, arguments); +            }; + +            obj.mock = function () { +                return col.mock.apply(col, arguments); +            }; + +            return obj; +        } +    }; + +    if (commonJSModule) { +        module.exports = collection; +    } else { +        sinon.collection = collection; +    } +}(typeof sinon == "object" && sinon || null)); + +/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ +/*global module, require, window*/ +/** + * Fake timer API + * setTimeout + * setInterval + * clearTimeout + * clearInterval + * tick + * reset + * Date + * + * Inspired by jsUnitMockTimeOut from JsUnit + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +if (typeof sinon == "undefined") { +    var sinon = {}; +} + +(function (global) { +    var id = 1; + +    function addTimer(args, recurring) { +        if (args.length === 0) { +            throw new Error("Function requires at least 1 parameter"); +        } + +        var toId = id++; +        var delay = args[1] || 0; + +        if (!this.timeouts) { +            this.timeouts = {}; +        } + +        this.timeouts[toId] = { +            id: toId, +            func: args[0], +            callAt: this.now + delay, +            invokeArgs: Array.prototype.slice.call(args, 2) +        }; + +        if (recurring === true) { +            this.timeouts[toId].interval = delay; +        } + +        return toId; +    } + +    function parseTime(str) { +        if (!str) { +            return 0; +        } + +        var strings = str.split(":"); +        var l = strings.length, i = l; +        var ms = 0, parsed; + +        if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { +            throw new Error("tick only understands numbers and 'h:m:s'"); +        } + +        while (i--) { +            parsed = parseInt(strings[i], 10); + +            if (parsed >= 60) { +                throw new Error("Invalid time " + str); +            } + +            ms += parsed * Math.pow(60, (l - i - 1)); +        } + +        return ms * 1000; +    } + +    function createObject(object) { +        var newObject; + +        if (Object.create) { +            newObject = Object.create(object); +        } else { +            var F = function () {}; +            F.prototype = object; +            newObject = new F(); +        } + +        newObject.Date.clock = newObject; +        return newObject; +    } + +    sinon.clock = { +        now: 0, + +        create: function create(now) { +            var clock = createObject(this); + +            if (typeof now == "number") { +                clock.now = now; +            } + +            if (!!now && typeof now == "object") { +                throw new TypeError("now should be milliseconds since UNIX epoch"); +            } + +            return clock; +        }, + +        setTimeout: function setTimeout(callback, timeout) { +            return addTimer.call(this, arguments, false); +        }, + +        clearTimeout: function clearTimeout(timerId) { +            if (!this.timeouts) { +                this.timeouts = []; +            } + +            if (timerId in this.timeouts) { +                delete this.timeouts[timerId]; +            } +        }, + +        setInterval: function setInterval(callback, timeout) { +            return addTimer.call(this, arguments, true); +        }, + +        clearInterval: function clearInterval(timerId) { +            this.clearTimeout(timerId); +        }, + +        tick: function tick(ms) { +            ms = typeof ms == "number" ? ms : parseTime(ms); +            var tickFrom = this.now, tickTo = this.now + ms, previous = this.now; +            var timer = this.firstTimerInRange(tickFrom, tickTo); + +            var firstException; +            while (timer && tickFrom <= tickTo) { +                if (this.timeouts[timer.id]) { +                    tickFrom = this.now = timer.callAt; +                    try { +                      this.callTimer(timer); +                    } catch (e) { +                      firstException = firstException || e; +                    } +                } + +                timer = this.firstTimerInRange(previous, tickTo); +                previous = tickFrom; +            } + +            this.now = tickTo; + +            if (firstException) { +              throw firstException; +            } + +            return this.now; +        }, + +        firstTimerInRange: function (from, to) { +            var timer, smallest, originalTimer; + +            for (var id in this.timeouts) { +                if (this.timeouts.hasOwnProperty(id)) { +                    if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) { +                        continue; +                    } + +                    if (!smallest || this.timeouts[id].callAt < smallest) { +                        originalTimer = this.timeouts[id]; +                        smallest = this.timeouts[id].callAt; + +                        timer = { +                            func: this.timeouts[id].func, +                            callAt: this.timeouts[id].callAt, +                            interval: this.timeouts[id].interval, +                            id: this.timeouts[id].id, +                            invokeArgs: this.timeouts[id].invokeArgs +                        }; +                    } +                } +            } + +            return timer || null; +        }, + +        callTimer: function (timer) { +            if (typeof timer.interval == "number") { +                this.timeouts[timer.id].callAt += timer.interval; +            } else { +                delete this.timeouts[timer.id]; +            } + +            try { +                if (typeof timer.func == "function") { +                    timer.func.apply(null, timer.invokeArgs); +                } else { +                    eval(timer.func); +                } +            } catch (e) { +              var exception = e; +            } + +            if (!this.timeouts[timer.id]) { +                if (exception) { +                  throw exception; +                } +                return; +            } + +            if (exception) { +              throw exception; +            } +        }, + +        reset: function reset() { +            this.timeouts = {}; +        }, + +        Date: (function () { +            var NativeDate = Date; + +            function ClockDate(year, month, date, hour, minute, second, ms) { +                // Defensive and verbose to avoid potential harm in passing +                // explicit undefined when user does not pass argument +                switch (arguments.length) { +                case 0: +                    return new NativeDate(ClockDate.clock.now); +                case 1: +                    return new NativeDate(year); +                case 2: +                    return new NativeDate(year, month); +                case 3: +                    return new NativeDate(year, month, date); +                case 4: +                    return new NativeDate(year, month, date, hour); +                case 5: +                    return new NativeDate(year, month, date, hour, minute); +                case 6: +                    return new NativeDate(year, month, date, hour, minute, second); +                default: +                    return new NativeDate(year, month, date, hour, minute, second, ms); +                } +            } + +            return mirrorDateProperties(ClockDate, NativeDate); +        }()) +    }; + +    function mirrorDateProperties(target, source) { +        if (source.now) { +            target.now = function now() { +                return target.clock.now; +            }; +        } else { +            delete target.now; +        } + +        if (source.toSource) { +            target.toSource = function toSource() { +                return source.toSource(); +            }; +        } else { +            delete target.toSource; +        } + +        target.toString = function toString() { +            return source.toString(); +        }; + +        target.prototype = source.prototype; +        target.parse = source.parse; +        target.UTC = source.UTC; +        target.prototype.toUTCString = source.prototype.toUTCString; +        return target; +    } + +    var methods = ["Date", "setTimeout", "setInterval", +                   "clearTimeout", "clearInterval"]; + +    function restore() { +        var method; + +        for (var i = 0, l = this.methods.length; i < l; i++) { +            method = this.methods[i]; +            if (global[method].hadOwnProperty) { +                global[method] = this["_" + method]; +            } else { +                delete global[method]; +            } +        } + +        // Prevent multiple executions which will completely remove these props +        this.methods = []; +    } + +    function stubGlobal(method, clock) { +        clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method); +        clock["_" + method] = global[method]; + +        if (method == "Date") { +            var date = mirrorDateProperties(clock[method], global[method]); +            global[method] = date; +        } else { +            global[method] = function () { +                return clock[method].apply(clock, arguments); +            }; + +            for (var prop in clock[method]) { +                if (clock[method].hasOwnProperty(prop)) { +                    global[method][prop] = clock[method][prop]; +                } +            } +        } + +        global[method].clock = clock; +    } + +    sinon.useFakeTimers = function useFakeTimers(now) { +        var clock = sinon.clock.create(now); +        clock.restore = restore; +        clock.methods = Array.prototype.slice.call(arguments, +                                                   typeof now == "number" ? 1 : 0); + +        if (clock.methods.length === 0) { +            clock.methods = methods; +        } + +        for (var i = 0, l = clock.methods.length; i < l; i++) { +            stubGlobal(clock.methods[i], clock); +        } + +        return clock; +    }; +}(typeof global != "undefined" && typeof global !== "function" ? global : this)); + +sinon.timers = { +    setTimeout: setTimeout, +    clearTimeout: clearTimeout, +    setInterval: setInterval, +    clearInterval: clearInterval, +    Date: Date +}; + +if (typeof module == "object" && typeof require == "function") { +    module.exports = sinon; +} + +/*jslint eqeqeq: false, onevar: false*/ +/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ +/** + * Minimal Event interface implementation + * + * Original implementation by Sven Fuchs: https://gist.github.com/995028 + * Modifications and tests by Christian Johansen. + * + * @author Sven Fuchs (svenfuchs@artweb-design.de) + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2011 Sven Fuchs, Christian Johansen + */ + +if (typeof sinon == "undefined") { +    this.sinon = {}; +} + +(function () { +    var push = [].push; + +    sinon.Event = function Event(type, bubbles, cancelable, target) { +        this.initEvent(type, bubbles, cancelable, target); +    }; + +    sinon.Event.prototype = { +        initEvent: function(type, bubbles, cancelable, target) { +            this.type = type; +            this.bubbles = bubbles; +            this.cancelable = cancelable; +            this.target = target; +        }, + +        stopPropagation: function () {}, + +        preventDefault: function () { +            this.defaultPrevented = true; +        } +    }; + +    sinon.EventTarget = { +        addEventListener: function addEventListener(event, listener, useCapture) { +            this.eventListeners = this.eventListeners || {}; +            this.eventListeners[event] = this.eventListeners[event] || []; +            push.call(this.eventListeners[event], listener); +        }, + +        removeEventListener: function removeEventListener(event, listener, useCapture) { +            var listeners = this.eventListeners && this.eventListeners[event] || []; + +            for (var i = 0, l = listeners.length; i < l; ++i) { +                if (listeners[i] == listener) { +                    return listeners.splice(i, 1); +                } +            } +        }, + +        dispatchEvent: function dispatchEvent(event) { +            var type = event.type; +            var listeners = this.eventListeners && this.eventListeners[type] || []; + +            for (var i = 0; i < listeners.length; i++) { +                if (typeof listeners[i] == "function") { +                    listeners[i].call(this, event); +                } else { +                    listeners[i].handleEvent(event); +                } +            } + +            return !!event.defaultPrevented; +        } +    }; +}()); + +/** + * @depend ../../sinon.js + * @depend event.js + */ +/*jslint eqeqeq: false, onevar: false*/ +/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ +/** + * Fake XMLHttpRequest object + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +if (typeof sinon == "undefined") { +    this.sinon = {}; +} +sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest }; + +// wrapper for global +(function(global) { +    var xhr = sinon.xhr; +    xhr.GlobalXMLHttpRequest = global.XMLHttpRequest; +    xhr.GlobalActiveXObject = global.ActiveXObject; +    xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined"; +    xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined"; +    xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX +                                     ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; + +    /*jsl:ignore*/ +    var unsafeHeaders = { +        "Accept-Charset": true, +        "Accept-Encoding": true, +        "Connection": true, +        "Content-Length": true, +        "Cookie": true, +        "Cookie2": true, +        "Content-Transfer-Encoding": true, +        "Date": true, +        "Expect": true, +        "Host": true, +        "Keep-Alive": true, +        "Referer": true, +        "TE": true, +        "Trailer": true, +        "Transfer-Encoding": true, +        "Upgrade": true, +        "User-Agent": true, +        "Via": true +    }; +    /*jsl:end*/ + +    function FakeXMLHttpRequest() { +        this.readyState = FakeXMLHttpRequest.UNSENT; +        this.requestHeaders = {}; +        this.requestBody = null; +        this.status = 0; +        this.statusText = ""; + +        var xhr = this; + +        ["loadstart", "load", "abort", "loadend"].forEach(function (eventName) { +            xhr.addEventListener(eventName, function (event) { +                var listener = xhr["on" + eventName]; + +                if (listener && typeof listener == "function") { +                    listener(event); +                } +            }); +        }); + +        if (typeof FakeXMLHttpRequest.onCreate == "function") { +            FakeXMLHttpRequest.onCreate(this); +        } +    } + +    function verifyState(xhr) { +        if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { +            throw new Error("INVALID_STATE_ERR"); +        } + +        if (xhr.sendFlag) { +            throw new Error("INVALID_STATE_ERR"); +        } +    } + +    // filtering to enable a white-list version of Sinon FakeXhr, +    // where whitelisted requests are passed through to real XHR +    function each(collection, callback) { +        if (!collection) return; +        for (var i = 0, l = collection.length; i < l; i += 1) { +            callback(collection[i]); +        } +    } +    function some(collection, callback) { +        for (var index = 0; index < collection.length; index++) { +            if(callback(collection[index]) === true) return true; +        }; +        return false; +    } +    // largest arity in XHR is 5 - XHR#open +    var apply = function(obj,method,args) { +        switch(args.length) { +        case 0: return obj[method](); +        case 1: return obj[method](args[0]); +        case 2: return obj[method](args[0],args[1]); +        case 3: return obj[method](args[0],args[1],args[2]); +        case 4: return obj[method](args[0],args[1],args[2],args[3]); +        case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]); +        }; +    }; + +    FakeXMLHttpRequest.filters = []; +    FakeXMLHttpRequest.addFilter = function(fn) { +        this.filters.push(fn) +    }; +    var IE6Re = /MSIE 6/; +    FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) { +        var xhr = new sinon.xhr.workingXHR(); +        each(["open","setRequestHeader","send","abort","getResponseHeader", +              "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"], +             function(method) { +                 fakeXhr[method] = function() { +                   return apply(xhr,method,arguments); +                 }; +             }); + +        var copyAttrs = function(args) { +            each(args, function(attr) { +              try { +                fakeXhr[attr] = xhr[attr] +              } catch(e) { +                if(!IE6Re.test(navigator.userAgent)) throw e; +              } +            }); +        }; + +        var stateChange = function() { +            fakeXhr.readyState = xhr.readyState; +            if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { +                copyAttrs(["status","statusText"]); +            } +            if(xhr.readyState >= FakeXMLHttpRequest.LOADING) { +                copyAttrs(["responseText"]); +            } +            if(xhr.readyState === FakeXMLHttpRequest.DONE) { +                copyAttrs(["responseXML"]); +            } +            if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr); +        }; +        if(xhr.addEventListener) { +          for(var event in fakeXhr.eventListeners) { +              if(fakeXhr.eventListeners.hasOwnProperty(event)) { +                  each(fakeXhr.eventListeners[event],function(handler) { +                      xhr.addEventListener(event, handler); +                  }); +              } +          } +          xhr.addEventListener("readystatechange",stateChange); +        } else { +          xhr.onreadystatechange = stateChange; +        } +        apply(xhr,"open",xhrArgs); +    }; +    FakeXMLHttpRequest.useFilters = false; + +    function verifyRequestSent(xhr) { +        if (xhr.readyState == FakeXMLHttpRequest.DONE) { +            throw new Error("Request done"); +        } +    } + +    function verifyHeadersReceived(xhr) { +        if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { +            throw new Error("No headers received"); +        } +    } + +    function verifyResponseBodyType(body) { +        if (typeof body != "string") { +            var error = new Error("Attempted to respond to fake XMLHttpRequest with " + +                                 body + ", which is not a string."); +            error.name = "InvalidBodyException"; +            throw error; +        } +    } + +    sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { +        async: true, + +        open: function open(method, url, async, username, password) { +            this.method = method; +            this.url = url; +            this.async = typeof async == "boolean" ? async : true; +            this.username = username; +            this.password = password; +            this.responseText = null; +            this.responseXML = null; +            this.requestHeaders = {}; +            this.sendFlag = false; +            if(sinon.FakeXMLHttpRequest.useFilters === true) { +                var xhrArgs = arguments; +                var defake = some(FakeXMLHttpRequest.filters,function(filter) { +                    return filter.apply(this,xhrArgs) +                }); +                if (defake) { +                  return sinon.FakeXMLHttpRequest.defake(this,arguments); +                } +            } +            this.readyStateChange(FakeXMLHttpRequest.OPENED); +        }, + +        readyStateChange: function readyStateChange(state) { +            this.readyState = state; + +            if (typeof this.onreadystatechange == "function") { +                try { +                    this.onreadystatechange(); +                } catch (e) { +                    sinon.logError("Fake XHR onreadystatechange handler", e); +                } +            } + +            this.dispatchEvent(new sinon.Event("readystatechange")); + +            switch (this.readyState) { +                case FakeXMLHttpRequest.DONE: +                    this.dispatchEvent(new sinon.Event("load", false, false, this)); +                    this.dispatchEvent(new sinon.Event("loadend", false, false, this)); +                    break; +            } +        }, + +        setRequestHeader: function setRequestHeader(header, value) { +            verifyState(this); + +            if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { +                throw new Error("Refused to set unsafe header \"" + header + "\""); +            } + +            if (this.requestHeaders[header]) { +                this.requestHeaders[header] += "," + value; +            } else { +                this.requestHeaders[header] = value; +            } +        }, + +        // Helps testing +        setResponseHeaders: function setResponseHeaders(headers) { +            this.responseHeaders = {}; + +            for (var header in headers) { +                if (headers.hasOwnProperty(header)) { +                    this.responseHeaders[header] = headers[header]; +                } +            } + +            if (this.async) { +                this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); +            } else { +                this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; +            } +        }, + +        // Currently treats ALL data as a DOMString (i.e. no Document) +        send: function send(data) { +            verifyState(this); + +            if (!/^(get|head)$/i.test(this.method)) { +                if (this.requestHeaders["Content-Type"]) { +                    var value = this.requestHeaders["Content-Type"].split(";"); +                    this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8"; +                } else { +                    this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; +                } + +                this.requestBody = data; +            } + +            this.errorFlag = false; +            this.sendFlag = this.async; +            this.readyStateChange(FakeXMLHttpRequest.OPENED); + +            if (typeof this.onSend == "function") { +                this.onSend(this); +            } + +            this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); +        }, + +        abort: function abort() { +            this.aborted = true; +            this.responseText = null; +            this.errorFlag = true; +            this.requestHeaders = {}; + +            if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) { +                this.readyStateChange(sinon.FakeXMLHttpRequest.DONE); +                this.sendFlag = false; +            } + +            this.readyState = sinon.FakeXMLHttpRequest.UNSENT; + +            this.dispatchEvent(new sinon.Event("abort", false, false, this)); +            if (typeof this.onerror === "function") { +                this.onerror(); +            } +        }, + +        getResponseHeader: function getResponseHeader(header) { +            if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { +                return null; +            } + +            if (/^Set-Cookie2?$/i.test(header)) { +                return null; +            } + +            header = header.toLowerCase(); + +            for (var h in this.responseHeaders) { +                if (h.toLowerCase() == header) { +                    return this.responseHeaders[h]; +                } +            } + +            return null; +        }, + +        getAllResponseHeaders: function getAllResponseHeaders() { +            if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { +                return ""; +            } + +            var headers = ""; + +            for (var header in this.responseHeaders) { +                if (this.responseHeaders.hasOwnProperty(header) && +                    !/^Set-Cookie2?$/i.test(header)) { +                    headers += header + ": " + this.responseHeaders[header] + "\r\n"; +                } +            } + +            return headers; +        }, + +        setResponseBody: function setResponseBody(body) { +            verifyRequestSent(this); +            verifyHeadersReceived(this); +            verifyResponseBodyType(body); + +            var chunkSize = this.chunkSize || 10; +            var index = 0; +            this.responseText = ""; + +            do { +                if (this.async) { +                    this.readyStateChange(FakeXMLHttpRequest.LOADING); +                } + +                this.responseText += body.substring(index, index + chunkSize); +                index += chunkSize; +            } while (index < body.length); + +            var type = this.getResponseHeader("Content-Type"); + +            if (this.responseText && +                (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { +                try { +                    this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); +                } catch (e) { +                    // Unable to parse XML - no biggie +                } +            } + +            if (this.async) { +                this.readyStateChange(FakeXMLHttpRequest.DONE); +            } else { +                this.readyState = FakeXMLHttpRequest.DONE; +            } +        }, + +        respond: function respond(status, headers, body) { +            this.setResponseHeaders(headers || {}); +            this.status = typeof status == "number" ? status : 200; +            this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; +            this.setResponseBody(body || ""); +            if (typeof this.onload === "function"){ +                this.onload(); +            } + +        } +    }); + +    sinon.extend(FakeXMLHttpRequest, { +        UNSENT: 0, +        OPENED: 1, +        HEADERS_RECEIVED: 2, +        LOADING: 3, +        DONE: 4 +    }); + +    // Borrowed from JSpec +    FakeXMLHttpRequest.parseXML = function parseXML(text) { +        var xmlDoc; + +        if (typeof DOMParser != "undefined") { +            var parser = new DOMParser(); +            xmlDoc = parser.parseFromString(text, "text/xml"); +        } else { +            xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); +            xmlDoc.async = "false"; +            xmlDoc.loadXML(text); +        } + +        return xmlDoc; +    }; + +    FakeXMLHttpRequest.statusCodes = { +        100: "Continue", +        101: "Switching Protocols", +        200: "OK", +        201: "Created", +        202: "Accepted", +        203: "Non-Authoritative Information", +        204: "No Content", +        205: "Reset Content", +        206: "Partial Content", +        300: "Multiple Choice", +        301: "Moved Permanently", +        302: "Found", +        303: "See Other", +        304: "Not Modified", +        305: "Use Proxy", +        307: "Temporary Redirect", +        400: "Bad Request", +        401: "Unauthorized", +        402: "Payment Required", +        403: "Forbidden", +        404: "Not Found", +        405: "Method Not Allowed", +        406: "Not Acceptable", +        407: "Proxy Authentication Required", +        408: "Request Timeout", +        409: "Conflict", +        410: "Gone", +        411: "Length Required", +        412: "Precondition Failed", +        413: "Request Entity Too Large", +        414: "Request-URI Too Long", +        415: "Unsupported Media Type", +        416: "Requested Range Not Satisfiable", +        417: "Expectation Failed", +        422: "Unprocessable Entity", +        500: "Internal Server Error", +        501: "Not Implemented", +        502: "Bad Gateway", +        503: "Service Unavailable", +        504: "Gateway Timeout", +        505: "HTTP Version Not Supported" +    }; + +    sinon.useFakeXMLHttpRequest = function () { +        sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) { +            if (xhr.supportsXHR) { +                global.XMLHttpRequest = xhr.GlobalXMLHttpRequest; +            } + +            if (xhr.supportsActiveX) { +                global.ActiveXObject = xhr.GlobalActiveXObject; +            } + +            delete sinon.FakeXMLHttpRequest.restore; + +            if (keepOnCreate !== true) { +                delete sinon.FakeXMLHttpRequest.onCreate; +            } +        }; +        if (xhr.supportsXHR) { +            global.XMLHttpRequest = sinon.FakeXMLHttpRequest; +        } + +        if (xhr.supportsActiveX) { +            global.ActiveXObject = function ActiveXObject(objId) { +                if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { + +                    return new sinon.FakeXMLHttpRequest(); +                } + +                return new xhr.GlobalActiveXObject(objId); +            }; +        } + +        return sinon.FakeXMLHttpRequest; +    }; + +    sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; +})(this); + +if (typeof module == "object" && typeof require == "function") { +    module.exports = sinon; +} + +/** + * @depend fake_xml_http_request.js + */ +/*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/ +/*global module, require, window*/ +/** + * The Sinon "server" mimics a web server that receives requests from + * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, + * both synchronously and asynchronously. To respond synchronuously, canned + * answers have to be provided upfront. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +if (typeof sinon == "undefined") { +    var sinon = {}; +} + +sinon.fakeServer = (function () { +    var push = [].push; +    function F() {} + +    function create(proto) { +        F.prototype = proto; +        return new F(); +    } + +    function responseArray(handler) { +        var response = handler; + +        if (Object.prototype.toString.call(handler) != "[object Array]") { +            response = [200, {}, handler]; +        } + +        if (typeof response[2] != "string") { +            throw new TypeError("Fake server response body should be string, but was " + +                                typeof response[2]); +        } + +        return response; +    } + +    var wloc = typeof window !== "undefined" ? window.location : {}; +    var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); + +    function matchOne(response, reqMethod, reqUrl) { +        var rmeth = response.method; +        var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); +        var url = response.url; +        var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); + +        return matchMethod && matchUrl; +    } + +    function match(response, request) { +        var requestMethod = this.getHTTPMethod(request); +        var requestUrl = request.url; + +        if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { +            requestUrl = requestUrl.replace(rCurrLoc, ""); +        } + +        if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { +            if (typeof response.response == "function") { +                var ru = response.url; +                var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1)); +                return response.response.apply(response, args); +            } + +            return true; +        } + +        return false; +    } + +    function log(response, request) { +        var str; + +        str =  "Request:\n"  + sinon.format(request)  + "\n\n"; +        str += "Response:\n" + sinon.format(response) + "\n\n"; + +        sinon.log(str); +    } + +    return { +        create: function () { +            var server = create(this); +            this.xhr = sinon.useFakeXMLHttpRequest(); +            server.requests = []; + +            this.xhr.onCreate = function (xhrObj) { +                server.addRequest(xhrObj); +            }; + +            return server; +        }, + +        addRequest: function addRequest(xhrObj) { +            var server = this; +            push.call(this.requests, xhrObj); + +            xhrObj.onSend = function () { +                server.handleRequest(this); +            }; + +            if (this.autoRespond && !this.responding) { +                setTimeout(function () { +                    server.responding = false; +                    server.respond(); +                }, this.autoRespondAfter || 10); + +                this.responding = true; +            } +        }, + +        getHTTPMethod: function getHTTPMethod(request) { +            if (this.fakeHTTPMethods && /post/i.test(request.method)) { +                var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); +                return !!matches ? matches[1] : request.method; +            } + +            return request.method; +        }, + +        handleRequest: function handleRequest(xhr) { +            if (xhr.async) { +                if (!this.queue) { +                    this.queue = []; +                } + +                push.call(this.queue, xhr); +            } else { +                this.processRequest(xhr); +            } +        }, + +        respondWith: function respondWith(method, url, body) { +            if (arguments.length == 1 && typeof method != "function") { +                this.response = responseArray(method); +                return; +            } + +            if (!this.responses) { this.responses = []; } + +            if (arguments.length == 1) { +                body = method; +                url = method = null; +            } + +            if (arguments.length == 2) { +                body = url; +                url = method; +                method = null; +            } + +            push.call(this.responses, { +                method: method, +                url: url, +                response: typeof body == "function" ? body : responseArray(body) +            }); +        }, + +        respond: function respond() { +            if (arguments.length > 0) this.respondWith.apply(this, arguments); +            var queue = this.queue || []; +            var request; + +            while(request = queue.shift()) { +                this.processRequest(request); +            } +        }, + +        processRequest: function processRequest(request) { +            try { +                if (request.aborted) { +                    return; +                } + +                var response = this.response || [404, {}, ""]; + +                if (this.responses) { +                    for (var i = 0, l = this.responses.length; i < l; i++) { +                        if (match.call(this, this.responses[i], request)) { +                            response = this.responses[i].response; +                            break; +                        } +                    } +                } + +                if (request.readyState != 4) { +                    log(response, request); + +                    request.respond(response[0], response[1], response[2]); +                } +            } catch (e) { +                sinon.logError("Fake server request processing", e); +            } +        }, + +        restore: function restore() { +            return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); +        } +    }; +}()); + +if (typeof module == "object" && typeof require == "function") { +    module.exports = sinon; +} + +/** + * @depend fake_server.js + * @depend fake_timers.js + */ +/*jslint browser: true, eqeqeq: false, onevar: false*/ +/*global sinon*/ +/** + * Add-on for sinon.fakeServer that automatically handles a fake timer along with + * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery + * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, + * it polls the object for completion with setInterval. Dispite the direct + * motivation, there is nothing jQuery-specific in this file, so it can be used + * in any environment where the ajax implementation depends on setInterval or + * setTimeout. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +(function () { +    function Server() {} +    Server.prototype = sinon.fakeServer; + +    sinon.fakeServerWithClock = new Server(); + +    sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { +        if (xhr.async) { +            if (typeof setTimeout.clock == "object") { +                this.clock = setTimeout.clock; +            } else { +                this.clock = sinon.useFakeTimers(); +                this.resetClock = true; +            } + +            if (!this.longestTimeout) { +                var clockSetTimeout = this.clock.setTimeout; +                var clockSetInterval = this.clock.setInterval; +                var server = this; + +                this.clock.setTimeout = function (fn, timeout) { +                    server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); + +                    return clockSetTimeout.apply(this, arguments); +                }; + +                this.clock.setInterval = function (fn, timeout) { +                    server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); + +                    return clockSetInterval.apply(this, arguments); +                }; +            } +        } + +        return sinon.fakeServer.addRequest.call(this, xhr); +    }; + +    sinon.fakeServerWithClock.respond = function respond() { +        var returnVal = sinon.fakeServer.respond.apply(this, arguments); + +        if (this.clock) { +            this.clock.tick(this.longestTimeout || 0); +            this.longestTimeout = 0; + +            if (this.resetClock) { +                this.clock.restore(); +                this.resetClock = false; +            } +        } + +        return returnVal; +    }; + +    sinon.fakeServerWithClock.restore = function restore() { +        if (this.clock) { +            this.clock.restore(); +        } + +        return sinon.fakeServer.restore.apply(this, arguments); +    }; +}()); + +/** + * @depend ../sinon.js + * @depend collection.js + * @depend util/fake_timers.js + * @depend util/fake_server_with_clock.js + */ +/*jslint eqeqeq: false, onevar: false, plusplus: false*/ +/*global require, module*/ +/** + * Manages fake collections as well as fake utilities such as Sinon's + * timers and fake XHR implementation in one convenient object. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +if (typeof module == "object" && typeof require == "function") { +    var sinon = require("../sinon"); +    sinon.extend(sinon, require("./util/fake_timers")); +} + +(function () { +    var push = [].push; + +    function exposeValue(sandbox, config, key, value) { +        if (!value) { +            return; +        } + +        if (config.injectInto) { +            config.injectInto[key] = value; +        } else { +            push.call(sandbox.args, value); +        } +    } + +    function prepareSandboxFromConfig(config) { +        var sandbox = sinon.create(sinon.sandbox); + +        if (config.useFakeServer) { +            if (typeof config.useFakeServer == "object") { +                sandbox.serverPrototype = config.useFakeServer; +            } + +            sandbox.useFakeServer(); +        } + +        if (config.useFakeTimers) { +            if (typeof config.useFakeTimers == "object") { +                sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); +            } else { +                sandbox.useFakeTimers(); +            } +        } + +        return sandbox; +    } + +    sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { +        useFakeTimers: function useFakeTimers() { +            this.clock = sinon.useFakeTimers.apply(sinon, arguments); + +            return this.add(this.clock); +        }, + +        serverPrototype: sinon.fakeServer, + +        useFakeServer: function useFakeServer() { +            var proto = this.serverPrototype || sinon.fakeServer; + +            if (!proto || !proto.create) { +                return null; +            } + +            this.server = proto.create(); +            return this.add(this.server); +        }, + +        inject: function (obj) { +            sinon.collection.inject.call(this, obj); + +            if (this.clock) { +                obj.clock = this.clock; +            } + +            if (this.server) { +                obj.server = this.server; +                obj.requests = this.server.requests; +            } + +            return obj; +        }, + +        create: function (config) { +            if (!config) { +                return sinon.create(sinon.sandbox); +            } + +            var sandbox = prepareSandboxFromConfig(config); +            sandbox.args = sandbox.args || []; +            var prop, value, exposed = sandbox.inject({}); + +            if (config.properties) { +                for (var i = 0, l = config.properties.length; i < l; i++) { +                    prop = config.properties[i]; +                    value = exposed[prop] || prop == "sandbox" && sandbox; +                    exposeValue(sandbox, config, prop, value); +                } +            } else { +                exposeValue(sandbox, config, "sandbox", value); +            } + +            return sandbox; +        } +    }); + +    sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; + +    if (typeof module == "object" && typeof require == "function") { +        module.exports = sinon.sandbox; +    } +}()); + +/** + * @depend ../sinon.js + * @depend stub.js + * @depend mock.js + * @depend sandbox.js + */ +/*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/ +/*global module, require, sinon*/ +/** + * Test function, sandboxes fakes + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function test(callback) { +        var type = typeof callback; + +        if (type != "function") { +            throw new TypeError("sinon.test needs to wrap a test function, got " + type); +        } + +        return function () { +            var config = sinon.getConfig(sinon.config); +            config.injectInto = config.injectIntoThis && this || config.injectInto; +            var sandbox = sinon.sandbox.create(config); +            var exception, result; +            var args = Array.prototype.slice.call(arguments).concat(sandbox.args); + +            try { +                result = callback.apply(this, args); +            } catch (e) { +                exception = e; +            } + +            if (typeof exception !== "undefined") { +                sandbox.restore(); +                throw exception; +            } +            else { +                sandbox.verifyAndRestore(); +            } + +            return result; +        }; +    } + +    test.config = { +        injectIntoThis: true, +        injectInto: null, +        properties: ["spy", "stub", "mock", "clock", "server", "requests"], +        useFakeTimers: true, +        useFakeServer: true +    }; + +    if (commonJSModule) { +        module.exports = test; +    } else { +        sinon.test = test; +    } +}(typeof sinon == "object" && sinon || null)); + +/** + * @depend ../sinon.js + * @depend test.js + */ +/*jslint eqeqeq: false, onevar: false, eqeqeq: false*/ +/*global module, require, sinon*/ +/** + * Test case, sandboxes all test functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +(function (sinon) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon || !Object.prototype.hasOwnProperty) { +        return; +    } + +    function createTest(property, setUp, tearDown) { +        return function () { +            if (setUp) { +                setUp.apply(this, arguments); +            } + +            var exception, result; + +            try { +                result = property.apply(this, arguments); +            } catch (e) { +                exception = e; +            } + +            if (tearDown) { +                tearDown.apply(this, arguments); +            } + +            if (exception) { +                throw exception; +            } + +            return result; +        }; +    } + +    function testCase(tests, prefix) { +        /*jsl:ignore*/ +        if (!tests || typeof tests != "object") { +            throw new TypeError("sinon.testCase needs an object with test functions"); +        } +        /*jsl:end*/ + +        prefix = prefix || "test"; +        var rPrefix = new RegExp("^" + prefix); +        var methods = {}, testName, property, method; +        var setUp = tests.setUp; +        var tearDown = tests.tearDown; + +        for (testName in tests) { +            if (tests.hasOwnProperty(testName)) { +                property = tests[testName]; + +                if (/^(setUp|tearDown)$/.test(testName)) { +                    continue; +                } + +                if (typeof property == "function" && rPrefix.test(testName)) { +                    method = property; + +                    if (setUp || tearDown) { +                        method = createTest(property, setUp, tearDown); +                    } + +                    methods[testName] = sinon.test(method); +                } else { +                    methods[testName] = tests[testName]; +                } +            } +        } + +        return methods; +    } + +    if (commonJSModule) { +        module.exports = testCase; +    } else { +        sinon.testCase = testCase; +    } +}(typeof sinon == "object" && sinon || null)); + +/** + * @depend ../sinon.js + * @depend stub.js + */ +/*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/ +/*global module, require, sinon*/ +/** + * Assertions matching the test spy retrieval interface. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ + +(function (sinon, global) { +    var commonJSModule = typeof module == "object" && typeof require == "function"; +    var slice = Array.prototype.slice; +    var assert; + +    if (!sinon && commonJSModule) { +        sinon = require("../sinon"); +    } + +    if (!sinon) { +        return; +    } + +    function verifyIsStub() { +        var method; + +        for (var i = 0, l = arguments.length; i < l; ++i) { +            method = arguments[i]; + +            if (!method) { +                assert.fail("fake is not a spy"); +            } + +            if (typeof method != "function") { +                assert.fail(method + " is not a function"); +            } + +            if (typeof method.getCall != "function") { +                assert.fail(method + " is not stubbed"); +            } +        } +    } + +    function failAssertion(object, msg) { +        object = object || global; +        var failMethod = object.fail || assert.fail; +        failMethod.call(object, msg); +    } + +    function mirrorPropAsAssertion(name, method, message) { +        if (arguments.length == 2) { +            message = method; +            method = name; +        } + +        assert[name] = function (fake) { +            verifyIsStub(fake); + +            var args = slice.call(arguments, 1); +            var failed = false; + +            if (typeof method == "function") { +                failed = !method(fake); +            } else { +                failed = typeof fake[method] == "function" ? +                    !fake[method].apply(fake, args) : !fake[method]; +            } + +            if (failed) { +                failAssertion(this, fake.printf.apply(fake, [message].concat(args))); +            } else { +                assert.pass(name); +            } +        }; +    } + +    function exposedName(prefix, prop) { +        return !prefix || /^fail/.test(prop) ? prop : +            prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); +    }; + +    assert = { +        failException: "AssertError", + +        fail: function fail(message) { +            var error = new Error(message); +            error.name = this.failException || assert.failException; + +            throw error; +        }, + +        pass: function pass(assertion) {}, + +        callOrder: function assertCallOrder() { +            verifyIsStub.apply(null, arguments); +            var expected = "", actual = ""; + +            if (!sinon.calledInOrder(arguments)) { +                try { +                    expected = [].join.call(arguments, ", "); +                    var calls = slice.call(arguments); +                    var i = calls.length; +                    while (i) { +                        if (!calls[--i].called) { +                            calls.splice(i, 1); +                        } +                    } +                    actual = sinon.orderByFirstCall(calls).join(", "); +                } catch (e) { +                    // If this fails, we'll just fall back to the blank string +                } + +                failAssertion(this, "expected " + expected + " to be " + +                              "called in order but were called as " + actual); +            } else { +                assert.pass("callOrder"); +            } +        }, + +        callCount: function assertCallCount(method, count) { +            verifyIsStub(method); + +            if (method.callCount != count) { +                var msg = "expected %n to be called " + sinon.timesInWords(count) + +                    " but was called %c%C"; +                failAssertion(this, method.printf(msg)); +            } else { +                assert.pass("callCount"); +            } +        }, + +        expose: function expose(target, options) { +            if (!target) { +                throw new TypeError("target is null or undefined"); +            } + +            var o = options || {}; +            var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; +            var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; + +            for (var method in this) { +                if (method != "export" && (includeFail || !/^(fail)/.test(method))) { +                    target[exposedName(prefix, method)] = this[method]; +                } +            } + +            return target; +        } +    }; + +    mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); +    mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, +                          "expected %n to not have been called but was called %c%C"); +    mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); +    mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); +    mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); +    mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); +    mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); +    mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); +    mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); +    mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); +    mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); +    mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); +    mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); +    mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); +    mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); +    mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); +    mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); +    mirrorPropAsAssertion("threw", "%n did not throw exception%C"); +    mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); + +    if (commonJSModule) { +        module.exports = assert; +    } else { +        sinon.assert = assert; +    } +}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global)); + +return sinon;}.call(typeof window != 'undefined' && window || {})); diff --git a/lib/mousetrap/tests/libs/sinon-chai-2.4.0.js b/lib/mousetrap/tests/libs/sinon-chai-2.4.0.js new file mode 100644 index 0000000..26cee36 --- /dev/null +++ b/lib/mousetrap/tests/libs/sinon-chai-2.4.0.js @@ -0,0 +1,109 @@ +(function (sinonChai) { +    "use strict"; + +    // Module systems magic dance. + +    if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { +        // NodeJS +        module.exports = sinonChai; +    } else if (typeof define === "function" && define.amd) { +        // AMD +        define(function () { +            return sinonChai; +        }); +    } else { +        // Other environment (usually <script> tag): plug in to global chai instance directly. +        chai.use(sinonChai); +    } +}(function sinonChai(chai, utils) { +    "use strict"; + +    var slice = Array.prototype.slice; + +    function isSpy(putativeSpy) { +        return typeof putativeSpy === "function" && +               typeof putativeSpy.getCall === "function" && +               typeof putativeSpy.calledWithExactly === "function"; +    } + +    function isCall(putativeCall) { +        return putativeCall && isSpy(putativeCall.proxy); +    } + +    function assertCanWorkWith(assertion) { +        if (!isSpy(assertion._obj) && !isCall(assertion._obj)) { +            throw new TypeError(utils.inspect(assertion._obj) + " is not a spy or a call to a spy!"); +        } +    } + +    function getMessages(spy, action, nonNegatedSuffix, always, args) { +        var verbPhrase = always ? "always have " : "have "; +        nonNegatedSuffix = nonNegatedSuffix || ""; +        if (isSpy(spy.proxy)) { +            spy = spy.proxy; +        } + +        function printfArray(array) { +            return spy.printf.apply(spy, array); +        } + +        return { +            affirmative: printfArray(["expected %n to " + verbPhrase + action + nonNegatedSuffix].concat(args)), +            negative: printfArray(["expected %n to not " + verbPhrase + action].concat(args)) +        }; +    } + +    function sinonProperty(name, action, nonNegatedSuffix) { +        utils.addProperty(chai.Assertion.prototype, name, function () { +            assertCanWorkWith(this); + +            var messages = getMessages(this._obj, action, nonNegatedSuffix, false); +            this.assert(this._obj[name], messages.affirmative, messages.negative); +        }); +    } + +    function createSinonMethodHandler(sinonName, action, nonNegatedSuffix) { +        return function () { +            assertCanWorkWith(this); + +            var alwaysSinonMethod = "always" + sinonName[0].toUpperCase() + sinonName.substring(1); +            var shouldBeAlways = utils.flag(this, "always") && typeof this._obj[alwaysSinonMethod] === "function"; +            var sinonMethod = shouldBeAlways ? alwaysSinonMethod : sinonName; + +            var messages = getMessages(this._obj, action, nonNegatedSuffix, shouldBeAlways, slice.call(arguments)); +            this.assert(this._obj[sinonMethod].apply(this._obj, arguments), messages.affirmative, messages.negative); +        }; +    } + +    function sinonMethodAsProperty(name, action, nonNegatedSuffix) { +        var handler = createSinonMethodHandler(name, action, nonNegatedSuffix); +        utils.addProperty(chai.Assertion.prototype, name, handler); +    } + +    function exceptionalSinonMethod(chaiName, sinonName, action, nonNegatedSuffix) { +        var handler = createSinonMethodHandler(sinonName, action, nonNegatedSuffix); +        utils.addMethod(chai.Assertion.prototype, chaiName, handler); +    } + +    function sinonMethod(name, action, nonNegatedSuffix) { +        exceptionalSinonMethod(name, name, action, nonNegatedSuffix); +    } + +    utils.addProperty(chai.Assertion.prototype, "always", function () { +        utils.flag(this, "always", true); +    }); + +    sinonProperty("called", "been called", " at least once, but it was never called"); +    sinonProperty("calledOnce", "been called exactly once", ", but it was called %c%C"); +    sinonProperty("calledTwice", "been called exactly twice", ", but it was called %c%C"); +    sinonProperty("calledThrice", "been called exactly thrice", ", but it was called %c%C"); +    sinonMethodAsProperty("calledWithNew", "been called with new"); +    sinonMethod("calledBefore", "been called before %1"); +    sinonMethod("calledAfter", "been called after %1"); +    sinonMethod("calledOn", "been called with %1 as this", ", but it was called with %t instead"); +    sinonMethod("calledWith", "been called with arguments %*", "%C"); +    sinonMethod("calledWithExactly", "been called with exact arguments %*", "%C"); +    sinonMethod("calledWithMatch", "been called with arguments matching %*", "%C"); +    sinonMethod("returned", "returned %1"); +    exceptionalSinonMethod("thrown", "threw", "thrown %1"); +})); diff --git a/lib/mousetrap/tests/libs/sinon-ie-1.7.1.js b/lib/mousetrap/tests/libs/sinon-ie-1.7.1.js new file mode 100644 index 0000000..12e0a88 --- /dev/null +++ b/lib/mousetrap/tests/libs/sinon-ie-1.7.1.js @@ -0,0 +1,82 @@ +/** + * Sinon.JS 1.7.1, 2013/05/07 + * + * @author Christian Johansen (christian@cjohansen.no) + * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS + * + * (The BSD License) + * + * Copyright (c) 2010-2013, Christian Johansen, christian@cjohansen.no + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + *     * Redistributions of source code must retain the above copyright notice, + *       this list of conditions and the following disclaimer. + *     * Redistributions in binary form must reproduce the above copyright notice, + *       this list of conditions and the following disclaimer in the documentation + *       and/or other materials provided with the distribution. + *     * Neither the name of Christian Johansen nor the names of his contributors + *       may be used to endorse or promote products derived from this software + *       without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/*global sinon, setTimeout, setInterval, clearTimeout, clearInterval, Date*/ +/** + * Helps IE run the fake timers. By defining global functions, IE allows + * them to be overwritten at a later point. If these are not defined like + * this, overwriting them will result in anything from an exception to browser + * crash. + * + * If you don't require fake timers to work in IE, don't include this file. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +function setTimeout() {} +function clearTimeout() {} +function setInterval() {} +function clearInterval() {} +function Date() {} + +// Reassign the original functions. Now their writable attribute +// should be true. Hackish, I know, but it works. +setTimeout = sinon.timers.setTimeout; +clearTimeout = sinon.timers.clearTimeout; +setInterval = sinon.timers.setInterval; +clearInterval = sinon.timers.clearInterval; +Date = sinon.timers.Date; + +/*global sinon*/ +/** + * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows + * them to be overwritten at a later point. If these are not defined like + * this, overwriting them will result in anything from an exception to browser + * crash. + * + * If you don't require fake XHR to work in IE, don't include this file. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +function XMLHttpRequest() {} + +// Reassign the original function. Now its writable attribute +// should be true. Hackish, I know, but it works. +XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; diff --git a/lib/mousetrap/tests/mousetrap.html b/lib/mousetrap/tests/mousetrap.html new file mode 100644 index 0000000..fc6afc1 --- /dev/null +++ b/lib/mousetrap/tests/mousetrap.html @@ -0,0 +1,34 @@ +<!DOCTYPE html> +<head> +    <meta charset="utf-8"> +    <title>Mousetrap Tests</title> +    <link rel="stylesheet" href="libs/mocha-1.9.0.css" /> +</head> +<body> +    <!-- used to test targeted keyboard shortcuts w/ Mousetrap.wrap --> +    <form style="display: none;"> +        <textarea></textarea> +    </form> + +    <div id="mocha"></div> +    <script src="../mousetrap.js"></script> +    <script src="libs/key-event.js"></script> +    <script src="libs/chai-1.6.0.js"></script> +    <!-- <script src="libs/chai-spies-0.5.0.js"></script> --> +    <script src="libs/sinon-chai-2.4.0.js"></script> +    <script src="libs/sinon-1.7.1.js"></script> +    <script src="libs/sinon-ie-1.7.1.js"></script> +    <script src="libs/mocha-1.9.0.js"></script> +    <script>mocha.setup('bdd')</script> +    <script src="test.mousetrap.js"></script> +    <script> +        mocha.globals(['Mousetrap']); + +        if (window.mochaPhantomJS) { +            window.mochaPhantomJS.run(); +        } +        else if (!window.PHANTOMJS) { +            mocha.run(); +        } +    </script> +</body> diff --git a/lib/mousetrap/tests/test.mousetrap.js b/lib/mousetrap/tests/test.mousetrap.js new file mode 100644 index 0000000..fdd24f7 --- /dev/null +++ b/lib/mousetrap/tests/test.mousetrap.js @@ -0,0 +1,684 @@ +/* jshint es5: true, browser: true, expr: true */ +/* globals describe, afterEach, chai, it, sinon, Mousetrap, KeyEvent, Event */ +var expect = chai.expect; +afterEach(function() { +    Mousetrap.reset(); +}); + +describe('Mousetrap.bind', function() { +    describe('basic', function() { +        it('z key fires when pressing z', function() { +            var spy = sinon.spy(); + +            Mousetrap.bind('z', spy); + +            KeyEvent.simulate('Z'.charCodeAt(0), 90); + +            // really slow for some reason +            // expect(spy).to.have.been.calledOnce; +            expect(spy.callCount).to.equal(1, 'callback should fire once'); +            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); +            expect(spy.args[0][1]).to.equal('z', 'second argument should be key combo'); +        }); + +        it('z key fires from keydown', function() { +            var spy = sinon.spy(); + +            Mousetrap.bind('z', spy, 'keydown'); + +            KeyEvent.simulate('Z'.charCodeAt(0), 90); + +            // really slow for some reason +            // expect(spy).to.have.been.calledOnce; +            expect(spy.callCount).to.equal(1, 'callback should fire once'); +            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); +            expect(spy.args[0][1]).to.equal('z', 'second argument should be key combo'); +        }); + +        it('z key does not fire when pressing b', function() { +            var spy = sinon.spy(); + +            Mousetrap.bind('z', spy); + +            KeyEvent.simulate('B'.charCodeAt(0), 66); + +            expect(spy.callCount).to.equal(0); +        }); + +        it('z key does not fire when holding a modifier key', function() { +            var spy = sinon.spy(); +            var modifiers = ['ctrl', 'alt', 'meta', 'shift']; +            var charCode; +            var modifier; + +            Mousetrap.bind('z', spy); + +            for (var i = 0; i < 4; i++) { +                modifier = modifiers[i]; +                charCode = 'Z'.charCodeAt(0); + +                // character code is different when alt is pressed +                if (modifier == 'alt') { +                    charCode = 'Ω'.charCodeAt(0); +                } + +                spy.reset(); + +                KeyEvent.simulate(charCode, 90, [modifier]); + +                expect(spy.callCount).to.equal(0); +            } +        }); + +        it('keyup events should fire', function() { +            var spy = sinon.spy(); + +            Mousetrap.bind('z', spy, 'keyup'); + +            KeyEvent.simulate('Z'.charCodeAt(0), 90); + +            expect(spy.callCount).to.equal(1, 'keyup event for "z" should fire'); + +            // for key held down we should only get one key up +            KeyEvent.simulate('Z'.charCodeAt(0), 90, [], document, 10); +            expect(spy.callCount).to.equal(2, 'keyup event for "z" should fire once for held down key'); +        }); + +        it('keyup event for 0 should fire', function() { +            var spy = sinon.spy(); + +            Mousetrap.bind('0', spy, 'keyup'); + +            KeyEvent.simulate(0, 48); + +            expect(spy.callCount).to.equal(1, 'keyup event for "0" should fire'); +        }); + +        it('rebinding a key overwrites the callback for that key', function() { +            var spy1 = sinon.spy(); +            var spy2 = sinon.spy(); +            Mousetrap.bind('x', spy1); +            Mousetrap.bind('x', spy2); + +            KeyEvent.simulate('X'.charCodeAt(0), 88); + +            expect(spy1.callCount).to.equal(0, 'original callback should not fire'); +            expect(spy2.callCount).to.equal(1, 'new callback should fire'); +        }); + +        it('binding an array of keys', function() { +            var spy = sinon.spy(); +            Mousetrap.bind(['a', 'b', 'c'], spy); + +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            expect(spy.callCount).to.equal(1, 'new callback was called'); +            expect(spy.args[0][1]).to.equal('a', 'callback should match "a"'); + +            KeyEvent.simulate('B'.charCodeAt(0), 66); +            expect(spy.callCount).to.equal(2, 'new callback was called twice'); +            expect(spy.args[1][1]).to.equal('b', 'callback should match "b"'); + +            KeyEvent.simulate('C'.charCodeAt(0), 67); +            expect(spy.callCount).to.equal(3, 'new callback was called three times'); +            expect(spy.args[2][1]).to.equal('c', 'callback should match "c"'); +        }); + +        it('return false should prevent default and stop propagation', function() { +            var spy = sinon.spy(function() { +                return false; +            }); + +            Mousetrap.bind('command+s', spy); + +            KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta']); + +            expect(spy.callCount).to.equal(1, 'callback should fire'); +            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); + +            expect(spy.args[0][0].defaultPrevented).to.be.true; + +            // cancelBubble is not correctly set to true in webkit/blink +            // +            // @see https://code.google.com/p/chromium/issues/detail?id=162270 +            // expect(spy.args[0][0].cancelBubble).to.be.true; + +            // try without return false +            spy = sinon.spy(); +            Mousetrap.bind('command+s', spy); +            KeyEvent.simulate('S'.charCodeAt(0), 83, ['meta']); + +            expect(spy.callCount).to.equal(1, 'callback should fire'); +            expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); +            expect(spy.args[0][0].cancelBubble).to.be.falsey; +            expect(spy.args[0][0].defaultPrevented).to.be.falsey; +        }); + +        it('capslock key is ignored', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('a', spy); + +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            expect(spy.callCount).to.equal(1, 'callback should fire for lowercase a'); + +            spy.reset(); +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            expect(spy.callCount).to.equal(1, 'callback should fire for capslock A'); + +            spy.reset(); +            KeyEvent.simulate('A'.charCodeAt(0), 65, ['shift']); +            expect(spy.callCount).to.equal(0, 'callback should not fire fort shift+a'); +        }); +    }); + +    describe('special characters', function() { +        it('binding special characters', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('*', spy); + +            KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift']); + +            expect(spy.callCount).to.equal(1, 'callback should fire'); +            expect(spy.args[0][1]).to.equal('*', 'callback should match *'); +        }); + +        it('binding special characters keyup', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('*', spy, 'keyup'); + +            KeyEvent.simulate('*'.charCodeAt(0), 56, ['shift']); + +            expect(spy.callCount).to.equal(1, 'callback should fire'); +            expect(spy.args[0][1]).to.equal('*', 'callback should match "*"'); +        }); + +        it('binding keys with no associated charCode', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('left', spy); + +            KeyEvent.simulate(0, 37); + +            expect(spy.callCount).to.equal(1, 'callback should fire'); +            expect(spy.args[0][1]).to.equal('left', 'callback should match "left"'); +        }); + +        it('binding plus key alone should work', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('+', spy); + +            // fires for regular + character +            KeyEvent.simulate('+'.charCodeAt(0), 43); + +            // and for shift+= +            KeyEvent.simulate(43, 187, ['shift']); + +            expect(spy.callCount).to.equal(2, 'callback should fire'); +            expect(spy.args[0][1]).to.equal('+', 'callback should match "+"'); +        }); + +        it('binding plus key as "plus" should work', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('plus', spy); + +            // fires for regular + character +            KeyEvent.simulate('+'.charCodeAt(0), 43); + +            // and for shift+= +            KeyEvent.simulate(43, 187, ['shift']); + +            expect(spy.callCount).to.equal(2, 'callback should fire'); +            expect(spy.args[0][1]).to.equal('plus', 'callback should match "plus"'); +        }); + +        it('binding to alt++ should work', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('alt++', spy); + +            KeyEvent.simulate('+'.charCodeAt(0), 43, ['alt']); +            expect(spy.callCount).to.equal(1, 'callback should fire'); +            expect(spy.args[0][1]).to.equal('alt++', 'callback should match "alt++"'); +        }); + +        it('binding to alt+shift++ should work as well', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('alt+shift++', spy); + +            KeyEvent.simulate('+'.charCodeAt(0), 43, ['shift', 'alt']); +            expect(spy.callCount).to.equal(1, 'callback should fire'); +            expect(spy.args[0][1]).to.equal('alt+shift++', 'callback should match "alt++"'); + +        }) +    }); + +    describe('combos with modifiers', function() { +        it('binding key combinations', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('command+o', spy); + +            KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta']); + +            expect(spy.callCount).to.equal(1, 'command+o callback should fire'); +            expect(spy.args[0][1]).to.equal('command+o', 'keyboard string returned is correct'); +        }); + +        it('binding key combos with multiple modifiers', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('command+shift+o', spy); +            KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta']); +            expect(spy.callCount).to.equal(0, 'command+o callback should not fire'); + +            KeyEvent.simulate('O'.charCodeAt(0), 79, ['meta', 'shift']); +            expect(spy.callCount).to.equal(1, 'command+o callback should fire'); +        }); +    }); + +    describe('sequences', function() { +        it('binding sequences', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('g i', spy); + +            KeyEvent.simulate('G'.charCodeAt(0), 71); +            expect(spy.callCount).to.equal(0, 'callback should not fire'); + +            KeyEvent.simulate('I'.charCodeAt(0), 73); +            expect(spy.callCount).to.equal(1, 'callback should fire'); +        }); + +        it('binding sequences with mixed types', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('g o enter', spy); + +            KeyEvent.simulate('G'.charCodeAt(0), 71); +            expect(spy.callCount).to.equal(0, 'callback should not fire'); + +            KeyEvent.simulate('O'.charCodeAt(0), 79); +            expect(spy.callCount).to.equal(0, 'callback should not fire'); + +            KeyEvent.simulate(0, 13); +            expect(spy.callCount).to.equal(1, 'callback should fire'); +        }); + +        it('binding sequences starting with modifier keys', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('option enter', spy); +            KeyEvent.simulate(0, 18, ['alt']); +            KeyEvent.simulate(0, 13); +            expect(spy.callCount).to.equal(1, 'callback should fire'); + +            spy = sinon.spy(); +            Mousetrap.bind('command enter', spy); +            KeyEvent.simulate(0, 91, ['meta']); +            KeyEvent.simulate(0, 13); +            expect(spy.callCount).to.equal(1, 'callback should fire'); + +            spy = sinon.spy(); +            Mousetrap.bind('escape enter', spy); +            KeyEvent.simulate(0, 27); +            KeyEvent.simulate(0, 13); +            expect(spy.callCount).to.equal(1, 'callback should fire'); +        }); + +        it('key within sequence should not fire', function() { +            var spy1 = sinon.spy(); +            var spy2 = sinon.spy(); +            Mousetrap.bind('a', spy1); +            Mousetrap.bind('c a t', spy2); + +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            expect(spy1.callCount).to.equal(1, 'callback 1 should fire'); +            spy1.reset(); + +            KeyEvent.simulate('C'.charCodeAt(0), 67); +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            KeyEvent.simulate('T'.charCodeAt(0), 84); +            expect(spy1.callCount).to.equal(0, 'callback for "a" key should not fire'); +            expect(spy2.callCount).to.equal(1, 'callback for "c a t" sequence should fire'); +        }); + +        it('keyup at end of sequence should not fire', function() { +            var spy1 = sinon.spy(); +            var spy2 = sinon.spy(); + +            Mousetrap.bind('t', spy1, 'keyup'); +            Mousetrap.bind('b a t', spy2); + +            KeyEvent.simulate('B'.charCodeAt(0), 66); +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            KeyEvent.simulate('T'.charCodeAt(0), 84); + +            expect(spy1.callCount).to.equal(0, 'callback for "t" keyup should not fire'); +            expect(spy2.callCount).to.equal(1, 'callback for "b a t" sequence should fire'); +        }); + +        it('keyup sequences should work', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('b a t', spy, 'keyup'); + +            KeyEvent.simulate('b'.charCodeAt(0), 66); +            KeyEvent.simulate('a'.charCodeAt(0), 65); + +            // hold the last key down for a while +            KeyEvent.simulate('t'.charCodeAt(0), 84, [], document, 10); + +            expect(spy.callCount).to.equal(1, 'callback for "b a t" sequence should fire on keyup'); +        }); + +        it('extra spaces in sequences should be ignored', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('b   a  t', spy); + +            KeyEvent.simulate('b'.charCodeAt(0), 66); +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            KeyEvent.simulate('t'.charCodeAt(0), 84); + +            expect(spy.callCount).to.equal(1, 'callback for "b a t" sequence should fire'); +        }); + +        it('modifiers and sequences play nicely', function() { +            var spy1 = sinon.spy(); +            var spy2 = sinon.spy(); + +            Mousetrap.bind('ctrl a', spy1); +            Mousetrap.bind('ctrl+b', spy2); + +            KeyEvent.simulate(0, 17, ['ctrl']); +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            expect(spy1.callCount).to.equal(1, '"ctrl a" should fire'); + +            KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl']); +            expect(spy2.callCount).to.equal(1, '"ctrl+b" should fire'); +        }); + +        it('sequences that start the same work', function() { +            var spy1 = sinon.spy(); +            var spy2 = sinon.spy(); + +            Mousetrap.bind('g g l', spy2); +            Mousetrap.bind('g g o', spy1); + +            KeyEvent.simulate('g'.charCodeAt(0), 71); +            KeyEvent.simulate('g'.charCodeAt(0), 71); +            KeyEvent.simulate('o'.charCodeAt(0), 79); +            expect(spy1.callCount).to.equal(1, '"g g o" should fire'); +            expect(spy2.callCount).to.equal(0, '"g g l" should not fire'); + +            spy1.reset(); +            spy2.reset(); +            KeyEvent.simulate('g'.charCodeAt(0), 71); +            KeyEvent.simulate('g'.charCodeAt(0), 71); +            KeyEvent.simulate('l'.charCodeAt(0), 76); +            expect(spy1.callCount).to.equal(0, '"g g o" should not fire'); +            expect(spy2.callCount).to.equal(1, '"g g l" should fire'); +        }); + +        it('sequences should not fire subsequences', function() { +            var spy1 = sinon.spy(); +            var spy2 = sinon.spy(); + +            Mousetrap.bind('a b c', spy1); +            Mousetrap.bind('b c', spy2); + +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            KeyEvent.simulate('B'.charCodeAt(0), 66); +            KeyEvent.simulate('C'.charCodeAt(0), 67); + +            expect(spy1.callCount).to.equal(1, '"a b c" should fire'); +            expect(spy2.callCount).to.equal(0, '"b c" should not fire'); + +            spy1.reset(); +            spy2.reset(); +            Mousetrap.bind('option b', spy1); +            Mousetrap.bind('a option b', spy2); + +            KeyEvent.simulate('A'.charCodeAt(0), 65); +            KeyEvent.simulate(0, 18, ['alt']); +            KeyEvent.simulate('B'.charCodeAt(0), 66); + +            expect(spy1.callCount).to.equal(0, '"option b" should not fire'); +            expect(spy2.callCount).to.equal(1, '"a option b" should fire'); +        }); + +        it('rebinding same sequence should override previous', function() { +            var spy1 = sinon.spy(); +            var spy2 = sinon.spy(); +            Mousetrap.bind('a b c', spy1); +            Mousetrap.bind('a b c', spy2); + +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            KeyEvent.simulate('b'.charCodeAt(0), 66); +            KeyEvent.simulate('c'.charCodeAt(0), 67); + +            expect(spy1.callCount).to.equal(0, 'first callback should not fire'); +            expect(spy2.callCount).to.equal(1, 'second callback should fire'); +        }); + +        it('broken sequences', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('h a t', spy); + +            KeyEvent.simulate('h'.charCodeAt(0), 72); +            KeyEvent.simulate('e'.charCodeAt(0), 69); +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            KeyEvent.simulate('r'.charCodeAt(0), 82); +            KeyEvent.simulate('t'.charCodeAt(0), 84); + +            expect(spy.callCount).to.equal(0, 'sequence for "h a t" should not fire for "h e a r t"'); +        }); + +        it('sequences containing combos should work', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('a ctrl+b', spy); + +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            KeyEvent.simulate('B'.charCodeAt(0), 66, ['ctrl']); + +            expect(spy.callCount).to.equal(1, '"a ctrl+b" should fire'); + +            Mousetrap.unbind('a ctrl+b'); + +            spy = sinon.spy(); +            Mousetrap.bind('ctrl+b a', spy); + +            KeyEvent.simulate('b'.charCodeAt(0), 66, ['ctrl']); +            KeyEvent.simulate('a'.charCodeAt(0), 65); + +            expect(spy.callCount).to.equal(1, '"ctrl+b a" should fire'); +        }); + +        it('sequences starting with spacebar should work', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('a space b c', spy); + +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            KeyEvent.simulate(32, 32); +            KeyEvent.simulate('b'.charCodeAt(0), 66); +            KeyEvent.simulate('c'.charCodeAt(0), 67); + +            expect(spy.callCount).to.equal(1, '"a space b c" should fire'); +        }); + +        it('konami code', function() { +            var spy = sinon.spy(); +            Mousetrap.bind('up up down down left right left right b a enter', spy); + +            KeyEvent.simulate(0, 38); +            KeyEvent.simulate(0, 38); +            KeyEvent.simulate(0, 40); +            KeyEvent.simulate(0, 40); +            KeyEvent.simulate(0, 37); +            KeyEvent.simulate(0, 39); +            KeyEvent.simulate(0, 37); +            KeyEvent.simulate(0, 39); +            KeyEvent.simulate('b'.charCodeAt(0), 66); +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            KeyEvent.simulate(0, 13); + +            expect(spy.callCount).to.equal(1, 'konami code should fire'); +        }); + +        it('sequence timer resets', function() { +            var spy = sinon.spy(); +            var clock = sinon.useFakeTimers(); + +            Mousetrap.bind('h a t', spy); + +            KeyEvent.simulate('h'.charCodeAt(0), 72); +            clock.tick(600); +            KeyEvent.simulate('a'.charCodeAt(0), 65); +            clock.tick(900); +            KeyEvent.simulate('t'.charCodeAt(0), 84); + +            expect(spy.callCount).to.equal(1, 'sequence should fire after waiting'); +            clock.restore(); +        }); + +        it('sequences timeout', function() { +            var spy = sinon.spy(); +            var clock = sinon.useFakeTimers(); + +            Mousetrap.bind('g t', spy); +            KeyEvent.simulate('g'.charCodeAt(0), 71); +            clock.tick(1000); +            KeyEvent.simulate('t'.charCodeAt(0), 84); + +            expect(spy.callCount).to.equal(0, 'sequence callback should not fire'); +            clock.restore(); +        }); +    }); + +    describe('default actions', function() { +        var keys = { +            keypress: [ +                ['a', 65], +                ['A', 65, ['shift']], +                ['7', 55], +                ['?', 191], +                ['*', 56], +                ['+', 187], +                ['$', 52], +                ['[', 219], +                ['.', 190] +            ], +            keydown: [ +                ['shift+\'', 222, ['shift']], +                ['shift+a', 65, ['shift']], +                ['shift+5', 53, ['shift']], +                ['command+shift+p', 80, ['meta', 'shift']], +                ['space', 32], +                ['left', 37] +            ] +        }; + +        function getCallback(key, keyCode, type, modifiers) { +            return function() { +                var spy = sinon.spy(); +                Mousetrap.bind(key, spy); + +                KeyEvent.simulate(key.charCodeAt(0), keyCode, modifiers); +                expect(spy.callCount).to.equal(1); +                expect(spy.args[0][0].type).to.equal(type); +            }; +        } + +        for (var type in keys) { +            for (var i = 0; i < keys[type].length; i++) { +                var key = keys[type][i][0]; +                var keyCode = keys[type][i][1]; +                var modifiers = keys[type][i][2] || []; +                it('"' + key + '" uses "' + type + '"', getCallback(key, keyCode, type, modifiers)); +            } +        } +    }); +}); + +describe('Mousetrap.unbind', function() { +    it('unbind works', function() { +        var spy = sinon.spy(); +        Mousetrap.bind('a', spy); +        KeyEvent.simulate('a'.charCodeAt(0), 65); +        expect(spy.callCount).to.equal(1, 'callback for a should fire'); + +        Mousetrap.unbind('a'); +        KeyEvent.simulate('a'.charCodeAt(0), 65); +        expect(spy.callCount).to.equal(1, 'callback for a should not fire after unbind'); +    }); + +    it('unbind accepts an array', function() { +        var spy = sinon.spy(); +        Mousetrap.bind(['a', 'b', 'c'], spy); +        KeyEvent.simulate('a'.charCodeAt(0), 65); +        KeyEvent.simulate('b'.charCodeAt(0), 66); +        KeyEvent.simulate('c'.charCodeAt(0), 67); +        expect(spy.callCount).to.equal(3, 'callback should have fired 3 times'); + +        Mousetrap.unbind(['a', 'b', 'c']); +        KeyEvent.simulate('a'.charCodeAt(0), 65); +        KeyEvent.simulate('b'.charCodeAt(0), 66); +        KeyEvent.simulate('c'.charCodeAt(0), 67); +        expect(spy.callCount).to.equal(3, 'callback should not fire after unbind'); +    }); +}); + +describe('wrapping a specific element', function() { +    var form = document.querySelector('form'); +    var textarea = form.querySelector('textarea'); + +    it('z key fires when pressing z in the target element', function() { +        var spy = sinon.spy(); + +        Mousetrap(form).bind('z', spy); + +        KeyEvent.simulate('Z'.charCodeAt(0), 90, [], form); + +        expect(spy.callCount).to.equal(1, 'callback should fire once'); +        expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); +        expect(spy.args[0][1]).to.equal('z', 'second argument should be key combo'); +    }); + +    it('z key fires when pressing z in a child of the target element', function() { +        var spy = sinon.spy(); + +        Mousetrap(form).bind('z', spy); + +        KeyEvent.simulate('Z'.charCodeAt(0), 90, [], textarea); + +        expect(spy.callCount).to.equal(1, 'callback should fire once'); +        expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); +        expect(spy.args[0][1]).to.equal('z', 'second argument should be key combo'); +    }); + +    it('z key does not fire when pressing z outside the target element', function() { +        var spy = sinon.spy(); + +        Mousetrap(textarea).bind('z', spy); + +        KeyEvent.simulate('Z'.charCodeAt(0), 90); + +        expect(spy.callCount).to.equal(0, 'callback should not have fired'); +    }); + +    it('should work when constructing a new mousetrap object', function() { +        var spy = sinon.spy(); + +        var mousetrap = new Mousetrap(form); +        mousetrap.bind('a', spy); + +        KeyEvent.simulate('a'.charCodeAt(0), 65, [], textarea); + +        expect(spy.callCount).to.equal(1, 'callback should fire once'); +        expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); +        expect(spy.args[0][1]).to.equal('a', 'second argument should be key combo'); +    }); + +    it('should allow you to create an empty mousetrap constructor', function() { +        var spy = sinon.spy(); + +        var mousetrap = new Mousetrap(); +        mousetrap.bind('a', spy); + +        KeyEvent.simulate('a'.charCodeAt(0), 65); + +        expect(spy.callCount).to.equal(1, 'callback should fire once'); +        expect(spy.args[0][0]).to.be.an.instanceOf(Event, 'first argument should be Event'); +        expect(spy.args[0][1]).to.equal('a', 'second argument should be key combo'); +    }); +}); | 
