/*!
 * jQuery JavaScript Library v1.12.4
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2016-05-20T17:17Z
 */

(function( global, factory ) {
    
        if ( typeof module === "object" && typeof module.exports === "object" ) {
            // For CommonJS and CommonJS-like environments where a proper `window`
            // is present, execute the factory and get jQuery.
            // For environments that do not have a `window` with a `document`
            // (such as Node.js), expose a factory as module.exports.
            // This accentuates the need for the creation of a real `window`.
            // e.g. var jQuery = require("jquery")(window);
            // See ticket #14549 for more info.
            module.exports = global.document ?
                factory( global, true ) :
                function( w ) {
                    if ( !w.document ) {
                        throw new Error( "jQuery requires a window with a document" );
                    }
                    return factory( w );
                };
        } else {
            factory( global );
        }
    
    // Pass this if window is not defined yet
    }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
    
    // Support: Firefox 18+
    // Can't be in strict mode, several libs including ASP.NET trace
    // the stack via arguments.caller.callee and Firefox dies if
    // you try to trace through "use strict" call chains. (#13335)
    //"use strict";
    var deletedIds = [];
    
    var document = window.document;
    
    var slice = deletedIds.slice;
    
    var concat = deletedIds.concat;
    
    var push = deletedIds.push;
    
    var indexOf = deletedIds.indexOf;
    
    var class2type = {};
    
    var toString = class2type.toString;
    
    var hasOwn = class2type.hasOwnProperty;
    
    var support = {};
    
    
    
    var
        version = "1.12.4",
    
        // Define a local copy of jQuery
        jQuery = function( selector, context ) {
    
            // The jQuery object is actually just the init constructor 'enhanced'
            // Need init if jQuery is called (just allow error to be thrown if not included)
            return new jQuery.fn.init( selector, context );
        },
    
        // Support: Android<4.1, IE<9
        // Make sure we trim BOM and NBSP
        rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
    
        // Matches dashed string for camelizing
        rmsPrefix = /^-ms-/,
        rdashAlpha = /-([\da-z])/gi,
    
        // Used by jQuery.camelCase as callback to replace()
        fcamelCase = function( all, letter ) {
            return letter.toUpperCase();
        };
    
    jQuery.fn = jQuery.prototype = {
    
        // The current version of jQuery being used
        jquery: version,
    
        constructor: jQuery,
    
        // Start with an empty selector
        selector: "",
    
        // The default length of a jQuery object is 0
        length: 0,
    
        toArray: function() {
            return slice.call( this );
        },
    
        // Get the Nth element in the matched element set OR
        // Get the whole matched element set as a clean array
        get: function( num ) {
            return num != null ?
    
                // Return just the one element from the set
                ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
    
                // Return all the elements in a clean array
                slice.call( this );
        },
    
        // Take an array of elements and push it onto the stack
        // (returning the new matched element set)
        pushStack: function( elems ) {
    
            // Build a new jQuery matched element set
            var ret = jQuery.merge( this.constructor(), elems );
    
            // Add the old object onto the stack (as a reference)
            ret.prevObject = this;
            ret.context = this.context;
    
            // Return the newly-formed element set
            return ret;
        },
    
        // Execute a callback for every element in the matched set.
        each: function( callback ) {
            return jQuery.each( this, callback );
        },
    
        map: function( callback ) {
            return this.pushStack( jQuery.map( this, function( elem, i ) {
                return callback.call( elem, i, elem );
            } ) );
        },
    
        slice: function() {
            return this.pushStack( slice.apply( this, arguments ) );
        },
    
        first: function() {
            return this.eq( 0 );
        },
    
        last: function() {
            return this.eq( -1 );
        },
    
        eq: function( i ) {
            var len = this.length,
                j = +i + ( i < 0 ? len : 0 );
            return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
        },
    
        end: function() {
            return this.prevObject || this.constructor();
        },
    
        // For internal use only.
        // Behaves like an Array's method, not like a jQuery method.
        push: push,
        sort: deletedIds.sort,
        splice: deletedIds.splice
    };
    
    jQuery.extend = jQuery.fn.extend = function() {
        var src, copyIsArray, copy, name, options, clone,
            target = arguments[ 0 ] || {},
            i = 1,
            length = arguments.length,
            deep = false;
    
        // Handle a deep copy situation
        if ( typeof target === "boolean" ) {
            deep = target;
    
            // skip the boolean and the target
            target = arguments[ i ] || {};
            i++;
        }
    
        // Handle case when target is a string or something (possible in deep copy)
        if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
            target = {};
        }
    
        // extend jQuery itself if only one argument is passed
        if ( i === length ) {
            target = this;
            i--;
        }
    
        for ( ; i < length; i++ ) {
    
            // Only deal with non-null/undefined values
            if ( ( options = arguments[ i ] ) != null ) {
    
                // Extend the base object
                for ( name in options ) {
                    src = target[ name ];
                    copy = options[ name ];
    
                    // Prevent never-ending loop
                    if ( target === copy ) {
                        continue;
                    }
    
                    // Recurse if we're merging plain objects or arrays
                    if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
                        ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
    
                        if ( copyIsArray ) {
                            copyIsArray = false;
                            clone = src && jQuery.isArray( src ) ? src : [];
    
                        } else {
                            clone = src && jQuery.isPlainObject( src ) ? src : {};
                        }
    
                        // Never move original objects, clone them
                        target[ name ] = jQuery.extend( deep, clone, copy );
    
                    // Don't bring in undefined values
                    } else if ( copy !== undefined ) {
                        target[ name ] = copy;
                    }
                }
            }
        }
    
        // Return the modified object
        return target;
    };
    
    jQuery.extend( {
    
        // Unique for each copy of jQuery on the page
        expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
    
        // Assume jQuery is ready without the ready module
        isReady: true,
    
        error: function( msg ) {
            throw new Error( msg );
        },
    
        noop: function() {},
    
        // See test/unit/core.js for details concerning isFunction.
        // Since version 1.3, DOM methods and functions like alert
        // aren't supported. They return false on IE (#2968).
        isFunction: function( obj ) {
            return jQuery.type( obj ) === "function";
        },
    
        isArray: Array.isArray || function( obj ) {
            return jQuery.type( obj ) === "array";
        },
    
        isWindow: function( obj ) {
            /* jshint eqeqeq: false */
            return obj != null && obj == obj.window;
        },
    
        isNumeric: function( obj ) {
    
            // parseFloat NaNs numeric-cast false positives (null|true|false|"")
            // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
            // subtraction forces infinities to NaN
            // adding 1 corrects loss of precision from parseFloat (#15100)
            var realStringObj = obj && obj.toString();
            return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
        },
    
        isEmptyObject: function( obj ) {
            var name;
            for ( name in obj ) {
                return false;
            }
            return true;
        },
    
        isPlainObject: function( obj ) {
            var key;
    
            // Must be an Object.
            // Because of IE, we also have to check the presence of the constructor property.
            // Make sure that DOM nodes and window objects don't pass through, as well
            if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
                return false;
            }
    
            try {
    
                // Not own constructor property must be Object
                if ( obj.constructor &&
                    !hasOwn.call( obj, "constructor" ) &&
                    !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
                    return false;
                }
            } catch ( e ) {
    
                // IE8,9 Will throw exceptions on certain host objects #9897
                return false;
            }
    
            // Support: IE<9
            // Handle iteration over inherited properties before own properties.
            if ( !support.ownFirst ) {
                for ( key in obj ) {
                    return hasOwn.call( obj, key );
                }
            }
    
            // Own properties are enumerated firstly, so to speed up,
            // if last one is own, then all properties are own.
            for ( key in obj ) {}
    
            return key === undefined || hasOwn.call( obj, key );
        },
    
        type: function( obj ) {
            if ( obj == null ) {
                return obj + "";
            }
            return typeof obj === "object" || typeof obj === "function" ?
                class2type[ toString.call( obj ) ] || "object" :
                typeof obj;
        },
    
        // Workarounds based on findings by Jim Driscoll
        // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
        globalEval: function( data ) {
            if ( data && jQuery.trim( data ) ) {
    
                // We use execScript on Internet Explorer
                // We use an anonymous function so that context is window
                // rather than jQuery in Firefox
                ( window.execScript || function( data ) {
                    window[ "eval" ].call( window, data ); // jscs:ignore requireDotNotation
                } )( data );
            }
        },
    
        // Convert dashed to camelCase; used by the css and data modules
        // Microsoft forgot to hump their vendor prefix (#9572)
        camelCase: function( string ) {
            return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
        },
    
        nodeName: function( elem, name ) {
            return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
        },
    
        each: function( obj, callback ) {
            var length, i = 0;
    
            if ( isArrayLike( obj ) ) {
                length = obj.length;
                for ( ; i < length; i++ ) {
                    if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
                        break;
                    }
                }
            } else {
                for ( i in obj ) {
                    if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
                        break;
                    }
                }
            }
    
            return obj;
        },
    
        // Support: Android<4.1, IE<9
        trim: function( text ) {
            return text == null ?
                "" :
                ( text + "" ).replace( rtrim, "" );
        },
    
        // results is for internal usage only
        makeArray: function( arr, results ) {
            var ret = results || [];
    
            if ( arr != null ) {
                if ( isArrayLike( Object( arr ) ) ) {
                    jQuery.merge( ret,
                        typeof arr === "string" ?
                        [ arr ] : arr
                    );
                } else {
                    push.call( ret, arr );
                }
            }
    
            return ret;
        },
    
        inArray: function( elem, arr, i ) {
            var len;
    
            if ( arr ) {
                if ( indexOf ) {
                    return indexOf.call( arr, elem, i );
                }
    
                len = arr.length;
                i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
    
                for ( ; i < len; i++ ) {
    
                    // Skip accessing in sparse arrays
                    if ( i in arr && arr[ i ] === elem ) {
                        return i;
                    }
                }
            }
    
            return -1;
        },
    
        merge: function( first, second ) {
            var len = +second.length,
                j = 0,
                i = first.length;
    
            while ( j < len ) {
                first[ i++ ] = second[ j++ ];
            }
    
            // Support: IE<9
            // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
            if ( len !== len ) {
                while ( second[ j ] !== undefined ) {
                    first[ i++ ] = second[ j++ ];
                }
            }
    
            first.length = i;
    
            return first;
        },
    
        grep: function( elems, callback, invert ) {
            var callbackInverse,
                matches = [],
                i = 0,
                length = elems.length,
                callbackExpect = !invert;
    
            // Go through the array, only saving the items
            // that pass the validator function
            for ( ; i < length; i++ ) {
                callbackInverse = !callback( elems[ i ], i );
                if ( callbackInverse !== callbackExpect ) {
                    matches.push( elems[ i ] );
                }
            }
    
            return matches;
        },
    
        // arg is for internal usage only
        map: function( elems, callback, arg ) {
            var length, value,
                i = 0,
                ret = [];
    
            // Go through the array, translating each of the items to their new values
            if ( isArrayLike( elems ) ) {
                length = elems.length;
                for ( ; i < length; i++ ) {
                    value = callback( elems[ i ], i, arg );
    
                    if ( value != null ) {
                        ret.push( value );
                    }
                }
    
            // Go through every key on the object,
            } else {
                for ( i in elems ) {
                    value = callback( elems[ i ], i, arg );
    
                    if ( value != null ) {
                        ret.push( value );
                    }
                }
            }
    
            // Flatten any nested arrays
            return concat.apply( [], ret );
        },
    
        // A global GUID counter for objects
        guid: 1,
    
        // Bind a function to a context, optionally partially applying any
        // arguments.
        proxy: function( fn, context ) {
            var args, proxy, tmp;
    
            if ( typeof context === "string" ) {
                tmp = fn[ context ];
                context = fn;
                fn = tmp;
            }
    
            // Quick check to determine if target is callable, in the spec
            // this throws a TypeError, but we will just return undefined.
            if ( !jQuery.isFunction( fn ) ) {
                return undefined;
            }
    
            // Simulated bind
            args = slice.call( arguments, 2 );
            proxy = function() {
                return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
            };
    
            // Set the guid of unique handler to the same of original handler, so it can be removed
            proxy.guid = fn.guid = fn.guid || jQuery.guid++;
    
            return proxy;
        },
    
        now: function() {
            return +( new Date() );
        },
    
        // jQuery.support is not used in Core but other projects attach their
        // properties to it so it needs to exist.
        support: support
    } );
    
    // JSHint would error on this code due to the Symbol not being defined in ES5.
    // Defining this global in .jshintrc would create a danger of using the global
    // unguarded in another place, it seems safer to just disable JSHint for these
    // three lines.
    /* jshint ignore: start */
    if ( typeof Symbol === "function" ) {
        jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ];
    }
    /* jshint ignore: end */
    
    // Populate the class2type map
    jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
    function( i, name ) {
        class2type[ "[object " + name + "]" ] = name.toLowerCase();
    } );
    
    function isArrayLike( obj ) {
    
        // Support: iOS 8.2 (not reproducible in simulator)
        // `in` check used to prevent JIT error (gh-2145)
        // hasOwn isn't used here due to false negatives
        // regarding Nodelist length in IE
        var length = !!obj && "length" in obj && obj.length,
            type = jQuery.type( obj );
    
        if ( type === "function" || jQuery.isWindow( obj ) ) {
            return false;
        }
    
        return type === "array" || length === 0 ||
            typeof length === "number" && length > 0 && ( length - 1 ) in obj;
    }
    var Sizzle =
    /*!
     * Sizzle CSS Selector Engine v2.2.1
     * http://sizzlejs.com/
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license
     * http://jquery.org/license
     *
     * Date: 2015-10-17
     */
    (function( window ) {
    
    var i,
        support,
        Expr,
        getText,
        isXML,
        tokenize,
        compile,
        select,
        outermostContext,
        sortInput,
        hasDuplicate,
    
        // Local document vars
        setDocument,
        document,
        docElem,
        documentIsHTML,
        rbuggyQSA,
        rbuggyMatches,
        matches,
        contains,
    
        // Instance-specific data
        expando = "sizzle" + 1 * new Date(),
        preferredDoc = window.document,
        dirruns = 0,
        done = 0,
        classCache = createCache(),
        tokenCache = createCache(),
        compilerCache = createCache(),
        sortOrder = function( a, b ) {
            if ( a === b ) {
                hasDuplicate = true;
            }
            return 0;
        },
    
        // General-purpose constants
        MAX_NEGATIVE = 1 << 31,
    
        // Instance methods
        hasOwn = ({}).hasOwnProperty,
        arr = [],
        pop = arr.pop,
        push_native = arr.push,
        push = arr.push,
        slice = arr.slice,
        // Use a stripped-down indexOf as it's faster than native
        // http://jsperf.com/thor-indexof-vs-for/5
        indexOf = function( list, elem ) {
            var i = 0,
                len = list.length;
            for ( ; i < len; i++ ) {
                if ( list[i] === elem ) {
                    return i;
                }
            }
            return -1;
        },
    
        booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
    
        // Regular expressions
    
        // http://www.w3.org/TR/css3-selectors/#whitespace
        whitespace = "[\\x20\\t\\r\\n\\f]",
    
        // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
        identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
    
        // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
        attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
            // Operator (capture 2)
            "*([*^$|!~]?=)" + whitespace +
            // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
            "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
            "*\\]",
    
        pseudos = ":(" + identifier + ")(?:\\((" +
            // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
            // 1. quoted (capture 3; capture 4 or capture 5)
            "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
            // 2. simple (capture 6)
            "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
            // 3. anything else (capture 2)
            ".*" +
            ")\\)|)",
    
        // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
        rwhitespace = new RegExp( whitespace + "+", "g" ),
        rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
    
        rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
        rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
    
        rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
    
        rpseudo = new RegExp( pseudos ),
        ridentifier = new RegExp( "^" + identifier + "$" ),
    
        matchExpr = {
            "ID": new RegExp( "^#(" + identifier + ")" ),
            "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
            "TAG": new RegExp( "^(" + identifier + "|[*])" ),
            "ATTR": new RegExp( "^" + attributes ),
            "PSEUDO": new RegExp( "^" + pseudos ),
            "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
                "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
                "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
            "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
            // For use in libraries implementing .is()
            // We use this for POS matching in `select`
            "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
                whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
        },
    
        rinputs = /^(?:input|select|textarea|button)$/i,
        rheader = /^h\d$/i,
    
        rnative = /^[^{]+\{\s*\[native \w/,
    
        // Easily-parseable/retrievable ID or TAG or CLASS selectors
        rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
    
        rsibling = /[+~]/,
        rescape = /'|\\/g,
    
        // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
        runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
        funescape = function( _, escaped, escapedWhitespace ) {
            var high = "0x" + escaped - 0x10000;
            // NaN means non-codepoint
            // Support: Firefox<24
            // Workaround erroneous numeric interpretation of +"0x"
            return high !== high || escapedWhitespace ?
                escaped :
                high < 0 ?
                    // BMP codepoint
                    String.fromCharCode( high + 0x10000 ) :
                    // Supplemental Plane codepoint (surrogate pair)
                    String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
        },
    
        // Used for iframes
        // See setDocument()
        // Removing the function wrapper causes a "Permission Denied"
        // error in IE
        unloadHandler = function() {
            setDocument();
        };
    
    // Optimize for push.apply( _, NodeList )
    try {
        push.apply(
            (arr = slice.call( preferredDoc.childNodes )),
            preferredDoc.childNodes
        );
        // Support: Android<4.0
        // Detect silently failing push.apply
        arr[ preferredDoc.childNodes.length ].nodeType;
    } catch ( e ) {
        push = { apply: arr.length ?
    
            // Leverage slice if possible
            function( target, els ) {
                push_native.apply( target, slice.call(els) );
            } :
    
            // Support: IE<9
            // Otherwise append directly
            function( target, els ) {
                var j = target.length,
                    i = 0;
                // Can't trust NodeList.length
                while ( (target[j++] = els[i++]) ) {}
                target.length = j - 1;
            }
        };
    }
    
    function Sizzle( selector, context, results, seed ) {
        var m, i, elem, nid, nidselect, match, groups, newSelector,
            newContext = context && context.ownerDocument,
    
            // nodeType defaults to 9, since context defaults to document
            nodeType = context ? context.nodeType : 9;
    
        results = results || [];
    
        // Return early from calls with invalid selector or context
        if ( typeof selector !== "string" || !selector ||
            nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
    
            return results;
        }
    
        // Try to shortcut find operations (as opposed to filters) in HTML documents
        if ( !seed ) {
    
            if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
                setDocument( context );
            }
            context = context || document;
    
            if ( documentIsHTML ) {
    
                // If the selector is sufficiently simple, try using a "get*By*" DOM method
                // (excepting DocumentFragment context, where the methods don't exist)
                if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
    
                    // ID selector
                    if ( (m = match[1]) ) {
    
                        // Document context
                        if ( nodeType === 9 ) {
                            if ( (elem = context.getElementById( m )) ) {
    
                                // Support: IE, Opera, Webkit
                                // TODO: identify versions
                                // getElementById can match elements by name instead of ID
                                if ( elem.id === m ) {
                                    results.push( elem );
                                    return results;
                                }
                            } else {
                                return results;
                            }
    
                        // Element context
                        } else {
    
                            // Support: IE, Opera, Webkit
                            // TODO: identify versions
                            // getElementById can match elements by name instead of ID
                            if ( newContext && (elem = newContext.getElementById( m )) &&
                                contains( context, elem ) &&
                                elem.id === m ) {
    
                                results.push( elem );
                                return results;
                            }
                        }
    
                    // Type selector
                    } else if ( match[2] ) {
                        push.apply( results, context.getElementsByTagName( selector ) );
                        return results;
    
                    // Class selector
                    } else if ( (m = match[3]) && support.getElementsByClassName &&
                        context.getElementsByClassName ) {
    
                        push.apply( results, context.getElementsByClassName( m ) );
                        return results;
                    }
                }
    
                // Take advantage of querySelectorAll
                if ( support.qsa &&
                    !compilerCache[ selector + " " ] &&
                    (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
    
                    if ( nodeType !== 1 ) {
                        newContext = context;
                        newSelector = selector;
    
                    // qSA looks outside Element context, which is not what we want
                    // Thanks to Andrew Dupont for this workaround technique
                    // Support: IE <=8
                    // Exclude object elements
                    } else if ( context.nodeName.toLowerCase() !== "object" ) {
    
                        // Capture the context ID, setting it first if necessary
                        if ( (nid = context.getAttribute( "id" )) ) {
                            nid = nid.replace( rescape, "\\$&" );
                        } else {
                            context.setAttribute( "id", (nid = expando) );
                        }
    
                        // Prefix every selector in the list
                        groups = tokenize( selector );
                        i = groups.length;
                        nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
                        while ( i-- ) {
                            groups[i] = nidselect + " " + toSelector( groups[i] );
                        }
                        newSelector = groups.join( "," );
    
                        // Expand context for sibling selectors
                        newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
                            context;
                    }
    
                    if ( newSelector ) {
                        try {
                            push.apply( results,
                                newContext.querySelectorAll( newSelector )
                            );
                            return results;
                        } catch ( qsaError ) {
                        } finally {
                            if ( nid === expando ) {
                                context.removeAttribute( "id" );
                            }
                        }
                    }
                }
            }
        }
    
        // All others
        return select( selector.replace( rtrim, "$1" ), context, results, seed );
    }
    
    /**
     * Create key-value caches of limited size
     * @returns {function(string, object)} Returns the Object data after storing it on itself with
     *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
     *	deleting the oldest entry
     */
    function createCache() {
        var keys = [];
    
        function cache( key, value ) {
            // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
            if ( keys.push( key + " " ) > Expr.cacheLength ) {
                // Only keep the most recent entries
                delete cache[ keys.shift() ];
            }
            return (cache[ key + " " ] = value);
        }
        return cache;
    }
    
    /**
     * Mark a function for special use by Sizzle
     * @param {Function} fn The function to mark
     */
    function markFunction( fn ) {
        fn[ expando ] = true;
        return fn;
    }
    
    /**
     * Support testing using an element
     * @param {Function} fn Passed the created div and expects a boolean result
     */
    function assert( fn ) {
        var div = document.createElement("div");
    
        try {
            return !!fn( div );
        } catch (e) {
            return false;
        } finally {
            // Remove from its parent by default
            if ( div.parentNode ) {
                div.parentNode.removeChild( div );
            }
            // release memory in IE
            div = null;
        }
    }
    
    /**
     * Adds the same handler for all of the specified attrs
     * @param {String} attrs Pipe-separated list of attributes
     * @param {Function} handler The method that will be applied
     */
    function addHandle( attrs, handler ) {
        var arr = attrs.split("|"),
            i = arr.length;
    
        while ( i-- ) {
            Expr.attrHandle[ arr[i] ] = handler;
        }
    }
    
    /**
     * Checks document order of two siblings
     * @param {Element} a
     * @param {Element} b
     * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
     */
    function siblingCheck( a, b ) {
        var cur = b && a,
            diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
                ( ~b.sourceIndex || MAX_NEGATIVE ) -
                ( ~a.sourceIndex || MAX_NEGATIVE );
    
        // Use IE sourceIndex if available on both nodes
        if ( diff ) {
            return diff;
        }
    
        // Check if b follows a
        if ( cur ) {
            while ( (cur = cur.nextSibling) ) {
                if ( cur === b ) {
                    return -1;
                }
            }
        }
    
        return a ? 1 : -1;
    }
    
    /**
     * Returns a function to use in pseudos for input types
     * @param {String} type
     */
    function createInputPseudo( type ) {
        return function( elem ) {
            var name = elem.nodeName.toLowerCase();
            return name === "input" && elem.type === type;
        };
    }
    
    /**
     * Returns a function to use in pseudos for buttons
     * @param {String} type
     */
    function createButtonPseudo( type ) {
        return function( elem ) {
            var name = elem.nodeName.toLowerCase();
            return (name === "input" || name === "button") && elem.type === type;
        };
    }
    
    /**
     * Returns a function to use in pseudos for positionals
     * @param {Function} fn
     */
    function createPositionalPseudo( fn ) {
        return markFunction(function( argument ) {
            argument = +argument;
            return markFunction(function( seed, matches ) {
                var j,
                    matchIndexes = fn( [], seed.length, argument ),
                    i = matchIndexes.length;
    
                // Match elements found at the specified indexes
                while ( i-- ) {
                    if ( seed[ (j = matchIndexes[i]) ] ) {
                        seed[j] = !(matches[j] = seed[j]);
                    }
                }
            });
        });
    }
    
    /**
     * Checks a node for validity as a Sizzle context
     * @param {Element|Object=} context
     * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
     */
    function testContext( context ) {
        return context && typeof context.getElementsByTagName !== "undefined" && context;
    }
    
    // Expose support vars for convenience
    support = Sizzle.support = {};
    
    /**
     * Detects XML nodes
     * @param {Element|Object} elem An element or a document
     * @returns {Boolean} True iff elem is a non-HTML XML node
     */
    isXML = Sizzle.isXML = function( elem ) {
        // documentElement is verified for cases where it doesn't yet exist
        // (such as loading iframes in IE - #4833)
        var documentElement = elem && (elem.ownerDocument || elem).documentElement;
        return documentElement ? documentElement.nodeName !== "HTML" : false;
    };
    
    /**
     * Sets document-related variables once based on the current document
     * @param {Element|Object} [doc] An element or document object to use to set the document
     * @returns {Object} Returns the current document
     */
    setDocument = Sizzle.setDocument = function( node ) {
        var hasCompare, parent,
            doc = node ? node.ownerDocument || node : preferredDoc;
    
        // Return early if doc is invalid or already selected
        if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
            return document;
        }
    
        // Update global variables
        document = doc;
        docElem = document.documentElement;
        documentIsHTML = !isXML( document );
    
        // Support: IE 9-11, Edge
        // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
        if ( (parent = document.defaultView) && parent.top !== parent ) {
            // Support: IE 11
            if ( parent.addEventListener ) {
                parent.addEventListener( "unload", unloadHandler, false );
    
            // Support: IE 9 - 10 only
            } else if ( parent.attachEvent ) {
                parent.attachEvent( "onunload", unloadHandler );
            }
        }
    
        /* Attributes
        ---------------------------------------------------------------------- */
    
        // Support: IE<8
        // Verify that getAttribute really returns attributes and not properties
        // (excepting IE8 booleans)
        support.attributes = assert(function( div ) {
            div.className = "i";
            return !div.getAttribute("className");
        });
    
        /* getElement(s)By*
        ---------------------------------------------------------------------- */
    
        // Check if getElementsByTagName("*") returns only elements
        support.getElementsByTagName = assert(function( div ) {
            div.appendChild( document.createComment("") );
            return !div.getElementsByTagName("*").length;
        });
    
        // Support: IE<9
        support.getElementsByClassName = rnative.test( document.getElementsByClassName );
    
        // Support: IE<10
        // Check if getElementById returns elements by name
        // The broken getElementById methods don't pick up programatically-set names,
        // so use a roundabout getElementsByName test
        support.getById = assert(function( div ) {
            docElem.appendChild( div ).id = expando;
            return !document.getElementsByName || !document.getElementsByName( expando ).length;
        });
    
        // ID find and filter
        if ( support.getById ) {
            Expr.find["ID"] = function( id, context ) {
                if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
                    var m = context.getElementById( id );
                    return m ? [ m ] : [];
                }
            };
            Expr.filter["ID"] = function( id ) {
                var attrId = id.replace( runescape, funescape );
                return function( elem ) {
                    return elem.getAttribute("id") === attrId;
                };
            };
        } else {
            // Support: IE6/7
            // getElementById is not reliable as a find shortcut
            delete Expr.find["ID"];
    
            Expr.filter["ID"] =  function( id ) {
                var attrId = id.replace( runescape, funescape );
                return function( elem ) {
                    var node = typeof elem.getAttributeNode !== "undefined" &&
                        elem.getAttributeNode("id");
                    return node && node.value === attrId;
                };
            };
        }
    
        // Tag
        Expr.find["TAG"] = support.getElementsByTagName ?
            function( tag, context ) {
                if ( typeof context.getElementsByTagName !== "undefined" ) {
                    return context.getElementsByTagName( tag );
    
                // DocumentFragment nodes don't have gEBTN
                } else if ( support.qsa ) {
                    return context.querySelectorAll( tag );
                }
            } :
    
            function( tag, context ) {
                var elem,
                    tmp = [],
                    i = 0,
                    // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
                    results = context.getElementsByTagName( tag );
    
                // Filter out possible comments
                if ( tag === "*" ) {
                    while ( (elem = results[i++]) ) {
                        if ( elem.nodeType === 1 ) {
                            tmp.push( elem );
                        }
                    }
    
                    return tmp;
                }
                return results;
            };
    
        // Class
        Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
            if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
                return context.getElementsByClassName( className );
            }
        };
    
        /* QSA/matchesSelector
        ---------------------------------------------------------------------- */
    
        // QSA and matchesSelector support
    
        // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
        rbuggyMatches = [];
    
        // qSa(:focus) reports false when true (Chrome 21)
        // We allow this because of a bug in IE8/9 that throws an error
        // whenever `document.activeElement` is accessed on an iframe
        // So, we allow :focus to pass through QSA all the time to avoid the IE error
        // See http://bugs.jquery.com/ticket/13378
        rbuggyQSA = [];
    
        if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
            // Build QSA regex
            // Regex strategy adopted from Diego Perini
            assert(function( div ) {
                // Select is set to empty string on purpose
                // This is to test IE's treatment of not explicitly
                // setting a boolean content attribute,
                // since its presence should be enough
                // http://bugs.jquery.com/ticket/12359
                docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
                    "<select id='" + expando + "-\r\\' msallowcapture=''>" +
                    "<option selected=''></option></select>";
    
                // Support: IE8, Opera 11-12.16
                // Nothing should be selected when empty strings follow ^= or $= or *=
                // The test attribute must be unknown in Opera but "safe" for WinRT
                // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
                if ( div.querySelectorAll("[msallowcapture^='']").length ) {
                    rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
                }
    
                // Support: IE8
                // Boolean attributes and "value" are not treated correctly
                if ( !div.querySelectorAll("[selected]").length ) {
                    rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
                }
    
                // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
                if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
                    rbuggyQSA.push("~=");
                }
    
                // Webkit/Opera - :checked should return selected option elements
                // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
                // IE8 throws error here and will not see later tests
                if ( !div.querySelectorAll(":checked").length ) {
                    rbuggyQSA.push(":checked");
                }
    
                // Support: Safari 8+, iOS 8+
                // https://bugs.webkit.org/show_bug.cgi?id=136851
                // In-page `selector#id sibing-combinator selector` fails
                if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
                    rbuggyQSA.push(".#.+[+~]");
                }
            });
    
            assert(function( div ) {
                // Support: Windows 8 Native Apps
                // The type and name attributes are restricted during .innerHTML assignment
                var input = document.createElement("input");
                input.setAttribute( "type", "hidden" );
                div.appendChild( input ).setAttribute( "name", "D" );
    
                // Support: IE8
                // Enforce case-sensitivity of name attribute
                if ( div.querySelectorAll("[name=d]").length ) {
                    rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
                }
    
                // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
                // IE8 throws error here and will not see later tests
                if ( !div.querySelectorAll(":enabled").length ) {
                    rbuggyQSA.push( ":enabled", ":disabled" );
                }
    
                // Opera 10-11 does not throw on post-comma invalid pseudos
                div.querySelectorAll("*,:x");
                rbuggyQSA.push(",.*:");
            });
        }
    
        if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
            docElem.webkitMatchesSelector ||
            docElem.mozMatchesSelector ||
            docElem.oMatchesSelector ||
            docElem.msMatchesSelector) )) ) {
    
            assert(function( div ) {
                // Check to see if it's possible to do matchesSelector
                // on a disconnected node (IE 9)
                support.disconnectedMatch = matches.call( div, "div" );
    
                // This should fail with an exception
                // Gecko does not error, returns false instead
                matches.call( div, "[s!='']:x" );
                rbuggyMatches.push( "!=", pseudos );
            });
        }
    
        rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
        rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
    
        /* Contains
        ---------------------------------------------------------------------- */
        hasCompare = rnative.test( docElem.compareDocumentPosition );
    
        // Element contains another
        // Purposefully self-exclusive
        // As in, an element does not contain itself
        contains = hasCompare || rnative.test( docElem.contains ) ?
            function( a, b ) {
                var adown = a.nodeType === 9 ? a.documentElement : a,
                    bup = b && b.parentNode;
                return a === bup || !!( bup && bup.nodeType === 1 && (
                    adown.contains ?
                        adown.contains( bup ) :
                        a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
                ));
            } :
            function( a, b ) {
                if ( b ) {
                    while ( (b = b.parentNode) ) {
                        if ( b === a ) {
                            return true;
                        }
                    }
                }
                return false;
            };
    
        /* Sorting
        ---------------------------------------------------------------------- */
    
        // Document order sorting
        sortOrder = hasCompare ?
        function( a, b ) {
    
            // Flag for duplicate removal
            if ( a === b ) {
                hasDuplicate = true;
                return 0;
            }
    
            // Sort on method existence if only one input has compareDocumentPosition
            var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
            if ( compare ) {
                return compare;
            }
    
            // Calculate position if both inputs belong to the same document
            compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
                a.compareDocumentPosition( b ) :
    
                // Otherwise we know they are disconnected
                1;
    
            // Disconnected nodes
            if ( compare & 1 ||
                (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
    
                // Choose the first element that is related to our preferred document
                if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
                    return -1;
                }
                if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
                    return 1;
                }
    
                // Maintain original order
                return sortInput ?
                    ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
                    0;
            }
    
            return compare & 4 ? -1 : 1;
        } :
        function( a, b ) {
            // Exit early if the nodes are identical
            if ( a === b ) {
                hasDuplicate = true;
                return 0;
            }
    
            var cur,
                i = 0,
                aup = a.parentNode,
                bup = b.parentNode,
                ap = [ a ],
                bp = [ b ];
    
            // Parentless nodes are either documents or disconnected
            if ( !aup || !bup ) {
                return a === document ? -1 :
                    b === document ? 1 :
                    aup ? -1 :
                    bup ? 1 :
                    sortInput ?
                    ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
                    0;
    
            // If the nodes are siblings, we can do a quick check
            } else if ( aup === bup ) {
                return siblingCheck( a, b );
            }
    
            // Otherwise we need full lists of their ancestors for comparison
            cur = a;
            while ( (cur = cur.parentNode) ) {
                ap.unshift( cur );
            }
            cur = b;
            while ( (cur = cur.parentNode) ) {
                bp.unshift( cur );
            }
    
            // Walk down the tree looking for a discrepancy
            while ( ap[i] === bp[i] ) {
                i++;
            }
    
            return i ?
                // Do a sibling check if the nodes have a common ancestor
                siblingCheck( ap[i], bp[i] ) :
    
                // Otherwise nodes in our document sort first
                ap[i] === preferredDoc ? -1 :
                bp[i] === preferredDoc ? 1 :
                0;
        };
    
        return document;
    };
    
    Sizzle.matches = function( expr, elements ) {
        return Sizzle( expr, null, null, elements );
    };
    
    Sizzle.matchesSelector = function( elem, expr ) {
        // Set document vars if needed
        if ( ( elem.ownerDocument || elem ) !== document ) {
            setDocument( elem );
        }
    
        // Make sure that attribute selectors are quoted
        expr = expr.replace( rattributeQuotes, "='$1']" );
    
        if ( support.matchesSelector && documentIsHTML &&
            !compilerCache[ expr + " " ] &&
            ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
            ( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {
    
            try {
                var ret = matches.call( elem, expr );
    
                // IE 9's matchesSelector returns false on disconnected nodes
                if ( ret || support.disconnectedMatch ||
                        // As well, disconnected nodes are said to be in a document
                        // fragment in IE 9
                        elem.document && elem.document.nodeType !== 11 ) {
                    return ret;
                }
            } catch (e) {}
        }
    
        return Sizzle( expr, document, null, [ elem ] ).length > 0;
    };
    
    Sizzle.contains = function( context, elem ) {
        // Set document vars if needed
        if ( ( context.ownerDocument || context ) !== document ) {
            setDocument( context );
        }
        return contains( context, elem );
    };
    
    Sizzle.attr = function( elem, name ) {
        // Set document vars if needed
        if ( ( elem.ownerDocument || elem ) !== document ) {
            setDocument( elem );
        }
    
        var fn = Expr.attrHandle[ name.toLowerCase() ],
            // Don't get fooled by Object.prototype properties (jQuery #13807)
            val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
                fn( elem, name, !documentIsHTML ) :
                undefined;
    
        return val !== undefined ?
            val :
            support.attributes || !documentIsHTML ?
                elem.getAttribute( name ) :
                (val = elem.getAttributeNode(name)) && val.specified ?
                    val.value :
                    null;
    };
    
    Sizzle.error = function( msg ) {
        throw new Error( "Syntax error, unrecognized expression: " + msg );
    };
    
    /**
     * Document sorting and removing duplicates
     * @param {ArrayLike} results
     */
    Sizzle.uniqueSort = function( results ) {
        var elem,
            duplicates = [],
            j = 0,
            i = 0;
    
        // Unless we *know* we can detect duplicates, assume their presence
        hasDuplicate = !support.detectDuplicates;
        sortInput = !support.sortStable && results.slice( 0 );
        results.sort( sortOrder );
    
        if ( hasDuplicate ) {
            while ( (elem = results[i++]) ) {
                if ( elem === results[ i ] ) {
                    j = duplicates.push( i );
                }
            }
            while ( j-- ) {
                results.splice( duplicates[ j ], 1 );
            }
        }
    
        // Clear input after sorting to release objects
        // See https://github.com/jquery/sizzle/pull/225
        sortInput = null;
    
        return results;
    };
    
    /**
     * Utility function for retrieving the text value of an array of DOM nodes
     * @param {Array|Element} elem
     */
    getText = Sizzle.getText = function( elem ) {
        var node,
            ret = "",
            i = 0,
            nodeType = elem.nodeType;
    
        if ( !nodeType ) {
            // If no nodeType, this is expected to be an array
            while ( (node = elem[i++]) ) {
                // Do not traverse comment nodes
                ret += getText( node );
            }
        } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
            // Use textContent for elements
            // innerText usage removed for consistency of new lines (jQuery #11153)
            if ( typeof elem.textContent === "string" ) {
                return elem.textContent;
            } else {
                // Traverse its children
                for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
                    ret += getText( elem );
                }
            }
        } else if ( nodeType === 3 || nodeType === 4 ) {
            return elem.nodeValue;
        }
        // Do not include comment or processing instruction nodes
    
        return ret;
    };
    
    Expr = Sizzle.selectors = {
    
        // Can be adjusted by the user
        cacheLength: 50,
    
        createPseudo: markFunction,
    
        match: matchExpr,
    
        attrHandle: {},
    
        find: {},
    
        relative: {
            ">": { dir: "parentNode", first: true },
            " ": { dir: "parentNode" },
            "+": { dir: "previousSibling", first: true },
            "~": { dir: "previousSibling" }
        },
    
        preFilter: {
            "ATTR": function( match ) {
                match[1] = match[1].replace( runescape, funescape );
    
                // Move the given value to match[3] whether quoted or unquoted
                match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
    
                if ( match[2] === "~=" ) {
                    match[3] = " " + match[3] + " ";
                }
    
                return match.slice( 0, 4 );
            },
    
            "CHILD": function( match ) {
                /* matches from matchExpr["CHILD"]
                    1 type (only|nth|...)
                    2 what (child|of-type)
                    3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
                    4 xn-component of xn+y argument ([+-]?\d*n|)
                    5 sign of xn-component
                    6 x of xn-component
                    7 sign of y-component
                    8 y of y-component
                */
                match[1] = match[1].toLowerCase();
    
                if ( match[1].slice( 0, 3 ) === "nth" ) {
                    // nth-* requires argument
                    if ( !match[3] ) {
                        Sizzle.error( match[0] );
                    }
    
                    // numeric x and y parameters for Expr.filter.CHILD
                    // remember that false/true cast respectively to 0/1
                    match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
                    match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
    
                // other types prohibit arguments
                } else if ( match[3] ) {
                    Sizzle.error( match[0] );
                }
    
                return match;
            },
    
            "PSEUDO": function( match ) {
                var excess,
                    unquoted = !match[6] && match[2];
    
                if ( matchExpr["CHILD"].test( match[0] ) ) {
                    return null;
                }
    
                // Accept quoted arguments as-is
                if ( match[3] ) {
                    match[2] = match[4] || match[5] || "";
    
                // Strip excess characters from unquoted arguments
                } else if ( unquoted && rpseudo.test( unquoted ) &&
                    // Get excess from tokenize (recursively)
                    (excess = tokenize( unquoted, true )) &&
                    // advance to the next closing parenthesis
                    (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
    
                    // excess is a negative index
                    match[0] = match[0].slice( 0, excess );
                    match[2] = unquoted.slice( 0, excess );
                }
    
                // Return only captures needed by the pseudo filter method (type and argument)
                return match.slice( 0, 3 );
            }
        },
    
        filter: {
    
            "TAG": function( nodeNameSelector ) {
                var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
                return nodeNameSelector === "*" ?
                    function() { return true; } :
                    function( elem ) {
                        return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
                    };
            },
    
            "CLASS": function( className ) {
                var pattern = classCache[ className + " " ];
    
                return pattern ||
                    (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
                    classCache( className, function( elem ) {
                        return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
                    });
            },
    
            "ATTR": function( name, operator, check ) {
                return function( elem ) {
                    var result = Sizzle.attr( elem, name );
    
                    if ( result == null ) {
                        return operator === "!=";
                    }
                    if ( !operator ) {
                        return true;
                    }
    
                    result += "";
    
                    return operator === "=" ? result === check :
                        operator === "!=" ? result !== check :
                        operator === "^=" ? check && result.indexOf( check ) === 0 :
                        operator === "*=" ? check && result.indexOf( check ) > -1 :
                        operator === "$=" ? check && result.slice( -check.length ) === check :
                        operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
                        operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
                        false;
                };
            },
    
            "CHILD": function( type, what, argument, first, last ) {
                var simple = type.slice( 0, 3 ) !== "nth",
                    forward = type.slice( -4 ) !== "last",
                    ofType = what === "of-type";
    
                return first === 1 && last === 0 ?
    
                    // Shortcut for :nth-*(n)
                    function( elem ) {
                        return !!elem.parentNode;
                    } :
    
                    function( elem, context, xml ) {
                        var cache, uniqueCache, outerCache, node, nodeIndex, start,
                            dir = simple !== forward ? "nextSibling" : "previousSibling",
                            parent = elem.parentNode,
                            name = ofType && elem.nodeName.toLowerCase(),
                            useCache = !xml && !ofType,
                            diff = false;
    
                        if ( parent ) {
    
                            // :(first|last|only)-(child|of-type)
                            if ( simple ) {
                                while ( dir ) {
                                    node = elem;
                                    while ( (node = node[ dir ]) ) {
                                        if ( ofType ?
                                            node.nodeName.toLowerCase() === name :
                                            node.nodeType === 1 ) {
    
                                            return false;
                                        }
                                    }
                                    // Reverse direction for :only-* (if we haven't yet done so)
                                    start = dir = type === "only" && !start && "nextSibling";
                                }
                                return true;
                            }
    
                            start = [ forward ? parent.firstChild : parent.lastChild ];
    
                            // non-xml :nth-child(...) stores cache data on `parent`
                            if ( forward && useCache ) {
    
                                // Seek `elem` from a previously-cached index
    
                                // ...in a gzip-friendly way
                                node = parent;
                                outerCache = node[ expando ] || (node[ expando ] = {});
    
                                // Support: IE <9 only
                                // Defend against cloned attroperties (jQuery gh-1709)
                                uniqueCache = outerCache[ node.uniqueID ] ||
                                    (outerCache[ node.uniqueID ] = {});
    
                                cache = uniqueCache[ type ] || [];
                                nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
                                diff = nodeIndex && cache[ 2 ];
                                node = nodeIndex && parent.childNodes[ nodeIndex ];
    
                                while ( (node = ++nodeIndex && node && node[ dir ] ||
    
                                    // Fallback to seeking `elem` from the start
                                    (diff = nodeIndex = 0) || start.pop()) ) {
    
                                    // When found, cache indexes on `parent` and break
                                    if ( node.nodeType === 1 && ++diff && node === elem ) {
                                        uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
                                        break;
                                    }
                                }
    
                            } else {
                                // Use previously-cached element index if available
                                if ( useCache ) {
                                    // ...in a gzip-friendly way
                                    node = elem;
                                    outerCache = node[ expando ] || (node[ expando ] = {});
    
                                    // Support: IE <9 only
                                    // Defend against cloned attroperties (jQuery gh-1709)
                                    uniqueCache = outerCache[ node.uniqueID ] ||
                                        (outerCache[ node.uniqueID ] = {});
    
                                    cache = uniqueCache[ type ] || [];
                                    nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
                                    diff = nodeIndex;
                                }
    
                                // xml :nth-child(...)
                                // or :nth-last-child(...) or :nth(-last)?-of-type(...)
                                if ( diff === false ) {
                                    // Use the same loop as above to seek `elem` from the start
                                    while ( (node = ++nodeIndex && node && node[ dir ] ||
                                        (diff = nodeIndex = 0) || start.pop()) ) {
    
                                        if ( ( ofType ?
                                            node.nodeName.toLowerCase() === name :
                                            node.nodeType === 1 ) &&
                                            ++diff ) {
    
                                            // Cache the index of each encountered element
                                            if ( useCache ) {
                                                outerCache = node[ expando ] || (node[ expando ] = {});
    
                                                // Support: IE <9 only
                                                // Defend against cloned attroperties (jQuery gh-1709)
                                                uniqueCache = outerCache[ node.uniqueID ] ||
                                                    (outerCache[ node.uniqueID ] = {});
    
                                                uniqueCache[ type ] = [ dirruns, diff ];
                                            }
    
                                            if ( node === elem ) {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
    
                            // Incorporate the offset, then check against cycle size
                            diff -= last;
                            return diff === first || ( diff % first === 0 && diff / first >= 0 );
                        }
                    };
            },
    
            "PSEUDO": function( pseudo, argument ) {
                // pseudo-class names are case-insensitive
                // http://www.w3.org/TR/selectors/#pseudo-classes
                // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
                // Remember that setFilters inherits from pseudos
                var args,
                    fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
                        Sizzle.error( "unsupported pseudo: " + pseudo );
    
                // The user may use createPseudo to indicate that
                // arguments are needed to create the filter function
                // just as Sizzle does
                if ( fn[ expando ] ) {
                    return fn( argument );
                }
    
                // But maintain support for old signatures
                if ( fn.length > 1 ) {
                    args = [ pseudo, pseudo, "", argument ];
                    return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
                        markFunction(function( seed, matches ) {
                            var idx,
                                matched = fn( seed, argument ),
                                i = matched.length;
                            while ( i-- ) {
                                idx = indexOf( seed, matched[i] );
                                seed[ idx ] = !( matches[ idx ] = matched[i] );
                            }
                        }) :
                        function( elem ) {
                            return fn( elem, 0, args );
                        };
                }
    
                return fn;
            }
        },
    
        pseudos: {
            // Potentially complex pseudos
            "not": markFunction(function( selector ) {
                // Trim the selector passed to compile
                // to avoid treating leading and trailing
                // spaces as combinators
                var input = [],
                    results = [],
                    matcher = compile( selector.replace( rtrim, "$1" ) );
    
                return matcher[ expando ] ?
                    markFunction(function( seed, matches, context, xml ) {
                        var elem,
                            unmatched = matcher( seed, null, xml, [] ),
                            i = seed.length;
    
                        // Match elements unmatched by `matcher`
                        while ( i-- ) {
                            if ( (elem = unmatched[i]) ) {
                                seed[i] = !(matches[i] = elem);
                            }
                        }
                    }) :
                    function( elem, context, xml ) {
                        input[0] = elem;
                        matcher( input, null, xml, results );
                        // Don't keep the element (issue #299)
                        input[0] = null;
                        return !results.pop();
                    };
            }),
    
            "has": markFunction(function( selector ) {
                return function( elem ) {
                    return Sizzle( selector, elem ).length > 0;
                };
            }),
    
            "contains": markFunction(function( text ) {
                text = text.replace( runescape, funescape );
                return function( elem ) {
                    return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
                };
            }),
    
            // "Whether an element is represented by a :lang() selector
            // is based solely on the element's language value
            // being equal to the identifier C,
            // or beginning with the identifier C immediately followed by "-".
            // The matching of C against the element's language value is performed case-insensitively.
            // The identifier C does not have to be a valid language name."
            // http://www.w3.org/TR/selectors/#lang-pseudo
            "lang": markFunction( function( lang ) {
                // lang value must be a valid identifier
                if ( !ridentifier.test(lang || "") ) {
                    Sizzle.error( "unsupported lang: " + lang );
                }
                lang = lang.replace( runescape, funescape ).toLowerCase();
                return function( elem ) {
                    var elemLang;
                    do {
                        if ( (elemLang = documentIsHTML ?
                            elem.lang :
                            elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
    
                            elemLang = elemLang.toLowerCase();
                            return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
                        }
                    } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
                    return false;
                };
            }),
    
            // Miscellaneous
            "target": function( elem ) {
                var hash = window.location && window.location.hash;
                return hash && hash.slice( 1 ) === elem.id;
            },
    
            "root": function( elem ) {
                return elem === docElem;
            },
    
            "focus": function( elem ) {
                return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
            },
    
            // Boolean properties
            "enabled": function( elem ) {
                return elem.disabled === false;
            },
    
            "disabled": function( elem ) {
                return elem.disabled === true;
            },
    
            "checked": function( elem ) {
                // In CSS3, :checked should return both checked and selected elements
                // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
                var nodeName = elem.nodeName.toLowerCase();
                return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
            },
    
            "selected": function( elem ) {
                // Accessing this property makes selected-by-default
                // options in Safari work properly
                if ( elem.parentNode ) {
                    elem.parentNode.selectedIndex;
                }
    
                return elem.selected === true;
            },
    
            // Contents
            "empty": function( elem ) {
                // http://www.w3.org/TR/selectors/#empty-pseudo
                // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
                //   but not by others (comment: 8; processing instruction: 7; etc.)
                // nodeType < 6 works because attributes (2) do not appear as children
                for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
                    if ( elem.nodeType < 6 ) {
                        return false;
                    }
                }
                return true;
            },
    
            "parent": function( elem ) {
                return !Expr.pseudos["empty"]( elem );
            },
    
            // Element/input types
            "header": function( elem ) {
                return rheader.test( elem.nodeName );
            },
    
            "input": function( elem ) {
                return rinputs.test( elem.nodeName );
            },
    
            "button": function( elem ) {
                var name = elem.nodeName.toLowerCase();
                return name === "input" && elem.type === "button" || name === "button";
            },
    
            "text": function( elem ) {
                var attr;
                return elem.nodeName.toLowerCase() === "input" &&
                    elem.type === "text" &&
    
                    // Support: IE<8
                    // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
                    ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
            },
    
            // Position-in-collection
            "first": createPositionalPseudo(function() {
                return [ 0 ];
            }),
    
            "last": createPositionalPseudo(function( matchIndexes, length ) {
                return [ length - 1 ];
            }),
    
            "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
                return [ argument < 0 ? argument + length : argument ];
            }),
    
            "even": createPositionalPseudo(function( matchIndexes, length ) {
                var i = 0;
                for ( ; i < length; i += 2 ) {
                    matchIndexes.push( i );
                }
                return matchIndexes;
            }),
    
            "odd": createPositionalPseudo(function( matchIndexes, length ) {
                var i = 1;
                for ( ; i < length; i += 2 ) {
                    matchIndexes.push( i );
                }
                return matchIndexes;
            }),
    
            "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
                var i = argument < 0 ? argument + length : argument;
                for ( ; --i >= 0; ) {
                    matchIndexes.push( i );
                }
                return matchIndexes;
            }),
    
            "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
                var i = argument < 0 ? argument + length : argument;
                for ( ; ++i < length; ) {
                    matchIndexes.push( i );
                }
                return matchIndexes;
            })
        }
    };
    
    Expr.pseudos["nth"] = Expr.pseudos["eq"];
    
    // Add button/input type pseudos
    for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
        Expr.pseudos[ i ] = createInputPseudo( i );
    }
    for ( i in { submit: true, reset: true } ) {
        Expr.pseudos[ i ] = createButtonPseudo( i );
    }
    
    // Easy API for creating new setFilters
    function setFilters() {}
    setFilters.prototype = Expr.filters = Expr.pseudos;
    Expr.setFilters = new setFilters();
    
    tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
        var matched, match, tokens, type,
            soFar, groups, preFilters,
            cached = tokenCache[ selector + " " ];
    
        if ( cached ) {
            return parseOnly ? 0 : cached.slice( 0 );
        }
    
        soFar = selector;
        groups = [];
        preFilters = Expr.preFilter;
    
        while ( soFar ) {
    
            // Comma and first run
            if ( !matched || (match = rcomma.exec( soFar )) ) {
                if ( match ) {
                    // Don't consume trailing commas as valid
                    soFar = soFar.slice( match[0].length ) || soFar;
                }
                groups.push( (tokens = []) );
            }
    
            matched = false;
    
            // Combinators
            if ( (match = rcombinators.exec( soFar )) ) {
                matched = match.shift();
                tokens.push({
                    value: matched,
                    // Cast descendant combinators to space
                    type: match[0].replace( rtrim, " " )
                });
                soFar = soFar.slice( matched.length );
            }
    
            // Filters
            for ( type in Expr.filter ) {
                if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
                    (match = preFilters[ type ]( match ))) ) {
                    matched = match.shift();
                    tokens.push({
                        value: matched,
                        type: type,
                        matches: match
                    });
                    soFar = soFar.slice( matched.length );
                }
            }
    
            if ( !matched ) {
                break;
            }
        }
    
        // Return the length of the invalid excess
        // if we're just parsing
        // Otherwise, throw an error or return tokens
        return parseOnly ?
            soFar.length :
            soFar ?
                Sizzle.error( selector ) :
                // Cache the tokens
                tokenCache( selector, groups ).slice( 0 );
    };
    
    function toSelector( tokens ) {
        var i = 0,
            len = tokens.length,
            selector = "";
        for ( ; i < len; i++ ) {
            selector += tokens[i].value;
        }
        return selector;
    }
    
    function addCombinator( matcher, combinator, base ) {
        var dir = combinator.dir,
            checkNonElements = base && dir === "parentNode",
            doneName = done++;
    
        return combinator.first ?
            // Check against closest ancestor/preceding element
            function( elem, context, xml ) {
                while ( (elem = elem[ dir ]) ) {
                    if ( elem.nodeType === 1 || checkNonElements ) {
                        return matcher( elem, context, xml );
                    }
                }
            } :
    
            // Check against all ancestor/preceding elements
            function( elem, context, xml ) {
                var oldCache, uniqueCache, outerCache,
                    newCache = [ dirruns, doneName ];
    
                // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
                if ( xml ) {
                    while ( (elem = elem[ dir ]) ) {
                        if ( elem.nodeType === 1 || checkNonElements ) {
                            if ( matcher( elem, context, xml ) ) {
                                return true;
                            }
                        }
                    }
                } else {
                    while ( (elem = elem[ dir ]) ) {
                        if ( elem.nodeType === 1 || checkNonElements ) {
                            outerCache = elem[ expando ] || (elem[ expando ] = {});
    
                            // Support: IE <9 only
                            // Defend against cloned attroperties (jQuery gh-1709)
                            uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
    
                            if ( (oldCache = uniqueCache[ dir ]) &&
                                oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
    
                                // Assign to newCache so results back-propagate to previous elements
                                return (newCache[ 2 ] = oldCache[ 2 ]);
                            } else {
                                // Reuse newcache so results back-propagate to previous elements
                                uniqueCache[ dir ] = newCache;
    
                                // A match means we're done; a fail means we have to keep checking
                                if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            };
    }
    
    function elementMatcher( matchers ) {
        return matchers.length > 1 ?
            function( elem, context, xml ) {
                var i = matchers.length;
                while ( i-- ) {
                    if ( !matchers[i]( elem, context, xml ) ) {
                        return false;
                    }
                }
                return true;
            } :
            matchers[0];
    }
    
    function multipleContexts( selector, contexts, results ) {
        var i = 0,
            len = contexts.length;
        for ( ; i < len; i++ ) {
            Sizzle( selector, contexts[i], results );
        }
        return results;
    }
    
    function condense( unmatched, map, filter, context, xml ) {
        var elem,
            newUnmatched = [],
            i = 0,
            len = unmatched.length,
            mapped = map != null;
    
        for ( ; i < len; i++ ) {
            if ( (elem = unmatched[i]) ) {
                if ( !filter || filter( elem, context, xml ) ) {
                    newUnmatched.push( elem );
                    if ( mapped ) {
                        map.push( i );
                    }
                }
            }
        }
    
        return newUnmatched;
    }
    
    function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
        if ( postFilter && !postFilter[ expando ] ) {
            postFilter = setMatcher( postFilter );
        }
        if ( postFinder && !postFinder[ expando ] ) {
            postFinder = setMatcher( postFinder, postSelector );
        }
        return markFunction(function( seed, results, context, xml ) {
            var temp, i, elem,
                preMap = [],
                postMap = [],
                preexisting = results.length,
    
                // Get initial elements from seed or context
                elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
    
                // Prefilter to get matcher input, preserving a map for seed-results synchronization
                matcherIn = preFilter && ( seed || !selector ) ?
                    condense( elems, preMap, preFilter, context, xml ) :
                    elems,
    
                matcherOut = matcher ?
                    // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
                    postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
    
                        // ...intermediate processing is necessary
                        [] :
    
                        // ...otherwise use results directly
                        results :
                    matcherIn;
    
            // Find primary matches
            if ( matcher ) {
                matcher( matcherIn, matcherOut, context, xml );
            }
    
            // Apply postFilter
            if ( postFilter ) {
                temp = condense( matcherOut, postMap );
                postFilter( temp, [], context, xml );
    
                // Un-match failing elements by moving them back to matcherIn
                i = temp.length;
                while ( i-- ) {
                    if ( (elem = temp[i]) ) {
                        matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
                    }
                }
            }
    
            if ( seed ) {
                if ( postFinder || preFilter ) {
                    if ( postFinder ) {
                        // Get the final matcherOut by condensing this intermediate into postFinder contexts
                        temp = [];
                        i = matcherOut.length;
                        while ( i-- ) {
                            if ( (elem = matcherOut[i]) ) {
                                // Restore matcherIn since elem is not yet a final match
                                temp.push( (matcherIn[i] = elem) );
                            }
                        }
                        postFinder( null, (matcherOut = []), temp, xml );
                    }
    
                    // Move matched elements from seed to results to keep them synchronized
                    i = matcherOut.length;
                    while ( i-- ) {
                        if ( (elem = matcherOut[i]) &&
                            (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
    
                            seed[temp] = !(results[temp] = elem);
                        }
                    }
                }
    
            // Add elements to results, through postFinder if defined
            } else {
                matcherOut = condense(
                    matcherOut === results ?
                        matcherOut.splice( preexisting, matcherOut.length ) :
                        matcherOut
                );
                if ( postFinder ) {
                    postFinder( null, results, matcherOut, xml );
                } else {
                    push.apply( results, matcherOut );
                }
            }
        });
    }
    
    function matcherFromTokens( tokens ) {
        var checkContext, matcher, j,
            len = tokens.length,
            leadingRelative = Expr.relative[ tokens[0].type ],
            implicitRelative = leadingRelative || Expr.relative[" "],
            i = leadingRelative ? 1 : 0,
    
            // The foundational matcher ensures that elements are reachable from top-level context(s)
            matchContext = addCombinator( function( elem ) {
                return elem === checkContext;
            }, implicitRelative, true ),
            matchAnyContext = addCombinator( function( elem ) {
                return indexOf( checkContext, elem ) > -1;
            }, implicitRelative, true ),
            matchers = [ function( elem, context, xml ) {
                var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
                    (checkContext = context).nodeType ?
                        matchContext( elem, context, xml ) :
                        matchAnyContext( elem, context, xml ) );
                // Avoid hanging onto element (issue #299)
                checkContext = null;
                return ret;
            } ];
    
        for ( ; i < len; i++ ) {
            if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
                matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
            } else {
                matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
    
                // Return special upon seeing a positional matcher
                if ( matcher[ expando ] ) {
                    // Find the next relative operator (if any) for proper handling
                    j = ++i;
                    for ( ; j < len; j++ ) {
                        if ( Expr.relative[ tokens[j].type ] ) {
                            break;
                        }
                    }
                    return setMatcher(
                        i > 1 && elementMatcher( matchers ),
                        i > 1 && toSelector(
                            // If the preceding token was a descendant combinator, insert an implicit any-element `*`
                            tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
                        ).replace( rtrim, "$1" ),
                        matcher,
                        i < j && matcherFromTokens( tokens.slice( i, j ) ),
                        j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
                        j < len && toSelector( tokens )
                    );
                }
                matchers.push( matcher );
            }
        }
    
        return elementMatcher( matchers );
    }
    
    function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
        var bySet = setMatchers.length > 0,
            byElement = elementMatchers.length > 0,
            superMatcher = function( seed, context, xml, results, outermost ) {
                var elem, j, matcher,
                    matchedCount = 0,
                    i = "0",
                    unmatched = seed && [],
                    setMatched = [],
                    contextBackup = outermostContext,
                    // We must always have either seed elements or outermost context
                    elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
                    // Use integer dirruns iff this is the outermost matcher
                    dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
                    len = elems.length;
    
                if ( outermost ) {
                    outermostContext = context === document || context || outermost;
                }
    
                // Add elements passing elementMatchers directly to results
                // Support: IE<9, Safari
                // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
                for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
                    if ( byElement && elem ) {
                        j = 0;
                        if ( !context && elem.ownerDocument !== document ) {
                            setDocument( elem );
                            xml = !documentIsHTML;
                        }
                        while ( (matcher = elementMatchers[j++]) ) {
                            if ( matcher( elem, context || document, xml) ) {
                                results.push( elem );
                                break;
                            }
                        }
                        if ( outermost ) {
                            dirruns = dirrunsUnique;
                        }
                    }
    
                    // Track unmatched elements for set filters
                    if ( bySet ) {
                        // They will have gone through all possible matchers
                        if ( (elem = !matcher && elem) ) {
                            matchedCount--;
                        }
    
                        // Lengthen the array for every element, matched or not
                        if ( seed ) {
                            unmatched.push( elem );
                        }
                    }
                }
    
                // `i` is now the count of elements visited above, and adding it to `matchedCount`
                // makes the latter nonnegative.
                matchedCount += i;
    
                // Apply set filters to unmatched elements
                // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
                // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
                // no element matchers and no seed.
                // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
                // case, which will result in a "00" `matchedCount` that differs from `i` but is also
                // numerically zero.
                if ( bySet && i !== matchedCount ) {
                    j = 0;
                    while ( (matcher = setMatchers[j++]) ) {
                        matcher( unmatched, setMatched, context, xml );
                    }
    
                    if ( seed ) {
                        // Reintegrate element matches to eliminate the need for sorting
                        if ( matchedCount > 0 ) {
                            while ( i-- ) {
                                if ( !(unmatched[i] || setMatched[i]) ) {
                                    setMatched[i] = pop.call( results );
                                }
                            }
                        }
    
                        // Discard index placeholder values to get only actual matches
                        setMatched = condense( setMatched );
                    }
    
                    // Add matches to results
                    push.apply( results, setMatched );
    
                    // Seedless set matches succeeding multiple successful matchers stipulate sorting
                    if ( outermost && !seed && setMatched.length > 0 &&
                        ( matchedCount + setMatchers.length ) > 1 ) {
    
                        Sizzle.uniqueSort( results );
                    }
                }
    
                // Override manipulation of globals by nested matchers
                if ( outermost ) {
                    dirruns = dirrunsUnique;
                    outermostContext = contextBackup;
                }
    
                return unmatched;
            };
    
        return bySet ?
            markFunction( superMatcher ) :
            superMatcher;
    }
    
    compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
        var i,
            setMatchers = [],
            elementMatchers = [],
            cached = compilerCache[ selector + " " ];
    
        if ( !cached ) {
            // Generate a function of recursive functions that can be used to check each element
            if ( !match ) {
                match = tokenize( selector );
            }
            i = match.length;
            while ( i-- ) {
                cached = matcherFromTokens( match[i] );
                if ( cached[ expando ] ) {
                    setMatchers.push( cached );
                } else {
                    elementMatchers.push( cached );
                }
            }
    
            // Cache the compiled function
            cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
    
            // Save selector and tokenization
            cached.selector = selector;
        }
        return cached;
    };
    
    /**
     * A low-level selection function that works with Sizzle's compiled
     *  selector functions
     * @param {String|Function} selector A selector or a pre-compiled
     *  selector function built with Sizzle.compile
     * @param {Element} context
     * @param {Array} [results]
     * @param {Array} [seed] A set of elements to match against
     */
    select = Sizzle.select = function( selector, context, results, seed ) {
        var i, tokens, token, type, find,
            compiled = typeof selector === "function" && selector,
            match = !seed && tokenize( (selector = compiled.selector || selector) );
    
        results = results || [];
    
        // Try to minimize operations if there is only one selector in the list and no seed
        // (the latter of which guarantees us context)
        if ( match.length === 1 ) {
    
            // Reduce context if the leading compound selector is an ID
            tokens = match[0] = match[0].slice( 0 );
            if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
                    support.getById && context.nodeType === 9 && documentIsHTML &&
                    Expr.relative[ tokens[1].type ] ) {
    
                context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
                if ( !context ) {
                    return results;
    
                // Precompiled matchers will still verify ancestry, so step up a level
                } else if ( compiled ) {
                    context = context.parentNode;
                }
    
                selector = selector.slice( tokens.shift().value.length );
            }
    
            // Fetch a seed set for right-to-left matching
            i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
            while ( i-- ) {
                token = tokens[i];
    
                // Abort if we hit a combinator
                if ( Expr.relative[ (type = token.type) ] ) {
                    break;
                }
                if ( (find = Expr.find[ type ]) ) {
                    // Search, expanding context for leading sibling combinators
                    if ( (seed = find(
                        token.matches[0].replace( runescape, funescape ),
                        rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
                    )) ) {
    
                        // If seed is empty or no tokens remain, we can return early
                        tokens.splice( i, 1 );
                        selector = seed.length && toSelector( tokens );
                        if ( !selector ) {
                            push.apply( results, seed );
                            return results;
                        }
    
                        break;
                    }
                }
            }
        }
    
        // Compile and execute a filtering function if one is not provided
        // Provide `match` to avoid retokenization if we modified the selector above
        ( compiled || compile( selector, match ) )(
            seed,
            context,
            !documentIsHTML,
            results,
            !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
        );
        return results;
    };
    
    // One-time assignments
    
    // Sort stability
    support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
    
    // Support: Chrome 14-35+
    // Always assume duplicates if they aren't passed to the comparison function
    support.detectDuplicates = !!hasDuplicate;
    
    // Initialize against the default document
    setDocument();
    
    // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
    // Detached nodes confoundingly follow *each other*
    support.sortDetached = assert(function( div1 ) {
        // Should return 1, but returns 4 (following)
        return div1.compareDocumentPosition( document.createElement("div") ) & 1;
    });
    
    // Support: IE<8
    // Prevent attribute/property "interpolation"
    // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
    if ( !assert(function( div ) {
        div.innerHTML = "<a href='#'></a>";
        return div.firstChild.getAttribute("href") === "#" ;
    }) ) {
        addHandle( "type|href|height|width", function( elem, name, isXML ) {
            if ( !isXML ) {
                return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
            }
        });
    }
    
    // Support: IE<9
    // Use defaultValue in place of getAttribute("value")
    if ( !support.attributes || !assert(function( div ) {
        div.innerHTML = "<input/>";
        div.firstChild.setAttribute( "value", "" );
        return div.firstChild.getAttribute( "value" ) === "";
    }) ) {
        addHandle( "value", function( elem, name, isXML ) {
            if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
                return elem.defaultValue;
            }
        });
    }
    
    // Support: IE<9
    // Use getAttributeNode to fetch booleans when getAttribute lies
    if ( !assert(function( div ) {
        return div.getAttribute("disabled") == null;
    }) ) {
        addHandle( booleans, function( elem, name, isXML ) {
            var val;
            if ( !isXML ) {
                return elem[ name ] === true ? name.toLowerCase() :
                        (val = elem.getAttributeNode( name )) && val.specified ?
                        val.value :
                    null;
            }
        });
    }
    
    return Sizzle;
    
    })( window );
    
    
    
    jQuery.find = Sizzle;
    jQuery.expr = Sizzle.selectors;
    jQuery.expr[ ":" ] = jQuery.expr.pseudos;
    jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
    jQuery.text = Sizzle.getText;
    jQuery.isXMLDoc = Sizzle.isXML;
    jQuery.contains = Sizzle.contains;
    
    
    
    var dir = function( elem, dir, until ) {
        var matched = [],
            truncate = until !== undefined;
    
        while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
            if ( elem.nodeType === 1 ) {
                if ( truncate && jQuery( elem ).is( until ) ) {
                    break;
                }
                matched.push( elem );
            }
        }
        return matched;
    };
    
    
    var siblings = function( n, elem ) {
        var matched = [];
    
        for ( ; n; n = n.nextSibling ) {
            if ( n.nodeType === 1 && n !== elem ) {
                matched.push( n );
            }
        }
    
        return matched;
    };
    
    
    var rneedsContext = jQuery.expr.match.needsContext;
    
    var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );
    
    
    
    var risSimple = /^.[^:#\[\.,]*$/;
    
    // Implement the identical functionality for filter and not
    function winnow( elements, qualifier, not ) {
        if ( jQuery.isFunction( qualifier ) ) {
            return jQuery.grep( elements, function( elem, i ) {
                /* jshint -W018 */
                return !!qualifier.call( elem, i, elem ) !== not;
            } );
    
        }
    
        if ( qualifier.nodeType ) {
            return jQuery.grep( elements, function( elem ) {
                return ( elem === qualifier ) !== not;
            } );
    
        }
    
        if ( typeof qualifier === "string" ) {
            if ( risSimple.test( qualifier ) ) {
                return jQuery.filter( qualifier, elements, not );
            }
    
            qualifier = jQuery.filter( qualifier, elements );
        }
    
        return jQuery.grep( elements, function( elem ) {
            return ( jQuery.inArray( elem, qualifier ) > -1 ) !== not;
        } );
    }
    
    jQuery.filter = function( expr, elems, not ) {
        var elem = elems[ 0 ];
    
        if ( not ) {
            expr = ":not(" + expr + ")";
        }
    
        return elems.length === 1 && elem.nodeType === 1 ?
            jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
            jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
                return elem.nodeType === 1;
            } ) );
    };
    
    jQuery.fn.extend( {
        find: function( selector ) {
            var i,
                ret = [],
                self = this,
                len = self.length;
    
            if ( typeof selector !== "string" ) {
                return this.pushStack( jQuery( selector ).filter( function() {
                    for ( i = 0; i < len; i++ ) {
                        if ( jQuery.contains( self[ i ], this ) ) {
                            return true;
                        }
                    }
                } ) );
            }
    
            for ( i = 0; i < len; i++ ) {
                jQuery.find( selector, self[ i ], ret );
            }
    
            // Needed because $( selector, context ) becomes $( context ).find( selector )
            ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
            ret.selector = this.selector ? this.selector + " " + selector : selector;
            return ret;
        },
        filter: function( selector ) {
            return this.pushStack( winnow( this, selector || [], false ) );
        },
        not: function( selector ) {
            return this.pushStack( winnow( this, selector || [], true ) );
        },
        is: function( selector ) {
            return !!winnow(
                this,
    
                // If this is a positional/relative selector, check membership in the returned set
                // so $("p:first").is("p:last") won't return true for a doc with two "p".
                typeof selector === "string" && rneedsContext.test( selector ) ?
                    jQuery( selector ) :
                    selector || [],
                false
            ).length;
        }
    } );
    
    
    // Initialize a jQuery object
    
    
    // A central reference to the root jQuery(document)
    var rootjQuery,
    
        // A simple way to check for HTML strings
        // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
        // Strict HTML recognition (#11290: must start with <)
        rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
    
        init = jQuery.fn.init = function( selector, context, root ) {
            var match, elem;
    
            // HANDLE: $(""), $(null), $(undefined), $(false)
            if ( !selector ) {
                return this;
            }
    
            // init accepts an alternate rootjQuery
            // so migrate can support jQuery.sub (gh-2101)
            root = root || rootjQuery;
    
            // Handle HTML strings
            if ( typeof selector === "string" ) {
                if ( selector.charAt( 0 ) === "<" &&
                    selector.charAt( selector.length - 1 ) === ">" &&
                    selector.length >= 3 ) {
    
                    // Assume that strings that start and end with <> are HTML and skip the regex check
                    match = [ null, selector, null ];
    
                } else {
                    match = rquickExpr.exec( selector );
                }
    
                // Match html or make sure no context is specified for #id
                if ( match && ( match[ 1 ] || !context ) ) {
    
                    // HANDLE: $(html) -> $(array)
                    if ( match[ 1 ] ) {
                        context = context instanceof jQuery ? context[ 0 ] : context;
    
                        // scripts is true for back-compat
                        // Intentionally let the error be thrown if parseHTML is not present
                        jQuery.merge( this, jQuery.parseHTML(
                            match[ 1 ],
                            context && context.nodeType ? context.ownerDocument || context : document,
                            true
                        ) );
    
                        // HANDLE: $(html, props)
                        if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
                            for ( match in context ) {
    
                                // Properties of context are called as methods if possible
                                if ( jQuery.isFunction( this[ match ] ) ) {
                                    this[ match ]( context[ match ] );
    
                                // ...and otherwise set as attributes
                                } else {
                                    this.attr( match, context[ match ] );
                                }
                            }
                        }
    
                        return this;
    
                    // HANDLE: $(#id)
                    } else {
                        elem = document.getElementById( match[ 2 ] );
    
                        // Check parentNode to catch when Blackberry 4.6 returns
                        // nodes that are no longer in the document #6963
                        if ( elem && elem.parentNode ) {
    
                            // Handle the case where IE and Opera return items
                            // by name instead of ID
                            if ( elem.id !== match[ 2 ] ) {
                                return rootjQuery.find( selector );
                            }
    
                            // Otherwise, we inject the element directly into the jQuery object
                            this.length = 1;
                            this[ 0 ] = elem;
                        }
    
                        this.context = document;
                        this.selector = selector;
                        return this;
                    }
    
                // HANDLE: $(expr, $(...))
                } else if ( !context || context.jquery ) {
                    return ( context || root ).find( selector );
    
                // HANDLE: $(expr, context)
                // (which is just equivalent to: $(context).find(expr)
                } else {
                    return this.constructor( context ).find( selector );
                }
    
            // HANDLE: $(DOMElement)
            } else if ( selector.nodeType ) {
                this.context = this[ 0 ] = selector;
                this.length = 1;
                return this;
    
            // HANDLE: $(function)
            // Shortcut for document ready
            } else if ( jQuery.isFunction( selector ) ) {
                return typeof root.ready !== "undefined" ?
                    root.ready( selector ) :
    
                    // Execute immediately if ready is not present
                    selector( jQuery );
            }
    
            if ( selector.selector !== undefined ) {
                this.selector = selector.selector;
                this.context = selector.context;
            }
    
            return jQuery.makeArray( selector, this );
        };
    
    // Give the init function the jQuery prototype for later instantiation
    init.prototype = jQuery.fn;
    
    // Initialize central reference
    rootjQuery = jQuery( document );
    
    
    var rparentsprev = /^(?:parents|prev(?:Until|All))/,
    
        // methods guaranteed to produce a unique set when starting from a unique set
        guaranteedUnique = {
            children: true,
            contents: true,
            next: true,
            prev: true
        };
    
    jQuery.fn.extend( {
        has: function( target ) {
            var i,
                targets = jQuery( target, this ),
                len = targets.length;
    
            return this.filter( function() {
                for ( i = 0; i < len; i++ ) {
                    if ( jQuery.contains( this, targets[ i ] ) ) {
                        return true;
                    }
                }
            } );
        },
    
        closest: function( selectors, context ) {
            var cur,
                i = 0,
                l = this.length,
                matched = [],
                pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
                    jQuery( selectors, context || this.context ) :
                    0;
    
            for ( ; i < l; i++ ) {
                for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
    
                    // Always skip document fragments
                    if ( cur.nodeType < 11 && ( pos ?
                        pos.index( cur ) > -1 :
    
                        // Don't pass non-elements to Sizzle
                        cur.nodeType === 1 &&
                            jQuery.find.matchesSelector( cur, selectors ) ) ) {
    
                        matched.push( cur );
                        break;
                    }
                }
            }
    
            return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
        },
    
        // Determine the position of an element within
        // the matched set of elements
        index: function( elem ) {
    
            // No argument, return index in parent
            if ( !elem ) {
                return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
            }
    
            // index in selector
            if ( typeof elem === "string" ) {
                return jQuery.inArray( this[ 0 ], jQuery( elem ) );
            }
    
            // Locate the position of the desired element
            return jQuery.inArray(
    
                // If it receives a jQuery object, the first element is used
                elem.jquery ? elem[ 0 ] : elem, this );
        },
    
        add: function( selector, context ) {
            return this.pushStack(
                jQuery.uniqueSort(
                    jQuery.merge( this.get(), jQuery( selector, context ) )
                )
            );
        },
    
        addBack: function( selector ) {
            return this.add( selector == null ?
                this.prevObject : this.prevObject.filter( selector )
            );
        }
    } );
    
    function sibling( cur, dir ) {
        do {
            cur = cur[ dir ];
        } while ( cur && cur.nodeType !== 1 );
    
        return cur;
    }
    
    jQuery.each( {
        parent: function( elem ) {
            var parent = elem.parentNode;
            return parent && parent.nodeType !== 11 ? parent : null;
        },
        parents: function( elem ) {
            return dir( elem, "parentNode" );
        },
        parentsUntil: function( elem, i, until ) {
            return dir( elem, "parentNode", until );
        },
        next: function( elem ) {
            return sibling( elem, "nextSibling" );
        },
        prev: function( elem ) {
            return sibling( elem, "previousSibling" );
        },
        nextAll: function( elem ) {
            return dir( elem, "nextSibling" );
        },
        prevAll: function( elem ) {
            return dir( elem, "previousSibling" );
        },
        nextUntil: function( elem, i, until ) {
            return dir( elem, "nextSibling", until );
        },
        prevUntil: function( elem, i, until ) {
            return dir( elem, "previousSibling", until );
        },
        siblings: function( elem ) {
            return siblings( ( elem.parentNode || {} ).firstChild, elem );
        },
        children: function( elem ) {
            return siblings( elem.firstChild );
        },
        contents: function( elem ) {
            return jQuery.nodeName( elem, "iframe" ) ?
                elem.contentDocument || elem.contentWindow.document :
                jQuery.merge( [], elem.childNodes );
        }
    }, function( name, fn ) {
        jQuery.fn[ name ] = function( until, selector ) {
            var ret = jQuery.map( this, fn, until );
    
            if ( name.slice( -5 ) !== "Until" ) {
                selector = until;
            }
    
            if ( selector && typeof selector === "string" ) {
                ret = jQuery.filter( selector, ret );
            }
    
            if ( this.length > 1 ) {
    
                // Remove duplicates
                if ( !guaranteedUnique[ name ] ) {
                    ret = jQuery.uniqueSort( ret );
                }
    
                // Reverse order for parents* and prev-derivatives
                if ( rparentsprev.test( name ) ) {
                    ret = ret.reverse();
                }
            }
    
            return this.pushStack( ret );
        };
    } );
    var rnotwhite = ( /\S+/g );
    
    
    
    // Convert String-formatted options into Object-formatted ones
    function createOptions( options ) {
        var object = {};
        jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
            object[ flag ] = true;
        } );
        return object;
    }
    
    /*
     * Create a callback list using the following parameters:
     *
     *	options: an optional list of space-separated options that will change how
     *			the callback list behaves or a more traditional option object
     *
     * By default a callback list will act like an event callback list and can be
     * "fired" multiple times.
     *
     * Possible options:
     *
     *	once:			will ensure the callback list can only be fired once (like a Deferred)
     *
     *	memory:			will keep track of previous values and will call any callback added
     *					after the list has been fired right away with the latest "memorized"
     *					values (like a Deferred)
     *
     *	unique:			will ensure a callback can only be added once (no duplicate in the list)
     *
     *	stopOnFalse:	interrupt callings when a callback returns false
     *
     */
    jQuery.Callbacks = function( options ) {
    
        // Convert options from String-formatted to Object-formatted if needed
        // (we check in cache first)
        options = typeof options === "string" ?
            createOptions( options ) :
            jQuery.extend( {}, options );
    
        var // Flag to know if list is currently firing
            firing,
    
            // Last fire value for non-forgettable lists
            memory,
    
            // Flag to know if list was already fired
            fired,
    
            // Flag to prevent firing
            locked,
    
            // Actual callback list
            list = [],
    
            // Queue of execution data for repeatable lists
            queue = [],
    
            // Index of currently firing callback (modified by add/remove as needed)
            firingIndex = -1,
    
            // Fire callbacks
            fire = function() {
    
                // Enforce single-firing
                locked = options.once;
    
                // Execute callbacks for all pending executions,
                // respecting firingIndex overrides and runtime changes
                fired = firing = true;
                for ( ; queue.length; firingIndex = -1 ) {
                    memory = queue.shift();
                    while ( ++firingIndex < list.length ) {
    
                        // Run callback and check for early termination
                        if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
                            options.stopOnFalse ) {
    
                            // Jump to end and forget the data so .add doesn't re-fire
                            firingIndex = list.length;
                            memory = false;
                        }
                    }
                }
    
                // Forget the data if we're done with it
                if ( !options.memory ) {
                    memory = false;
                }
    
                firing = false;
    
                // Clean up if we're done firing for good
                if ( locked ) {
    
                    // Keep an empty list if we have data for future add calls
                    if ( memory ) {
                        list = [];
    
                    // Otherwise, this object is spent
                    } else {
                        list = "";
                    }
                }
            },
    
            // Actual Callbacks object
            self = {
    
                // Add a callback or a collection of callbacks to the list
                add: function() {
                    if ( list ) {
    
                        // If we have memory from a past run, we should fire after adding
                        if ( memory && !firing ) {
                            firingIndex = list.length - 1;
                            queue.push( memory );
                        }
    
                        ( function add( args ) {
                            jQuery.each( args, function( _, arg ) {
                                if ( jQuery.isFunction( arg ) ) {
                                    if ( !options.unique || !self.has( arg ) ) {
                                        list.push( arg );
                                    }
                                } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
    
                                    // Inspect recursively
                                    add( arg );
                                }
                            } );
                        } )( arguments );
    
                        if ( memory && !firing ) {
                            fire();
                        }
                    }
                    return this;
                },
    
                // Remove a callback from the list
                remove: function() {
                    jQuery.each( arguments, function( _, arg ) {
                        var index;
                        while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
                            list.splice( index, 1 );
    
                            // Handle firing indexes
                            if ( index <= firingIndex ) {
                                firingIndex--;
                            }
                        }
                    } );
                    return this;
                },
    
                // Check if a given callback is in the list.
                // If no argument is given, return whether or not list has callbacks attached.
                has: function( fn ) {
                    return fn ?
                        jQuery.inArray( fn, list ) > -1 :
                        list.length > 0;
                },
    
                // Remove all callbacks from the list
                empty: function() {
                    if ( list ) {
                        list = [];
                    }
                    return this;
                },
    
                // Disable .fire and .add
                // Abort any current/pending executions
                // Clear all callbacks and values
                disable: function() {
                    locked = queue = [];
                    list = memory = "";
                    return this;
                },
                disabled: function() {
                    return !list;
                },
    
                // Disable .fire
                // Also disable .add unless we have memory (since it would have no effect)
                // Abort any pending executions
                lock: function() {
                    locked = true;
                    if ( !memory ) {
                        self.disable();
                    }
                    return this;
                },
                locked: function() {
                    return !!locked;
                },
    
                // Call all callbacks with the given context and arguments
                fireWith: function( context, args ) {
                    if ( !locked ) {
                        args = args || [];
                        args = [ context, args.slice ? args.slice() : args ];
                        queue.push( args );
                        if ( !firing ) {
                            fire();
                        }
                    }
                    return this;
                },
    
                // Call all the callbacks with the given arguments
                fire: function() {
                    self.fireWith( this, arguments );
                    return this;
                },
    
                // To know if the callbacks have already been called at least once
                fired: function() {
                    return !!fired;
                }
            };
    
        return self;
    };
    
    
    jQuery.extend( {
    
        Deferred: function( func ) {
            var tuples = [
    
                    // action, add listener, listener list, final state
                    [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ],
                    [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ],
                    [ "notify", "progress", jQuery.Callbacks( "memory" ) ]
                ],
                state = "pending",
                promise = {
                    state: function() {
                        return state;
                    },
                    always: function() {
                        deferred.done( arguments ).fail( arguments );
                        return this;
                    },
                    then: function( /* fnDone, fnFail, fnProgress */ ) {
                        var fns = arguments;
                        return jQuery.Deferred( function( newDefer ) {
                            jQuery.each( tuples, function( i, tuple ) {
                                var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
    
                                // deferred[ done | fail | progress ] for forwarding actions to newDefer
                                deferred[ tuple[ 1 ] ]( function() {
                                    var returned = fn && fn.apply( this, arguments );
                                    if ( returned && jQuery.isFunction( returned.promise ) ) {
                                        returned.promise()
                                            .progress( newDefer.notify )
                                            .done( newDefer.resolve )
                                            .fail( newDefer.reject );
                                    } else {
                                        newDefer[ tuple[ 0 ] + "With" ](
                                            this === promise ? newDefer.promise() : this,
                                            fn ? [ returned ] : arguments
                                        );
                                    }
                                } );
                            } );
                            fns = null;
                        } ).promise();
                    },
    
                    // Get a promise for this deferred
                    // If obj is provided, the promise aspect is added to the object
                    promise: function( obj ) {
                        return obj != null ? jQuery.extend( obj, promise ) : promise;
                    }
                },
                deferred = {};
    
            // Keep pipe for back-compat
            promise.pipe = promise.then;
    
            // Add list-specific methods
            jQuery.each( tuples, function( i, tuple ) {
                var list = tuple[ 2 ],
                    stateString = tuple[ 3 ];
    
                // promise[ done | fail | progress ] = list.add
                promise[ tuple[ 1 ] ] = list.add;
    
                // Handle state
                if ( stateString ) {
                    list.add( function() {
    
                        // state = [ resolved | rejected ]
                        state = stateString;
    
                    // [ reject_list | resolve_list ].disable; progress_list.lock
                    }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
                }
    
                // deferred[ resolve | reject | notify ]
                deferred[ tuple[ 0 ] ] = function() {
                    deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments );
                    return this;
                };
                deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
            } );
    
            // Make the deferred a promise
            promise.promise( deferred );
    
            // Call given func if any
            if ( func ) {
                func.call( deferred, deferred );
            }
    
            // All done!
            return deferred;
        },
    
        // Deferred helper
        when: function( subordinate /* , ..., subordinateN */ ) {
            var i = 0,
                resolveValues = slice.call( arguments ),
                length = resolveValues.length,
    
                // the count of uncompleted subordinates
                remaining = length !== 1 ||
                    ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
    
                // the master Deferred.
                // If resolveValues consist of only a single Deferred, just use that.
                deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
    
                // Update function for both resolve and progress values
                updateFunc = function( i, contexts, values ) {
                    return function( value ) {
                        contexts[ i ] = this;
                        values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
                        if ( values === progressValues ) {
                            deferred.notifyWith( contexts, values );
    
                        } else if ( !( --remaining ) ) {
                            deferred.resolveWith( contexts, values );
                        }
                    };
                },
    
                progressValues, progressContexts, resolveContexts;
    
            // add listeners to Deferred subordinates; treat others as resolved
            if ( length > 1 ) {
                progressValues = new Array( length );
                progressContexts = new Array( length );
                resolveContexts = new Array( length );
                for ( ; i < length; i++ ) {
                    if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
                        resolveValues[ i ].promise()
                            .progress( updateFunc( i, progressContexts, progressValues ) )
                            .done( updateFunc( i, resolveContexts, resolveValues ) )
                            .fail( deferred.reject );
                    } else {
                        --remaining;
                    }
                }
            }
    
            // if we're not waiting on anything, resolve the master
            if ( !remaining ) {
                deferred.resolveWith( resolveContexts, resolveValues );
            }
    
            return deferred.promise();
        }
    } );
    
    
    // The deferred used on DOM ready
    var readyList;
    
    jQuery.fn.ready = function( fn ) {
    
        // Add the callback
        jQuery.ready.promise().done( fn );
    
        return this;
    };
    
    jQuery.extend( {
    
        // Is the DOM ready to be used? Set to true once it occurs.
        isReady: false,
    
        // A counter to track how many items to wait for before
        // the ready event fires. See #6781
        readyWait: 1,
    
        // Hold (or release) the ready event
        holdReady: function( hold ) {
            if ( hold ) {
                jQuery.readyWait++;
            } else {
                jQuery.ready( true );
            }
        },
    
        // Handle when the DOM is ready
        ready: function( wait ) {
    
            // Abort if there are pending holds or we're already ready
            if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
                return;
            }
    
            // Remember that the DOM is ready
            jQuery.isReady = true;
    
            // If a normal DOM Ready event fired, decrement, and wait if need be
            if ( wait !== true && --jQuery.readyWait > 0 ) {
                return;
            }
    
            // If there are functions bound, to execute
            readyList.resolveWith( document, [ jQuery ] );
    
            // Trigger any bound ready events
            if ( jQuery.fn.triggerHandler ) {
                jQuery( document ).triggerHandler( "ready" );
                jQuery( document ).off( "ready" );
            }
        }
    } );
    
    /**
     * Clean-up method for dom ready events
     */
    function detach() {
        if ( document.addEventListener ) {
            document.removeEventListener( "DOMContentLoaded", completed );
            window.removeEventListener( "load", completed );
    
        } else {
            document.detachEvent( "onreadystatechange", completed );
            window.detachEvent( "onload", completed );
        }
    }
    
    /**
     * The ready event handler and self cleanup method
     */
    function completed() {
    
        // readyState === "complete" is good enough for us to call the dom ready in oldIE
        if ( document.addEventListener ||
            window.event.type === "load" ||
            document.readyState === "complete" ) {
    
            detach();
            jQuery.ready();
        }
    }
    
    jQuery.ready.promise = function( obj ) {
        if ( !readyList ) {
    
            readyList = jQuery.Deferred();
    
            // Catch cases where $(document).ready() is called
            // after the browser event has already occurred.
            // Support: IE6-10
            // Older IE sometimes signals "interactive" too soon
            if ( document.readyState === "complete" ||
                ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
    
                // Handle it asynchronously to allow scripts the opportunity to delay ready
                window.setTimeout( jQuery.ready );
    
            // Standards-based browsers support DOMContentLoaded
            } else if ( document.addEventListener ) {
    
                // Use the handy event callback
                document.addEventListener( "DOMContentLoaded", completed );
    
                // A fallback to window.onload, that will always work
                window.addEventListener( "load", completed );
    
            // If IE event model is used
            } else {
    
                // Ensure firing before onload, maybe late but safe also for iframes
                document.attachEvent( "onreadystatechange", completed );
    
                // A fallback to window.onload, that will always work
                window.attachEvent( "onload", completed );
    
                // If IE and not a frame
                // continually check to see if the document is ready
                var top = false;
    
                try {
                    top = window.frameElement == null && document.documentElement;
                } catch ( e ) {}
    
                if ( top && top.doScroll ) {
                    ( function doScrollCheck() {
                        if ( !jQuery.isReady ) {
    
                            try {
    
                                // Use the trick by Diego Perini
                                // http://javascript.nwbox.com/IEContentLoaded/
                                top.doScroll( "left" );
                            } catch ( e ) {
                                return window.setTimeout( doScrollCheck, 50 );
                            }
    
                            // detach all dom ready events
                            detach();
    
                            // and execute any waiting functions
                            jQuery.ready();
                        }
                    } )();
                }
            }
        }
        return readyList.promise( obj );
    };
    
    // Kick off the DOM ready check even if the user does not
    jQuery.ready.promise();
    
    
    
    
    // Support: IE<9
    // Iteration over object's inherited properties before its own
    var i;
    for ( i in jQuery( support ) ) {
        break;
    }
    support.ownFirst = i === "0";
    
    // Note: most support tests are defined in their respective modules.
    // false until the test is run
    support.inlineBlockNeedsLayout = false;
    
    // Execute ASAP in case we need to set body.style.zoom
    jQuery( function() {
    
        // Minified: var a,b,c,d
        var val, div, body, container;
    
        body = document.getElementsByTagName( "body" )[ 0 ];
        if ( !body || !body.style ) {
    
            // Return for frameset docs that don't have a body
            return;
        }
    
        // Setup
        div = document.createElement( "div" );
        container = document.createElement( "div" );
        container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
        body.appendChild( container ).appendChild( div );
    
        if ( typeof div.style.zoom !== "undefined" ) {
    
            // Support: IE<8
            // Check if natively block-level elements act like inline-block
            // elements when setting their display to 'inline' and giving
            // them layout
            div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
    
            support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
            if ( val ) {
    
                // Prevent IE 6 from affecting layout for positioned elements #11048
                // Prevent IE from shrinking the body in IE 7 mode #12869
                // Support: IE<8
                body.style.zoom = 1;
            }
        }
    
        body.removeChild( container );
    } );
    
    
    ( function() {
        var div = document.createElement( "div" );
    
        // Support: IE<9
        support.deleteExpando = true;
        try {
            delete div.test;
        } catch ( e ) {
            support.deleteExpando = false;
        }
    
        // Null elements to avoid leaks in IE.
        div = null;
    } )();
    var acceptData = function( elem ) {
        var noData = jQuery.noData[ ( elem.nodeName + " " ).toLowerCase() ],
            nodeType = +elem.nodeType || 1;
    
        // Do not set data on non-element DOM nodes because it will not be cleared (#8335).
        return nodeType !== 1 && nodeType !== 9 ?
            false :
    
            // Nodes accept data unless otherwise specified; rejection can be conditional
            !noData || noData !== true && elem.getAttribute( "classid" ) === noData;
    };
    
    
    
    
    var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
        rmultiDash = /([A-Z])/g;
    
    function dataAttr( elem, key, data ) {
    
        // If nothing was found internally, try to fetch any
        // data from the HTML5 data-* attribute
        if ( data === undefined && elem.nodeType === 1 ) {
    
            var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
    
            data = elem.getAttribute( name );
    
            if ( typeof data === "string" ) {
                try {
                    data = data === "true" ? true :
                        data === "false" ? false :
                        data === "null" ? null :
    
                        // Only convert to a number if it doesn't change the string
                        +data + "" === data ? +data :
                        rbrace.test( data ) ? jQuery.parseJSON( data ) :
                        data;
                } catch ( e ) {}
    
                // Make sure we set the data so it isn't changed later
                jQuery.data( elem, key, data );
    
            } else {
                data = undefined;
            }
        }
    
        return data;
    }
    
    // checks a cache object for emptiness
    function isEmptyDataObject( obj ) {
        var name;
        for ( name in obj ) {
    
            // if the public data object is empty, the private is still empty
            if ( name === "data" && jQuery.isEmptyObject( obj[ name ] ) ) {
                continue;
            }
            if ( name !== "toJSON" ) {
                return false;
            }
        }
    
        return true;
    }
    
    function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
        if ( !acceptData( elem ) ) {
            return;
        }
    
        var ret, thisCache,
            internalKey = jQuery.expando,
    
            // We have to handle DOM nodes and JS objects differently because IE6-7
            // can't GC object references properly across the DOM-JS boundary
            isNode = elem.nodeType,
    
            // Only DOM nodes need the global jQuery cache; JS object data is
            // attached directly to the object so GC can occur automatically
            cache = isNode ? jQuery.cache : elem,
    
            // Only defining an ID for JS objects if its cache already exists allows
            // the code to shortcut on the same path as a DOM node with no cache
            id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
    
        // Avoid doing any more work than we need to when trying to get data on an
        // object that has no data at all
        if ( ( !id || !cache[ id ] || ( !pvt && !cache[ id ].data ) ) &&
            data === undefined && typeof name === "string" ) {
            return;
        }
    
        if ( !id ) {
    
            // Only DOM nodes need a new unique ID for each element since their data
            // ends up in the global cache
            if ( isNode ) {
                id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
            } else {
                id = internalKey;
            }
        }
    
        if ( !cache[ id ] ) {
    
            // Avoid exposing jQuery metadata on plain JS objects when the object
            // is serialized using JSON.stringify
            cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
        }
    
        // An object can be passed to jQuery.data instead of a key/value pair; this gets
        // shallow copied over onto the existing cache
        if ( typeof name === "object" || typeof name === "function" ) {
            if ( pvt ) {
                cache[ id ] = jQuery.extend( cache[ id ], name );
            } else {
                cache[ id ].data = jQuery.extend( cache[ id ].data, name );
            }
        }
    
        thisCache = cache[ id ];
    
        // jQuery data() is stored in a separate object inside the object's internal data
        // cache in order to avoid key collisions between internal data and user-defined
        // data.
        if ( !pvt ) {
            if ( !thisCache.data ) {
                thisCache.data = {};
            }
    
            thisCache = thisCache.data;
        }
    
        if ( data !== undefined ) {
            thisCache[ jQuery.camelCase( name ) ] = data;
        }
    
        // Check for both converted-to-camel and non-converted data property names
        // If a data property was specified
        if ( typeof name === "string" ) {
    
            // First Try to find as-is property data
            ret = thisCache[ name ];
    
            // Test for null|undefined property data
            if ( ret == null ) {
    
                // Try to find the camelCased property
                ret = thisCache[ jQuery.camelCase( name ) ];
            }
        } else {
            ret = thisCache;
        }
    
        return ret;
    }
    
    function internalRemoveData( elem, name, pvt ) {
        if ( !acceptData( elem ) ) {
            return;
        }
    
        var thisCache, i,
            isNode = elem.nodeType,
    
            // See jQuery.data for more information
            cache = isNode ? jQuery.cache : elem,
            id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
    
        // If there is already no cache entry for this object, there is no
        // purpose in continuing
        if ( !cache[ id ] ) {
            return;
        }
    
        if ( name ) {
    
            thisCache = pvt ? cache[ id ] : cache[ id ].data;
    
            if ( thisCache ) {
    
                // Support array or space separated string names for data keys
                if ( !jQuery.isArray( name ) ) {
    
                    // try the string as a key before any manipulation
                    if ( name in thisCache ) {
                        name = [ name ];
                    } else {
    
                        // split the camel cased version by spaces unless a key with the spaces exists
                        name = jQuery.camelCase( name );
                        if ( name in thisCache ) {
                            name = [ name ];
                        } else {
                            name = name.split( " " );
                        }
                    }
                } else {
    
                    // If "name" is an array of keys...
                    // When data is initially created, via ("key", "val") signature,
                    // keys will be converted to camelCase.
                    // Since there is no way to tell _how_ a key was added, remove
                    // both plain key and camelCase key. #12786
                    // This will only penalize the array argument path.
                    name = name.concat( jQuery.map( name, jQuery.camelCase ) );
                }
    
                i = name.length;
                while ( i-- ) {
                    delete thisCache[ name[ i ] ];
                }
    
                // If there is no data left in the cache, we want to continue
                // and let the cache object itself get destroyed
                if ( pvt ? !isEmptyDataObject( thisCache ) : !jQuery.isEmptyObject( thisCache ) ) {
                    return;
                }
            }
        }
    
        // See jQuery.data for more information
        if ( !pvt ) {
            delete cache[ id ].data;
    
            // Don't destroy the parent cache unless the internal data object
            // had been the only thing left in it
            if ( !isEmptyDataObject( cache[ id ] ) ) {
                return;
            }
        }
    
        // Destroy the cache
        if ( isNode ) {
            jQuery.cleanData( [ elem ], true );
    
        // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
        /* jshint eqeqeq: false */
        } else if ( support.deleteExpando || cache != cache.window ) {
            /* jshint eqeqeq: true */
            delete cache[ id ];
    
        // When all else fails, undefined
        } else {
            cache[ id ] = undefined;
        }
    }
    
    jQuery.extend( {
        cache: {},
    
        // The following elements (space-suffixed to avoid Object.prototype collisions)
        // throw uncatchable exceptions if you attempt to set expando properties
        noData: {
            "applet ": true,
            "embed ": true,
    
            // ...but Flash objects (which have this classid) *can* handle expandos
            "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
        },
    
        hasData: function( elem ) {
            elem = elem.nodeType ? jQuery.cache[ elem[ jQuery.expando ] ] : elem[ jQuery.expando ];
            return !!elem && !isEmptyDataObject( elem );
        },
    
        data: function( elem, name, data ) {
            return internalData( elem, name, data );
        },
    
        removeData: function( elem, name ) {
            return internalRemoveData( elem, name );
        },
    
        // For internal use only.
        _data: function( elem, name, data ) {
            return internalData( elem, name, data, true );
        },
    
        _removeData: function( elem, name ) {
            return internalRemoveData( elem, name, true );
        }
    } );
    
    jQuery.fn.extend( {
        data: function( key, value ) {
            var i, name, data,
                elem = this[ 0 ],
                attrs = elem && elem.attributes;
    
            // Special expections of .data basically thwart jQuery.access,
            // so implement the relevant behavior ourselves
    
            // Gets all values
            if ( key === undefined ) {
                if ( this.length ) {
                    data = jQuery.data( elem );
    
                    if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
                        i = attrs.length;
                        while ( i-- ) {
    
                            // Support: IE11+
                            // The attrs elements can be null (#14894)
                            if ( attrs[ i ] ) {
                                name = attrs[ i ].name;
                                if ( name.indexOf( "data-" ) === 0 ) {
                                    name = jQuery.camelCase( name.slice( 5 ) );
                                    dataAttr( elem, name, data[ name ] );
                                }
                            }
                        }
                        jQuery._data( elem, "parsedAttrs", true );
                    }
                }
    
                return data;
            }
    
            // Sets multiple values
            if ( typeof key === "object" ) {
                return this.each( function() {
                    jQuery.data( this, key );
                } );
            }
    
            return arguments.length > 1 ?
    
                // Sets one value
                this.each( function() {
                    jQuery.data( this, key, value );
                } ) :
    
                // Gets one value
                // Try to fetch any internally stored data first
                elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
        },
    
        removeData: function( key ) {
            return this.each( function() {
                jQuery.removeData( this, key );
            } );
        }
    } );
    
    
    jQuery.extend( {
        queue: function( elem, type, data ) {
            var queue;
    
            if ( elem ) {
                type = ( type || "fx" ) + "queue";
                queue = jQuery._data( elem, type );
    
                // Speed up dequeue by getting out quickly if this is just a lookup
                if ( data ) {
                    if ( !queue || jQuery.isArray( data ) ) {
                        queue = jQuery._data( elem, type, jQuery.makeArray( data ) );
                    } else {
                        queue.push( data );
                    }
                }
                return queue || [];
            }
        },
    
        dequeue: function( elem, type ) {
            type = type || "fx";
    
            var queue = jQuery.queue( elem, type ),
                startLength = queue.length,
                fn = queue.shift(),
                hooks = jQuery._queueHooks( elem, type ),
                next = function() {
                    jQuery.dequeue( elem, type );
                };
    
            // If the fx queue is dequeued, always remove the progress sentinel
            if ( fn === "inprogress" ) {
                fn = queue.shift();
                startLength--;
            }
    
            if ( fn ) {
    
                // Add a progress sentinel to prevent the fx queue from being
                // automatically dequeued
                if ( type === "fx" ) {
                    queue.unshift( "inprogress" );
                }
    
                // clear up the last queue stop function
                delete hooks.stop;
                fn.call( elem, next, hooks );
            }
    
            if ( !startLength && hooks ) {
                hooks.empty.fire();
            }
        },
    
        // not intended for public consumption - generates a queueHooks object,
        // or returns the current one
        _queueHooks: function( elem, type ) {
            var key = type + "queueHooks";
            return jQuery._data( elem, key ) || jQuery._data( elem, key, {
                empty: jQuery.Callbacks( "once memory" ).add( function() {
                    jQuery._removeData( elem, type + "queue" );
                    jQuery._removeData( elem, key );
                } )
            } );
        }
    } );
    
    jQuery.fn.extend( {
        queue: function( type, data ) {
            var setter = 2;
    
            if ( typeof type !== "string" ) {
                data = type;
                type = "fx";
                setter--;
            }
    
            if ( arguments.length < setter ) {
                return jQuery.queue( this[ 0 ], type );
            }
    
            return data === undefined ?
                this :
                this.each( function() {
                    var queue = jQuery.queue( this, type, data );
    
                    // ensure a hooks for this queue
                    jQuery._queueHooks( this, type );
    
                    if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
                        jQuery.dequeue( this, type );
                    }
                } );
        },
        dequeue: function( type ) {
            return this.each( function() {
                jQuery.dequeue( this, type );
            } );
        },
        clearQueue: function( type ) {
            return this.queue( type || "fx", [] );
        },
    
        // Get a promise resolved when queues of a certain type
        // are emptied (fx is the type by default)
        promise: function( type, obj ) {
            var tmp,
                count = 1,
                defer = jQuery.Deferred(),
                elements = this,
                i = this.length,
                resolve = function() {
                    if ( !( --count ) ) {
                        defer.resolveWith( elements, [ elements ] );
                    }
                };
    
            if ( typeof type !== "string" ) {
                obj = type;
                type = undefined;
            }
            type = type || "fx";
    
            while ( i-- ) {
                tmp = jQuery._data( elements[ i ], type + "queueHooks" );
                if ( tmp && tmp.empty ) {
                    count++;
                    tmp.empty.add( resolve );
                }
            }
            resolve();
            return defer.promise( obj );
        }
    } );
    
    
    ( function() {
        var shrinkWrapBlocksVal;
    
        support.shrinkWrapBlocks = function() {
            if ( shrinkWrapBlocksVal != null ) {
                return shrinkWrapBlocksVal;
            }
    
            // Will be changed later if needed.
            shrinkWrapBlocksVal = false;
    
            // Minified: var b,c,d
            var div, body, container;
    
            body = document.getElementsByTagName( "body" )[ 0 ];
            if ( !body || !body.style ) {
    
                // Test fired too early or in an unsupported environment, exit.
                return;
            }
    
            // Setup
            div = document.createElement( "div" );
            container = document.createElement( "div" );
            container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
            body.appendChild( container ).appendChild( div );
    
            // Support: IE6
            // Check if elements with layout shrink-wrap their children
            if ( typeof div.style.zoom !== "undefined" ) {
    
                // Reset CSS: box-sizing; display; margin; border
                div.style.cssText =
    
                    // Support: Firefox<29, Android 2.3
                    // Vendor-prefix box-sizing
                    "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
                    "box-sizing:content-box;display:block;margin:0;border:0;" +
                    "padding:1px;width:1px;zoom:1";
                div.appendChild( document.createElement( "div" ) ).style.width = "5px";
                shrinkWrapBlocksVal = div.offsetWidth !== 3;
            }
    
            body.removeChild( container );
    
            return shrinkWrapBlocksVal;
        };
    
    } )();
    var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
    
    var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
    
    
    var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
    
    var isHidden = function( elem, el ) {
    
            // isHidden might be called from jQuery#filter function;
            // in that case, element will be second argument
            elem = el || elem;
            return jQuery.css( elem, "display" ) === "none" ||
                !jQuery.contains( elem.ownerDocument, elem );
        };
    
    
    
    function adjustCSS( elem, prop, valueParts, tween ) {
        var adjusted,
            scale = 1,
            maxIterations = 20,
            currentValue = tween ?
                function() { return tween.cur(); } :
                function() { return jQuery.css( elem, prop, "" ); },
            initial = currentValue(),
            unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
    
            // Starting value computation is required for potential unit mismatches
            initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
                rcssNum.exec( jQuery.css( elem, prop ) );
    
        if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
    
            // Trust units reported by jQuery.css
            unit = unit || initialInUnit[ 3 ];
    
            // Make sure we update the tween properties later on
            valueParts = valueParts || [];
    
            // Iteratively approximate from a nonzero starting point
            initialInUnit = +initial || 1;
    
            do {
    
                // If previous iteration zeroed out, double until we get *something*.
                // Use string for doubling so we don't accidentally see scale as unchanged below
                scale = scale || ".5";
    
                // Adjust and apply
                initialInUnit = initialInUnit / scale;
                jQuery.style( elem, prop, initialInUnit + unit );
    
            // Update scale, tolerating zero or NaN from tween.cur()
            // Break the loop if scale is unchanged or perfect, or if we've just had enough.
            } while (
                scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
            );
        }
    
        if ( valueParts ) {
            initialInUnit = +initialInUnit || +initial || 0;
    
            // Apply relative offset (+=/-=) if specified
            adjusted = valueParts[ 1 ] ?
                initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
                +valueParts[ 2 ];
            if ( tween ) {
                tween.unit = unit;
                tween.start = initialInUnit;
                tween.end = adjusted;
            }
        }
        return adjusted;
    }
    
    
    // Multifunctional method to get and set values of a collection
    // The value/s can optionally be executed if it's a function
    var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
        var i = 0,
            length = elems.length,
            bulk = key == null;
    
        // Sets many values
        if ( jQuery.type( key ) === "object" ) {
            chainable = true;
            for ( i in key ) {
                access( elems, fn, i, key[ i ], true, emptyGet, raw );
            }
    
        // Sets one value
        } else if ( value !== undefined ) {
            chainable = true;
    
            if ( !jQuery.isFunction( value ) ) {
                raw = true;
            }
    
            if ( bulk ) {
    
                // Bulk operations run against the entire set
                if ( raw ) {
                    fn.call( elems, value );
                    fn = null;
    
                // ...except when executing function values
                } else {
                    bulk = fn;
                    fn = function( elem, key, value ) {
                        return bulk.call( jQuery( elem ), value );
                    };
                }
            }
    
            if ( fn ) {
                for ( ; i < length; i++ ) {
                    fn(
                        elems[ i ],
                        key,
                        raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) )
                    );
                }
            }
        }
    
        return chainable ?
            elems :
    
            // Gets
            bulk ?
                fn.call( elems ) :
                length ? fn( elems[ 0 ], key ) : emptyGet;
    };
    var rcheckableType = ( /^(?:checkbox|radio)$/i );
    
    var rtagName = ( /<([\w:-]+)/ );
    
    var rscriptType = ( /^$|\/(?:java|ecma)script/i );
    
    var rleadingWhitespace = ( /^\s+/ );
    
    var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" +
            "details|dialog|figcaption|figure|footer|header|hgroup|main|" +
            "mark|meter|nav|output|picture|progress|section|summary|template|time|video";
    
    
    
    function createSafeFragment( document ) {
        var list = nodeNames.split( "|" ),
            safeFrag = document.createDocumentFragment();
    
        if ( safeFrag.createElement ) {
            while ( list.length ) {
                safeFrag.createElement(
                    list.pop()
                );
            }
        }
        return safeFrag;
    }
    
    
    ( function() {
        var div = document.createElement( "div" ),
            fragment = document.createDocumentFragment(),
            input = document.createElement( "input" );
    
        // Setup
        div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
    
        // IE strips leading whitespace when .innerHTML is used
        support.leadingWhitespace = div.firstChild.nodeType === 3;
    
        // Make sure that tbody elements aren't automatically inserted
        // IE will insert them into empty tables
        support.tbody = !div.getElementsByTagName( "tbody" ).length;
    
        // Make sure that link elements get serialized correctly by innerHTML
        // This requires a wrapper element in IE
        support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
    
        // Makes sure cloning an html5 element does not cause problems
        // Where outerHTML is undefined, this still works
        support.html5Clone =
            document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
    
        // Check if a disconnected checkbox will retain its checked
        // value of true after appended to the DOM (IE6/7)
        input.type = "checkbox";
        input.checked = true;
        fragment.appendChild( input );
        support.appendChecked = input.checked;
    
        // Make sure textarea (and checkbox) defaultValue is properly cloned
        // Support: IE6-IE11+
        div.innerHTML = "<textarea>x</textarea>";
        support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
    
        // #11217 - WebKit loses check when the name is after the checked attribute
        fragment.appendChild( div );
    
        // Support: Windows Web Apps (WWA)
        // `name` and `type` must use .setAttribute for WWA (#14901)
        input = document.createElement( "input" );
        input.setAttribute( "type", "radio" );
        input.setAttribute( "checked", "checked" );
        input.setAttribute( "name", "t" );
    
        div.appendChild( input );
    
        // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
        // old WebKit doesn't clone checked state correctly in fragments
        support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
    
        // Support: IE<9
        // Cloned elements keep attachEvent handlers, we use addEventListener on IE9+
        support.noCloneEvent = !!div.addEventListener;
    
        // Support: IE<9
        // Since attributes and properties are the same in IE,
        // cleanData must set properties to undefined rather than use removeAttribute
        div[ jQuery.expando ] = 1;
        support.attributes = !div.getAttribute( jQuery.expando );
    } )();
    
    
    // We have to close these tags to support XHTML (#13200)
    var wrapMap = {
        option: [ 1, "<select multiple='multiple'>", "</select>" ],
        legend: [ 1, "<fieldset>", "</fieldset>" ],
        area: [ 1, "<map>", "</map>" ],
    
        // Support: IE8
        param: [ 1, "<object>", "</object>" ],
        thead: [ 1, "<table>", "</table>" ],
        tr: [ 2, "<table><tbody>", "</tbody></table>" ],
        col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
        td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
    
        // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
        // unless wrapped in a div with non-breaking characters in front of it.
        _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
    };
    
    // Support: IE8-IE9
    wrapMap.optgroup = wrapMap.option;
    
    wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
    wrapMap.th = wrapMap.td;
    
    
    function getAll( context, tag ) {
        var elems, elem,
            i = 0,
            found = typeof context.getElementsByTagName !== "undefined" ?
                context.getElementsByTagName( tag || "*" ) :
                typeof context.querySelectorAll !== "undefined" ?
                    context.querySelectorAll( tag || "*" ) :
                    undefined;
    
        if ( !found ) {
            for ( found = [], elems = context.childNodes || context;
                ( elem = elems[ i ] ) != null;
                i++
            ) {
                if ( !tag || jQuery.nodeName( elem, tag ) ) {
                    found.push( elem );
                } else {
                    jQuery.merge( found, getAll( elem, tag ) );
                }
            }
        }
    
        return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
            jQuery.merge( [ context ], found ) :
            found;
    }
    
    
    // Mark scripts as having already been evaluated
    function setGlobalEval( elems, refElements ) {
        var elem,
            i = 0;
        for ( ; ( elem = elems[ i ] ) != null; i++ ) {
            jQuery._data(
                elem,
                "globalEval",
                !refElements || jQuery._data( refElements[ i ], "globalEval" )
            );
        }
    }
    
    
    var rhtml = /<|&#?\w+;/,
        rtbody = /<tbody/i;
    
    function fixDefaultChecked( elem ) {
        if ( rcheckableType.test( elem.type ) ) {
            elem.defaultChecked = elem.checked;
        }
    }
    
    function buildFragment( elems, context, scripts, selection, ignored ) {
        var j, elem, contains,
            tmp, tag, tbody, wrap,
            l = elems.length,
    
            // Ensure a safe fragment
            safe = createSafeFragment( context ),
    
            nodes = [],
            i = 0;
    
        for ( ; i < l; i++ ) {
            elem = elems[ i ];
    
            if ( elem || elem === 0 ) {
    
                // Add nodes directly
                if ( jQuery.type( elem ) === "object" ) {
                    jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
    
                // Convert non-html into a text node
                } else if ( !rhtml.test( elem ) ) {
                    nodes.push( context.createTextNode( elem ) );
    
                // Convert html into DOM nodes
                } else {
                    tmp = tmp || safe.appendChild( context.createElement( "div" ) );
    
                    // Deserialize a standard representation
                    tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
                    wrap = wrapMap[ tag ] || wrapMap._default;
    
                    tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
    
                    // Descend through wrappers to the right content
                    j = wrap[ 0 ];
                    while ( j-- ) {
                        tmp = tmp.lastChild;
                    }
    
                    // Manually add leading whitespace removed by IE
                    if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
                        nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[ 0 ] ) );
                    }
    
                    // Remove IE's autoinserted <tbody> from table fragments
                    if ( !support.tbody ) {
    
                        // String was a <table>, *may* have spurious <tbody>
                        elem = tag === "table" && !rtbody.test( elem ) ?
                            tmp.firstChild :
    
                            // String was a bare <thead> or <tfoot>
                            wrap[ 1 ] === "<table>" && !rtbody.test( elem ) ?
                                tmp :
                                0;
    
                        j = elem && elem.childNodes.length;
                        while ( j-- ) {
                            if ( jQuery.nodeName( ( tbody = elem.childNodes[ j ] ), "tbody" ) &&
                                !tbody.childNodes.length ) {
    
                                elem.removeChild( tbody );
                            }
                        }
                    }
    
                    jQuery.merge( nodes, tmp.childNodes );
    
                    // Fix #12392 for WebKit and IE > 9
                    tmp.textContent = "";
    
                    // Fix #12392 for oldIE
                    while ( tmp.firstChild ) {
                        tmp.removeChild( tmp.firstChild );
                    }
    
                    // Remember the top-level container for proper cleanup
                    tmp = safe.lastChild;
                }
            }
        }
    
        // Fix #11356: Clear elements from fragment
        if ( tmp ) {
            safe.removeChild( tmp );
        }
    
        // Reset defaultChecked for any radios and checkboxes
        // about to be appended to the DOM in IE 6/7 (#8060)
        if ( !support.appendChecked ) {
            jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
        }
    
        i = 0;
        while ( ( elem = nodes[ i++ ] ) ) {
    
            // Skip elements already in the context collection (trac-4087)
            if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
                if ( ignored ) {
                    ignored.push( elem );
                }
    
                continue;
            }
    
            contains = jQuery.contains( elem.ownerDocument, elem );
    
            // Append to fragment
            tmp = getAll( safe.appendChild( elem ), "script" );
    
            // Preserve script evaluation history
            if ( contains ) {
                setGlobalEval( tmp );
            }
    
            // Capture executables
            if ( scripts ) {
                j = 0;
                while ( ( elem = tmp[ j++ ] ) ) {
                    if ( rscriptType.test( elem.type || "" ) ) {
                        scripts.push( elem );
                    }
                }
            }
        }
    
        tmp = null;
    
        return safe;
    }
    
    
    ( function() {
        var i, eventName,
            div = document.createElement( "div" );
    
        // Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events)
        for ( i in { submit: true, change: true, focusin: true } ) {
            eventName = "on" + i;
    
            if ( !( support[ i ] = eventName in window ) ) {
    
                // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
                div.setAttribute( eventName, "t" );
                support[ i ] = div.attributes[ eventName ].expando === false;
            }
        }
    
        // Null elements to avoid leaks in IE.
        div = null;
    } )();
    
    
    var rformElems = /^(?:input|select|textarea)$/i,
        rkeyEvent = /^key/,
        rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
        rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
        rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
    
    function returnTrue() {
        return true;
    }
    
    function returnFalse() {
        return false;
    }
    
    // Support: IE9
    // See #13393 for more info
    function safeActiveElement() {
        try {
            return document.activeElement;
        } catch ( err ) { }
    }
    
    function on( elem, types, selector, data, fn, one ) {
        var origFn, type;
    
        // Types can be a map of types/handlers
        if ( typeof types === "object" ) {
    
            // ( types-Object, selector, data )
            if ( typeof selector !== "string" ) {
    
                // ( types-Object, data )
                data = data || selector;
                selector = undefined;
            }
            for ( type in types ) {
                on( elem, type, selector, data, types[ type ], one );
            }
            return elem;
        }
    
        if ( data == null && fn == null ) {
    
            // ( types, fn )
            fn = selector;
            data = selector = undefined;
        } else if ( fn == null ) {
            if ( typeof selector === "string" ) {
    
                // ( types, selector, fn )
                fn = data;
                data = undefined;
            } else {
    
                // ( types, data, fn )
                fn = data;
                data = selector;
                selector = undefined;
            }
        }
        if ( fn === false ) {
            fn = returnFalse;
        } else if ( !fn ) {
            return elem;
        }
    
        if ( one === 1 ) {
            origFn = fn;
            fn = function( event ) {
    
                // Can use an empty set, since event contains the info
                jQuery().off( event );
                return origFn.apply( this, arguments );
            };
    
            // Use same guid so caller can remove using origFn
            fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
        }
        return elem.each( function() {
            jQuery.event.add( this, types, fn, data, selector );
        } );
    }
    
    /*
     * Helper functions for managing events -- not part of the public interface.
     * Props to Dean Edwards' addEvent library for many of the ideas.
     */
    jQuery.event = {
    
        global: {},
    
        add: function( elem, types, handler, data, selector ) {
            var tmp, events, t, handleObjIn,
                special, eventHandle, handleObj,
                handlers, type, namespaces, origType,
                elemData = jQuery._data( elem );
    
            // Don't attach events to noData or text/comment nodes (but allow plain objects)
            if ( !elemData ) {
                return;
            }
    
            // Caller can pass in an object of custom data in lieu of the handler
            if ( handler.handler ) {
                handleObjIn = handler;
                handler = handleObjIn.handler;
                selector = handleObjIn.selector;
            }
    
            // Make sure that the handler has a unique ID, used to find/remove it later
            if ( !handler.guid ) {
                handler.guid = jQuery.guid++;
            }
    
            // Init the element's event structure and main handler, if this is the first
            if ( !( events = elemData.events ) ) {
                events = elemData.events = {};
            }
            if ( !( eventHandle = elemData.handle ) ) {
                eventHandle = elemData.handle = function( e ) {
    
                    // Discard the second event of a jQuery.event.trigger() and
                    // when an event is called after a page has unloaded
                    return typeof jQuery !== "undefined" &&
                        ( !e || jQuery.event.triggered !== e.type ) ?
                        jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
                        undefined;
                };
    
                // Add elem as a property of the handle fn to prevent a memory leak
                // with IE non-native events
                eventHandle.elem = elem;
            }
    
            // Handle multiple events separated by a space
            types = ( types || "" ).match( rnotwhite ) || [ "" ];
            t = types.length;
            while ( t-- ) {
                tmp = rtypenamespace.exec( types[ t ] ) || [];
                type = origType = tmp[ 1 ];
                namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
    
                // There *must* be a type, no attaching namespace-only handlers
                if ( !type ) {
                    continue;
                }
    
                // If event changes its type, use the special event handlers for the changed type
                special = jQuery.event.special[ type ] || {};
    
                // If selector defined, determine special event api type, otherwise given type
                type = ( selector ? special.delegateType : special.bindType ) || type;
    
                // Update special based on newly reset type
                special = jQuery.event.special[ type ] || {};
    
                // handleObj is passed to all event handlers
                handleObj = jQuery.extend( {
                    type: type,
                    origType: origType,
                    data: data,
                    handler: handler,
                    guid: handler.guid,
                    selector: selector,
                    needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
                    namespace: namespaces.join( "." )
                }, handleObjIn );
    
                // Init the event handler queue if we're the first
                if ( !( handlers = events[ type ] ) ) {
                    handlers = events[ type ] = [];
                    handlers.delegateCount = 0;
    
                    // Only use addEventListener/attachEvent if the special events handler returns false
                    if ( !special.setup ||
                        special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
    
                        // Bind the global event handler to the element
                        if ( elem.addEventListener ) {
                            elem.addEventListener( type, eventHandle, false );
    
                        } else if ( elem.attachEvent ) {
                            elem.attachEvent( "on" + type, eventHandle );
                        }
                    }
                }
    
                if ( special.add ) {
                    special.add.call( elem, handleObj );
    
                    if ( !handleObj.handler.guid ) {
                        handleObj.handler.guid = handler.guid;
                    }
                }
    
                // Add to the element's handler list, delegates in front
                if ( selector ) {
                    handlers.splice( handlers.delegateCount++, 0, handleObj );
                } else {
                    handlers.push( handleObj );
                }
    
                // Keep track of which events have ever been used, for event optimization
                jQuery.event.global[ type ] = true;
            }
    
            // Nullify elem to prevent memory leaks in IE
            elem = null;
        },
    
        // Detach an event or set of events from an element
        remove: function( elem, types, handler, selector, mappedTypes ) {
            var j, handleObj, tmp,
                origCount, t, events,
                special, handlers, type,
                namespaces, origType,
                elemData = jQuery.hasData( elem ) && jQuery._data( elem );
    
            if ( !elemData || !( events = elemData.events ) ) {
                return;
            }
    
            // Once for each type.namespace in types; type may be omitted
            types = ( types || "" ).match( rnotwhite ) || [ "" ];
            t = types.length;
            while ( t-- ) {
                tmp = rtypenamespace.exec( types[ t ] ) || [];
                type = origType = tmp[ 1 ];
                namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
    
                // Unbind all events (on this namespace, if provided) for the element
                if ( !type ) {
                    for ( type in events ) {
                        jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
                    }
                    continue;
                }
    
                special = jQuery.event.special[ type ] || {};
                type = ( selector ? special.delegateType : special.bindType ) || type;
                handlers = events[ type ] || [];
                tmp = tmp[ 2 ] &&
                    new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
    
                // Remove matching events
                origCount = j = handlers.length;
                while ( j-- ) {
                    handleObj = handlers[ j ];
    
                    if ( ( mappedTypes || origType === handleObj.origType ) &&
                        ( !handler || handler.guid === handleObj.guid ) &&
                        ( !tmp || tmp.test( handleObj.namespace ) ) &&
                        ( !selector || selector === handleObj.selector ||
                            selector === "**" && handleObj.selector ) ) {
                        handlers.splice( j, 1 );
    
                        if ( handleObj.selector ) {
                            handlers.delegateCount--;
                        }
                        if ( special.remove ) {
                            special.remove.call( elem, handleObj );
                        }
                    }
                }
    
                // Remove generic event handler if we removed something and no more handlers exist
                // (avoids potential for endless recursion during removal of special event handlers)
                if ( origCount && !handlers.length ) {
                    if ( !special.teardown ||
                        special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
    
                        jQuery.removeEvent( elem, type, elemData.handle );
                    }
    
                    delete events[ type ];
                }
            }
    
            // Remove the expando if it's no longer used
            if ( jQuery.isEmptyObject( events ) ) {
                delete elemData.handle;
    
                // removeData also checks for emptiness and clears the expando if empty
                // so use it instead of delete
                jQuery._removeData( elem, "events" );
            }
        },
    
        trigger: function( event, data, elem, onlyHandlers ) {
            var handle, ontype, cur,
                bubbleType, special, tmp, i,
                eventPath = [ elem || document ],
                type = hasOwn.call( event, "type" ) ? event.type : event,
                namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
    
            cur = tmp = elem = elem || document;
    
            // Don't do events on text and comment nodes
            if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
                return;
            }
    
            // focus/blur morphs to focusin/out; ensure we're not firing them right now
            if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
                return;
            }
    
            if ( type.indexOf( "." ) > -1 ) {
    
                // Namespaced trigger; create a regexp to match event type in handle()
                namespaces = type.split( "." );
                type = namespaces.shift();
                namespaces.sort();
            }
            ontype = type.indexOf( ":" ) < 0 && "on" + type;
    
            // Caller can pass in a jQuery.Event object, Object, or just an event type string
            event = event[ jQuery.expando ] ?
                event :
                new jQuery.Event( type, typeof event === "object" && event );
    
            // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
            event.isTrigger = onlyHandlers ? 2 : 3;
            event.namespace = namespaces.join( "." );
            event.rnamespace = event.namespace ?
                new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
                null;
    
            // Clean up the event in case it is being reused
            event.result = undefined;
            if ( !event.target ) {
                event.target = elem;
            }
    
            // Clone any incoming data and prepend the event, creating the handler arg list
            data = data == null ?
                [ event ] :
                jQuery.makeArray( data, [ event ] );
    
            // Allow special events to draw outside the lines
            special = jQuery.event.special[ type ] || {};
            if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
                return;
            }
    
            // Determine event propagation path in advance, per W3C events spec (#9951)
            // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
            if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
    
                bubbleType = special.delegateType || type;
                if ( !rfocusMorph.test( bubbleType + type ) ) {
                    cur = cur.parentNode;
                }
                for ( ; cur; cur = cur.parentNode ) {
                    eventPath.push( cur );
                    tmp = cur;
                }
    
                // Only add window if we got to document (e.g., not plain obj or detached DOM)
                if ( tmp === ( elem.ownerDocument || document ) ) {
                    eventPath.push( tmp.defaultView || tmp.parentWindow || window );
                }
            }
    
            // Fire handlers on the event path
            i = 0;
            while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
    
                event.type = i > 1 ?
                    bubbleType :
                    special.bindType || type;
    
                // jQuery handler
                handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] &&
                    jQuery._data( cur, "handle" );
    
                if ( handle ) {
                    handle.apply( cur, data );
                }
    
                // Native handler
                handle = ontype && cur[ ontype ];
                if ( handle && handle.apply && acceptData( cur ) ) {
                    event.result = handle.apply( cur, data );
                    if ( event.result === false ) {
                        event.preventDefault();
                    }
                }
            }
            event.type = type;
    
            // If nobody prevented the default action, do it now
            if ( !onlyHandlers && !event.isDefaultPrevented() ) {
    
                if (
                    ( !special._default ||
                     special._default.apply( eventPath.pop(), data ) === false
                    ) && acceptData( elem )
                ) {
    
                    // Call a native DOM method on the target with the same name name as the event.
                    // Can't use an .isFunction() check here because IE6/7 fails that test.
                    // Don't do default actions on window, that's where global variables be (#6170)
                    if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
    
                        // Don't re-trigger an onFOO event when we call its FOO() method
                        tmp = elem[ ontype ];
    
                        if ( tmp ) {
                            elem[ ontype ] = null;
                        }
    
                        // Prevent re-triggering of the same event, since we already bubbled it above
                        jQuery.event.triggered = type;
                        try {
                            elem[ type ]();
                        } catch ( e ) {
    
                            // IE<9 dies on focus/blur to hidden element (#1486,#12518)
                            // only reproducible on winXP IE8 native, not IE9 in IE8 mode
                        }
                        jQuery.event.triggered = undefined;
    
                        if ( tmp ) {
                            elem[ ontype ] = tmp;
                        }
                    }
                }
            }
    
            return event.result;
        },
    
        dispatch: function( event ) {
    
            // Make a writable jQuery.Event from the native event object
            event = jQuery.event.fix( event );
    
            var i, j, ret, matched, handleObj,
                handlerQueue = [],
                args = slice.call( arguments ),
                handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
                special = jQuery.event.special[ event.type ] || {};
    
            // Use the fix-ed jQuery.Event rather than the (read-only) native event
            args[ 0 ] = event;
            event.delegateTarget = this;
    
            // Call the preDispatch hook for the mapped type, and let it bail if desired
            if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
                return;
            }
    
            // Determine handlers
            handlerQueue = jQuery.event.handlers.call( this, event, handlers );
    
            // Run delegates first; they may want to stop propagation beneath us
            i = 0;
            while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
                event.currentTarget = matched.elem;
    
                j = 0;
                while ( ( handleObj = matched.handlers[ j++ ] ) &&
                    !event.isImmediatePropagationStopped() ) {
    
                    // Triggered event must either 1) have no namespace, or 2) have namespace(s)
                    // a subset or equal to those in the bound event (both can have no namespace).
                    if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
    
                        event.handleObj = handleObj;
                        event.data = handleObj.data;
    
                        ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
                            handleObj.handler ).apply( matched.elem, args );
    
                        if ( ret !== undefined ) {
                            if ( ( event.result = ret ) === false ) {
                                event.preventDefault();
                                event.stopPropagation();
                            }
                        }
                    }
                }
            }
    
            // Call the postDispatch hook for the mapped type
            if ( special.postDispatch ) {
                special.postDispatch.call( this, event );
            }
    
            return event.result;
        },
    
        handlers: function( event, handlers ) {
            var i, matches, sel, handleObj,
                handlerQueue = [],
                delegateCount = handlers.delegateCount,
                cur = event.target;
    
            // Support (at least): Chrome, IE9
            // Find delegate handlers
            // Black-hole SVG <use> instance trees (#13180)
            //
            // Support: Firefox<=42+
            // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
            if ( delegateCount && cur.nodeType &&
                ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
    
                /* jshint eqeqeq: false */
                for ( ; cur != this; cur = cur.parentNode || this ) {
                    /* jshint eqeqeq: true */
    
                    // Don't check non-elements (#13208)
                    // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
                    if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
                        matches = [];
                        for ( i = 0; i < delegateCount; i++ ) {
                            handleObj = handlers[ i ];
    
                            // Don't conflict with Object.prototype properties (#13203)
                            sel = handleObj.selector + " ";
    
                            if ( matches[ sel ] === undefined ) {
                                matches[ sel ] = handleObj.needsContext ?
                                    jQuery( sel, this ).index( cur ) > -1 :
                                    jQuery.find( sel, this, null, [ cur ] ).length;
                            }
                            if ( matches[ sel ] ) {
                                matches.push( handleObj );
                            }
                        }
                        if ( matches.length ) {
                            handlerQueue.push( { elem: cur, handlers: matches } );
                        }
                    }
                }
            }
    
            // Add the remaining (directly-bound) handlers
            if ( delegateCount < handlers.length ) {
                handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
            }
    
            return handlerQueue;
        },
    
        fix: function( event ) {
            if ( event[ jQuery.expando ] ) {
                return event;
            }
    
            // Create a writable copy of the event object and normalize some properties
            var i, prop, copy,
                type = event.type,
                originalEvent = event,
                fixHook = this.fixHooks[ type ];
    
            if ( !fixHook ) {
                this.fixHooks[ type ] = fixHook =
                    rmouseEvent.test( type ) ? this.mouseHooks :
                    rkeyEvent.test( type ) ? this.keyHooks :
                    {};
            }
            copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
    
            event = new jQuery.Event( originalEvent );
    
            i = copy.length;
            while ( i-- ) {
                prop = copy[ i ];
                event[ prop ] = originalEvent[ prop ];
            }
    
            // Support: IE<9
            // Fix target property (#1925)
            if ( !event.target ) {
                event.target = originalEvent.srcElement || document;
            }
    
            // Support: Safari 6-8+
            // Target should not be a text node (#504, #13143)
            if ( event.target.nodeType === 3 ) {
                event.target = event.target.parentNode;
            }
    
            // Support: IE<9
            // For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
            event.metaKey = !!event.metaKey;
    
            return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
        },
    
        // Includes some event props shared by KeyEvent and MouseEvent
        props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " +
            "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ),
    
        fixHooks: {},
    
        keyHooks: {
            props: "char charCode key keyCode".split( " " ),
            filter: function( event, original ) {
    
                // Add which for key events
                if ( event.which == null ) {
                    event.which = original.charCode != null ? original.charCode : original.keyCode;
                }
    
                return event;
            }
        },
    
        mouseHooks: {
            props: ( "button buttons clientX clientY fromElement offsetX offsetY " +
                "pageX pageY screenX screenY toElement" ).split( " " ),
            filter: function( event, original ) {
                var body, eventDoc, doc,
                    button = original.button,
                    fromElement = original.fromElement;
    
                // Calculate pageX/Y if missing and clientX/Y available
                if ( event.pageX == null && original.clientX != null ) {
                    eventDoc = event.target.ownerDocument || document;
                    doc = eventDoc.documentElement;
                    body = eventDoc.body;
    
                    event.pageX = original.clientX +
                        ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
                        ( doc && doc.clientLeft || body && body.clientLeft || 0 );
                    event.pageY = original.clientY +
                        ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) -
                        ( doc && doc.clientTop  || body && body.clientTop  || 0 );
                }
    
                // Add relatedTarget, if necessary
                if ( !event.relatedTarget && fromElement ) {
                    event.relatedTarget = fromElement === event.target ?
                        original.toElement :
                        fromElement;
                }
    
                // Add which for click: 1 === left; 2 === middle; 3 === right
                // Note: button is not normalized, so don't use it
                if ( !event.which && button !== undefined ) {
                    event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
                }
    
                return event;
            }
        },
    
        special: {
            load: {
    
                // Prevent triggered image.load events from bubbling to window.load
                noBubble: true
            },
            focus: {
    
                // Fire native event if possible so blur/focus sequence is correct
                trigger: function() {
                    if ( this !== safeActiveElement() && this.focus ) {
                        try {
                            this.focus();
                            return false;
                        } catch ( e ) {
    
                            // Support: IE<9
                            // If we error on focus to hidden element (#1486, #12518),
                            // let .trigger() run the handlers
                        }
                    }
                },
                delegateType: "focusin"
            },
            blur: {
                trigger: function() {
                    if ( this === safeActiveElement() && this.blur ) {
                        this.blur();
                        return false;
                    }
                },
                delegateType: "focusout"
            },
            click: {
    
                // For checkbox, fire native event so checked state will be right
                trigger: function() {
                    if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
                        this.click();
                        return false;
                    }
                },
    
                // For cross-browser consistency, don't fire native .click() on links
                _default: function( event ) {
                    return jQuery.nodeName( event.target, "a" );
                }
            },
    
            beforeunload: {
                postDispatch: function( event ) {
    
                    // Support: Firefox 20+
                    // Firefox doesn't alert if the returnValue field is not set.
                    if ( event.result !== undefined && event.originalEvent ) {
                        event.originalEvent.returnValue = event.result;
                    }
                }
            }
        },
    
        // Piggyback on a donor event to simulate a different one
        simulate: function( type, elem, event ) {
            var e = jQuery.extend(
                new jQuery.Event(),
                event,
                {
                    type: type,
                    isSimulated: true
    
                    // Previously, `originalEvent: {}` was set here, so stopPropagation call
                    // would not be triggered on donor event, since in our own
                    // jQuery.event.stopPropagation function we had a check for existence of
                    // originalEvent.stopPropagation method, so, consequently it would be a noop.
                    //
                    // Guard for simulated events was moved to jQuery.event.stopPropagation function
                    // since `originalEvent` should point to the original event for the
                    // constancy with other events and for more focused logic
                }
            );
    
            jQuery.event.trigger( e, null, elem );
    
            if ( e.isDefaultPrevented() ) {
                event.preventDefault();
            }
        }
    };
    
    jQuery.removeEvent = document.removeEventListener ?
        function( elem, type, handle ) {
    
            // This "if" is needed for plain objects
            if ( elem.removeEventListener ) {
                elem.removeEventListener( type, handle );
            }
        } :
        function( elem, type, handle ) {
            var name = "on" + type;
    
            if ( elem.detachEvent ) {
    
                // #8545, #7054, preventing memory leaks for custom events in IE6-8
                // detachEvent needed property on element, by name of that event,
                // to properly expose it to GC
                if ( typeof elem[ name ] === "undefined" ) {
                    elem[ name ] = null;
                }
    
                elem.detachEvent( name, handle );
            }
        };
    
    jQuery.Event = function( src, props ) {
    
        // Allow instantiation without the 'new' keyword
        if ( !( this instanceof jQuery.Event ) ) {
            return new jQuery.Event( src, props );
        }
    
        // Event object
        if ( src && src.type ) {
            this.originalEvent = src;
            this.type = src.type;
    
            // Events bubbling up the document may have been marked as prevented
            // by a handler lower down the tree; reflect the correct value.
            this.isDefaultPrevented = src.defaultPrevented ||
                    src.defaultPrevented === undefined &&
    
                    // Support: IE < 9, Android < 4.0
                    src.returnValue === false ?
                returnTrue :
                returnFalse;
    
        // Event type
        } else {
            this.type = src;
        }
    
        // Put explicitly provided properties onto the event object
        if ( props ) {
            jQuery.extend( this, props );
        }
    
        // Create a timestamp if incoming event doesn't have one
        this.timeStamp = src && src.timeStamp || jQuery.now();
    
        // Mark it as fixed
        this[ jQuery.expando ] = true;
    };
    
    // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
    // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
    jQuery.Event.prototype = {
        constructor: jQuery.Event,
        isDefaultPrevented: returnFalse,
        isPropagationStopped: returnFalse,
        isImmediatePropagationStopped: returnFalse,
    
        preventDefault: function() {
            var e = this.originalEvent;
    
            this.isDefaultPrevented = returnTrue;
            if ( !e ) {
                return;
            }
    
            // If preventDefault exists, run it on the original event
            if ( e.preventDefault ) {
                e.preventDefault();
    
            // Support: IE
            // Otherwise set the returnValue property of the original event to false
            } else {
                e.returnValue = false;
            }
        },
        stopPropagation: function() {
            var e = this.originalEvent;
    
            this.isPropagationStopped = returnTrue;
    
            if ( !e || this.isSimulated ) {
                return;
            }
    
            // If stopPropagation exists, run it on the original event
            if ( e.stopPropagation ) {
                e.stopPropagation();
            }
    
            // Support: IE
            // Set the cancelBubble property of the original event to true
            e.cancelBubble = true;
        },
        stopImmediatePropagation: function() {
            var e = this.originalEvent;
    
            this.isImmediatePropagationStopped = returnTrue;
    
            if ( e && e.stopImmediatePropagation ) {
                e.stopImmediatePropagation();
            }
    
            this.stopPropagation();
        }
    };
    
    // Create mouseenter/leave events using mouseover/out and event-time checks
    // so that event delegation works in jQuery.
    // Do the same for pointerenter/pointerleave and pointerover/pointerout
    //
    // Support: Safari 7 only
    // Safari sends mouseenter too often; see:
    // https://code.google.com/p/chromium/issues/detail?id=470258
    // for the description of the bug (it existed in older Chrome versions as well).
    jQuery.each( {
        mouseenter: "mouseover",
        mouseleave: "mouseout",
        pointerenter: "pointerover",
        pointerleave: "pointerout"
    }, function( orig, fix ) {
        jQuery.event.special[ orig ] = {
            delegateType: fix,
            bindType: fix,
    
            handle: function( event ) {
                var ret,
                    target = this,
                    related = event.relatedTarget,
                    handleObj = event.handleObj;
    
                // For mouseenter/leave call the handler if related is outside the target.
                // NB: No relatedTarget if the mouse left/entered the browser window
                if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
                    event.type = handleObj.origType;
                    ret = handleObj.handler.apply( this, arguments );
                    event.type = fix;
                }
                return ret;
            }
        };
    } );
    
    // IE submit delegation
    if ( !support.submit ) {
    
        jQuery.event.special.submit = {
            setup: function() {
    
                // Only need this for delegated form submit events
                if ( jQuery.nodeName( this, "form" ) ) {
                    return false;
                }
    
                // Lazy-add a submit handler when a descendant form may potentially be submitted
                jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
    
                    // Node name check avoids a VML-related crash in IE (#9807)
                    var elem = e.target,
                        form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ?
    
                            // Support: IE <=8
                            // We use jQuery.prop instead of elem.form
                            // to allow fixing the IE8 delegated submit issue (gh-2332)
                            // by 3rd party polyfills/workarounds.
                            jQuery.prop( elem, "form" ) :
                            undefined;
    
                    if ( form && !jQuery._data( form, "submit" ) ) {
                        jQuery.event.add( form, "submit._submit", function( event ) {
                            event._submitBubble = true;
                        } );
                        jQuery._data( form, "submit", true );
                    }
                } );
    
                // return undefined since we don't need an event listener
            },
    
            postDispatch: function( event ) {
    
                // If form was submitted by the user, bubble the event up the tree
                if ( event._submitBubble ) {
                    delete event._submitBubble;
                    if ( this.parentNode && !event.isTrigger ) {
                        jQuery.event.simulate( "submit", this.parentNode, event );
                    }
                }
            },
    
            teardown: function() {
    
                // Only need this for delegated form submit events
                if ( jQuery.nodeName( this, "form" ) ) {
                    return false;
                }
    
                // Remove delegated handlers; cleanData eventually reaps submit handlers attached above
                jQuery.event.remove( this, "._submit" );
            }
        };
    }
    
    // IE change delegation and checkbox/radio fix
    if ( !support.change ) {
    
        jQuery.event.special.change = {
    
            setup: function() {
    
                if ( rformElems.test( this.nodeName ) ) {
    
                    // IE doesn't fire change on a check/radio until blur; trigger it on click
                    // after a propertychange. Eat the blur-change in special.change.handle.
                    // This still fires onchange a second time for check/radio after blur.
                    if ( this.type === "checkbox" || this.type === "radio" ) {
                        jQuery.event.add( this, "propertychange._change", function( event ) {
                            if ( event.originalEvent.propertyName === "checked" ) {
                                this._justChanged = true;
                            }
                        } );
                        jQuery.event.add( this, "click._change", function( event ) {
                            if ( this._justChanged && !event.isTrigger ) {
                                this._justChanged = false;
                            }
    
                            // Allow triggered, simulated change events (#11500)
                            jQuery.event.simulate( "change", this, event );
                        } );
                    }
                    return false;
                }
    
                // Delegated event; lazy-add a change handler on descendant inputs
                jQuery.event.add( this, "beforeactivate._change", function( e ) {
                    var elem = e.target;
    
                    if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "change" ) ) {
                        jQuery.event.add( elem, "change._change", function( event ) {
                            if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
                                jQuery.event.simulate( "change", this.parentNode, event );
                            }
                        } );
                        jQuery._data( elem, "change", true );
                    }
                } );
            },
    
            handle: function( event ) {
                var elem = event.target;
    
                // Swallow native change events from checkbox/radio, we already triggered them above
                if ( this !== elem || event.isSimulated || event.isTrigger ||
                    ( elem.type !== "radio" && elem.type !== "checkbox" ) ) {
    
                    return event.handleObj.handler.apply( this, arguments );
                }
            },
    
            teardown: function() {
                jQuery.event.remove( this, "._change" );
    
                return !rformElems.test( this.nodeName );
            }
        };
    }
    
    // Support: Firefox
    // Firefox doesn't have focus(in | out) events
    // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
    //
    // Support: Chrome, Safari
    // focus(in | out) events fire after focus & blur events,
    // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
    // Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857
    if ( !support.focusin ) {
        jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
    
            // Attach a single capturing handler on the document while someone wants focusin/focusout
            var handler = function( event ) {
                jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
            };
    
            jQuery.event.special[ fix ] = {
                setup: function() {
                    var doc = this.ownerDocument || this,
                        attaches = jQuery._data( doc, fix );
    
                    if ( !attaches ) {
                        doc.addEventListener( orig, handler, true );
                    }
                    jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
                },
                teardown: function() {
                    var doc = this.ownerDocument || this,
                        attaches = jQuery._data( doc, fix ) - 1;
    
                    if ( !attaches ) {
                        doc.removeEventListener( orig, handler, true );
                        jQuery._removeData( doc, fix );
                    } else {
                        jQuery._data( doc, fix, attaches );
                    }
                }
            };
        } );
    }
    
    jQuery.fn.extend( {
    
        on: function( types, selector, data, fn ) {
            return on( this, types, selector, data, fn );
        },
        one: function( types, selector, data, fn ) {
            return on( this, types, selector, data, fn, 1 );
        },
        off: function( types, selector, fn ) {
            var handleObj, type;
            if ( types && types.preventDefault && types.handleObj ) {
    
                // ( event )  dispatched jQuery.Event
                handleObj = types.handleObj;
                jQuery( types.delegateTarget ).off(
                    handleObj.namespace ?
                        handleObj.origType + "." + handleObj.namespace :
                        handleObj.origType,
                    handleObj.selector,
                    handleObj.handler
                );
                return this;
            }
            if ( typeof types === "object" ) {
    
                // ( types-object [, selector] )
                for ( type in types ) {
                    this.off( type, selector, types[ type ] );
                }
                return this;
            }
            if ( selector === false || typeof selector === "function" ) {
    
                // ( types [, fn] )
                fn = selector;
                selector = undefined;
            }
            if ( fn === false ) {
                fn = returnFalse;
            }
            return this.each( function() {
                jQuery.event.remove( this, types, fn, selector );
            } );
        },
    
        trigger: function( type, data ) {
            return this.each( function() {
                jQuery.event.trigger( type, data, this );
            } );
        },
        triggerHandler: function( type, data ) {
            var elem = this[ 0 ];
            if ( elem ) {
                return jQuery.event.trigger( type, data, elem, true );
            }
        }
    } );
    
    
    var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
        rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ),
        rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
    
        // Support: IE 10-11, Edge 10240+
        // In IE/Edge using regex groups here causes severe slowdowns.
        // See https://connect.microsoft.com/IE/feedback/details/1736512/
        rnoInnerhtml = /<script|<style|<link/i,
    
        // checked="checked" or checked
        rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
        rscriptTypeMasked = /^true\/(.*)/,
        rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
        safeFragment = createSafeFragment( document ),
        fragmentDiv = safeFragment.appendChild( document.createElement( "div" ) );
    
    // Support: IE<8
    // Manipulating tables requires a tbody
    function manipulationTarget( elem, content ) {
        return jQuery.nodeName( elem, "table" ) &&
            jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
    
            elem.getElementsByTagName( "tbody" )[ 0 ] ||
                elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) :
            elem;
    }
    
    // Replace/restore the type attribute of script elements for safe DOM manipulation
    function disableScript( elem ) {
        elem.type = ( jQuery.find.attr( elem, "type" ) !== null ) + "/" + elem.type;
        return elem;
    }
    function restoreScript( elem ) {
        var match = rscriptTypeMasked.exec( elem.type );
        if ( match ) {
            elem.type = match[ 1 ];
        } else {
            elem.removeAttribute( "type" );
        }
        return elem;
    }
    
    function cloneCopyEvent( src, dest ) {
        if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
            return;
        }
    
        var type, i, l,
            oldData = jQuery._data( src ),
            curData = jQuery._data( dest, oldData ),
            events = oldData.events;
    
        if ( events ) {
            delete curData.handle;
            curData.events = {};
    
            for ( type in events ) {
                for ( i = 0, l = events[ type ].length; i < l; i++ ) {
                    jQuery.event.add( dest, type, events[ type ][ i ] );
                }
            }
        }
    
        // make the cloned public data object a copy from the original
        if ( curData.data ) {
            curData.data = jQuery.extend( {}, curData.data );
        }
    }
    
    function fixCloneNodeIssues( src, dest ) {
        var nodeName, e, data;
    
        // We do not need to do anything for non-Elements
        if ( dest.nodeType !== 1 ) {
            return;
        }
    
        nodeName = dest.nodeName.toLowerCase();
    
        // IE6-8 copies events bound via attachEvent when using cloneNode.
        if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
            data = jQuery._data( dest );
    
            for ( e in data.events ) {
                jQuery.removeEvent( dest, e, data.handle );
            }
    
            // Event data gets referenced instead of copied if the expando gets copied too
            dest.removeAttribute( jQuery.expando );
        }
    
        // IE blanks contents when cloning scripts, and tries to evaluate newly-set text
        if ( nodeName === "script" && dest.text !== src.text ) {
            disableScript( dest ).text = src.text;
            restoreScript( dest );
    
        // IE6-10 improperly clones children of object elements using classid.
        // IE10 throws NoModificationAllowedError if parent is null, #12132.
        } else if ( nodeName === "object" ) {
            if ( dest.parentNode ) {
                dest.outerHTML = src.outerHTML;
            }
    
            // This path appears unavoidable for IE9. When cloning an object
            // element in IE9, the outerHTML strategy above is not sufficient.
            // If the src has innerHTML and the destination does not,
            // copy the src.innerHTML into the dest.innerHTML. #10324
            if ( support.html5Clone && ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) ) {
                dest.innerHTML = src.innerHTML;
            }
    
        } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
    
            // IE6-8 fails to persist the checked state of a cloned checkbox
            // or radio button. Worse, IE6-7 fail to give the cloned element
            // a checked appearance if the defaultChecked value isn't also set
    
            dest.defaultChecked = dest.checked = src.checked;
    
            // IE6-7 get confused and end up setting the value of a cloned
            // checkbox/radio button to an empty string instead of "on"
            if ( dest.value !== src.value ) {
                dest.value = src.value;
            }
    
        // IE6-8 fails to return the selected option to the default selected
        // state when cloning options
        } else if ( nodeName === "option" ) {
            dest.defaultSelected = dest.selected = src.defaultSelected;
    
        // IE6-8 fails to set the defaultValue to the correct value when
        // cloning other types of input fields
        } else if ( nodeName === "input" || nodeName === "textarea" ) {
            dest.defaultValue = src.defaultValue;
        }
    }
    
    function domManip( collection, args, callback, ignored ) {
    
        // Flatten any nested arrays
        args = concat.apply( [], args );
    
        var first, node, hasScripts,
            scripts, doc, fragment,
            i = 0,
            l = collection.length,
            iNoClone = l - 1,
            value = args[ 0 ],
            isFunction = jQuery.isFunction( value );
    
        // We can't cloneNode fragments that contain checked, in WebKit
        if ( isFunction ||
                ( l > 1 && typeof value === "string" &&
                    !support.checkClone && rchecked.test( value ) ) ) {
            return collection.each( function( index ) {
                var self = collection.eq( index );
                if ( isFunction ) {
                    args[ 0 ] = value.call( this, index, self.html() );
                }
                domManip( self, args, callback, ignored );
            } );
        }
    
        if ( l ) {
            fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
            first = fragment.firstChild;
    
            if ( fragment.childNodes.length === 1 ) {
                fragment = first;
            }
    
            // Require either new content or an interest in ignored elements to invoke the callback
            if ( first || ignored ) {
                scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
                hasScripts = scripts.length;
    
                // Use the original fragment for the last item
                // instead of the first because it can end up
                // being emptied incorrectly in certain situations (#8070).
                for ( ; i < l; i++ ) {
                    node = fragment;
    
                    if ( i !== iNoClone ) {
                        node = jQuery.clone( node, true, true );
    
                        // Keep references to cloned scripts for later restoration
                        if ( hasScripts ) {
    
                            // Support: Android<4.1, PhantomJS<2
                            // push.apply(_, arraylike) throws on ancient WebKit
                            jQuery.merge( scripts, getAll( node, "script" ) );
                        }
                    }
    
                    callback.call( collection[ i ], node, i );
                }
    
                if ( hasScripts ) {
                    doc = scripts[ scripts.length - 1 ].ownerDocument;
    
                    // Reenable scripts
                    jQuery.map( scripts, restoreScript );
    
                    // Evaluate executable scripts on first document insertion
                    for ( i = 0; i < hasScripts; i++ ) {
                        node = scripts[ i ];
                        if ( rscriptType.test( node.type || "" ) &&
                            !jQuery._data( node, "globalEval" ) &&
                            jQuery.contains( doc, node ) ) {
    
                            if ( node.src ) {
    
                                // Optional AJAX dependency, but won't run scripts if not present
                                if ( jQuery._evalUrl ) {
                                    jQuery._evalUrl( node.src );
                                }
                            } else {
                                jQuery.globalEval(
                                    ( node.text || node.textContent || node.innerHTML || "" )
                                        .replace( rcleanScript, "" )
                                );
                            }
                        }
                    }
                }
    
                // Fix #11809: Avoid leaking memory
                fragment = first = null;
            }
        }
    
        return collection;
    }
    
    function remove( elem, selector, keepData ) {
        var node,
            elems = selector ? jQuery.filter( selector, elem ) : elem,
            i = 0;
    
        for ( ; ( node = elems[ i ] ) != null; i++ ) {
    
            if ( !keepData && node.nodeType === 1 ) {
                jQuery.cleanData( getAll( node ) );
            }
    
            if ( node.parentNode ) {
                if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
                    setGlobalEval( getAll( node, "script" ) );
                }
                node.parentNode.removeChild( node );
            }
        }
    
        return elem;
    }
    
    jQuery.extend( {
        htmlPrefilter: function( html ) {
            return html.replace( rxhtmlTag, "<$1></$2>" );
        },
    
        clone: function( elem, dataAndEvents, deepDataAndEvents ) {
            var destElements, node, clone, i, srcElements,
                inPage = jQuery.contains( elem.ownerDocument, elem );
    
            if ( support.html5Clone || jQuery.isXMLDoc( elem ) ||
                !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
    
                clone = elem.cloneNode( true );
    
            // IE<=8 does not properly clone detached, unknown element nodes
            } else {
                fragmentDiv.innerHTML = elem.outerHTML;
                fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
            }
    
            if ( ( !support.noCloneEvent || !support.noCloneChecked ) &&
                    ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {
    
                // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
                destElements = getAll( clone );
                srcElements = getAll( elem );
    
                // Fix all IE cloning issues
                for ( i = 0; ( node = srcElements[ i ] ) != null; ++i ) {
    
                    // Ensure that the destination node is not null; Fixes #9587
                    if ( destElements[ i ] ) {
                        fixCloneNodeIssues( node, destElements[ i ] );
                    }
                }
            }
    
            // Copy the events from the original to the clone
            if ( dataAndEvents ) {
                if ( deepDataAndEvents ) {
                    srcElements = srcElements || getAll( elem );
                    destElements = destElements || getAll( clone );
    
                    for ( i = 0; ( node = srcElements[ i ] ) != null; i++ ) {
                        cloneCopyEvent( node, destElements[ i ] );
                    }
                } else {
                    cloneCopyEvent( elem, clone );
                }
            }
    
            // Preserve script evaluation history
            destElements = getAll( clone, "script" );
            if ( destElements.length > 0 ) {
                setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
            }
    
            destElements = srcElements = node = null;
    
            // Return the cloned set
            return clone;
        },
    
        cleanData: function( elems, /* internal */ forceAcceptData ) {
            var elem, type, id, data,
                i = 0,
                internalKey = jQuery.expando,
                cache = jQuery.cache,
                attributes = support.attributes,
                special = jQuery.event.special;
    
            for ( ; ( elem = elems[ i ] ) != null; i++ ) {
                if ( forceAcceptData || acceptData( elem ) ) {
    
                    id = elem[ internalKey ];
                    data = id && cache[ id ];
    
                    if ( data ) {
                        if ( data.events ) {
                            for ( type in data.events ) {
                                if ( special[ type ] ) {
                                    jQuery.event.remove( elem, type );
    
                                // This is a shortcut to avoid jQuery.event.remove's overhead
                                } else {
                                    jQuery.removeEvent( elem, type, data.handle );
                                }
                            }
                        }
    
                        // Remove cache only if it was not already removed by jQuery.event.remove
                        if ( cache[ id ] ) {
    
                            delete cache[ id ];
    
                            // Support: IE<9
                            // IE does not allow us to delete expando properties from nodes
                            // IE creates expando attributes along with the property
                            // IE does not have a removeAttribute function on Document nodes
                            if ( !attributes && typeof elem.removeAttribute !== "undefined" ) {
                                elem.removeAttribute( internalKey );
    
                            // Webkit & Blink performance suffers when deleting properties
                            // from DOM nodes, so set to undefined instead
                            // https://code.google.com/p/chromium/issues/detail?id=378607
                            } else {
                                elem[ internalKey ] = undefined;
                            }
    
                            deletedIds.push( id );
                        }
                    }
                }
            }
        }
    } );
    
    jQuery.fn.extend( {
    
        // Keep domManip exposed until 3.0 (gh-2225)
        domManip: domManip,
    
        detach: function( selector ) {
            return remove( this, selector, true );
        },
    
        remove: function( selector ) {
            return remove( this, selector );
        },
    
        text: function( value ) {
            return access( this, function( value ) {
                return value === undefined ?
                    jQuery.text( this ) :
                    this.empty().append(
                        ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value )
                    );
            }, null, value, arguments.length );
        },
    
        append: function() {
            return domManip( this, arguments, function( elem ) {
                if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
                    var target = manipulationTarget( this, elem );
                    target.appendChild( elem );
                }
            } );
        },
    
        prepend: function() {
            return domManip( this, arguments, function( elem ) {
                if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
                    var target = manipulationTarget( this, elem );
                    target.insertBefore( elem, target.firstChild );
                }
            } );
        },
    
        before: function() {
            return domManip( this, arguments, function( elem ) {
                if ( this.parentNode ) {
                    this.parentNode.insertBefore( elem, this );
                }
            } );
        },
    
        after: function() {
            return domManip( this, arguments, function( elem ) {
                if ( this.parentNode ) {
                    this.parentNode.insertBefore( elem, this.nextSibling );
                }
            } );
        },
    
        empty: function() {
            var elem,
                i = 0;
    
            for ( ; ( elem = this[ i ] ) != null; i++ ) {
    
                // Remove element nodes and prevent memory leaks
                if ( elem.nodeType === 1 ) {
                    jQuery.cleanData( getAll( elem, false ) );
                }
    
                // Remove any remaining nodes
                while ( elem.firstChild ) {
                    elem.removeChild( elem.firstChild );
                }
    
                // If this is a select, ensure that it displays empty (#12336)
                // Support: IE<9
                if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
                    elem.options.length = 0;
                }
            }
    
            return this;
        },
    
        clone: function( dataAndEvents, deepDataAndEvents ) {
            dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
            deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
    
            return this.map( function() {
                return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
            } );
        },
    
        html: function( value ) {
            return access( this, function( value ) {
                var elem = this[ 0 ] || {},
                    i = 0,
                    l = this.length;
    
                if ( value === undefined ) {
                    return elem.nodeType === 1 ?
                        elem.innerHTML.replace( rinlinejQuery, "" ) :
                        undefined;
                }
    
                // See if we can take a shortcut and just use innerHTML
                if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
                    ( support.htmlSerialize || !rnoshimcache.test( value )  ) &&
                    ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
                    !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
    
                    value = jQuery.htmlPrefilter( value );
    
                    try {
                        for ( ; i < l; i++ ) {
    
                            // Remove element nodes and prevent memory leaks
                            elem = this[ i ] || {};
                            if ( elem.nodeType === 1 ) {
                                jQuery.cleanData( getAll( elem, false ) );
                                elem.innerHTML = value;
                            }
                        }
    
                        elem = 0;
    
                    // If using innerHTML throws an exception, use the fallback method
                    } catch ( e ) {}
                }
    
                if ( elem ) {
                    this.empty().append( value );
                }
            }, null, value, arguments.length );
        },
    
        replaceWith: function() {
            var ignored = [];
    
            // Make the changes, replacing each non-ignored context element with the new content
            return domManip( this, arguments, function( elem ) {
                var parent = this.parentNode;
    
                if ( jQuery.inArray( this, ignored ) < 0 ) {
                    jQuery.cleanData( getAll( this ) );
                    if ( parent ) {
                        parent.replaceChild( elem, this );
                    }
                }
    
            // Force callback invocation
            }, ignored );
        }
    } );
    
    jQuery.each( {
        appendTo: "append",
        prependTo: "prepend",
        insertBefore: "before",
        insertAfter: "after",
        replaceAll: "replaceWith"
    }, function( name, original ) {
        jQuery.fn[ name ] = function( selector ) {
            var elems,
                i = 0,
                ret = [],
                insert = jQuery( selector ),
                last = insert.length - 1;
    
            for ( ; i <= last; i++ ) {
                elems = i === last ? this : this.clone( true );
                jQuery( insert[ i ] )[ original ]( elems );
    
                // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
                push.apply( ret, elems.get() );
            }
    
            return this.pushStack( ret );
        };
    } );
    
    
    var iframe,
        elemdisplay = {
    
            // Support: Firefox
            // We have to pre-define these values for FF (#10227)
            HTML: "block",
            BODY: "block"
        };
    
    /**
     * Retrieve the actual display of a element
     * @param {String} name nodeName of the element
     * @param {Object} doc Document object
     */
    
    // Called only from within defaultDisplay
    function actualDisplay( name, doc ) {
        var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
    
            display = jQuery.css( elem[ 0 ], "display" );
    
        // We don't have any data stored on the element,
        // so use "detach" method as fast way to get rid of the element
        elem.detach();
    
        return display;
    }
    
    /**
     * Try to determine the default display value of an element
     * @param {String} nodeName
     */
    function defaultDisplay( nodeName ) {
        var doc = document,
            display = elemdisplay[ nodeName ];
    
        if ( !display ) {
            display = actualDisplay( nodeName, doc );
    
            // If the simple way fails, read from inside an iframe
            if ( display === "none" || !display ) {
    
                // Use the already-created iframe if possible
                iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) )
                    .appendTo( doc.documentElement );
    
                // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
                doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
    
                // Support: IE
                doc.write();
                doc.close();
    
                display = actualDisplay( nodeName, doc );
                iframe.detach();
            }
    
            // Store the correct default display
            elemdisplay[ nodeName ] = display;
        }
    
        return display;
    }
    var rmargin = ( /^margin/ );
    
    var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
    
    var swap = function( elem, options, callback, args ) {
        var ret, name,
            old = {};
    
        // Remember the old values, and insert the new ones
        for ( name in options ) {
            old[ name ] = elem.style[ name ];
            elem.style[ name ] = options[ name ];
        }
    
        ret = callback.apply( elem, args || [] );
    
        // Revert the old values
        for ( name in options ) {
            elem.style[ name ] = old[ name ];
        }
    
        return ret;
    };
    
    
    var documentElement = document.documentElement;
    
    
    
    ( function() {
        var pixelPositionVal, pixelMarginRightVal, boxSizingReliableVal,
            reliableHiddenOffsetsVal, reliableMarginRightVal, reliableMarginLeftVal,
            container = document.createElement( "div" ),
            div = document.createElement( "div" );
    
        // Finish early in limited (non-browser) environments
        if ( !div.style ) {
            return;
        }
    
        div.style.cssText = "float:left;opacity:.5";
    
        // Support: IE<9
        // Make sure that element opacity exists (as opposed to filter)
        support.opacity = div.style.opacity === "0.5";
    
        // Verify style float existence
        // (IE uses styleFloat instead of cssFloat)
        support.cssFloat = !!div.style.cssFloat;
    
        div.style.backgroundClip = "content-box";
        div.cloneNode( true ).style.backgroundClip = "";
        support.clearCloneStyle = div.style.backgroundClip === "content-box";
    
        container = document.createElement( "div" );
        container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
            "padding:0;margin-top:1px;position:absolute";
        div.innerHTML = "";
        container.appendChild( div );
    
        // Support: Firefox<29, Android 2.3
        // Vendor-prefix box-sizing
        support.boxSizing = div.style.boxSizing === "" || div.style.MozBoxSizing === "" ||
            div.style.WebkitBoxSizing === "";
    
        jQuery.extend( support, {
            reliableHiddenOffsets: function() {
                if ( pixelPositionVal == null ) {
                    computeStyleTests();
                }
                return reliableHiddenOffsetsVal;
            },
    
            boxSizingReliable: function() {
    
                // We're checking for pixelPositionVal here instead of boxSizingReliableVal
                // since that compresses better and they're computed together anyway.
                if ( pixelPositionVal == null ) {
                    computeStyleTests();
                }
                return boxSizingReliableVal;
            },
    
            pixelMarginRight: function() {
    
                // Support: Android 4.0-4.3
                if ( pixelPositionVal == null ) {
                    computeStyleTests();
                }
                return pixelMarginRightVal;
            },
    
            pixelPosition: function() {
                if ( pixelPositionVal == null ) {
                    computeStyleTests();
                }
                return pixelPositionVal;
            },
    
            reliableMarginRight: function() {
    
                // Support: Android 2.3
                if ( pixelPositionVal == null ) {
                    computeStyleTests();
                }
                return reliableMarginRightVal;
            },
    
            reliableMarginLeft: function() {
    
                // Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37
                if ( pixelPositionVal == null ) {
                    computeStyleTests();
                }
                return reliableMarginLeftVal;
            }
        } );
    
        function computeStyleTests() {
            var contents, divStyle,
                documentElement = document.documentElement;
    
            // Setup
            documentElement.appendChild( container );
    
            div.style.cssText =
    
                // Support: Android 2.3
                // Vendor-prefix box-sizing
                "-webkit-box-sizing:border-box;box-sizing:border-box;" +
                "position:relative;display:block;" +
                "margin:auto;border:1px;padding:1px;" +
                "top:1%;width:50%";
    
            // Support: IE<9
            // Assume reasonable values in the absence of getComputedStyle
            pixelPositionVal = boxSizingReliableVal = reliableMarginLeftVal = false;
            pixelMarginRightVal = reliableMarginRightVal = true;
    
            // Check for getComputedStyle so that this code is not run in IE<9.
            if ( window.getComputedStyle ) {
                divStyle = window.getComputedStyle( div );
                pixelPositionVal = ( divStyle || {} ).top !== "1%";
                reliableMarginLeftVal = ( divStyle || {} ).marginLeft === "2px";
                boxSizingReliableVal = ( divStyle || { width: "4px" } ).width === "4px";
    
                // Support: Android 4.0 - 4.3 only
                // Some styles come back with percentage values, even though they shouldn't
                div.style.marginRight = "50%";
                pixelMarginRightVal = ( divStyle || { marginRight: "4px" } ).marginRight === "4px";
    
                // Support: Android 2.3 only
                // Div with explicit width and no margin-right incorrectly
                // gets computed margin-right based on width of container (#3333)
                // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
                contents = div.appendChild( document.createElement( "div" ) );
    
                // Reset CSS: box-sizing; display; margin; border; padding
                contents.style.cssText = div.style.cssText =
    
                    // Support: Android 2.3
                    // Vendor-prefix box-sizing
                    "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
                    "box-sizing:content-box;display:block;margin:0;border:0;padding:0";
                contents.style.marginRight = contents.style.width = "0";
                div.style.width = "1px";
    
                reliableMarginRightVal =
                    !parseFloat( ( window.getComputedStyle( contents ) || {} ).marginRight );
    
                div.removeChild( contents );
            }
    
            // Support: IE6-8
            // First check that getClientRects works as expected
            // Check if table cells still have offsetWidth/Height when they are set
            // to display:none and there are still other visible table cells in a
            // table row; if so, offsetWidth/Height are not reliable for use when
            // determining if an element has been hidden directly using
            // display:none (it is still safe to use offsets if a parent element is
            // hidden; don safety goggles and see bug #4512 for more information).
            div.style.display = "none";
            reliableHiddenOffsetsVal = div.getClientRects().length === 0;
            if ( reliableHiddenOffsetsVal ) {
                div.style.display = "";
                div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
                div.childNodes[ 0 ].style.borderCollapse = "separate";
                contents = div.getElementsByTagName( "td" );
                contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
                reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
                if ( reliableHiddenOffsetsVal ) {
                    contents[ 0 ].style.display = "";
                    contents[ 1 ].style.display = "none";
                    reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
                }
            }
    
            // Teardown
            documentElement.removeChild( container );
        }
    
    } )();
    
    
    var getStyles, curCSS,
        rposition = /^(top|right|bottom|left)$/;
    
    if ( window.getComputedStyle ) {
        getStyles = function( elem ) {
    
            // Support: IE<=11+, Firefox<=30+ (#15098, #14150)
            // IE throws on elements created in popups
            // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
            var view = elem.ownerDocument.defaultView;
    
            if ( !view || !view.opener ) {
                view = window;
            }
    
            return view.getComputedStyle( elem );
        };
    
        curCSS = function( elem, name, computed ) {
            var width, minWidth, maxWidth, ret,
                style = elem.style;
    
            computed = computed || getStyles( elem );
    
            // getPropertyValue is only needed for .css('filter') in IE9, see #12537
            ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
    
            // Support: Opera 12.1x only
            // Fall back to style even without computed
            // computed is undefined for elems on document fragments
            if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) {
                ret = jQuery.style( elem, name );
            }
    
            if ( computed ) {
    
                // A tribute to the "awesome hack by Dean Edwards"
                // Chrome < 17 and Safari 5.0 uses "computed value"
                // instead of "used value" for margin-right
                // Safari 5.1.7 (at least) returns percentage for a larger set of values,
                // but width seems to be reliably pixels
                // this is against the CSSOM draft spec:
                // http://dev.w3.org/csswg/cssom/#resolved-values
                if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
    
                    // Remember the original values
                    width = style.width;
                    minWidth = style.minWidth;
                    maxWidth = style.maxWidth;
    
                    // Put in the new values to get a computed value out
                    style.minWidth = style.maxWidth = style.width = ret;
                    ret = computed.width;
    
                    // Revert the changed values
                    style.width = width;
                    style.minWidth = minWidth;
                    style.maxWidth = maxWidth;
                }
            }
    
            // Support: IE
            // IE returns zIndex value as an integer.
            return ret === undefined ?
                ret :
                ret + "";
        };
    } else if ( documentElement.currentStyle ) {
        getStyles = function( elem ) {
            return elem.currentStyle;
        };
    
        curCSS = function( elem, name, computed ) {
            var left, rs, rsLeft, ret,
                style = elem.style;
    
            computed = computed || getStyles( elem );
            ret = computed ? computed[ name ] : undefined;
    
            // Avoid setting ret to empty string here
            // so we don't default to auto
            if ( ret == null && style && style[ name ] ) {
                ret = style[ name ];
            }
    
            // From the awesome hack by Dean Edwards
            // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
    
            // If we're not dealing with a regular pixel number
            // but a number that has a weird ending, we need to convert it to pixels
            // but not position css attributes, as those are
            // proportional to the parent element instead
            // and we can't measure the parent instead because it
            // might trigger a "stacking dolls" problem
            if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
    
                // Remember the original values
                left = style.left;
                rs = elem.runtimeStyle;
                rsLeft = rs && rs.left;
    
                // Put in the new values to get a computed value out
                if ( rsLeft ) {
                    rs.left = elem.currentStyle.left;
                }
                style.left = name === "fontSize" ? "1em" : ret;
                ret = style.pixelLeft + "px";
    
                // Revert the changed values
                style.left = left;
                if ( rsLeft ) {
                    rs.left = rsLeft;
                }
            }
    
            // Support: IE
            // IE returns zIndex value as an integer.
            return ret === undefined ?
                ret :
                ret + "" || "auto";
        };
    }
    
    
    
    
    function addGetHookIf( conditionFn, hookFn ) {
    
        // Define the hook, we'll check on the first run if it's really needed.
        return {
            get: function() {
                if ( conditionFn() ) {
    
                    // Hook not needed (or it's not possible to use it due
                    // to missing dependency), remove it.
                    delete this.get;
                    return;
                }
    
                // Hook needed; redefine it so that the support test is not executed again.
                return ( this.get = hookFn ).apply( this, arguments );
            }
        };
    }
    
    
    var
    
            ralpha = /alpha\([^)]*\)/i,
        ropacity = /opacity\s*=\s*([^)]*)/i,
    
        // swappable if display is none or starts with table except
        // "table", "table-cell", or "table-caption"
        // see here for display values:
        // https://developer.mozilla.org/en-US/docs/CSS/display
        rdisplayswap = /^(none|table(?!-c[ea]).+)/,
        rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
    
        cssShow = { position: "absolute", visibility: "hidden", display: "block" },
        cssNormalTransform = {
            letterSpacing: "0",
            fontWeight: "400"
        },
    
        cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
        emptyStyle = document.createElement( "div" ).style;
    
    
    // return a css property mapped to a potentially vendor prefixed property
    function vendorPropName( name ) {
    
        // shortcut for names that are not vendor prefixed
        if ( name in emptyStyle ) {
            return name;
        }
    
        // check for vendor prefixed names
        var capName = name.charAt( 0 ).toUpperCase() + name.slice( 1 ),
            i = cssPrefixes.length;
    
        while ( i-- ) {
            name = cssPrefixes[ i ] + capName;
            if ( name in emptyStyle ) {
                return name;
            }
        }
    }
    
    function showHide( elements, show ) {
        var display, elem, hidden,
            values = [],
            index = 0,
            length = elements.length;
    
        for ( ; index < length; index++ ) {
            elem = elements[ index ];
            if ( !elem.style ) {
                continue;
            }
    
            values[ index ] = jQuery._data( elem, "olddisplay" );
            display = elem.style.display;
            if ( show ) {
    
                // Reset the inline display of this element to learn if it is
                // being hidden by cascaded rules or not
                if ( !values[ index ] && display === "none" ) {
                    elem.style.display = "";
                }
    
                // Set elements which have been overridden with display: none
                // in a stylesheet to whatever the default browser style is
                // for such an element
                if ( elem.style.display === "" && isHidden( elem ) ) {
                    values[ index ] =
                        jQuery._data( elem, "olddisplay", defaultDisplay( elem.nodeName ) );
                }
            } else {
                hidden = isHidden( elem );
    
                if ( display && display !== "none" || !hidden ) {
                    jQuery._data(
                        elem,
                        "olddisplay",
                        hidden ? display : jQuery.css( elem, "display" )
                    );
                }
            }
        }
    
        // Set the display of most of the elements in a second loop
        // to avoid the constant reflow
        for ( index = 0; index < length; index++ ) {
            elem = elements[ index ];
            if ( !elem.style ) {
                continue;
            }
            if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
                elem.style.display = show ? values[ index ] || "" : "none";
            }
        }
    
        return elements;
    }
    
    function setPositiveNumber( elem, value, subtract ) {
        var matches = rnumsplit.exec( value );
        return matches ?
    
            // Guard against undefined "subtract", e.g., when used as in cssHooks
            Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
            value;
    }
    
    function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
        var i = extra === ( isBorderBox ? "border" : "content" ) ?
    
            // If we already have the right measurement, avoid augmentation
            4 :
    
            // Otherwise initialize for horizontal or vertical properties
            name === "width" ? 1 : 0,
    
            val = 0;
    
        for ( ; i < 4; i += 2 ) {
    
            // both box models exclude margin, so add it if we want it
            if ( extra === "margin" ) {
                val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
            }
    
            if ( isBorderBox ) {
    
                // border-box includes padding, so remove it if we want content
                if ( extra === "content" ) {
                    val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
                }
    
                // at this point, extra isn't border nor margin, so remove border
                if ( extra !== "margin" ) {
                    val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
                }
            } else {
    
                // at this point, extra isn't content, so add padding
                val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
    
                // at this point, extra isn't content nor padding, so add border
                if ( extra !== "padding" ) {
                    val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
                }
            }
        }
    
        return val;
    }
    
    function getWidthOrHeight( elem, name, extra ) {
    
        // Start with offset property, which is equivalent to the border-box value
        var valueIsBorderBox = true,
            val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
            styles = getStyles( elem ),
            isBorderBox = support.boxSizing &&
                jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
    
        // some non-html elements return undefined for offsetWidth, so check for null/undefined
        // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
        // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
        if ( val <= 0 || val == null ) {
    
            // Fall back to computed then uncomputed css if necessary
            val = curCSS( elem, name, styles );
            if ( val < 0 || val == null ) {
                val = elem.style[ name ];
            }
    
            // Computed unit is not pixels. Stop here and return.
            if ( rnumnonpx.test( val ) ) {
                return val;
            }
    
            // we need the check for style in case a browser which returns unreliable values
            // for getComputedStyle silently falls back to the reliable elem.style
            valueIsBorderBox = isBorderBox &&
                ( support.boxSizingReliable() || val === elem.style[ name ] );
    
            // Normalize "", auto, and prepare for extra
            val = parseFloat( val ) || 0;
        }
    
        // use the active box-sizing model to add/subtract irrelevant styles
        return ( val +
            augmentWidthOrHeight(
                elem,
                name,
                extra || ( isBorderBox ? "border" : "content" ),
                valueIsBorderBox,
                styles
            )
        ) + "px";
    }
    
    jQuery.extend( {
    
        // Add in style property hooks for overriding the default
        // behavior of getting and setting a style property
        cssHooks: {
            opacity: {
                get: function( elem, computed ) {
                    if ( computed ) {
    
                        // We should always get a number back from opacity
                        var ret = curCSS( elem, "opacity" );
                        return ret === "" ? "1" : ret;
                    }
                }
            }
        },
    
        // Don't automatically add "px" to these possibly-unitless properties
        cssNumber: {
            "animationIterationCount": true,
            "columnCount": true,
            "fillOpacity": true,
            "flexGrow": true,
            "flexShrink": true,
            "fontWeight": true,
            "lineHeight": true,
            "opacity": true,
            "order": true,
            "orphans": true,
            "widows": true,
            "zIndex": true,
            "zoom": true
        },
    
        // Add in properties whose names you wish to fix before
        // setting or getting the value
        cssProps: {
    
            // normalize float css property
            "float": support.cssFloat ? "cssFloat" : "styleFloat"
        },
    
        // Get and set the style property on a DOM Node
        style: function( elem, name, value, extra ) {
    
            // Don't set styles on text and comment nodes
            if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
                return;
            }
    
            // Make sure that we're working with the right name
            var ret, type, hooks,
                origName = jQuery.camelCase( name ),
                style = elem.style;
    
            name = jQuery.cssProps[ origName ] ||
                ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
    
            // gets hook for the prefixed version
            // followed by the unprefixed version
            hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
    
            // Check if we're setting a value
            if ( value !== undefined ) {
                type = typeof value;
    
                // Convert "+=" or "-=" to relative numbers (#7345)
                if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
                    value = adjustCSS( elem, name, ret );
    
                    // Fixes bug #9237
                    type = "number";
                }
    
                // Make sure that null and NaN values aren't set. See: #7116
                if ( value == null || value !== value ) {
                    return;
                }
    
                // If a number was passed in, add the unit (except for certain CSS properties)
                if ( type === "number" ) {
                    value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
                }
    
                // Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
                // but it would mean to define eight
                // (for every problematic property) identical functions
                if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
                    style[ name ] = "inherit";
                }
    
                // If a hook was provided, use that value, otherwise just set the specified value
                if ( !hooks || !( "set" in hooks ) ||
                    ( value = hooks.set( elem, value, extra ) ) !== undefined ) {
    
                    // Support: IE
                    // Swallow errors from 'invalid' CSS values (#5509)
                    try {
                        style[ name ] = value;
                    } catch ( e ) {}
                }
    
            } else {
    
                // If a hook was provided get the non-computed value from there
                if ( hooks && "get" in hooks &&
                    ( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
    
                    return ret;
                }
    
                // Otherwise just get the value from the style object
                return style[ name ];
            }
        },
    
        css: function( elem, name, extra, styles ) {
            var num, val, hooks,
                origName = jQuery.camelCase( name );
    
            // Make sure that we're working with the right name
            name = jQuery.cssProps[ origName ] ||
                ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
    
            // gets hook for the prefixed version
            // followed by the unprefixed version
            hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
    
            // If a hook was provided get the computed value from there
            if ( hooks && "get" in hooks ) {
                val = hooks.get( elem, true, extra );
            }
    
            // Otherwise, if a way to get the computed value exists, use that
            if ( val === undefined ) {
                val = curCSS( elem, name, styles );
            }
    
            //convert "normal" to computed value
            if ( val === "normal" && name in cssNormalTransform ) {
                val = cssNormalTransform[ name ];
            }
    
            // Return, converting to number if forced or a qualifier was provided and val looks numeric
            if ( extra === "" || extra ) {
                num = parseFloat( val );
                return extra === true || isFinite( num ) ? num || 0 : val;
            }
            return val;
        }
    } );
    
    jQuery.each( [ "height", "width" ], function( i, name ) {
        jQuery.cssHooks[ name ] = {
            get: function( elem, computed, extra ) {
                if ( computed ) {
    
                    // certain elements can have dimension info if we invisibly show them
                    // however, it must have a current display style that would benefit from this
                    return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
                        elem.offsetWidth === 0 ?
                            swap( elem, cssShow, function() {
                                return getWidthOrHeight( elem, name, extra );
                            } ) :
                            getWidthOrHeight( elem, name, extra );
                }
            },
    
            set: function( elem, value, extra ) {
                var styles = extra && getStyles( elem );
                return setPositiveNumber( elem, value, extra ?
                    augmentWidthOrHeight(
                        elem,
                        name,
                        extra,
                        support.boxSizing &&
                            jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
                        styles
                    ) : 0
                );
            }
        };
    } );
    
    if ( !support.opacity ) {
        jQuery.cssHooks.opacity = {
            get: function( elem, computed ) {
    
                // IE uses filters for opacity
                return ropacity.test( ( computed && elem.currentStyle ?
                    elem.currentStyle.filter :
                    elem.style.filter ) || "" ) ?
                        ( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
                        computed ? "1" : "";
            },
    
            set: function( elem, value ) {
                var style = elem.style,
                    currentStyle = elem.currentStyle,
                    opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
                    filter = currentStyle && currentStyle.filter || style.filter || "";
    
                // IE has trouble with opacity if it does not have layout
                // Force it by setting the zoom level
                style.zoom = 1;
    
                // if setting opacity to 1, and no other filters exist -
                // attempt to remove filter attribute #6652
                // if value === "", then remove inline opacity #12685
                if ( ( value >= 1 || value === "" ) &&
                        jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
                        style.removeAttribute ) {
    
                    // Setting style.filter to null, "" & " " still leave "filter:" in the cssText
                    // if "filter:" is present at all, clearType is disabled, we want to avoid this
                    // style.removeAttribute is IE Only, but so apparently is this code path...
                    style.removeAttribute( "filter" );
    
                    // if there is no filter style applied in a css rule
                    // or unset inline opacity, we are done
                    if ( value === "" || currentStyle && !currentStyle.filter ) {
                        return;
                    }
                }
    
                // otherwise, set new filter values
                style.filter = ralpha.test( filter ) ?
                    filter.replace( ralpha, opacity ) :
                    filter + " " + opacity;
            }
        };
    }
    
    jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
        function( elem, computed ) {
            if ( computed ) {
                return swap( elem, { "display": "inline-block" },
                    curCSS, [ elem, "marginRight" ] );
            }
        }
    );
    
    jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
        function( elem, computed ) {
            if ( computed ) {
                return (
                    parseFloat( curCSS( elem, "marginLeft" ) ) ||
    
                    // Support: IE<=11+
                    // Running getBoundingClientRect on a disconnected node in IE throws an error
                    // Support: IE8 only
                    // getClientRects() errors on disconnected elems
                    ( jQuery.contains( elem.ownerDocument, elem ) ?
                        elem.getBoundingClientRect().left -
                            swap( elem, { marginLeft: 0 }, function() {
                                return elem.getBoundingClientRect().left;
                            } ) :
                        0
                    )
                ) + "px";
            }
        }
    );
    
    // These hooks are used by animate to expand properties
    jQuery.each( {
        margin: "",
        padding: "",
        border: "Width"
    }, function( prefix, suffix ) {
        jQuery.cssHooks[ prefix + suffix ] = {
            expand: function( value ) {
                var i = 0,
                    expanded = {},
    
                    // assumes a single number if not a string
                    parts = typeof value === "string" ? value.split( " " ) : [ value ];
    
                for ( ; i < 4; i++ ) {
                    expanded[ prefix + cssExpand[ i ] + suffix ] =
                        parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
                }
    
                return expanded;
            }
        };
    
        if ( !rmargin.test( prefix ) ) {
            jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
        }
    } );
    
    jQuery.fn.extend( {
        css: function( name, value ) {
            return access( this, function( elem, name, value ) {
                var styles, len,
                    map = {},
                    i = 0;
    
                if ( jQuery.isArray( name ) ) {
                    styles = getStyles( elem );
                    len = name.length;
    
                    for ( ; i < len; i++ ) {
                        map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
                    }
    
                    return map;
                }
    
                return value !== undefined ?
                    jQuery.style( elem, name, value ) :
                    jQuery.css( elem, name );
            }, name, value, arguments.length > 1 );
        },
        show: function() {
            return showHide( this, true );
        },
        hide: function() {
            return showHide( this );
        },
        toggle: function( state ) {
            if ( typeof state === "boolean" ) {
                return state ? this.show() : this.hide();
            }
    
            return this.each( function() {
                if ( isHidden( this ) ) {
                    jQuery( this ).show();
                } else {
                    jQuery( this ).hide();
                }
            } );
        }
    } );
    
    
    function Tween( elem, options, prop, end, easing ) {
        return new Tween.prototype.init( elem, options, prop, end, easing );
    }
    jQuery.Tween = Tween;
    
    Tween.prototype = {
        constructor: Tween,
        init: function( elem, options, prop, end, easing, unit ) {
            this.elem = elem;
            this.prop = prop;
            this.easing = easing || jQuery.easing._default;
            this.options = options;
            this.start = this.now = this.cur();
            this.end = end;
            this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
        },
        cur: function() {
            var hooks = Tween.propHooks[ this.prop ];
    
            return hooks && hooks.get ?
                hooks.get( this ) :
                Tween.propHooks._default.get( this );
        },
        run: function( percent ) {
            var eased,
                hooks = Tween.propHooks[ this.prop ];
    
            if ( this.options.duration ) {
                this.pos = eased = jQuery.easing[ this.easing ](
                    percent, this.options.duration * percent, 0, 1, this.options.duration
                );
            } else {
                this.pos = eased = percent;
            }
            this.now = ( this.end - this.start ) * eased + this.start;
    
            if ( this.options.step ) {
                this.options.step.call( this.elem, this.now, this );
            }
    
            if ( hooks && hooks.set ) {
                hooks.set( this );
            } else {
                Tween.propHooks._default.set( this );
            }
            return this;
        }
    };
    
    Tween.prototype.init.prototype = Tween.prototype;
    
    Tween.propHooks = {
        _default: {
            get: function( tween ) {
                var result;
    
                // Use a property on the element directly when it is not a DOM element,
                // or when there is no matching style property that exists.
                if ( tween.elem.nodeType !== 1 ||
                    tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
                    return tween.elem[ tween.prop ];
                }
    
                // passing an empty string as a 3rd parameter to .css will automatically
                // attempt a parseFloat and fallback to a string if the parse fails
                // so, simple values such as "10px" are parsed to Float.
                // complex values such as "rotate(1rad)" are returned as is.
                result = jQuery.css( tween.elem, tween.prop, "" );
    
                // Empty strings, null, undefined and "auto" are converted to 0.
                return !result || result === "auto" ? 0 : result;
            },
            set: function( tween ) {
    
                // use step hook for back compat - use cssHook if its there - use .style if its
                // available and use plain properties where available
                if ( jQuery.fx.step[ tween.prop ] ) {
                    jQuery.fx.step[ tween.prop ]( tween );
                } else if ( tween.elem.nodeType === 1 &&
                    ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
                        jQuery.cssHooks[ tween.prop ] ) ) {
                    jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
                } else {
                    tween.elem[ tween.prop ] = tween.now;
                }
            }
        }
    };
    
    // Support: IE <=9
    // Panic based approach to setting things on disconnected nodes
    
    Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
        set: function( tween ) {
            if ( tween.elem.nodeType && tween.elem.parentNode ) {
                tween.elem[ tween.prop ] = tween.now;
            }
        }
    };
    
    jQuery.easing = {
        linear: function( p ) {
            return p;
        },
        swing: function( p ) {
            return 0.5 - Math.cos( p * Math.PI ) / 2;
        },
        _default: "swing"
    };
    
    jQuery.fx = Tween.prototype.init;
    
    // Back Compat <1.8 extension point
    jQuery.fx.step = {};
    
    
    
    
    var
        fxNow, timerId,
        rfxtypes = /^(?:toggle|show|hide)$/,
        rrun = /queueHooks$/;
    
    // Animations created synchronously will run synchronously
    function createFxNow() {
        window.setTimeout( function() {
            fxNow = undefined;
        } );
        return ( fxNow = jQuery.now() );
    }
    
    // Generate parameters to create a standard animation
    function genFx( type, includeWidth ) {
        var which,
            attrs = { height: type },
            i = 0;
    
        // if we include width, step value is 1 to do all cssExpand values,
        // if we don't include width, step value is 2 to skip over Left and Right
        includeWidth = includeWidth ? 1 : 0;
        for ( ; i < 4 ; i += 2 - includeWidth ) {
            which = cssExpand[ i ];
            attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
        }
    
        if ( includeWidth ) {
            attrs.opacity = attrs.width = type;
        }
    
        return attrs;
    }
    
    function createTween( value, prop, animation ) {
        var tween,
            collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
            index = 0,
            length = collection.length;
        for ( ; index < length; index++ ) {
            if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
    
                // we're done with this property
                return tween;
            }
        }
    }
    
    function defaultPrefilter( elem, props, opts ) {
        /* jshint validthis: true */
        var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
            anim = this,
            orig = {},
            style = elem.style,
            hidden = elem.nodeType && isHidden( elem ),
            dataShow = jQuery._data( elem, "fxshow" );
    
        // handle queue: false promises
        if ( !opts.queue ) {
            hooks = jQuery._queueHooks( elem, "fx" );
            if ( hooks.unqueued == null ) {
                hooks.unqueued = 0;
                oldfire = hooks.empty.fire;
                hooks.empty.fire = function() {
                    if ( !hooks.unqueued ) {
                        oldfire();
                    }
                };
            }
            hooks.unqueued++;
    
            anim.always( function() {
    
                // doing this makes sure that the complete handler will be called
                // before this completes
                anim.always( function() {
                    hooks.unqueued--;
                    if ( !jQuery.queue( elem, "fx" ).length ) {
                        hooks.empty.fire();
                    }
                } );
            } );
        }
    
        // height/width overflow pass
        if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
    
            // Make sure that nothing sneaks out
            // Record all 3 overflow attributes because IE does not
            // change the overflow attribute when overflowX and
            // overflowY are set to the same value
            opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
    
            // Set display property to inline-block for height/width
            // animations on inline elements that are having width/height animated
            display = jQuery.css( elem, "display" );
    
            // Test default display if display is currently "none"
            checkDisplay = display === "none" ?
                jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
    
            if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
    
                // inline-level elements accept inline-block;
                // block-level elements need to be inline with layout
                if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
                    style.display = "inline-block";
                } else {
                    style.zoom = 1;
                }
            }
        }
    
        if ( opts.overflow ) {
            style.overflow = "hidden";
            if ( !support.shrinkWrapBlocks() ) {
                anim.always( function() {
                    style.overflow = opts.overflow[ 0 ];
                    style.overflowX = opts.overflow[ 1 ];
                    style.overflowY = opts.overflow[ 2 ];
                } );
            }
        }
    
        // show/hide pass
        for ( prop in props ) {
            value = props[ prop ];
            if ( rfxtypes.exec( value ) ) {
                delete props[ prop ];
                toggle = toggle || value === "toggle";
                if ( value === ( hidden ? "hide" : "show" ) ) {
    
                    // If there is dataShow left over from a stopped hide or show
                    // and we are going to proceed with show, we should pretend to be hidden
                    if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
                        hidden = true;
                    } else {
                        continue;
                    }
                }
                orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
    
            // Any non-fx value stops us from restoring the original display value
            } else {
                display = undefined;
            }
        }
    
        if ( !jQuery.isEmptyObject( orig ) ) {
            if ( dataShow ) {
                if ( "hidden" in dataShow ) {
                    hidden = dataShow.hidden;
                }
            } else {
                dataShow = jQuery._data( elem, "fxshow", {} );
            }
    
            // store state if its toggle - enables .stop().toggle() to "reverse"
            if ( toggle ) {
                dataShow.hidden = !hidden;
            }
            if ( hidden ) {
                jQuery( elem ).show();
            } else {
                anim.done( function() {
                    jQuery( elem ).hide();
                } );
            }
            anim.done( function() {
                var prop;
                jQuery._removeData( elem, "fxshow" );
                for ( prop in orig ) {
                    jQuery.style( elem, prop, orig[ prop ] );
                }
            } );
            for ( prop in orig ) {
                tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
    
                if ( !( prop in dataShow ) ) {
                    dataShow[ prop ] = tween.start;
                    if ( hidden ) {
                        tween.end = tween.start;
                        tween.start = prop === "width" || prop === "height" ? 1 : 0;
                    }
                }
            }
    
        // If this is a noop like .hide().hide(), restore an overwritten display value
        } else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) {
            style.display = display;
        }
    }
    
    function propFilter( props, specialEasing ) {
        var index, name, easing, value, hooks;
    
        // camelCase, specialEasing and expand cssHook pass
        for ( index in props ) {
            name = jQuery.camelCase( index );
            easing = specialEasing[ name ];
            value = props[ index ];
            if ( jQuery.isArray( value ) ) {
                easing = value[ 1 ];
                value = props[ index ] = value[ 0 ];
            }
    
            if ( index !== name ) {
                props[ name ] = value;
                delete props[ index ];
            }
    
            hooks = jQuery.cssHooks[ name ];
            if ( hooks && "expand" in hooks ) {
                value = hooks.expand( value );
                delete props[ name ];
    
                // not quite $.extend, this wont overwrite keys already present.
                // also - reusing 'index' from above because we have the correct "name"
                for ( index in value ) {
                    if ( !( index in props ) ) {
                        props[ index ] = value[ index ];
                        specialEasing[ index ] = easing;
                    }
                }
            } else {
                specialEasing[ name ] = easing;
            }
        }
    }
    
    function Animation( elem, properties, options ) {
        var result,
            stopped,
            index = 0,
            length = Animation.prefilters.length,
            deferred = jQuery.Deferred().always( function() {
    
                // don't match elem in the :animated selector
                delete tick.elem;
            } ),
            tick = function() {
                if ( stopped ) {
                    return false;
                }
                var currentTime = fxNow || createFxNow(),
                    remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
    
                    // Support: Android 2.3
                    // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
                    temp = remaining / animation.duration || 0,
                    percent = 1 - temp,
                    index = 0,
                    length = animation.tweens.length;
    
                for ( ; index < length ; index++ ) {
                    animation.tweens[ index ].run( percent );
                }
    
                deferred.notifyWith( elem, [ animation, percent, remaining ] );
    
                if ( percent < 1 && length ) {
                    return remaining;
                } else {
                    deferred.resolveWith( elem, [ animation ] );
                    return false;
                }
            },
            animation = deferred.promise( {
                elem: elem,
                props: jQuery.extend( {}, properties ),
                opts: jQuery.extend( true, {
                    specialEasing: {},
                    easing: jQuery.easing._default
                }, options ),
                originalProperties: properties,
                originalOptions: options,
                startTime: fxNow || createFxNow(),
                duration: options.duration,
                tweens: [],
                createTween: function( prop, end ) {
                    var tween = jQuery.Tween( elem, animation.opts, prop, end,
                            animation.opts.specialEasing[ prop ] || animation.opts.easing );
                    animation.tweens.push( tween );
                    return tween;
                },
                stop: function( gotoEnd ) {
                    var index = 0,
    
                        // if we are going to the end, we want to run all the tweens
                        // otherwise we skip this part
                        length = gotoEnd ? animation.tweens.length : 0;
                    if ( stopped ) {
                        return this;
                    }
                    stopped = true;
                    for ( ; index < length ; index++ ) {
                        animation.tweens[ index ].run( 1 );
                    }
    
                    // resolve when we played the last frame
                    // otherwise, reject
                    if ( gotoEnd ) {
                        deferred.notifyWith( elem, [ animation, 1, 0 ] );
                        deferred.resolveWith( elem, [ animation, gotoEnd ] );
                    } else {
                        deferred.rejectWith( elem, [ animation, gotoEnd ] );
                    }
                    return this;
                }
            } ),
            props = animation.props;
    
        propFilter( props, animation.opts.specialEasing );
    
        for ( ; index < length ; index++ ) {
            result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
            if ( result ) {
                if ( jQuery.isFunction( result.stop ) ) {
                    jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
                        jQuery.proxy( result.stop, result );
                }
                return result;
            }
        }
    
        jQuery.map( props, createTween, animation );
    
        if ( jQuery.isFunction( animation.opts.start ) ) {
            animation.opts.start.call( elem, animation );
        }
    
        jQuery.fx.timer(
            jQuery.extend( tick, {
                elem: elem,
                anim: animation,
                queue: animation.opts.queue
            } )
        );
    
        // attach callbacks from options
        return animation.progress( animation.opts.progress )
            .done( animation.opts.done, animation.opts.complete )
            .fail( animation.opts.fail )
            .always( animation.opts.always );
    }
    
    jQuery.Animation = jQuery.extend( Animation, {
    
        tweeners: {
            "*": [ function( prop, value ) {
                var tween = this.createTween( prop, value );
                adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
                return tween;
            } ]
        },
    
        tweener: function( props, callback ) {
            if ( jQuery.isFunction( props ) ) {
                callback = props;
                props = [ "*" ];
            } else {
                props = props.match( rnotwhite );
            }
    
            var prop,
                index = 0,
                length = props.length;
    
            for ( ; index < length ; index++ ) {
                prop = props[ index ];
                Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
                Animation.tweeners[ prop ].unshift( callback );
            }
        },
    
        prefilters: [ defaultPrefilter ],
    
        prefilter: function( callback, prepend ) {
            if ( prepend ) {
                Animation.prefilters.unshift( callback );
            } else {
                Animation.prefilters.push( callback );
            }
        }
    } );
    
    jQuery.speed = function( speed, easing, fn ) {
        var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
            complete: fn || !fn && easing ||
                jQuery.isFunction( speed ) && speed,
            duration: speed,
            easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
        };
    
        opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
            opt.duration in jQuery.fx.speeds ?
                jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
    
        // normalize opt.queue - true/undefined/null -> "fx"
        if ( opt.queue == null || opt.queue === true ) {
            opt.queue = "fx";
        }
    
        // Queueing
        opt.old = opt.complete;
    
        opt.complete = function() {
            if ( jQuery.isFunction( opt.old ) ) {
                opt.old.call( this );
            }
    
            if ( opt.queue ) {
                jQuery.dequeue( this, opt.queue );
            }
        };
    
        return opt;
    };
    
    jQuery.fn.extend( {
        fadeTo: function( speed, to, easing, callback ) {
    
            // show any hidden elements after setting opacity to 0
            return this.filter( isHidden ).css( "opacity", 0 ).show()
    
                // animate to the value specified
                .end().animate( { opacity: to }, speed, easing, callback );
        },
        animate: function( prop, speed, easing, callback ) {
            var empty = jQuery.isEmptyObject( prop ),
                optall = jQuery.speed( speed, easing, callback ),
                doAnimation = function() {
    
                    // Operate on a copy of prop so per-property easing won't be lost
                    var anim = Animation( this, jQuery.extend( {}, prop ), optall );
    
                    // Empty animations, or finishing resolves immediately
                    if ( empty || jQuery._data( this, "finish" ) ) {
                        anim.stop( true );
                    }
                };
                doAnimation.finish = doAnimation;
    
            return empty || optall.queue === false ?
                this.each( doAnimation ) :
                this.queue( optall.queue, doAnimation );
        },
        stop: function( type, clearQueue, gotoEnd ) {
            var stopQueue = function( hooks ) {
                var stop = hooks.stop;
                delete hooks.stop;
                stop( gotoEnd );
            };
    
            if ( typeof type !== "string" ) {
                gotoEnd = clearQueue;
                clearQueue = type;
                type = undefined;
            }
            if ( clearQueue && type !== false ) {
                this.queue( type || "fx", [] );
            }
    
            return this.each( function() {
                var dequeue = true,
                    index = type != null && type + "queueHooks",
                    timers = jQuery.timers,
                    data = jQuery._data( this );
    
                if ( index ) {
                    if ( data[ index ] && data[ index ].stop ) {
                        stopQueue( data[ index ] );
                    }
                } else {
                    for ( index in data ) {
                        if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
                            stopQueue( data[ index ] );
                        }
                    }
                }
    
                for ( index = timers.length; index--; ) {
                    if ( timers[ index ].elem === this &&
                        ( type == null || timers[ index ].queue === type ) ) {
    
                        timers[ index ].anim.stop( gotoEnd );
                        dequeue = false;
                        timers.splice( index, 1 );
                    }
                }
    
                // start the next in the queue if the last step wasn't forced
                // timers currently will call their complete callbacks, which will dequeue
                // but only if they were gotoEnd
                if ( dequeue || !gotoEnd ) {
                    jQuery.dequeue( this, type );
                }
            } );
        },
        finish: function( type ) {
            if ( type !== false ) {
                type = type || "fx";
            }
            return this.each( function() {
                var index,
                    data = jQuery._data( this ),
                    queue = data[ type + "queue" ],
                    hooks = data[ type + "queueHooks" ],
                    timers = jQuery.timers,
                    length = queue ? queue.length : 0;
    
                // enable finishing flag on private data
                data.finish = true;
    
                // empty the queue first
                jQuery.queue( this, type, [] );
    
                if ( hooks && hooks.stop ) {
                    hooks.stop.call( this, true );
                }
    
                // look for any active animations, and finish them
                for ( index = timers.length; index--; ) {
                    if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
                        timers[ index ].anim.stop( true );
                        timers.splice( index, 1 );
                    }
                }
    
                // look for any animations in the old queue and finish them
                for ( index = 0; index < length; index++ ) {
                    if ( queue[ index ] && queue[ index ].finish ) {
                        queue[ index ].finish.call( this );
                    }
                }
    
                // turn off finishing flag
                delete data.finish;
            } );
        }
    } );
    
    jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
        var cssFn = jQuery.fn[ name ];
        jQuery.fn[ name ] = function( speed, easing, callback ) {
            return speed == null || typeof speed === "boolean" ?
                cssFn.apply( this, arguments ) :
                this.animate( genFx( name, true ), speed, easing, callback );
        };
    } );
    
    // Generate shortcuts for custom animations
    jQuery.each( {
        slideDown: genFx( "show" ),
        slideUp: genFx( "hide" ),
        slideToggle: genFx( "toggle" ),
        fadeIn: { opacity: "show" },
        fadeOut: { opacity: "hide" },
        fadeToggle: { opacity: "toggle" }
    }, function( name, props ) {
        jQuery.fn[ name ] = function( speed, easing, callback ) {
            return this.animate( props, speed, easing, callback );
        };
    } );
    
    jQuery.timers = [];
    jQuery.fx.tick = function() {
        var timer,
            timers = jQuery.timers,
            i = 0;
    
        fxNow = jQuery.now();
    
        for ( ; i < timers.length; i++ ) {
            timer = timers[ i ];
    
            // Checks the timer has not already been removed
            if ( !timer() && timers[ i ] === timer ) {
                timers.splice( i--, 1 );
            }
        }
    
        if ( !timers.length ) {
            jQuery.fx.stop();
        }
        fxNow = undefined;
    };
    
    jQuery.fx.timer = function( timer ) {
        jQuery.timers.push( timer );
        if ( timer() ) {
            jQuery.fx.start();
        } else {
            jQuery.timers.pop();
        }
    };
    
    jQuery.fx.interval = 13;
    
    jQuery.fx.start = function() {
        if ( !timerId ) {
            timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
        }
    };
    
    jQuery.fx.stop = function() {
        window.clearInterval( timerId );
        timerId = null;
    };
    
    jQuery.fx.speeds = {
        slow: 600,
        fast: 200,
    
        // Default speed
        _default: 400
    };
    
    
    // Based off of the plugin by Clint Helfers, with permission.
    // http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
    jQuery.fn.delay = function( time, type ) {
        time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
        type = type || "fx";
    
        return this.queue( type, function( next, hooks ) {
            var timeout = window.setTimeout( next, time );
            hooks.stop = function() {
                window.clearTimeout( timeout );
            };
        } );
    };
    
    
    ( function() {
        var a,
            input = document.createElement( "input" ),
            div = document.createElement( "div" ),
            select = document.createElement( "select" ),
            opt = select.appendChild( document.createElement( "option" ) );
    
        // Setup
        div = document.createElement( "div" );
        div.setAttribute( "className", "t" );
        div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
        a = div.getElementsByTagName( "a" )[ 0 ];
    
        // Support: Windows Web Apps (WWA)
        // `type` must use .setAttribute for WWA (#14901)
        input.setAttribute( "type", "checkbox" );
        div.appendChild( input );
    
        a = div.getElementsByTagName( "a" )[ 0 ];
    
        // First batch of tests.
        a.style.cssText = "top:1px";
    
        // Test setAttribute on camelCase class.
        // If it works, we need attrFixes when doing get/setAttribute (ie6/7)
        support.getSetAttribute = div.className !== "t";
    
        // Get the style information from getAttribute
        // (IE uses .cssText instead)
        support.style = /top/.test( a.getAttribute( "style" ) );
    
        // Make sure that URLs aren't manipulated
        // (IE normalizes it by default)
        support.hrefNormalized = a.getAttribute( "href" ) === "/a";
    
        // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
        support.checkOn = !!input.value;
    
        // Make sure that a selected-by-default option has a working selected property.
        // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
        support.optSelected = opt.selected;
    
        // Tests for enctype support on a form (#6743)
        support.enctype = !!document.createElement( "form" ).enctype;
    
        // Make sure that the options inside disabled selects aren't marked as disabled
        // (WebKit marks them as disabled)
        select.disabled = true;
        support.optDisabled = !opt.disabled;
    
        // Support: IE8 only
        // Check if we can trust getAttribute("value")
        input = document.createElement( "input" );
        input.setAttribute( "value", "" );
        support.input = input.getAttribute( "value" ) === "";
    
        // Check if an input maintains its value after becoming a radio
        input.value = "t";
        input.setAttribute( "type", "radio" );
        support.radioValue = input.value === "t";
    } )();
    
    
    var rreturn = /\r/g,
        rspaces = /[\x20\t\r\n\f]+/g;
    
    jQuery.fn.extend( {
        val: function( value ) {
            var hooks, ret, isFunction,
                elem = this[ 0 ];
    
            if ( !arguments.length ) {
                if ( elem ) {
                    hooks = jQuery.valHooks[ elem.type ] ||
                        jQuery.valHooks[ elem.nodeName.toLowerCase() ];
    
                    if (
                        hooks &&
                        "get" in hooks &&
                        ( ret = hooks.get( elem, "value" ) ) !== undefined
                    ) {
                        return ret;
                    }
    
                    ret = elem.value;
    
                    return typeof ret === "string" ?
    
                        // handle most common string cases
                        ret.replace( rreturn, "" ) :
    
                        // handle cases where value is null/undef or number
                        ret == null ? "" : ret;
                }
    
                return;
            }
    
            isFunction = jQuery.isFunction( value );
    
            return this.each( function( i ) {
                var val;
    
                if ( this.nodeType !== 1 ) {
                    return;
                }
    
                if ( isFunction ) {
                    val = value.call( this, i, jQuery( this ).val() );
                } else {
                    val = value;
                }
    
                // Treat null/undefined as ""; convert numbers to string
                if ( val == null ) {
                    val = "";
                } else if ( typeof val === "number" ) {
                    val += "";
                } else if ( jQuery.isArray( val ) ) {
                    val = jQuery.map( val, function( value ) {
                        return value == null ? "" : value + "";
                    } );
                }
    
                hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
    
                // If set returns undefined, fall back to normal setting
                if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
                    this.value = val;
                }
            } );
        }
    } );
    
    jQuery.extend( {
        valHooks: {
            option: {
                get: function( elem ) {
                    var val = jQuery.find.attr( elem, "value" );
                    return val != null ?
                        val :
    
                        // Support: IE10-11+
                        // option.text throws exceptions (#14686, #14858)
                        // Strip and collapse whitespace
                        // https://html.spec.whatwg.org/#strip-and-collapse-whitespace
                        jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
                }
            },
            select: {
                get: function( elem ) {
                    var value, option,
                        options = elem.options,
                        index = elem.selectedIndex,
                        one = elem.type === "select-one" || index < 0,
                        values = one ? null : [],
                        max = one ? index + 1 : options.length,
                        i = index < 0 ?
                            max :
                            one ? index : 0;
    
                    // Loop through all the selected options
                    for ( ; i < max; i++ ) {
                        option = options[ i ];
    
                        // oldIE doesn't update selected after form reset (#2551)
                        if ( ( option.selected || i === index ) &&
    
                                // Don't return options that are disabled or in a disabled optgroup
                                ( support.optDisabled ?
                                    !option.disabled :
                                    option.getAttribute( "disabled" ) === null ) &&
                                ( !option.parentNode.disabled ||
                                    !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
    
                            // Get the specific value for the option
                            value = jQuery( option ).val();
    
                            // We don't need an array for one selects
                            if ( one ) {
                                return value;
                            }
    
                            // Multi-Selects return an array
                            values.push( value );
                        }
                    }
    
                    return values;
                },
    
                set: function( elem, value ) {
                    var optionSet, option,
                        options = elem.options,
                        values = jQuery.makeArray( value ),
                        i = options.length;
    
                    while ( i-- ) {
                        option = options[ i ];
    
                        if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) {
    
                            // Support: IE6
                            // When new option element is added to select box we need to
                            // force reflow of newly added node in order to workaround delay
                            // of initialization properties
                            try {
                                option.selected = optionSet = true;
    
                            } catch ( _ ) {
    
                                // Will be executed only in IE6
                                option.scrollHeight;
                            }
    
                        } else {
                            option.selected = false;
                        }
                    }
    
                    // Force browsers to behave consistently when non-matching value is set
                    if ( !optionSet ) {
                        elem.selectedIndex = -1;
                    }
    
                    return options;
                }
            }
        }
    } );
    
    // Radios and checkboxes getter/setter
    jQuery.each( [ "radio", "checkbox" ], function() {
        jQuery.valHooks[ this ] = {
            set: function( elem, value ) {
                if ( jQuery.isArray( value ) ) {
                    return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
                }
            }
        };
        if ( !support.checkOn ) {
            jQuery.valHooks[ this ].get = function( elem ) {
                return elem.getAttribute( "value" ) === null ? "on" : elem.value;
            };
        }
    } );
    
    
    
    
    var nodeHook, boolHook,
        attrHandle = jQuery.expr.attrHandle,
        ruseDefault = /^(?:checked|selected)$/i,
        getSetAttribute = support.getSetAttribute,
        getSetInput = support.input;
    
    jQuery.fn.extend( {
        attr: function( name, value ) {
            return access( this, jQuery.attr, name, value, arguments.length > 1 );
        },
    
        removeAttr: function( name ) {
            return this.each( function() {
                jQuery.removeAttr( this, name );
            } );
        }
    } );
    
    jQuery.extend( {
        attr: function( elem, name, value ) {
            var ret, hooks,
                nType = elem.nodeType;
    
            // Don't get/set attributes on text, comment and attribute nodes
            if ( nType === 3 || nType === 8 || nType === 2 ) {
                return;
            }
    
            // Fallback to prop when attributes are not supported
            if ( typeof elem.getAttribute === "undefined" ) {
                return jQuery.prop( elem, name, value );
            }
    
            // All attributes are lowercase
            // Grab necessary hook if one is defined
            if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
                name = name.toLowerCase();
                hooks = jQuery.attrHooks[ name ] ||
                    ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
            }
    
            if ( value !== undefined ) {
                if ( value === null ) {
                    jQuery.removeAttr( elem, name );
                    return;
                }
    
                if ( hooks && "set" in hooks &&
                    ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
                    return ret;
                }
    
                elem.setAttribute( name, value + "" );
                return value;
            }
    
            if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
                return ret;
            }
    
            ret = jQuery.find.attr( elem, name );
    
            // Non-existent attributes return null, we normalize to undefined
            return ret == null ? undefined : ret;
        },
    
        attrHooks: {
            type: {
                set: function( elem, value ) {
                    if ( !support.radioValue && value === "radio" &&
                        jQuery.nodeName( elem, "input" ) ) {
    
                        // Setting the type on a radio button after the value resets the value in IE8-9
                        // Reset value to default in case type is set after value during creation
                        var val = elem.value;
                        elem.setAttribute( "type", value );
                        if ( val ) {
                            elem.value = val;
                        }
                        return value;
                    }
                }
            }
        },
    
        removeAttr: function( elem, value ) {
            var name, propName,
                i = 0,
                attrNames = value && value.match( rnotwhite );
    
            if ( attrNames && elem.nodeType === 1 ) {
                while ( ( name = attrNames[ i++ ] ) ) {
                    propName = jQuery.propFix[ name ] || name;
    
                    // Boolean attributes get special treatment (#10870)
                    if ( jQuery.expr.match.bool.test( name ) ) {
    
                        // Set corresponding property to false
                        if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
                            elem[ propName ] = false;
    
                        // Support: IE<9
                        // Also clear defaultChecked/defaultSelected (if appropriate)
                        } else {
                            elem[ jQuery.camelCase( "default-" + name ) ] =
                                elem[ propName ] = false;
                        }
    
                    // See #9699 for explanation of this approach (setting first, then removal)
                    } else {
                        jQuery.attr( elem, name, "" );
                    }
    
                    elem.removeAttribute( getSetAttribute ? name : propName );
                }
            }
        }
    } );
    
    // Hooks for boolean attributes
    boolHook = {
        set: function( elem, value, name ) {
            if ( value === false ) {
    
                // Remove boolean attributes when set to false
                jQuery.removeAttr( elem, name );
            } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
    
                // IE<8 needs the *property* name
                elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
    
            } else {
    
                // Support: IE<9
                // Use defaultChecked and defaultSelected for oldIE
                elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
            }
            return name;
        }
    };
    
    jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
        var getter = attrHandle[ name ] || jQuery.find.attr;
    
        if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
            attrHandle[ name ] = function( elem, name, isXML ) {
                var ret, handle;
                if ( !isXML ) {
    
                    // Avoid an infinite loop by temporarily removing this function from the getter
                    handle = attrHandle[ name ];
                    attrHandle[ name ] = ret;
                    ret = getter( elem, name, isXML ) != null ?
                        name.toLowerCase() :
                        null;
                    attrHandle[ name ] = handle;
                }
                return ret;
            };
        } else {
            attrHandle[ name ] = function( elem, name, isXML ) {
                if ( !isXML ) {
                    return elem[ jQuery.camelCase( "default-" + name ) ] ?
                        name.toLowerCase() :
                        null;
                }
            };
        }
    } );
    
    // fix oldIE attroperties
    if ( !getSetInput || !getSetAttribute ) {
        jQuery.attrHooks.value = {
            set: function( elem, value, name ) {
                if ( jQuery.nodeName( elem, "input" ) ) {
    
                    // Does not return so that setAttribute is also used
                    elem.defaultValue = value;
                } else {
    
                    // Use nodeHook if defined (#1954); otherwise setAttribute is fine
                    return nodeHook && nodeHook.set( elem, value, name );
                }
            }
        };
    }
    
    // IE6/7 do not support getting/setting some attributes with get/setAttribute
    if ( !getSetAttribute ) {
    
        // Use this for any attribute in IE6/7
        // This fixes almost every IE6/7 issue
        nodeHook = {
            set: function( elem, value, name ) {
    
                // Set the existing or create a new attribute node
                var ret = elem.getAttributeNode( name );
                if ( !ret ) {
                    elem.setAttributeNode(
                        ( ret = elem.ownerDocument.createAttribute( name ) )
                    );
                }
    
                ret.value = value += "";
    
                // Break association with cloned elements by also using setAttribute (#9646)
                if ( name === "value" || value === elem.getAttribute( name ) ) {
                    return value;
                }
            }
        };
    
        // Some attributes are constructed with empty-string values when not defined
        attrHandle.id = attrHandle.name = attrHandle.coords =
            function( elem, name, isXML ) {
                var ret;
                if ( !isXML ) {
                    return ( ret = elem.getAttributeNode( name ) ) && ret.value !== "" ?
                        ret.value :
                        null;
                }
            };
    
        // Fixing value retrieval on a button requires this module
        jQuery.valHooks.button = {
            get: function( elem, name ) {
                var ret = elem.getAttributeNode( name );
                if ( ret && ret.specified ) {
                    return ret.value;
                }
            },
            set: nodeHook.set
        };
    
        // Set contenteditable to false on removals(#10429)
        // Setting to empty string throws an error as an invalid value
        jQuery.attrHooks.contenteditable = {
            set: function( elem, value, name ) {
                nodeHook.set( elem, value === "" ? false : value, name );
            }
        };
    
        // Set width and height to auto instead of 0 on empty string( Bug #8150 )
        // This is for removals
        jQuery.each( [ "width", "height" ], function( i, name ) {
            jQuery.attrHooks[ name ] = {
                set: function( elem, value ) {
                    if ( value === "" ) {
                        elem.setAttribute( name, "auto" );
                        return value;
                    }
                }
            };
        } );
    }
    
    if ( !support.style ) {
        jQuery.attrHooks.style = {
            get: function( elem ) {
    
                // Return undefined in the case of empty string
                // Note: IE uppercases css property names, but if we were to .toLowerCase()
                // .cssText, that would destroy case sensitivity in URL's, like in "background"
                return elem.style.cssText || undefined;
            },
            set: function( elem, value ) {
                return ( elem.style.cssText = value + "" );
            }
        };
    }
    
    
    
    
    var rfocusable = /^(?:input|select|textarea|button|object)$/i,
        rclickable = /^(?:a|area)$/i;
    
    jQuery.fn.extend( {
        prop: function( name, value ) {
            return access( this, jQuery.prop, name, value, arguments.length > 1 );
        },
    
        removeProp: function( name ) {
            name = jQuery.propFix[ name ] || name;
            return this.each( function() {
    
                // try/catch handles cases where IE balks (such as removing a property on window)
                try {
                    this[ name ] = undefined;
                    delete this[ name ];
                } catch ( e ) {}
            } );
        }
    } );
    
    jQuery.extend( {
        prop: function( elem, name, value ) {
            var ret, hooks,
                nType = elem.nodeType;
    
            // Don't get/set properties on text, comment and attribute nodes
            if ( nType === 3 || nType === 8 || nType === 2 ) {
                return;
            }
    
            if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
    
                // Fix name and attach hooks
                name = jQuery.propFix[ name ] || name;
                hooks = jQuery.propHooks[ name ];
            }
    
            if ( value !== undefined ) {
                if ( hooks && "set" in hooks &&
                    ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
                    return ret;
                }
    
                return ( elem[ name ] = value );
            }
    
            if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
                return ret;
            }
    
            return elem[ name ];
        },
    
        propHooks: {
            tabIndex: {
                get: function( elem ) {
    
                    // elem.tabIndex doesn't always return the
                    // correct value when it hasn't been explicitly set
                    // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
                    // Use proper attribute retrieval(#12072)
                    var tabindex = jQuery.find.attr( elem, "tabindex" );
    
                    return tabindex ?
                        parseInt( tabindex, 10 ) :
                        rfocusable.test( elem.nodeName ) ||
                            rclickable.test( elem.nodeName ) && elem.href ?
                                0 :
                                -1;
                }
            }
        },
    
        propFix: {
            "for": "htmlFor",
            "class": "className"
        }
    } );
    
    // Some attributes require a special call on IE
    // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
    if ( !support.hrefNormalized ) {
    
        // href/src property should get the full normalized URL (#10299/#12915)
        jQuery.each( [ "href", "src" ], function( i, name ) {
            jQuery.propHooks[ name ] = {
                get: function( elem ) {
                    return elem.getAttribute( name, 4 );
                }
            };
        } );
    }
    
    // Support: Safari, IE9+
    // Accessing the selectedIndex property
    // forces the browser to respect setting selected
    // on the option
    // The getter ensures a default option is selected
    // when in an optgroup
    if ( !support.optSelected ) {
        jQuery.propHooks.selected = {
            get: function( elem ) {
                var parent = elem.parentNode;
    
                if ( parent ) {
                    parent.selectedIndex;
    
                    // Make sure that it also works with optgroups, see #5701
                    if ( parent.parentNode ) {
                        parent.parentNode.selectedIndex;
                    }
                }
                return null;
            },
            set: function( elem ) {
                var parent = elem.parentNode;
                if ( parent ) {
                    parent.selectedIndex;
    
                    if ( parent.parentNode ) {
                        parent.parentNode.selectedIndex;
                    }
                }
            }
        };
    }
    
    jQuery.each( [
        "tabIndex",
        "readOnly",
        "maxLength",
        "cellSpacing",
        "cellPadding",
        "rowSpan",
        "colSpan",
        "useMap",
        "frameBorder",
        "contentEditable"
    ], function() {
        jQuery.propFix[ this.toLowerCase() ] = this;
    } );
    
    // IE6/7 call enctype encoding
    if ( !support.enctype ) {
        jQuery.propFix.enctype = "encoding";
    }
    
    
    
    
    var rclass = /[\t\r\n\f]/g;
    
    function getClass( elem ) {
        return jQuery.attr( elem, "class" ) || "";
    }
    
    jQuery.fn.extend( {
        addClass: function( value ) {
            var classes, elem, cur, curValue, clazz, j, finalValue,
                i = 0;
    
            if ( jQuery.isFunction( value ) ) {
                return this.each( function( j ) {
                    jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
                } );
            }
    
            if ( typeof value === "string" && value ) {
                classes = value.match( rnotwhite ) || [];
    
                while ( ( elem = this[ i++ ] ) ) {
                    curValue = getClass( elem );
                    cur = elem.nodeType === 1 &&
                        ( " " + curValue + " " ).replace( rclass, " " );
    
                    if ( cur ) {
                        j = 0;
                        while ( ( clazz = classes[ j++ ] ) ) {
                            if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
                                cur += clazz + " ";
                            }
                        }
    
                        // only assign if different to avoid unneeded rendering.
                        finalValue = jQuery.trim( cur );
                        if ( curValue !== finalValue ) {
                            jQuery.attr( elem, "class", finalValue );
                        }
                    }
                }
            }
    
            return this;
        },
    
        removeClass: function( value ) {
            var classes, elem, cur, curValue, clazz, j, finalValue,
                i = 0;
    
            if ( jQuery.isFunction( value ) ) {
                return this.each( function( j ) {
                    jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
                } );
            }
    
            if ( !arguments.length ) {
                return this.attr( "class", "" );
            }
    
            if ( typeof value === "string" && value ) {
                classes = value.match( rnotwhite ) || [];
    
                while ( ( elem = this[ i++ ] ) ) {
                    curValue = getClass( elem );
    
                    // This expression is here for better compressibility (see addClass)
                    cur = elem.nodeType === 1 &&
                        ( " " + curValue + " " ).replace( rclass, " " );
    
                    if ( cur ) {
                        j = 0;
                        while ( ( clazz = classes[ j++ ] ) ) {
    
                            // Remove *all* instances
                            while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
                                cur = cur.replace( " " + clazz + " ", " " );
                            }
                        }
    
                        // Only assign if different to avoid unneeded rendering.
                        finalValue = jQuery.trim( cur );
                        if ( curValue !== finalValue ) {
                            jQuery.attr( elem, "class", finalValue );
                        }
                    }
                }
            }
    
            return this;
        },
    
        toggleClass: function( value, stateVal ) {
            var type = typeof value;
    
            if ( typeof stateVal === "boolean" && type === "string" ) {
                return stateVal ? this.addClass( value ) : this.removeClass( value );
            }
    
            if ( jQuery.isFunction( value ) ) {
                return this.each( function( i ) {
                    jQuery( this ).toggleClass(
                        value.call( this, i, getClass( this ), stateVal ),
                        stateVal
                    );
                } );
            }
    
            return this.each( function() {
                var className, i, self, classNames;
    
                if ( type === "string" ) {
    
                    // Toggle individual class names
                    i = 0;
                    self = jQuery( this );
                    classNames = value.match( rnotwhite ) || [];
    
                    while ( ( className = classNames[ i++ ] ) ) {
    
                        // Check each className given, space separated list
                        if ( self.hasClass( className ) ) {
                            self.removeClass( className );
                        } else {
                            self.addClass( className );
                        }
                    }
    
                // Toggle whole class name
                } else if ( value === undefined || type === "boolean" ) {
                    className = getClass( this );
                    if ( className ) {
    
                        // store className if set
                        jQuery._data( this, "__className__", className );
                    }
    
                    // If the element has a class name or if we're passed "false",
                    // then remove the whole classname (if there was one, the above saved it).
                    // Otherwise bring back whatever was previously saved (if anything),
                    // falling back to the empty string if nothing was stored.
                    jQuery.attr( this, "class",
                        className || value === false ?
                        "" :
                        jQuery._data( this, "__className__" ) || ""
                    );
                }
            } );
        },
    
        hasClass: function( selector ) {
            var className, elem,
                i = 0;
    
            className = " " + selector + " ";
            while ( ( elem = this[ i++ ] ) ) {
                if ( elem.nodeType === 1 &&
                    ( " " + getClass( elem ) + " " ).replace( rclass, " " )
                        .indexOf( className ) > -1
                ) {
                    return true;
                }
            }
    
            return false;
        }
    } );
    
    
    
    
    // Return jQuery for attributes-only inclusion
    
    
    jQuery.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( i, name ) {
    
        // Handle event binding
        jQuery.fn[ name ] = function( data, fn ) {
            return arguments.length > 0 ?
                this.on( name, null, data, fn ) :
                this.trigger( name );
        };
    } );
    
    jQuery.fn.extend( {
        hover: function( fnOver, fnOut ) {
            return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
        }
    } );
    
    
    var location = window.location;
    
    var nonce = jQuery.now();
    
    var rquery = ( /\?/ );
    
    
    
    var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
    
    jQuery.parseJSON = function( data ) {
    
        // Attempt to parse using the native JSON parser first
        if ( window.JSON && window.JSON.parse ) {
    
            // Support: Android 2.3
            // Workaround failure to string-cast null input
            return window.JSON.parse( data + "" );
        }
    
        var requireNonComma,
            depth = null,
            str = jQuery.trim( data + "" );
    
        // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
        // after removing valid tokens
        return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
    
            // Force termination if we see a misplaced comma
            if ( requireNonComma && comma ) {
                depth = 0;
            }
    
            // Perform no more replacements after returning to outermost depth
            if ( depth === 0 ) {
                return token;
            }
    
            // Commas must not follow "[", "{", or ","
            requireNonComma = open || comma;
    
            // Determine new depth
            // array/object open ("[" or "{"): depth += true - false (increment)
            // array/object close ("]" or "}"): depth += false - true (decrement)
            // other cases ("," or primitive): depth += true - true (numeric cast)
            depth += !close - !open;
    
            // Remove this token
            return "";
        } ) ) ?
            ( Function( "return " + str ) )() :
            jQuery.error( "Invalid JSON: " + data );
    };
    
    
    // Cross-browser xml parsing
    jQuery.parseXML = function( data ) {
        var xml, tmp;
        if ( !data || typeof data !== "string" ) {
            return null;
        }
        try {
            if ( window.DOMParser ) { // Standard
                tmp = new window.DOMParser();
                xml = tmp.parseFromString( data, "text/xml" );
            } else { // IE
                xml = new window.ActiveXObject( "Microsoft.XMLDOM" );
                xml.async = "false";
                xml.loadXML( data );
            }
        } catch ( e ) {
            xml = undefined;
        }
        if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
            jQuery.error( "Invalid XML: " + data );
        }
        return xml;
    };
    
    
    var
        rhash = /#.*$/,
        rts = /([?&])_=[^&]*/,
    
        // IE leaves an \r character at EOL
        rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
    
        // #7653, #8125, #8152: local protocol detection
        rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
        rnoContent = /^(?:GET|HEAD)$/,
        rprotocol = /^\/\//,
        rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
    
        /* Prefilters
         * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
         * 2) These are called:
         *    - BEFORE asking for a transport
         *    - AFTER param serialization (s.data is a string if s.processData is true)
         * 3) key is the dataType
         * 4) the catchall symbol "*" can be used
         * 5) execution will start with transport dataType and THEN continue down to "*" if needed
         */
        prefilters = {},
    
        /* Transports bindings
         * 1) key is the dataType
         * 2) the catchall symbol "*" can be used
         * 3) selection will start with transport dataType and THEN go to "*" if needed
         */
        transports = {},
    
        // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
        allTypes = "*/".concat( "*" ),
    
        // Document location
        ajaxLocation = location.href,
    
        // Segment location into parts
        ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
    
    // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
    function addToPrefiltersOrTransports( structure ) {
    
        // dataTypeExpression is optional and defaults to "*"
        return function( dataTypeExpression, func ) {
    
            if ( typeof dataTypeExpression !== "string" ) {
                func = dataTypeExpression;
                dataTypeExpression = "*";
            }
    
            var dataType,
                i = 0,
                dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
    
            if ( jQuery.isFunction( func ) ) {
    
                // For each dataType in the dataTypeExpression
                while ( ( dataType = dataTypes[ i++ ] ) ) {
    
                    // Prepend if requested
                    if ( dataType.charAt( 0 ) === "+" ) {
                        dataType = dataType.slice( 1 ) || "*";
                        ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
    
                    // Otherwise append
                    } else {
                        ( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
                    }
                }
            }
        };
    }
    
    // Base inspection function for prefilters and transports
    function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
    
        var inspected = {},
            seekingTransport = ( structure === transports );
    
        function inspect( dataType ) {
            var selected;
            inspected[ dataType ] = true;
            jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
                var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
                if ( typeof dataTypeOrTransport === "string" &&
                    !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
    
                    options.dataTypes.unshift( dataTypeOrTransport );
                    inspect( dataTypeOrTransport );
                    return false;
                } else if ( seekingTransport ) {
                    return !( selected = dataTypeOrTransport );
                }
            } );
            return selected;
        }
    
        return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
    }
    
    // A special extend for ajax options
    // that takes "flat" options (not to be deep extended)
    // Fixes #9887
    function ajaxExtend( target, src ) {
        var deep, key,
            flatOptions = jQuery.ajaxSettings.flatOptions || {};
    
        for ( key in src ) {
            if ( src[ key ] !== undefined ) {
                ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
            }
        }
        if ( deep ) {
            jQuery.extend( true, target, deep );
        }
    
        return target;
    }
    
    /* Handles responses to an ajax request:
     * - finds the right dataType (mediates between content-type and expected dataType)
     * - returns the corresponding response
     */
    function ajaxHandleResponses( s, jqXHR, responses ) {
        var firstDataType, ct, finalDataType, type,
            contents = s.contents,
            dataTypes = s.dataTypes;
    
        // Remove auto dataType and get content-type in the process
        while ( dataTypes[ 0 ] === "*" ) {
            dataTypes.shift();
            if ( ct === undefined ) {
                ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
            }
        }
    
        // Check if we're dealing with a known content-type
        if ( ct ) {
            for ( type in contents ) {
                if ( contents[ type ] && contents[ type ].test( ct ) ) {
                    dataTypes.unshift( type );
                    break;
                }
            }
        }
    
        // Check to see if we have a response for the expected dataType
        if ( dataTypes[ 0 ] in responses ) {
            finalDataType = dataTypes[ 0 ];
        } else {
    
            // Try convertible dataTypes
            for ( type in responses ) {
                if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
                    finalDataType = type;
                    break;
                }
                if ( !firstDataType ) {
                    firstDataType = type;
                }
            }
    
            // Or just use first one
            finalDataType = finalDataType || firstDataType;
        }
    
        // If we found a dataType
        // We add the dataType to the list if needed
        // and return the corresponding response
        if ( finalDataType ) {
            if ( finalDataType !== dataTypes[ 0 ] ) {
                dataTypes.unshift( finalDataType );
            }
            return responses[ finalDataType ];
        }
    }
    
    /* Chain conversions given the request and the original response
     * Also sets the responseXXX fields on the jqXHR instance
     */
    function ajaxConvert( s, response, jqXHR, isSuccess ) {
        var conv2, current, conv, tmp, prev,
            converters = {},
    
            // Work with a copy of dataTypes in case we need to modify it for conversion
            dataTypes = s.dataTypes.slice();
    
        // Create converters map with lowercased keys
        if ( dataTypes[ 1 ] ) {
            for ( conv in s.converters ) {
                converters[ conv.toLowerCase() ] = s.converters[ conv ];
            }
        }
    
        current = dataTypes.shift();
    
        // Convert to each sequential dataType
        while ( current ) {
    
            if ( s.responseFields[ current ] ) {
                jqXHR[ s.responseFields[ current ] ] = response;
            }
    
            // Apply the dataFilter if provided
            if ( !prev && isSuccess && s.dataFilter ) {
                response = s.dataFilter( response, s.dataType );
            }
    
            prev = current;
            current = dataTypes.shift();
    
            if ( current ) {
    
                // There's only work to do if current dataType is non-auto
                if ( current === "*" ) {
    
                    current = prev;
    
                // Convert response if prev dataType is non-auto and differs from current
                } else if ( prev !== "*" && prev !== current ) {
    
                    // Seek a direct converter
                    conv = converters[ prev + " " + current ] || converters[ "* " + current ];
    
                    // If none found, seek a pair
                    if ( !conv ) {
                        for ( conv2 in converters ) {
    
                            // If conv2 outputs current
                            tmp = conv2.split( " " );
                            if ( tmp[ 1 ] === current ) {
    
                                // If prev can be converted to accepted input
                                conv = converters[ prev + " " + tmp[ 0 ] ] ||
                                    converters[ "* " + tmp[ 0 ] ];
                                if ( conv ) {
    
                                    // Condense equivalence converters
                                    if ( conv === true ) {
                                        conv = converters[ conv2 ];
    
                                    // Otherwise, insert the intermediate dataType
                                    } else if ( converters[ conv2 ] !== true ) {
                                        current = tmp[ 0 ];
                                        dataTypes.unshift( tmp[ 1 ] );
                                    }
                                    break;
                                }
                            }
                        }
                    }
    
                    // Apply converter (if not an equivalence)
                    if ( conv !== true ) {
    
                        // Unless errors are allowed to bubble, catch and return them
                        if ( conv && s[ "throws" ] ) { // jscs:ignore requireDotNotation
                            response = conv( response );
                        } else {
                            try {
                                response = conv( response );
                            } catch ( e ) {
                                return {
                                    state: "parsererror",
                                    error: conv ? e : "No conversion from " + prev + " to " + current
                                };
                            }
                        }
                    }
                }
            }
        }
    
        return { state: "success", data: response };
    }
    
    jQuery.extend( {
    
        // Counter for holding the number of active queries
        active: 0,
    
        // Last-Modified header cache for next request
        lastModified: {},
        etag: {},
    
        ajaxSettings: {
            url: ajaxLocation,
            type: "GET",
            isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
            global: true,
            processData: true,
            async: true,
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            /*
            timeout: 0,
            data: null,
            dataType: null,
            username: null,
            password: null,
            cache: null,
            throws: false,
            traditional: false,
            headers: {},
            */
    
            accepts: {
                "*": allTypes,
                text: "text/plain",
                html: "text/html",
                xml: "application/xml, text/xml",
                json: "application/json, text/javascript"
            },
    
            contents: {
                xml: /\bxml\b/,
                html: /\bhtml/,
                json: /\bjson\b/
            },
    
            responseFields: {
                xml: "responseXML",
                text: "responseText",
                json: "responseJSON"
            },
    
            // Data converters
            // Keys separate source (or catchall "*") and destination types with a single space
            converters: {
    
                // Convert anything to text
                "* text": String,
    
                // Text to html (true = no transformation)
                "text html": true,
    
                // Evaluate text as a json expression
                "text json": jQuery.parseJSON,
    
                // Parse text as xml
                "text xml": jQuery.parseXML
            },
    
            // For options that shouldn't be deep extended:
            // you can add your own custom options here if
            // and when you create one that shouldn't be
            // deep extended (see ajaxExtend)
            flatOptions: {
                url: true,
                context: true
            }
        },
    
        // Creates a full fledged settings object into target
        // with both ajaxSettings and settings fields.
        // If target is omitted, writes into ajaxSettings.
        ajaxSetup: function( target, settings ) {
            return settings ?
    
                // Building a settings object
                ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
    
                // Extending ajaxSettings
                ajaxExtend( jQuery.ajaxSettings, target );
        },
    
        ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
        ajaxTransport: addToPrefiltersOrTransports( transports ),
    
        // Main method
        ajax: function( url, options ) {
    
            // If url is an object, simulate pre-1.5 signature
            if ( typeof url === "object" ) {
                options = url;
                url = undefined;
            }
    
            // Force options to be an object
            options = options || {};
    
            var
    
                // Cross-domain detection vars
                parts,
    
                // Loop variable
                i,
    
                // URL without anti-cache param
                cacheURL,
    
                // Response headers as string
                responseHeadersString,
    
                // timeout handle
                timeoutTimer,
    
                // To know if global events are to be dispatched
                fireGlobals,
    
                transport,
    
                // Response headers
                responseHeaders,
    
                // Create the final options object
                s = jQuery.ajaxSetup( {}, options ),
    
                // Callbacks context
                callbackContext = s.context || s,
    
                // Context for global events is callbackContext if it is a DOM node or jQuery collection
                globalEventContext = s.context &&
                    ( callbackContext.nodeType || callbackContext.jquery ) ?
                        jQuery( callbackContext ) :
                        jQuery.event,
    
                // Deferreds
                deferred = jQuery.Deferred(),
                completeDeferred = jQuery.Callbacks( "once memory" ),
    
                // Status-dependent callbacks
                statusCode = s.statusCode || {},
    
                // Headers (they are sent all at once)
                requestHeaders = {},
                requestHeadersNames = {},
    
                // The jqXHR state
                state = 0,
    
                // Default abort message
                strAbort = "canceled",
    
                // Fake xhr
                jqXHR = {
                    readyState: 0,
    
                    // Builds headers hashtable if needed
                    getResponseHeader: function( key ) {
                        var match;
                        if ( state === 2 ) {
                            if ( !responseHeaders ) {
                                responseHeaders = {};
                                while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
                                    responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
                                }
                            }
                            match = responseHeaders[ key.toLowerCase() ];
                        }
                        return match == null ? null : match;
                    },
    
                    // Raw string
                    getAllResponseHeaders: function() {
                        return state === 2 ? responseHeadersString : null;
                    },
    
                    // Caches the header
                    setRequestHeader: function( name, value ) {
                        var lname = name.toLowerCase();
                        if ( !state ) {
                            name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
                            requestHeaders[ name ] = value;
                        }
                        return this;
                    },
    
                    // Overrides response content-type header
                    overrideMimeType: function( type ) {
                        if ( !state ) {
                            s.mimeType = type;
                        }
                        return this;
                    },
    
                    // Status-dependent callbacks
                    statusCode: function( map ) {
                        var code;
                        if ( map ) {
                            if ( state < 2 ) {
                                for ( code in map ) {
    
                                    // Lazy-add the new callback in a way that preserves old ones
                                    statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
                                }
                            } else {
    
                                // Execute the appropriate callbacks
                                jqXHR.always( map[ jqXHR.status ] );
                            }
                        }
                        return this;
                    },
    
                    // Cancel the request
                    abort: function( statusText ) {
                        var finalText = statusText || strAbort;
                        if ( transport ) {
                            transport.abort( finalText );
                        }
                        done( 0, finalText );
                        return this;
                    }
                };
    
            // Attach deferreds
            deferred.promise( jqXHR ).complete = completeDeferred.add;
            jqXHR.success = jqXHR.done;
            jqXHR.error = jqXHR.fail;
    
            // Remove hash character (#7531: and string promotion)
            // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
            // Handle falsy url in the settings object (#10093: consistency with old signature)
            // We also use the url parameter if available
            s.url = ( ( url || s.url || ajaxLocation ) + "" )
                .replace( rhash, "" )
                .replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
    
            // Alias method option to type as per ticket #12004
            s.type = options.method || options.type || s.method || s.type;
    
            // Extract dataTypes list
            s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
    
            // A cross-domain request is in order when we have a protocol:host:port mismatch
            if ( s.crossDomain == null ) {
                parts = rurl.exec( s.url.toLowerCase() );
                s.crossDomain = !!( parts &&
                    ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
                        ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
                            ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
                );
            }
    
            // Convert data if not already a string
            if ( s.data && s.processData && typeof s.data !== "string" ) {
                s.data = jQuery.param( s.data, s.traditional );
            }
    
            // Apply prefilters
            inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
    
            // If request was aborted inside a prefilter, stop there
            if ( state === 2 ) {
                return jqXHR;
            }
    
            // We can fire global events as of now if asked to
            // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
            fireGlobals = jQuery.event && s.global;
    
            // Watch for a new set of requests
            if ( fireGlobals && jQuery.active++ === 0 ) {
                jQuery.event.trigger( "ajaxStart" );
            }
    
            // Uppercase the type
            s.type = s.type.toUpperCase();
    
            // Determine if request has content
            s.hasContent = !rnoContent.test( s.type );
    
            // Save the URL in case we're toying with the If-Modified-Since
            // and/or If-None-Match header later on
            cacheURL = s.url;
    
            // More options handling for requests with no content
            if ( !s.hasContent ) {
    
                // If data is available, append data to url
                if ( s.data ) {
                    cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
    
                    // #9682: remove data so that it's not used in an eventual retry
                    delete s.data;
                }
    
                // Add anti-cache in url if needed
                if ( s.cache === false ) {
                    s.url = rts.test( cacheURL ) ?
    
                        // If there is already a '_' parameter, set its value
                        cacheURL.replace( rts, "$1_=" + nonce++ ) :
    
                        // Otherwise add one to the end
                        cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
                }
            }
    
            // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
            if ( s.ifModified ) {
                if ( jQuery.lastModified[ cacheURL ] ) {
                    jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
                }
                if ( jQuery.etag[ cacheURL ] ) {
                    jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
                }
            }
    
            // Set the correct header, if data is being sent
            if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
                jqXHR.setRequestHeader( "Content-Type", s.contentType );
            }
    
            // Set the Accepts header for the server, depending on the dataType
            jqXHR.setRequestHeader(
                "Accept",
                s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
                    s.accepts[ s.dataTypes[ 0 ] ] +
                        ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
                    s.accepts[ "*" ]
            );
    
            // Check for headers option
            for ( i in s.headers ) {
                jqXHR.setRequestHeader( i, s.headers[ i ] );
            }
    
            // Allow custom headers/mimetypes and early abort
            if ( s.beforeSend &&
                ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
    
                // Abort if not done already and return
                return jqXHR.abort();
            }
    
            // aborting is no longer a cancellation
            strAbort = "abort";
    
            // Install callbacks on deferreds
            for ( i in { success: 1, error: 1, complete: 1 } ) {
                jqXHR[ i ]( s[ i ] );
            }
    
            // Get transport
            transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
    
            // If no transport, we auto-abort
            if ( !transport ) {
                done( -1, "No Transport" );
            } else {
                jqXHR.readyState = 1;
    
                // Send global event
                if ( fireGlobals ) {
                    globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
                }
    
                // If request was aborted inside ajaxSend, stop there
                if ( state === 2 ) {
                    return jqXHR;
                }
    
                // Timeout
                if ( s.async && s.timeout > 0 ) {
                    timeoutTimer = window.setTimeout( function() {
                        jqXHR.abort( "timeout" );
                    }, s.timeout );
                }
    
                try {
                    state = 1;
                    transport.send( requestHeaders, done );
                } catch ( e ) {
    
                    // Propagate exception as error if not done
                    if ( state < 2 ) {
                        done( -1, e );
    
                    // Simply rethrow otherwise
                    } else {
                        throw e;
                    }
                }
            }
    
            // Callback for when everything is done
            function done( status, nativeStatusText, responses, headers ) {
                var isSuccess, success, error, response, modified,
                    statusText = nativeStatusText;
    
                // Called once
                if ( state === 2 ) {
                    return;
                }
    
                // State is "done" now
                state = 2;
    
                // Clear timeout if it exists
                if ( timeoutTimer ) {
                    window.clearTimeout( timeoutTimer );
                }
    
                // Dereference transport for early garbage collection
                // (no matter how long the jqXHR object will be used)
                transport = undefined;
    
                // Cache response headers
                responseHeadersString = headers || "";
    
                // Set readyState
                jqXHR.readyState = status > 0 ? 4 : 0;
    
                // Determine if successful
                isSuccess = status >= 200 && status < 300 || status === 304;
    
                // Get response data
                if ( responses ) {
                    response = ajaxHandleResponses( s, jqXHR, responses );
                }
    
                // Convert no matter what (that way responseXXX fields are always set)
                response = ajaxConvert( s, response, jqXHR, isSuccess );
    
                // If successful, handle type chaining
                if ( isSuccess ) {
    
                    // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
                    if ( s.ifModified ) {
                        modified = jqXHR.getResponseHeader( "Last-Modified" );
                        if ( modified ) {
                            jQuery.lastModified[ cacheURL ] = modified;
                        }
                        modified = jqXHR.getResponseHeader( "etag" );
                        if ( modified ) {
                            jQuery.etag[ cacheURL ] = modified;
                        }
                    }
    
                    // if no content
                    if ( status === 204 || s.type === "HEAD" ) {
                        statusText = "nocontent";
    
                    // if not modified
                    } else if ( status === 304 ) {
                        statusText = "notmodified";
    
                    // If we have data, let's convert it
                    } else {
                        statusText = response.state;
                        success = response.data;
                        error = response.error;
                        isSuccess = !error;
                    }
                } else {
    
                    // We extract error from statusText
                    // then normalize statusText and status for non-aborts
                    error = statusText;
                    if ( status || !statusText ) {
                        statusText = "error";
                        if ( status < 0 ) {
                            status = 0;
                        }
                    }
                }
    
                // Set data for the fake xhr object
                jqXHR.status = status;
                jqXHR.statusText = ( nativeStatusText || statusText ) + "";
    
                // Success/Error
                if ( isSuccess ) {
                    deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
                } else {
                    deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
                }
    
                // Status-dependent callbacks
                jqXHR.statusCode( statusCode );
                statusCode = undefined;
    
                if ( fireGlobals ) {
                    globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
                        [ jqXHR, s, isSuccess ? success : error ] );
                }
    
                // Complete
                completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
    
                if ( fireGlobals ) {
                    globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
    
                    // Handle the global AJAX counter
                    if ( !( --jQuery.active ) ) {
                        jQuery.event.trigger( "ajaxStop" );
                    }
                }
            }
    
            return jqXHR;
        },
    
        getJSON: function( url, data, callback ) {
            return jQuery.get( url, data, callback, "json" );
        },
    
        getScript: function( url, callback ) {
            return jQuery.get( url, undefined, callback, "script" );
        }
    } );
    
    jQuery.each( [ "get", "post" ], function( i, method ) {
        jQuery[ method ] = function( url, data, callback, type ) {
    
            // shift arguments if data argument was omitted
            if ( jQuery.isFunction( data ) ) {
                type = type || callback;
                callback = data;
                data = undefined;
            }
    
            // The url can be an options object (which then must have .url)
            return jQuery.ajax( jQuery.extend( {
                url: url,
                type: method,
                dataType: type,
                data: data,
                success: callback
            }, jQuery.isPlainObject( url ) && url ) );
        };
    } );
    
    
    jQuery._evalUrl = function( url ) {
        return jQuery.ajax( {
            url: url,
    
            // Make this explicit, since user can override this through ajaxSetup (#11264)
            type: "GET",
            dataType: "script",
            cache: true,
            async: false,
            global: false,
            "throws": true
        } );
    };
    
    
    jQuery.fn.extend( {
        wrapAll: function( html ) {
            if ( jQuery.isFunction( html ) ) {
                return this.each( function( i ) {
                    jQuery( this ).wrapAll( html.call( this, i ) );
                } );
            }
    
            if ( this[ 0 ] ) {
    
                // The elements to wrap the target around
                var wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
    
                if ( this[ 0 ].parentNode ) {
                    wrap.insertBefore( this[ 0 ] );
                }
    
                wrap.map( function() {
                    var elem = this;
    
                    while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
                        elem = elem.firstChild;
                    }
    
                    return elem;
                } ).append( this );
            }
    
            return this;
        },
    
        wrapInner: function( html ) {
            if ( jQuery.isFunction( html ) ) {
                return this.each( function( i ) {
                    jQuery( this ).wrapInner( html.call( this, i ) );
                } );
            }
    
            return this.each( function() {
                var self = jQuery( this ),
                    contents = self.contents();
    
                if ( contents.length ) {
                    contents.wrapAll( html );
    
                } else {
                    self.append( html );
                }
            } );
        },
    
        wrap: function( html ) {
            var isFunction = jQuery.isFunction( html );
    
            return this.each( function( i ) {
                jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
            } );
        },
    
        unwrap: function() {
            return this.parent().each( function() {
                if ( !jQuery.nodeName( this, "body" ) ) {
                    jQuery( this ).replaceWith( this.childNodes );
                }
            } ).end();
        }
    } );
    
    
    function getDisplay( elem ) {
        return elem.style && elem.style.display || jQuery.css( elem, "display" );
    }
    
    function filterHidden( elem ) {
    
        // Disconnected elements are considered hidden
        if ( !jQuery.contains( elem.ownerDocument || document, elem ) ) {
            return true;
        }
        while ( elem && elem.nodeType === 1 ) {
            if ( getDisplay( elem ) === "none" || elem.type === "hidden" ) {
                return true;
            }
            elem = elem.parentNode;
        }
        return false;
    }
    
    jQuery.expr.filters.hidden = function( elem ) {
    
        // Support: Opera <= 12.12
        // Opera reports offsetWidths and offsetHeights less than zero on some elements
        return support.reliableHiddenOffsets() ?
            ( elem.offsetWidth <= 0 && elem.offsetHeight <= 0 &&
                !elem.getClientRects().length ) :
                filterHidden( elem );
    };
    
    jQuery.expr.filters.visible = function( elem ) {
        return !jQuery.expr.filters.hidden( elem );
    };
    
    
    
    
    var r20 = /%20/g,
        rbracket = /\[\]$/,
        rCRLF = /\r?\n/g,
        rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
        rsubmittable = /^(?:input|select|textarea|keygen)/i;
    
    function buildParams( prefix, obj, traditional, add ) {
        var name;
    
        if ( jQuery.isArray( obj ) ) {
    
            // Serialize array item.
            jQuery.each( obj, function( i, v ) {
                if ( traditional || rbracket.test( prefix ) ) {
    
                    // Treat each array item as a scalar.
                    add( prefix, v );
    
                } else {
    
                    // Item is non-scalar (array or object), encode its numeric index.
                    buildParams(
                        prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
                        v,
                        traditional,
                        add
                    );
                }
            } );
    
        } else if ( !traditional && jQuery.type( obj ) === "object" ) {
    
            // Serialize object item.
            for ( name in obj ) {
                buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
            }
    
        } else {
    
            // Serialize scalar item.
            add( prefix, obj );
        }
    }
    
    // Serialize an array of form elements or a set of
    // key/values into a query string
    jQuery.param = function( a, traditional ) {
        var prefix,
            s = [],
            add = function( key, value ) {
    
                // If value is a function, invoke it and return its value
                value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
                s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
            };
    
        // Set traditional to true for jQuery <= 1.3.2 behavior.
        if ( traditional === undefined ) {
            traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
        }
    
        // If an array was passed in, assume that it is an array of form elements.
        if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
    
            // Serialize the form elements
            jQuery.each( a, function() {
                add( this.name, this.value );
            } );
    
        } else {
    
            // If traditional, encode the "old" way (the way 1.3.2 or older
            // did it), otherwise encode params recursively.
            for ( prefix in a ) {
                buildParams( prefix, a[ prefix ], traditional, add );
            }
        }
    
        // Return the resulting serialization
        return s.join( "&" ).replace( r20, "+" );
    };
    
    jQuery.fn.extend( {
        serialize: function() {
            return jQuery.param( this.serializeArray() );
        },
        serializeArray: function() {
            return this.map( function() {
    
                // Can add propHook for "elements" to filter or add form elements
                var elements = jQuery.prop( this, "elements" );
                return elements ? jQuery.makeArray( elements ) : this;
            } )
            .filter( function() {
                var type = this.type;
    
                // Use .is(":disabled") so that fieldset[disabled] works
                return this.name && !jQuery( this ).is( ":disabled" ) &&
                    rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
                    ( this.checked || !rcheckableType.test( type ) );
            } )
            .map( function( i, elem ) {
                var val = jQuery( this ).val();
    
                return val == null ?
                    null :
                    jQuery.isArray( val ) ?
                        jQuery.map( val, function( val ) {
                            return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                        } ) :
                        { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
            } ).get();
        }
    } );
    
    
    // Create the request object
    // (This is still attached to ajaxSettings for backward compatibility)
    jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
    
        // Support: IE6-IE8
        function() {
    
            // XHR cannot access local files, always use ActiveX for that case
            if ( this.isLocal ) {
                return createActiveXHR();
            }
    
            // Support: IE 9-11
            // IE seems to error on cross-domain PATCH requests when ActiveX XHR
            // is used. In IE 9+ always use the native XHR.
            // Note: this condition won't catch Edge as it doesn't define
            // document.documentMode but it also doesn't support ActiveX so it won't
            // reach this code.
            if ( document.documentMode > 8 ) {
                return createStandardXHR();
            }
    
            // Support: IE<9
            // oldIE XHR does not support non-RFC2616 methods (#13240)
            // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
            // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
            // Although this check for six methods instead of eight
            // since IE also does not support "trace" and "connect"
            return /^(get|post|head|put|delete|options)$/i.test( this.type ) &&
                createStandardXHR() || createActiveXHR();
        } :
    
        // For all other browsers, use the standard XMLHttpRequest object
        createStandardXHR;
    
    var xhrId = 0,
        xhrCallbacks = {},
        xhrSupported = jQuery.ajaxSettings.xhr();
    
    // Support: IE<10
    // Open requests must be manually aborted on unload (#5280)
    // See https://support.microsoft.com/kb/2856746 for more info
    if ( window.attachEvent ) {
        window.attachEvent( "onunload", function() {
            for ( var key in xhrCallbacks ) {
                xhrCallbacks[ key ]( undefined, true );
            }
        } );
    }
    
    // Determine support properties
    support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
    xhrSupported = support.ajax = !!xhrSupported;
    
    // Create transport if the browser can provide an xhr
    if ( xhrSupported ) {
    
        jQuery.ajaxTransport( function( options ) {
    
            // Cross domain only allowed if supported through XMLHttpRequest
            if ( !options.crossDomain || support.cors ) {
    
                var callback;
    
                return {
                    send: function( headers, complete ) {
                        var i,
                            xhr = options.xhr(),
                            id = ++xhrId;
    
                        // Open the socket
                        xhr.open(
                            options.type,
                            options.url,
                            options.async,
                            options.username,
                            options.password
                        );
    
                        // Apply custom fields if provided
                        if ( options.xhrFields ) {
                            for ( i in options.xhrFields ) {
                                xhr[ i ] = options.xhrFields[ i ];
                            }
                        }
    
                        // Override mime type if needed
                        if ( options.mimeType && xhr.overrideMimeType ) {
                            xhr.overrideMimeType( options.mimeType );
                        }
    
                        // X-Requested-With header
                        // For cross-domain requests, seeing as conditions for a preflight are
                        // akin to a jigsaw puzzle, we simply never set it to be sure.
                        // (it can always be set on a per-request basis or even using ajaxSetup)
                        // For same-domain requests, won't change header if already provided.
                        if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
                            headers[ "X-Requested-With" ] = "XMLHttpRequest";
                        }
    
                        // Set headers
                        for ( i in headers ) {
    
                            // Support: IE<9
                            // IE's ActiveXObject throws a 'Type Mismatch' exception when setting
                            // request header to a null-value.
                            //
                            // To keep consistent with other XHR implementations, cast the value
                            // to string and ignore `undefined`.
                            if ( headers[ i ] !== undefined ) {
                                xhr.setRequestHeader( i, headers[ i ] + "" );
                            }
                        }
    
                        // Do send the request
                        // This may raise an exception which is actually
                        // handled in jQuery.ajax (so no try/catch here)
                        xhr.send( ( options.hasContent && options.data ) || null );
    
                        // Listener
                        callback = function( _, isAbort ) {
                            var status, statusText, responses;
    
                            // Was never called and is aborted or complete
                            if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
    
                                // Clean up
                                delete xhrCallbacks[ id ];
                                callback = undefined;
                                xhr.onreadystatechange = jQuery.noop;
    
                                // Abort manually if needed
                                if ( isAbort ) {
                                    if ( xhr.readyState !== 4 ) {
                                        xhr.abort();
                                    }
                                } else {
                                    responses = {};
                                    status = xhr.status;
    
                                    // Support: IE<10
                                    // Accessing binary-data responseText throws an exception
                                    // (#11426)
                                    if ( typeof xhr.responseText === "string" ) {
                                        responses.text = xhr.responseText;
                                    }
    
                                    // Firefox throws an exception when accessing
                                    // statusText for faulty cross-domain requests
                                    try {
                                        statusText = xhr.statusText;
                                    } catch ( e ) {
    
                                        // We normalize with Webkit giving an empty statusText
                                        statusText = "";
                                    }
    
                                    // Filter status for non standard behaviors
    
                                    // If the request is local and we have data: assume a success
                                    // (success with no data won't get notified, that's the best we
                                    // can do given current implementations)
                                    if ( !status && options.isLocal && !options.crossDomain ) {
                                        status = responses.text ? 200 : 404;
    
                                    // IE - #1450: sometimes returns 1223 when it should be 204
                                    } else if ( status === 1223 ) {
                                        status = 204;
                                    }
                                }
                            }
    
                            // Call complete if needed
                            if ( responses ) {
                                complete( status, statusText, responses, xhr.getAllResponseHeaders() );
                            }
                        };
    
                        // Do send the request
                        // `xhr.send` may raise an exception, but it will be
                        // handled in jQuery.ajax (so no try/catch here)
                        if ( !options.async ) {
    
                            // If we're in sync mode we fire the callback
                            callback();
                        } else if ( xhr.readyState === 4 ) {
    
                            // (IE6 & IE7) if it's in cache and has been
                            // retrieved directly we need to fire the callback
                            window.setTimeout( callback );
                        } else {
    
                            // Register the callback, but delay it in case `xhr.send` throws
                            // Add to the list of active xhr callbacks
                            xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
                        }
                    },
    
                    abort: function() {
                        if ( callback ) {
                            callback( undefined, true );
                        }
                    }
                };
            }
        } );
    }
    
    // Functions to create xhrs
    function createStandardXHR() {
        try {
            return new window.XMLHttpRequest();
        } catch ( e ) {}
    }
    
    function createActiveXHR() {
        try {
            return new window.ActiveXObject( "Microsoft.XMLHTTP" );
        } catch ( e ) {}
    }
    
    
    
    
    // Install script dataType
    jQuery.ajaxSetup( {
        accepts: {
            script: "text/javascript, application/javascript, " +
                "application/ecmascript, application/x-ecmascript"
        },
        contents: {
            script: /\b(?:java|ecma)script\b/
        },
        converters: {
            "text script": function( text ) {
                jQuery.globalEval( text );
                return text;
            }
        }
    } );
    
    // Handle cache's special case and global
    jQuery.ajaxPrefilter( "script", function( s ) {
        if ( s.cache === undefined ) {
            s.cache = false;
        }
        if ( s.crossDomain ) {
            s.type = "GET";
            s.global = false;
        }
    } );
    
    // Bind script tag hack transport
    jQuery.ajaxTransport( "script", function( s ) {
    
        // This transport only deals with cross domain requests
        if ( s.crossDomain ) {
    
            var script,
                head = document.head || jQuery( "head" )[ 0 ] || document.documentElement;
    
            return {
    
                send: function( _, callback ) {
    
                    script = document.createElement( "script" );
    
                    script.async = true;
    
                    if ( s.scriptCharset ) {
                        script.charset = s.scriptCharset;
                    }
    
                    script.src = s.url;
    
                    // Attach handlers for all browsers
                    script.onload = script.onreadystatechange = function( _, isAbort ) {
    
                        if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
    
                            // Handle memory leak in IE
                            script.onload = script.onreadystatechange = null;
    
                            // Remove the script
                            if ( script.parentNode ) {
                                script.parentNode.removeChild( script );
                            }
    
                            // Dereference the script
                            script = null;
    
                            // Callback if not abort
                            if ( !isAbort ) {
                                callback( 200, "success" );
                            }
                        }
                    };
    
                    // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
                    // Use native DOM manipulation to avoid our domManip AJAX trickery
                    head.insertBefore( script, head.firstChild );
                },
    
                abort: function() {
                    if ( script ) {
                        script.onload( undefined, true );
                    }
                }
            };
        }
    } );
    
    
    
    
    var oldCallbacks = [],
        rjsonp = /(=)\?(?=&|$)|\?\?/;
    
    // Default jsonp settings
    jQuery.ajaxSetup( {
        jsonp: "callback",
        jsonpCallback: function() {
            var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
            this[ callback ] = true;
            return callback;
        }
    } );
    
    // Detect, normalize options and install callbacks for jsonp requests
    jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
    
        var callbackName, overwritten, responseContainer,
            jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
                "url" :
                typeof s.data === "string" &&
                    ( s.contentType || "" )
                        .indexOf( "application/x-www-form-urlencoded" ) === 0 &&
                    rjsonp.test( s.data ) && "data"
            );
    
        // Handle iff the expected data type is "jsonp" or we have a parameter to set
        if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
    
            // Get callback name, remembering preexisting value associated with it
            callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
                s.jsonpCallback() :
                s.jsonpCallback;
    
            // Insert callback into url or form data
            if ( jsonProp ) {
                s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
            } else if ( s.jsonp !== false ) {
                s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
            }
    
            // Use data converter to retrieve json after script execution
            s.converters[ "script json" ] = function() {
                if ( !responseContainer ) {
                    jQuery.error( callbackName + " was not called" );
                }
                return responseContainer[ 0 ];
            };
    
            // force json dataType
            s.dataTypes[ 0 ] = "json";
    
            // Install callback
            overwritten = window[ callbackName ];
            window[ callbackName ] = function() {
                responseContainer = arguments;
            };
    
            // Clean-up function (fires after converters)
            jqXHR.always( function() {
    
                // If previous value didn't exist - remove it
                if ( overwritten === undefined ) {
                    jQuery( window ).removeProp( callbackName );
    
                // Otherwise restore preexisting value
                } else {
                    window[ callbackName ] = overwritten;
                }
    
                // Save back as free
                if ( s[ callbackName ] ) {
    
                    // make sure that re-using the options doesn't screw things around
                    s.jsonpCallback = originalSettings.jsonpCallback;
    
                    // save the callback name for future use
                    oldCallbacks.push( callbackName );
                }
    
                // Call if it was a function and we have a response
                if ( responseContainer && jQuery.isFunction( overwritten ) ) {
                    overwritten( responseContainer[ 0 ] );
                }
    
                responseContainer = overwritten = undefined;
            } );
    
            // Delegate to script
            return "script";
        }
    } );
    
    
    
    
    // data: string of html
    // context (optional): If specified, the fragment will be created in this context,
    // defaults to document
    // keepScripts (optional): If true, will include scripts passed in the html string
    jQuery.parseHTML = function( data, context, keepScripts ) {
        if ( !data || typeof data !== "string" ) {
            return null;
        }
        if ( typeof context === "boolean" ) {
            keepScripts = context;
            context = false;
        }
        context = context || document;
    
        var parsed = rsingleTag.exec( data ),
            scripts = !keepScripts && [];
    
        // Single tag
        if ( parsed ) {
            return [ context.createElement( parsed[ 1 ] ) ];
        }
    
        parsed = buildFragment( [ data ], context, scripts );
    
        if ( scripts && scripts.length ) {
            jQuery( scripts ).remove();
        }
    
        return jQuery.merge( [], parsed.childNodes );
    };
    
    
    // Keep a copy of the old load method
    var _load = jQuery.fn.load;
    
    /**
     * Load a url into a page
     */
    jQuery.fn.load = function( url, params, callback ) {
        if ( typeof url !== "string" && _load ) {
            return _load.apply( this, arguments );
        }
    
        var selector, type, response,
            self = this,
            off = url.indexOf( " " );
    
        if ( off > -1 ) {
            selector = jQuery.trim( url.slice( off, url.length ) );
            url = url.slice( 0, off );
        }
    
        // If it's a function
        if ( jQuery.isFunction( params ) ) {
    
            // We assume that it's the callback
            callback = params;
            params = undefined;
    
        // Otherwise, build a param string
        } else if ( params && typeof params === "object" ) {
            type = "POST";
        }
    
        // If we have elements to modify, make the request
        if ( self.length > 0 ) {
            jQuery.ajax( {
                url: url,
    
                // If "type" variable is undefined, then "GET" method will be used.
                // Make value of this field explicit since
                // user can override it through ajaxSetup method
                type: type || "GET",
                dataType: "html",
                data: params
            } ).done( function( responseText ) {
    
                // Save response for use in complete callback
                response = arguments;
    
                self.html( selector ?
    
                    // If a selector was specified, locate the right elements in a dummy div
                    // Exclude scripts to avoid IE 'Permission Denied' errors
                    jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
    
                    // Otherwise use the full result
                    responseText );
    
            // If the request succeeds, this function gets "data", "status", "jqXHR"
            // but they are ignored because response was set above.
            // If it fails, this function gets "jqXHR", "status", "error"
            } ).always( callback && function( jqXHR, status ) {
                self.each( function() {
                    callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
                } );
            } );
        }
    
        return this;
    };
    
    
    
    
    // Attach a bunch of functions for handling common AJAX events
    jQuery.each( [
        "ajaxStart",
        "ajaxStop",
        "ajaxComplete",
        "ajaxError",
        "ajaxSuccess",
        "ajaxSend"
    ], function( i, type ) {
        jQuery.fn[ type ] = function( fn ) {
            return this.on( type, fn );
        };
    } );
    
    
    
    
    jQuery.expr.filters.animated = function( elem ) {
        return jQuery.grep( jQuery.timers, function( fn ) {
            return elem === fn.elem;
        } ).length;
    };
    
    
    
    
    
    /**
     * Gets a window from an element
     */
    function getWindow( elem ) {
        return jQuery.isWindow( elem ) ?
            elem :
            elem.nodeType === 9 ?
                elem.defaultView || elem.parentWindow :
                false;
    }
    
    jQuery.offset = {
        setOffset: function( elem, options, i ) {
            var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
                position = jQuery.css( elem, "position" ),
                curElem = jQuery( elem ),
                props = {};
    
            // set position first, in-case top/left are set even on static elem
            if ( position === "static" ) {
                elem.style.position = "relative";
            }
    
            curOffset = curElem.offset();
            curCSSTop = jQuery.css( elem, "top" );
            curCSSLeft = jQuery.css( elem, "left" );
            calculatePosition = ( position === "absolute" || position === "fixed" ) &&
                jQuery.inArray( "auto", [ curCSSTop, curCSSLeft ] ) > -1;
    
            // need to be able to calculate position if either top or left
            // is auto and position is either absolute or fixed
            if ( calculatePosition ) {
                curPosition = curElem.position();
                curTop = curPosition.top;
                curLeft = curPosition.left;
            } else {
                curTop = parseFloat( curCSSTop ) || 0;
                curLeft = parseFloat( curCSSLeft ) || 0;
            }
    
            if ( jQuery.isFunction( options ) ) {
    
                // Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
                options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
            }
    
            if ( options.top != null ) {
                props.top = ( options.top - curOffset.top ) + curTop;
            }
            if ( options.left != null ) {
                props.left = ( options.left - curOffset.left ) + curLeft;
            }
    
            if ( "using" in options ) {
                options.using.call( elem, props );
            } else {
                curElem.css( props );
            }
        }
    };
    
    jQuery.fn.extend( {
        offset: function( options ) {
            if ( arguments.length ) {
                return options === undefined ?
                    this :
                    this.each( function( i ) {
                        jQuery.offset.setOffset( this, options, i );
                    } );
            }
    
            var docElem, win,
                box = { top: 0, left: 0 },
                elem = this[ 0 ],
                doc = elem && elem.ownerDocument;
    
            if ( !doc ) {
                return;
            }
    
            docElem = doc.documentElement;
    
            // Make sure it's not a disconnected DOM node
            if ( !jQuery.contains( docElem, elem ) ) {
                return box;
            }
    
            // If we don't have gBCR, just use 0,0 rather than error
            // BlackBerry 5, iOS 3 (original iPhone)
            if ( typeof elem.getBoundingClientRect !== "undefined" ) {
                box = elem.getBoundingClientRect();
            }
            win = getWindow( doc );
            return {
                top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
                left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
            };
        },
    
        position: function() {
            if ( !this[ 0 ] ) {
                return;
            }
    
            var offsetParent, offset,
                parentOffset = { top: 0, left: 0 },
                elem = this[ 0 ];
    
            // Fixed elements are offset from window (parentOffset = {top:0, left: 0},
            // because it is its only offset parent
            if ( jQuery.css( elem, "position" ) === "fixed" ) {
    
                // we assume that getBoundingClientRect is available when computed position is fixed
                offset = elem.getBoundingClientRect();
            } else {
    
                // Get *real* offsetParent
                offsetParent = this.offsetParent();
    
                // Get correct offsets
                offset = this.offset();
                if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
                    parentOffset = offsetParent.offset();
                }
    
                // Add offsetParent borders
                parentOffset.top  += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
                parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
            }
    
            // Subtract parent offsets and element margins
            // note: when an element has margin: auto the offsetLeft and marginLeft
            // are the same in Safari causing offset.left to incorrectly be 0
            return {
                top:  offset.top  - parentOffset.top - jQuery.css( elem, "marginTop", true ),
                left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
            };
        },
    
        offsetParent: function() {
            return this.map( function() {
                var offsetParent = this.offsetParent;
    
                while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) &&
                    jQuery.css( offsetParent, "position" ) === "static" ) ) {
                    offsetParent = offsetParent.offsetParent;
                }
                return offsetParent || documentElement;
            } );
        }
    } );
    
    // Create scrollLeft and scrollTop methods
    jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
        var top = /Y/.test( prop );
    
        jQuery.fn[ method ] = function( val ) {
            return access( this, function( elem, method, val ) {
                var win = getWindow( elem );
    
                if ( val === undefined ) {
                    return win ? ( prop in win ) ? win[ prop ] :
                        win.document.documentElement[ method ] :
                        elem[ method ];
                }
    
                if ( win ) {
                    win.scrollTo(
                        !top ? val : jQuery( win ).scrollLeft(),
                        top ? val : jQuery( win ).scrollTop()
                    );
    
                } else {
                    elem[ method ] = val;
                }
            }, method, val, arguments.length, null );
        };
    } );
    
    // Support: Safari<7-8+, Chrome<37-44+
    // Add the top/left cssHooks using jQuery.fn.position
    // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
    // getComputedStyle returns percent when specified for top/left/bottom/right
    // rather than make the css module depend on the offset module, we just check for it here
    jQuery.each( [ "top", "left" ], function( i, prop ) {
        jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
            function( elem, computed ) {
                if ( computed ) {
                    computed = curCSS( elem, prop );
    
                    // if curCSS returns percentage, fallback to offset
                    return rnumnonpx.test( computed ) ?
                        jQuery( elem ).position()[ prop ] + "px" :
                        computed;
                }
            }
        );
    } );
    
    
    // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
    jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
        jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
        function( defaultExtra, funcName ) {
    
            // margin is only for outerHeight, outerWidth
            jQuery.fn[ funcName ] = function( margin, value ) {
                var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
                    extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
    
                return access( this, function( elem, type, value ) {
                    var doc;
    
                    if ( jQuery.isWindow( elem ) ) {
    
                        // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
                        // isn't a whole lot we can do. See pull request at this URL for discussion:
                        // https://github.com/jquery/jquery/pull/764
                        return elem.document.documentElement[ "client" + name ];
                    }
    
                    // Get document width or height
                    if ( elem.nodeType === 9 ) {
                        doc = elem.documentElement;
    
                        // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
                        // whichever is greatest
                        // unfortunately, this causes bug #3838 in IE6/8 only,
                        // but there is currently no good, small way to fix it.
                        return Math.max(
                            elem.body[ "scroll" + name ], doc[ "scroll" + name ],
                            elem.body[ "offset" + name ], doc[ "offset" + name ],
                            doc[ "client" + name ]
                        );
                    }
    
                    return value === undefined ?
    
                        // Get width or height on the element, requesting but not forcing parseFloat
                        jQuery.css( elem, type, extra ) :
    
                        // Set width or height on the element
                        jQuery.style( elem, type, value, extra );
                }, type, chainable ? margin : undefined, chainable, null );
            };
        } );
    } );
    
    
    jQuery.fn.extend( {
    
        bind: function( types, data, fn ) {
            return this.on( types, null, data, fn );
        },
        unbind: function( types, fn ) {
            return this.off( types, null, fn );
        },
    
        delegate: function( selector, types, data, fn ) {
            return this.on( types, selector, data, fn );
        },
        undelegate: function( selector, types, fn ) {
    
            // ( namespace ) or ( selector, types [, fn] )
            return arguments.length === 1 ?
                this.off( selector, "**" ) :
                this.off( types, selector || "**", fn );
        }
    } );
    
    // The number of elements contained in the matched element set
    jQuery.fn.size = function() {
        return this.length;
    };
    
    jQuery.fn.andSelf = jQuery.fn.addBack;
    
    
    
    
    // Register as a named AMD module, since jQuery can be concatenated with other
    // files that may use define, but not via a proper concatenation script that
    // understands anonymous AMD modules. A named AMD is safest and most robust
    // way to register. Lowercase jquery is used because AMD module names are
    // derived from file names, and jQuery is normally delivered in a lowercase
    // file name. Do this after creating the global so that if an AMD module wants
    // to call noConflict to hide this version of jQuery, it will work.
    
    // Note that for maximum portability, libraries that are not jQuery should
    // declare themselves as anonymous modules, and avoid setting a global if an
    // AMD loader is present. jQuery is a special case. For more information, see
    // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
    
    if ( typeof define === "function" && define.amd ) {
        define( "jquery", [], function() {
            return jQuery;
        } );
    }
    
    
    
    var
    
        // Map over jQuery in case of overwrite
        _jQuery = window.jQuery,
    
        // Map over the $ in case of overwrite
        _$ = window.$;
    
    jQuery.noConflict = function( deep ) {
        if ( window.$ === jQuery ) {
            window.$ = _$;
        }
    
        if ( deep && window.jQuery === jQuery ) {
            window.jQuery = _jQuery;
        }
    
        return jQuery;
    };
    
    // Expose jQuery and $ identifiers, even in
    // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
    // and CommonJS for browser emulators (#13566)
    if ( !noGlobal ) {
        window.jQuery = window.$ = jQuery;
    }
    
    return jQuery;
    }));
    
    /*!
     * Bootstrap v3.3.7 (http://getbootstrap.com)
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under the MIT license
     */
    
    if (typeof jQuery === 'undefined') {
      throw new Error('Bootstrap\'s JavaScript requires jQuery')
    }
    
    +function ($) {
      'use strict';
      var version = $.fn.jquery.split(' ')[0].split('.')
      if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {
        throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')
      }
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: transition.js v3.3.7
     * http://getbootstrap.com/javascript/#transitions
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
      // ============================================================
    
      function transitionEnd() {
        var el = document.createElement('bootstrap')
    
        var transEndEventNames = {
          WebkitTransition : 'webkitTransitionEnd',
          MozTransition    : 'transitionend',
          OTransition      : 'oTransitionEnd otransitionend',
          transition       : 'transitionend'
        }
    
        for (var name in transEndEventNames) {
          if (el.style[name] !== undefined) {
            return { end: transEndEventNames[name] }
          }
        }
    
        return false // explicit for ie8 (  ._.)
      }
    
      // http://blog.alexmaccaw.com/css-transitions
      $.fn.emulateTransitionEnd = function (duration) {
        var called = false
        var $el = this
        $(this).one('bsTransitionEnd', function () { called = true })
        var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
        setTimeout(callback, duration)
        return this
      }
    
      $(function () {
        $.support.transition = transitionEnd()
    
        if (!$.support.transition) return
    
        $.event.special.bsTransitionEnd = {
          bindType: $.support.transition.end,
          delegateType: $.support.transition.end,
          handle: function (e) {
            if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
          }
        }
      })
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: alert.js v3.3.7
     * http://getbootstrap.com/javascript/#alerts
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // ALERT CLASS DEFINITION
      // ======================
    
      var dismiss = '[data-dismiss="alert"]'
      var Alert   = function (el) {
        $(el).on('click', dismiss, this.close)
      }
    
      Alert.VERSION = '3.3.7'
    
      Alert.TRANSITION_DURATION = 150
    
      Alert.prototype.close = function (e) {
        var $this    = $(this)
        var selector = $this.attr('data-target')
    
        if (!selector) {
          selector = $this.attr('href')
          selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }
    
        var $parent = $(selector === '#' ? [] : selector)
    
        if (e) e.preventDefault()
    
        if (!$parent.length) {
          $parent = $this.closest('.alert')
        }
    
        $parent.trigger(e = $.Event('close.bs.alert'))
    
        if (e.isDefaultPrevented()) return
    
        $parent.removeClass('in')
    
        function removeElement() {
          // detach from parent, fire event then clean up data
          $parent.detach().trigger('closed.bs.alert').remove()
        }
    
        $.support.transition && $parent.hasClass('fade') ?
          $parent
            .one('bsTransitionEnd', removeElement)
            .emulateTransitionEnd(Alert.TRANSITION_DURATION) :
          removeElement()
      }
    
    
      // ALERT PLUGIN DEFINITION
      // =======================
    
      function Plugin(option) {
        return this.each(function () {
          var $this = $(this)
          var data  = $this.data('bs.alert')
    
          if (!data) $this.data('bs.alert', (data = new Alert(this)))
          if (typeof option == 'string') data[option].call($this)
        })
      }
    
      var old = $.fn.alert
    
      $.fn.alert             = Plugin
      $.fn.alert.Constructor = Alert
    
    
      // ALERT NO CONFLICT
      // =================
    
      $.fn.alert.noConflict = function () {
        $.fn.alert = old
        return this
      }
    
    
      // ALERT DATA-API
      // ==============
    
      $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: button.js v3.3.7
     * http://getbootstrap.com/javascript/#buttons
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // BUTTON PUBLIC CLASS DEFINITION
      // ==============================
    
      var Button = function (element, options) {
        this.$element  = $(element)
        this.options   = $.extend({}, Button.DEFAULTS, options)
        this.isLoading = false
      }
    
      Button.VERSION  = '3.3.7'
    
      Button.DEFAULTS = {
        loadingText: 'loading...'
      }
    
      Button.prototype.setState = function (state) {
        var d    = 'disabled'
        var $el  = this.$element
        var val  = $el.is('input') ? 'val' : 'html'
        var data = $el.data()
    
        state += 'Text'
    
        if (data.resetText == null) $el.data('resetText', $el[val]())
    
        // push to event loop to allow forms to submit
        setTimeout($.proxy(function () {
          $el[val](data[state] == null ? this.options[state] : data[state])
    
          if (state == 'loadingText') {
            this.isLoading = true
            $el.addClass(d).attr(d, d).prop(d, true)
          } else if (this.isLoading) {
            this.isLoading = false
            $el.removeClass(d).removeAttr(d).prop(d, false)
          }
        }, this), 0)
      }
    
      Button.prototype.toggle = function () {
        var changed = true
        var $parent = this.$element.closest('[data-toggle="buttons"]')
    
        if ($parent.length) {
          var $input = this.$element.find('input')
          if ($input.prop('type') == 'radio') {
            if ($input.prop('checked')) changed = false
            $parent.find('.active').removeClass('active')
            this.$element.addClass('active')
          } else if ($input.prop('type') == 'checkbox') {
            if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
            this.$element.toggleClass('active')
          }
          $input.prop('checked', this.$element.hasClass('active'))
          if (changed) $input.trigger('change')
        } else {
          this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
          this.$element.toggleClass('active')
        }
      }
    
    
      // BUTTON PLUGIN DEFINITION
      // ========================
    
      function Plugin(option) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.button')
          var options = typeof option == 'object' && option
    
          if (!data) $this.data('bs.button', (data = new Button(this, options)))
    
          if (option == 'toggle') data.toggle()
          else if (option) data.setState(option)
        })
      }
    
      var old = $.fn.button
    
      $.fn.button             = Plugin
      $.fn.button.Constructor = Button
    
    
      // BUTTON NO CONFLICT
      // ==================
    
      $.fn.button.noConflict = function () {
        $.fn.button = old
        return this
      }
    
    
      // BUTTON DATA-API
      // ===============
    
      $(document)
        .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
          var $btn = $(e.target).closest('.btn')
          Plugin.call($btn, 'toggle')
          if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
            // Prevent double click on radios, and the double selections (so cancellation) on checkboxes
            e.preventDefault()
            // The target component still receive the focus
            if ($btn.is('input,button')) $btn.trigger('focus')
            else $btn.find('input:visible,button:visible').first().trigger('focus')
          }
        })
        .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
          $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
        })
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: carousel.js v3.3.7
     * http://getbootstrap.com/javascript/#carousel
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // CAROUSEL CLASS DEFINITION
      // =========================
    
      var Carousel = function (element, options) {
        this.$element    = $(element)
        this.$indicators = this.$element.find('.carousel-indicators')
        this.options     = options
        this.paused      = null
        this.sliding     = null
        this.interval    = null
        this.$active     = null
        this.$items      = null
    
        this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
    
        this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
          .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
          .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
      }
    
      Carousel.VERSION  = '3.3.7'
    
      Carousel.TRANSITION_DURATION = 600
    
      Carousel.DEFAULTS = {
        interval: 5000,
        pause: 'hover',
        wrap: true,
        keyboard: true
      }
    
      Carousel.prototype.keydown = function (e) {
        if (/input|textarea/i.test(e.target.tagName)) return
        switch (e.which) {
          case 37: this.prev(); break
          case 39: this.next(); break
          default: return
        }
    
        e.preventDefault()
      }
    
      Carousel.prototype.cycle = function (e) {
        e || (this.paused = false)
    
        this.interval && clearInterval(this.interval)
    
        this.options.interval
          && !this.paused
          && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
    
        return this
      }
    
      Carousel.prototype.getItemIndex = function (item) {
        this.$items = item.parent().children('.item')
        return this.$items.index(item || this.$active)
      }
    
      Carousel.prototype.getItemForDirection = function (direction, active) {
        var activeIndex = this.getItemIndex(active)
        var willWrap = (direction == 'prev' && activeIndex === 0)
                    || (direction == 'next' && activeIndex == (this.$items.length - 1))
        if (willWrap && !this.options.wrap) return active
        var delta = direction == 'prev' ? -1 : 1
        var itemIndex = (activeIndex + delta) % this.$items.length
        return this.$items.eq(itemIndex)
      }
    
      Carousel.prototype.to = function (pos) {
        var that        = this
        var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
    
        if (pos > (this.$items.length - 1) || pos < 0) return
    
        if (this.sliding)       return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
        if (activeIndex == pos) return this.pause().cycle()
    
        return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
      }
    
      Carousel.prototype.pause = function (e) {
        e || (this.paused = true)
    
        if (this.$element.find('.next, .prev').length && $.support.transition) {
          this.$element.trigger($.support.transition.end)
          this.cycle(true)
        }
    
        this.interval = clearInterval(this.interval)
    
        return this
      }
    
      Carousel.prototype.next = function () {
        if (this.sliding) return
        return this.slide('next')
      }
    
      Carousel.prototype.prev = function () {
        if (this.sliding) return
        return this.slide('prev')
      }
    
      Carousel.prototype.slide = function (type, next) {
        var $active   = this.$element.find('.item.active')
        var $next     = next || this.getItemForDirection(type, $active)
        var isCycling = this.interval
        var direction = type == 'next' ? 'left' : 'right'
        var that      = this
    
        if ($next.hasClass('active')) return (this.sliding = false)
    
        var relatedTarget = $next[0]
        var slideEvent = $.Event('slide.bs.carousel', {
          relatedTarget: relatedTarget,
          direction: direction
        })
        this.$element.trigger(slideEvent)
        if (slideEvent.isDefaultPrevented()) return
    
        this.sliding = true
    
        isCycling && this.pause()
    
        if (this.$indicators.length) {
          this.$indicators.find('.active').removeClass('active')
          var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
          $nextIndicator && $nextIndicator.addClass('active')
        }
    
        var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
        if ($.support.transition && this.$element.hasClass('slide')) {
          $next.addClass(type)
          $next[0].offsetWidth // force reflow
          $active.addClass(direction)
          $next.addClass(direction)
          $active
            .one('bsTransitionEnd', function () {
              $next.removeClass([type, direction].join(' ')).addClass('active')
              $active.removeClass(['active', direction].join(' '))
              that.sliding = false
              setTimeout(function () {
                that.$element.trigger(slidEvent)
              }, 0)
            })
            .emulateTransitionEnd(Carousel.TRANSITION_DURATION)
        } else {
          $active.removeClass('active')
          $next.addClass('active')
          this.sliding = false
          this.$element.trigger(slidEvent)
        }
    
        isCycling && this.cycle()
    
        return this
      }
    
    
      // CAROUSEL PLUGIN DEFINITION
      // ==========================
    
      function Plugin(option) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.carousel')
          var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
          var action  = typeof option == 'string' ? option : options.slide
    
          if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
          if (typeof option == 'number') data.to(option)
          else if (action) data[action]()
          else if (options.interval) data.pause().cycle()
        })
      }
    
      var old = $.fn.carousel
    
      $.fn.carousel             = Plugin
      $.fn.carousel.Constructor = Carousel
    
    
      // CAROUSEL NO CONFLICT
      // ====================
    
      $.fn.carousel.noConflict = function () {
        $.fn.carousel = old
        return this
      }
    
    
      // CAROUSEL DATA-API
      // =================
    
      var clickHandler = function (e) {
        var href
        var $this   = $(this)
        var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
        if (!$target.hasClass('carousel')) return
        var options = $.extend({}, $target.data(), $this.data())
        var slideIndex = $this.attr('data-slide-to')
        if (slideIndex) options.interval = false
    
        Plugin.call($target, options)
    
        if (slideIndex) {
          $target.data('bs.carousel').to(slideIndex)
        }
    
        e.preventDefault()
      }
    
      $(document)
        .on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
        .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
    
      $(window).on('load', function () {
        $('[data-ride="carousel"]').each(function () {
          var $carousel = $(this)
          Plugin.call($carousel, $carousel.data())
        })
      })
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: collapse.js v3.3.7
     * http://getbootstrap.com/javascript/#collapse
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    /* jshint latedef: false */
    
    +function ($) {
      'use strict';
    
      // COLLAPSE PUBLIC CLASS DEFINITION
      // ================================
    
      var Collapse = function (element, options) {
        this.$element      = $(element)
        this.options       = $.extend({}, Collapse.DEFAULTS, options)
        this.$trigger      = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
                               '[data-toggle="collapse"][data-target="#' + element.id + '"]')
        this.transitioning = null
    
        if (this.options.parent) {
          this.$parent = this.getParent()
        } else {
          this.addAriaAndCollapsedClass(this.$element, this.$trigger)
        }
    
        if (this.options.toggle) this.toggle()
      }
    
      Collapse.VERSION  = '3.3.7'
    
      Collapse.TRANSITION_DURATION = 350
    
      Collapse.DEFAULTS = {
        toggle: true
      }
    
      Collapse.prototype.dimension = function () {
        var hasWidth = this.$element.hasClass('width')
        return hasWidth ? 'width' : 'height'
      }
    
      Collapse.prototype.show = function () {
        if (this.transitioning || this.$element.hasClass('in')) return
    
        var activesData
        var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
    
        if (actives && actives.length) {
          activesData = actives.data('bs.collapse')
          if (activesData && activesData.transitioning) return
        }
    
        var startEvent = $.Event('show.bs.collapse')
        this.$element.trigger(startEvent)
        if (startEvent.isDefaultPrevented()) return
    
        if (actives && actives.length) {
          Plugin.call(actives, 'hide')
          activesData || actives.data('bs.collapse', null)
        }
    
        var dimension = this.dimension()
    
        this.$element
          .removeClass('collapse')
          .addClass('collapsing')[dimension](0)
          .attr('aria-expanded', true)
    
        this.$trigger
          .removeClass('collapsed')
          .attr('aria-expanded', true)
    
        this.transitioning = 1
    
        var complete = function () {
          this.$element
            .removeClass('collapsing')
            .addClass('collapse in')[dimension]('')
          this.transitioning = 0
          this.$element
            .trigger('shown.bs.collapse')
        }
    
        if (!$.support.transition) return complete.call(this)
    
        var scrollSize = $.camelCase(['scroll', dimension].join('-'))
    
        this.$element
          .one('bsTransitionEnd', $.proxy(complete, this))
          .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
      }
    
      Collapse.prototype.hide = function () {
        if (this.transitioning || !this.$element.hasClass('in')) return
    
        var startEvent = $.Event('hide.bs.collapse')
        this.$element.trigger(startEvent)
        if (startEvent.isDefaultPrevented()) return
    
        var dimension = this.dimension()
    
        this.$element[dimension](this.$element[dimension]())[0].offsetHeight
    
        this.$element
          .addClass('collapsing')
          .removeClass('collapse in')
          .attr('aria-expanded', false)
    
        this.$trigger
          .addClass('collapsed')
          .attr('aria-expanded', false)
    
        this.transitioning = 1
    
        var complete = function () {
          this.transitioning = 0
          this.$element
            .removeClass('collapsing')
            .addClass('collapse')
            .trigger('hidden.bs.collapse')
        }
    
        if (!$.support.transition) return complete.call(this)
    
        this.$element
          [dimension](0)
          .one('bsTransitionEnd', $.proxy(complete, this))
          .emulateTransitionEnd(Collapse.TRANSITION_DURATION)
      }
    
      Collapse.prototype.toggle = function () {
        this[this.$element.hasClass('in') ? 'hide' : 'show']()
      }
    
      Collapse.prototype.getParent = function () {
        return $(this.options.parent)
          .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
          .each($.proxy(function (i, element) {
            var $element = $(element)
            this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
          }, this))
          .end()
      }
    
      Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
        var isOpen = $element.hasClass('in')
    
        $element.attr('aria-expanded', isOpen)
        $trigger
          .toggleClass('collapsed', !isOpen)
          .attr('aria-expanded', isOpen)
      }
    
      function getTargetFromTrigger($trigger) {
        var href
        var target = $trigger.attr('data-target')
          || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
    
        return $(target)
      }
    
    
      // COLLAPSE PLUGIN DEFINITION
      // ==========================
    
      function Plugin(option) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.collapse')
          var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
    
          if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
          if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
          if (typeof option == 'string') data[option]()
        })
      }
    
      var old = $.fn.collapse
    
      $.fn.collapse             = Plugin
      $.fn.collapse.Constructor = Collapse
    
    
      // COLLAPSE NO CONFLICT
      // ====================
    
      $.fn.collapse.noConflict = function () {
        $.fn.collapse = old
        return this
      }
    
    
      // COLLAPSE DATA-API
      // =================
    
      $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
        var $this   = $(this)
    
        if (!$this.attr('data-target')) e.preventDefault()
    
        var $target = getTargetFromTrigger($this)
        var data    = $target.data('bs.collapse')
        var option  = data ? 'toggle' : $this.data()
    
        Plugin.call($target, option)
      })
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: dropdown.js v3.3.7
     * http://getbootstrap.com/javascript/#dropdowns
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // DROPDOWN CLASS DEFINITION
      // =========================
    
      var backdrop = '.dropdown-backdrop'
      var toggle   = '[data-toggle="dropdown"]'
      var Dropdown = function (element) {
        $(element).on('click.bs.dropdown', this.toggle)
      }
    
      Dropdown.VERSION = '3.3.7'
    
      function getParent($this) {
        var selector = $this.attr('data-target')
    
        if (!selector) {
          selector = $this.attr('href')
          selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }
    
        var $parent = selector && $(selector)
    
        return $parent && $parent.length ? $parent : $this.parent()
      }
    
      function clearMenus(e) {
        if (e && e.which === 3) return
        $(backdrop).remove()
        $(toggle).each(function () {
          var $this         = $(this)
          var $parent       = getParent($this)
          var relatedTarget = { relatedTarget: this }
    
          if (!$parent.hasClass('open')) return
    
          if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
    
          $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
    
          if (e.isDefaultPrevented()) return
    
          $this.attr('aria-expanded', 'false')
          $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
        })
      }
    
      Dropdown.prototype.toggle = function (e) {
        var $this = $(this)
    
        if ($this.is('.disabled, :disabled')) return
    
        var $parent  = getParent($this)
        var isActive = $parent.hasClass('open')
    
        clearMenus()
    
        if (!isActive) {
          if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
            // if mobile we use a backdrop because click events don't delegate
            $(document.createElement('div'))
              .addClass('dropdown-backdrop')
              .insertAfter($(this))
              .on('click', clearMenus)
          }
    
          var relatedTarget = { relatedTarget: this }
          $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
    
          if (e.isDefaultPrevented()) return
    
          $this
            .trigger('focus')
            .attr('aria-expanded', 'true')
    
          $parent
            .toggleClass('open')
            .trigger($.Event('shown.bs.dropdown', relatedTarget))
        }
    
        return false
      }
    
      Dropdown.prototype.keydown = function (e) {
        if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
    
        var $this = $(this)
    
        e.preventDefault()
        e.stopPropagation()
    
        if ($this.is('.disabled, :disabled')) return
    
        var $parent  = getParent($this)
        var isActive = $parent.hasClass('open')
    
        if (!isActive && e.which != 27 || isActive && e.which == 27) {
          if (e.which == 27) $parent.find(toggle).trigger('focus')
          return $this.trigger('click')
        }
    
        var desc = ' li:not(.disabled):visible a'
        var $items = $parent.find('.dropdown-menu' + desc)
    
        if (!$items.length) return
    
        var index = $items.index(e.target)
    
        if (e.which == 38 && index > 0)                 index--         // up
        if (e.which == 40 && index < $items.length - 1) index++         // down
        if (!~index)                                    index = 0
    
        $items.eq(index).trigger('focus')
      }
    
    
      // DROPDOWN PLUGIN DEFINITION
      // ==========================
    
      function Plugin(option) {
        return this.each(function () {
          var $this = $(this)
          var data  = $this.data('bs.dropdown')
    
          if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
          if (typeof option == 'string') data[option].call($this)
        })
      }
    
      var old = $.fn.dropdown
    
      $.fn.dropdown             = Plugin
      $.fn.dropdown.Constructor = Dropdown
    
    
      // DROPDOWN NO CONFLICT
      // ====================
    
      $.fn.dropdown.noConflict = function () {
        $.fn.dropdown = old
        return this
      }
    
    
      // APPLY TO STANDARD DROPDOWN ELEMENTS
      // ===================================
    
      $(document)
        .on('click.bs.dropdown.data-api', clearMenus)
        .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
        .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
        .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
        .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: modal.js v3.3.7
     * http://getbootstrap.com/javascript/#modals
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // MODAL CLASS DEFINITION
      // ======================
    
      var Modal = function (element, options) {
        this.options             = options
        this.$body               = $(document.body)
        this.$element            = $(element)
        this.$dialog             = this.$element.find('.modal-dialog')
        this.$backdrop           = null
        this.isShown             = null
        this.originalBodyPad     = null
        this.scrollbarWidth      = 0
        this.ignoreBackdropClick = false
    
        if (this.options.remote) {
          this.$element
            .find('.modal-content')
            .load(this.options.remote, $.proxy(function () {
              this.$element.trigger('loaded.bs.modal')
            }, this))
        }
      }
    
      Modal.VERSION  = '3.3.7'
    
      Modal.TRANSITION_DURATION = 300
      Modal.BACKDROP_TRANSITION_DURATION = 150
    
      Modal.DEFAULTS = {
        backdrop: true,
        keyboard: true,
        show: true
      }
    
      Modal.prototype.toggle = function (_relatedTarget) {
        return this.isShown ? this.hide() : this.show(_relatedTarget)
      }
    
      Modal.prototype.show = function (_relatedTarget) {
        var that = this
        var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
    
        this.$element.trigger(e)
    
        if (this.isShown || e.isDefaultPrevented()) return
    
        this.isShown = true
    
        this.checkScrollbar()
        this.setScrollbar()
        this.$body.addClass('modal-open')
    
        this.escape()
        this.resize()
    
        this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
    
        this.$dialog.on('mousedown.dismiss.bs.modal', function () {
          that.$element.one('mouseup.dismiss.bs.modal', function (e) {
            if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
          })
        })
    
        this.backdrop(function () {
          var transition = $.support.transition && that.$element.hasClass('fade')
    
          if (!that.$element.parent().length) {
            that.$element.appendTo(that.$body) // don't move modals dom position
          }
    
          that.$element
            .show()
            .scrollTop(0)
    
          that.adjustDialog()
    
          if (transition) {
            that.$element[0].offsetWidth // force reflow
          }
    
          that.$element.addClass('in')
    
          that.enforceFocus()
    
          var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
    
          transition ?
            that.$dialog // wait for modal to slide in
              .one('bsTransitionEnd', function () {
                that.$element.trigger('focus').trigger(e)
              })
              .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
            that.$element.trigger('focus').trigger(e)
        })
      }
    
      Modal.prototype.hide = function (e) {
        if (e) e.preventDefault()
    
        e = $.Event('hide.bs.modal')
    
        this.$element.trigger(e)
    
        if (!this.isShown || e.isDefaultPrevented()) return
    
        this.isShown = false
    
        this.escape()
        this.resize()
    
        $(document).off('focusin.bs.modal')
    
        this.$element
          .removeClass('in')
          .off('click.dismiss.bs.modal')
          .off('mouseup.dismiss.bs.modal')
    
        this.$dialog.off('mousedown.dismiss.bs.modal')
    
        $.support.transition && this.$element.hasClass('fade') ?
          this.$element
            .one('bsTransitionEnd', $.proxy(this.hideModal, this))
            .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
          this.hideModal()
      }
    
      Modal.prototype.enforceFocus = function () {
        $(document)
          .off('focusin.bs.modal') // guard against infinite focus loop
          .on('focusin.bs.modal', $.proxy(function (e) {
            if (document !== e.target &&
                this.$element[0] !== e.target &&
                !this.$element.has(e.target).length) {
              this.$element.trigger('focus')
            }
          }, this))
      }
    
      Modal.prototype.escape = function () {
        if (this.isShown && this.options.keyboard) {
          this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
            e.which == 27 && this.hide()
          }, this))
        } else if (!this.isShown) {
          this.$element.off('keydown.dismiss.bs.modal')
        }
      }
    
      Modal.prototype.resize = function () {
        if (this.isShown) {
          $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
        } else {
          $(window).off('resize.bs.modal')
        }
      }
    
      Modal.prototype.hideModal = function () {
        var that = this
        this.$element.hide()
        this.backdrop(function () {
          that.$body.removeClass('modal-open')
          that.resetAdjustments()
          that.resetScrollbar()
          that.$element.trigger('hidden.bs.modal')
        })
      }
    
      Modal.prototype.removeBackdrop = function () {
        this.$backdrop && this.$backdrop.remove()
        this.$backdrop = null
      }
    
      Modal.prototype.backdrop = function (callback) {
        var that = this
        var animate = this.$element.hasClass('fade') ? 'fade' : ''
    
        if (this.isShown && this.options.backdrop) {
          var doAnimate = $.support.transition && animate
    
          this.$backdrop = $(document.createElement('div'))
            .addClass('modal-backdrop ' + animate)
            .appendTo(this.$body)
    
          this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
            if (this.ignoreBackdropClick) {
              this.ignoreBackdropClick = false
              return
            }
            if (e.target !== e.currentTarget) return
            this.options.backdrop == 'static'
              ? this.$element[0].focus()
              : this.hide()
          }, this))
    
          if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
    
          this.$backdrop.addClass('in')
    
          if (!callback) return
    
          doAnimate ?
            this.$backdrop
              .one('bsTransitionEnd', callback)
              .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
            callback()
    
        } else if (!this.isShown && this.$backdrop) {
          this.$backdrop.removeClass('in')
    
          var callbackRemove = function () {
            that.removeBackdrop()
            callback && callback()
          }
          $.support.transition && this.$element.hasClass('fade') ?
            this.$backdrop
              .one('bsTransitionEnd', callbackRemove)
              .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
            callbackRemove()
    
        } else if (callback) {
          callback()
        }
      }
    
      // these following methods are used to handle overflowing modals
    
      Modal.prototype.handleUpdate = function () {
        this.adjustDialog()
      }
    
      Modal.prototype.adjustDialog = function () {
        var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
    
        this.$element.css({
          paddingLeft:  !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
          paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
        })
      }
    
      Modal.prototype.resetAdjustments = function () {
        this.$element.css({
          paddingLeft: '',
          paddingRight: ''
        })
      }
    
      Modal.prototype.checkScrollbar = function () {
        var fullWindowWidth = window.innerWidth
        if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
          var documentElementRect = document.documentElement.getBoundingClientRect()
          fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
        }
        this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
        this.scrollbarWidth = this.measureScrollbar()
      }
    
      Modal.prototype.setScrollbar = function () {
        var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
        this.originalBodyPad = document.body.style.paddingRight || ''
        if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
      }
    
      Modal.prototype.resetScrollbar = function () {
        this.$body.css('padding-right', this.originalBodyPad)
      }
    
      Modal.prototype.measureScrollbar = function () { // thx walsh
        var scrollDiv = document.createElement('div')
        scrollDiv.className = 'modal-scrollbar-measure'
        this.$body.append(scrollDiv)
        var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
        this.$body[0].removeChild(scrollDiv)
        return scrollbarWidth
      }
    
    
      // MODAL PLUGIN DEFINITION
      // =======================
    
      function Plugin(option, _relatedTarget) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.modal')
          var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
    
          if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
          if (typeof option == 'string') data[option](_relatedTarget)
          else if (options.show) data.show(_relatedTarget)
        })
      }
    
      var old = $.fn.modal
    
      $.fn.modal             = Plugin
      $.fn.modal.Constructor = Modal
    
    
      // MODAL NO CONFLICT
      // =================
    
      $.fn.modal.noConflict = function () {
        $.fn.modal = old
        return this
      }
    
    
      // MODAL DATA-API
      // ==============
    
      $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
        var $this   = $(this)
        var href    = $this.attr('href')
        var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
        var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
    
        if ($this.is('a')) e.preventDefault()
    
        $target.one('show.bs.modal', function (showEvent) {
          if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
          $target.one('hidden.bs.modal', function () {
            $this.is(':visible') && $this.trigger('focus')
          })
        })
        Plugin.call($target, option, this)
      })
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: tooltip.js v3.3.7
     * http://getbootstrap.com/javascript/#tooltip
     * Inspired by the original jQuery.tipsy by Jason Frame
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // TOOLTIP PUBLIC CLASS DEFINITION
      // ===============================
    
      var Tooltip = function (element, options) {
        this.type       = null
        this.options    = null
        this.enabled    = null
        this.timeout    = null
        this.hoverState = null
        this.$element   = null
        this.inState    = null
    
        this.init('tooltip', element, options)
      }
    
      Tooltip.VERSION  = '3.3.7'
    
      Tooltip.TRANSITION_DURATION = 150
    
      Tooltip.DEFAULTS = {
        animation: true,
        placement: 'top',
        selector: false,
        template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
        trigger: 'hover focus',
        title: '',
        delay: 0,
        html: false,
        container: false,
        viewport: {
          selector: 'body',
          padding: 0
        }
      }
    
      Tooltip.prototype.init = function (type, element, options) {
        this.enabled   = true
        this.type      = type
        this.$element  = $(element)
        this.options   = this.getOptions(options)
        this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
        this.inState   = { click: false, hover: false, focus: false }
    
        if (this.$element[0] instanceof document.constructor && !this.options.selector) {
          throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
        }
    
        var triggers = this.options.trigger.split(' ')
    
        for (var i = triggers.length; i--;) {
          var trigger = triggers[i]
    
          if (trigger == 'click') {
            this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
          } else if (trigger != 'manual') {
            var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin'
            var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
    
            this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
            this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
          }
        }
    
        this.options.selector ?
          (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
          this.fixTitle()
      }
    
      Tooltip.prototype.getDefaults = function () {
        return Tooltip.DEFAULTS
      }
    
      Tooltip.prototype.getOptions = function (options) {
        options = $.extend({}, this.getDefaults(), this.$element.data(), options)
    
        if (options.delay && typeof options.delay == 'number') {
          options.delay = {
            show: options.delay,
            hide: options.delay
          }
        }
    
        return options
      }
    
      Tooltip.prototype.getDelegateOptions = function () {
        var options  = {}
        var defaults = this.getDefaults()
    
        this._options && $.each(this._options, function (key, value) {
          if (defaults[key] != value) options[key] = value
        })
    
        return options
      }
    
      Tooltip.prototype.enter = function (obj) {
        var self = obj instanceof this.constructor ?
          obj : $(obj.currentTarget).data('bs.' + this.type)
    
        if (!self) {
          self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
          $(obj.currentTarget).data('bs.' + this.type, self)
        }
    
        if (obj instanceof $.Event) {
          self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
        }
    
        if (self.tip().hasClass('in') || self.hoverState == 'in') {
          self.hoverState = 'in'
          return
        }
    
        clearTimeout(self.timeout)
    
        self.hoverState = 'in'
    
        if (!self.options.delay || !self.options.delay.show) return self.show()
    
        self.timeout = setTimeout(function () {
          if (self.hoverState == 'in') self.show()
        }, self.options.delay.show)
      }
    
      Tooltip.prototype.isInStateTrue = function () {
        for (var key in this.inState) {
          if (this.inState[key]) return true
        }
    
        return false
      }
    
      Tooltip.prototype.leave = function (obj) {
        var self = obj instanceof this.constructor ?
          obj : $(obj.currentTarget).data('bs.' + this.type)
    
        if (!self) {
          self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
          $(obj.currentTarget).data('bs.' + this.type, self)
        }
    
        if (obj instanceof $.Event) {
          self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
        }
    
        if (self.isInStateTrue()) return
    
        clearTimeout(self.timeout)
    
        self.hoverState = 'out'
    
        if (!self.options.delay || !self.options.delay.hide) return self.hide()
    
        self.timeout = setTimeout(function () {
          if (self.hoverState == 'out') self.hide()
        }, self.options.delay.hide)
      }
    
      Tooltip.prototype.show = function () {
        var e = $.Event('show.bs.' + this.type)
    
        if (this.hasContent() && this.enabled) {
          this.$element.trigger(e)
    
          var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
          if (e.isDefaultPrevented() || !inDom) return
          var that = this
    
          var $tip = this.tip()
    
          var tipId = this.getUID(this.type)
    
          this.setContent()
          $tip.attr('id', tipId)
          this.$element.attr('aria-describedby', tipId)
    
          if (this.options.animation) $tip.addClass('fade')
    
          var placement = typeof this.options.placement == 'function' ?
            this.options.placement.call(this, $tip[0], this.$element[0]) :
            this.options.placement
    
          var autoToken = /\s?auto?\s?/i
          var autoPlace = autoToken.test(placement)
          if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
    
          $tip
            .detach()
            .css({ top: 0, left: 0, display: 'block' })
            .addClass(placement)
            .data('bs.' + this.type, this)
    
          this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
          this.$element.trigger('inserted.bs.' + this.type)
    
          var pos          = this.getPosition()
          var actualWidth  = $tip[0].offsetWidth
          var actualHeight = $tip[0].offsetHeight
    
          if (autoPlace) {
            var orgPlacement = placement
            var viewportDim = this.getPosition(this.$viewport)
    
            placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top'    :
                        placement == 'top'    && pos.top    - actualHeight < viewportDim.top    ? 'bottom' :
                        placement == 'right'  && pos.right  + actualWidth  > viewportDim.width  ? 'left'   :
                        placement == 'left'   && pos.left   - actualWidth  < viewportDim.left   ? 'right'  :
                        placement
    
            $tip
              .removeClass(orgPlacement)
              .addClass(placement)
          }
    
          var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
    
          this.applyPlacement(calculatedOffset, placement)
    
          var complete = function () {
            var prevHoverState = that.hoverState
            that.$element.trigger('shown.bs.' + that.type)
            that.hoverState = null
    
            if (prevHoverState == 'out') that.leave(that)
          }
    
          $.support.transition && this.$tip.hasClass('fade') ?
            $tip
              .one('bsTransitionEnd', complete)
              .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
            complete()
        }
      }
    
      Tooltip.prototype.applyPlacement = function (offset, placement) {
        var $tip   = this.tip()
        var width  = $tip[0].offsetWidth
        var height = $tip[0].offsetHeight
    
        // manually read margins because getBoundingClientRect includes difference
        var marginTop = parseInt($tip.css('margin-top'), 10)
        var marginLeft = parseInt($tip.css('margin-left'), 10)
    
        // we must check for NaN for ie 8/9
        if (isNaN(marginTop))  marginTop  = 0
        if (isNaN(marginLeft)) marginLeft = 0
    
        offset.top  += marginTop
        offset.left += marginLeft
    
        // $.fn.offset doesn't round pixel values
        // so we use setOffset directly with our own function B-0
        $.offset.setOffset($tip[0], $.extend({
          using: function (props) {
            $tip.css({
              top: Math.round(props.top),
              left: Math.round(props.left)
            })
          }
        }, offset), 0)
    
        $tip.addClass('in')
    
        // check to see if placing tip in new offset caused the tip to resize itself
        var actualWidth  = $tip[0].offsetWidth
        var actualHeight = $tip[0].offsetHeight
    
        if (placement == 'top' && actualHeight != height) {
          offset.top = offset.top + height - actualHeight
        }
    
        var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
    
        if (delta.left) offset.left += delta.left
        else offset.top += delta.top
    
        var isVertical          = /top|bottom/.test(placement)
        var arrowDelta          = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
        var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
    
        $tip.offset(offset)
        this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
      }
    
      Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
        this.arrow()
          .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
          .css(isVertical ? 'top' : 'left', '')
      }
    
      Tooltip.prototype.setContent = function () {
        var $tip  = this.tip()
        var title = this.getTitle()
    
        $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
        $tip.removeClass('fade in top bottom left right')
      }
    
      Tooltip.prototype.hide = function (callback) {
        var that = this
        var $tip = $(this.$tip)
        var e    = $.Event('hide.bs.' + this.type)
    
        function complete() {
          if (that.hoverState != 'in') $tip.detach()
          if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
            that.$element
              .removeAttr('aria-describedby')
              .trigger('hidden.bs.' + that.type)
          }
          callback && callback()
        }
    
        this.$element.trigger(e)
    
        if (e.isDefaultPrevented()) return
    
        $tip.removeClass('in')
    
        $.support.transition && $tip.hasClass('fade') ?
          $tip
            .one('bsTransitionEnd', complete)
            .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
          complete()
    
        this.hoverState = null
    
        return this
      }
    
      Tooltip.prototype.fixTitle = function () {
        var $e = this.$element
        if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
          $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
        }
      }
    
      Tooltip.prototype.hasContent = function () {
        return this.getTitle()
      }
    
      Tooltip.prototype.getPosition = function ($element) {
        $element   = $element || this.$element
    
        var el     = $element[0]
        var isBody = el.tagName == 'BODY'
    
        var elRect    = el.getBoundingClientRect()
        if (elRect.width == null) {
          // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
          elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
        }
        var isSvg = window.SVGElement && el instanceof window.SVGElement
        // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
        // See https://github.com/twbs/bootstrap/issues/20280
        var elOffset  = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
        var scroll    = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
        var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
    
        return $.extend({}, elRect, scroll, outerDims, elOffset)
      }
    
      Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
        return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2 } :
               placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
               placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
            /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
    
      }
    
      Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
        var delta = { top: 0, left: 0 }
        if (!this.$viewport) return delta
    
        var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
        var viewportDimensions = this.getPosition(this.$viewport)
    
        if (/right|left/.test(placement)) {
          var topEdgeOffset    = pos.top - viewportPadding - viewportDimensions.scroll
          var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
          if (topEdgeOffset < viewportDimensions.top) { // top overflow
            delta.top = viewportDimensions.top - topEdgeOffset
          } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
            delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
          }
        } else {
          var leftEdgeOffset  = pos.left - viewportPadding
          var rightEdgeOffset = pos.left + viewportPadding + actualWidth
          if (leftEdgeOffset < viewportDimensions.left) { // left overflow
            delta.left = viewportDimensions.left - leftEdgeOffset
          } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
            delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
          }
        }
    
        return delta
      }
    
      Tooltip.prototype.getTitle = function () {
        var title
        var $e = this.$element
        var o  = this.options
    
        title = $e.attr('data-original-title')
          || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)
    
        return title
      }
    
      Tooltip.prototype.getUID = function (prefix) {
        do prefix += ~~(Math.random() * 1000000)
        while (document.getElementById(prefix))
        return prefix
      }
    
      Tooltip.prototype.tip = function () {
        if (!this.$tip) {
          this.$tip = $(this.options.template)
          if (this.$tip.length != 1) {
            throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
          }
        }
        return this.$tip
      }
    
      Tooltip.prototype.arrow = function () {
        return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
      }
    
      Tooltip.prototype.enable = function () {
        this.enabled = true
      }
    
      Tooltip.prototype.disable = function () {
        this.enabled = false
      }
    
      Tooltip.prototype.toggleEnabled = function () {
        this.enabled = !this.enabled
      }
    
      Tooltip.prototype.toggle = function (e) {
        var self = this
        if (e) {
          self = $(e.currentTarget).data('bs.' + this.type)
          if (!self) {
            self = new this.constructor(e.currentTarget, this.getDelegateOptions())
            $(e.currentTarget).data('bs.' + this.type, self)
          }
        }
    
        if (e) {
          self.inState.click = !self.inState.click
          if (self.isInStateTrue()) self.enter(self)
          else self.leave(self)
        } else {
          self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
        }
      }
    
      Tooltip.prototype.destroy = function () {
        var that = this
        clearTimeout(this.timeout)
        this.hide(function () {
          that.$element.off('.' + that.type).removeData('bs.' + that.type)
          if (that.$tip) {
            that.$tip.detach()
          }
          that.$tip = null
          that.$arrow = null
          that.$viewport = null
          that.$element = null
        })
      }
    
    
      // TOOLTIP PLUGIN DEFINITION
      // =========================
    
      function Plugin(option) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.tooltip')
          var options = typeof option == 'object' && option
    
          if (!data && /destroy|hide/.test(option)) return
          if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
          if (typeof option == 'string') data[option]()
        })
      }
    
      var old = $.fn.tooltip
    
      $.fn.tooltip             = Plugin
      $.fn.tooltip.Constructor = Tooltip
    
    
      // TOOLTIP NO CONFLICT
      // ===================
    
      $.fn.tooltip.noConflict = function () {
        $.fn.tooltip = old
        return this
      }
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: popover.js v3.3.7
     * http://getbootstrap.com/javascript/#popovers
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // POPOVER PUBLIC CLASS DEFINITION
      // ===============================
    
      var Popover = function (element, options) {
        this.init('popover', element, options)
      }
    
      if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
    
      Popover.VERSION  = '3.3.7'
    
      Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
        placement: 'right',
        trigger: 'click',
        content: '',
        template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
      })
    
    
      // NOTE: POPOVER EXTENDS tooltip.js
      // ================================
    
      Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
    
      Popover.prototype.constructor = Popover
    
      Popover.prototype.getDefaults = function () {
        return Popover.DEFAULTS
      }
    
      Popover.prototype.setContent = function () {
        var $tip    = this.tip()
        var title   = this.getTitle()
        var content = this.getContent()
    
        $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
        $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
          this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
        ](content)
    
        $tip.removeClass('fade top bottom left right in')
    
        // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
        // this manually by checking the contents.
        if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
      }
    
      Popover.prototype.hasContent = function () {
        return this.getTitle() || this.getContent()
      }
    
      Popover.prototype.getContent = function () {
        var $e = this.$element
        var o  = this.options
    
        return $e.attr('data-content')
          || (typeof o.content == 'function' ?
                o.content.call($e[0]) :
                o.content)
      }
    
      Popover.prototype.arrow = function () {
        return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
      }
    
    
      // POPOVER PLUGIN DEFINITION
      // =========================
    
      function Plugin(option) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.popover')
          var options = typeof option == 'object' && option
    
          if (!data && /destroy|hide/.test(option)) return
          if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
          if (typeof option == 'string') data[option]()
        })
      }
    
      var old = $.fn.popover
    
      $.fn.popover             = Plugin
      $.fn.popover.Constructor = Popover
    
    
      // POPOVER NO CONFLICT
      // ===================
    
      $.fn.popover.noConflict = function () {
        $.fn.popover = old
        return this
      }
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: scrollspy.js v3.3.7
     * http://getbootstrap.com/javascript/#scrollspy
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // SCROLLSPY CLASS DEFINITION
      // ==========================
    
      function ScrollSpy(element, options) {
        this.$body          = $(document.body)
        this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
        this.options        = $.extend({}, ScrollSpy.DEFAULTS, options)
        this.selector       = (this.options.target || '') + ' .nav li > a'
        this.offsets        = []
        this.targets        = []
        this.activeTarget   = null
        this.scrollHeight   = 0
    
        this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
        this.refresh()
        this.process()
      }
    
      ScrollSpy.VERSION  = '3.3.7'
    
      ScrollSpy.DEFAULTS = {
        offset: 10
      }
    
      ScrollSpy.prototype.getScrollHeight = function () {
        return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
      }
    
      ScrollSpy.prototype.refresh = function () {
        var that          = this
        var offsetMethod  = 'offset'
        var offsetBase    = 0
    
        this.offsets      = []
        this.targets      = []
        this.scrollHeight = this.getScrollHeight()
    
        if (!$.isWindow(this.$scrollElement[0])) {
          offsetMethod = 'position'
          offsetBase   = this.$scrollElement.scrollTop()
        }
    
        this.$body
          .find(this.selector)
          .map(function () {
            var $el   = $(this)
            var href  = $el.data('target') || $el.attr('href')
            var $href = /^#./.test(href) && $(href)
    
            return ($href
              && $href.length
              && $href.is(':visible')
              && [[$href[offsetMethod]().top + offsetBase, href]]) || null
          })
          .sort(function (a, b) { return a[0] - b[0] })
          .each(function () {
            that.offsets.push(this[0])
            that.targets.push(this[1])
          })
      }
    
      ScrollSpy.prototype.process = function () {
        var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
        var scrollHeight = this.getScrollHeight()
        var maxScroll    = this.options.offset + scrollHeight - this.$scrollElement.height()
        var offsets      = this.offsets
        var targets      = this.targets
        var activeTarget = this.activeTarget
        var i
    
        if (this.scrollHeight != scrollHeight) {
          this.refresh()
        }
    
        if (scrollTop >= maxScroll) {
          return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
        }
    
        if (activeTarget && scrollTop < offsets[0]) {
          this.activeTarget = null
          return this.clear()
        }
    
        for (i = offsets.length; i--;) {
          activeTarget != targets[i]
            && scrollTop >= offsets[i]
            && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
            && this.activate(targets[i])
        }
      }
    
      ScrollSpy.prototype.activate = function (target) {
        this.activeTarget = target
    
        this.clear()
    
        var selector = this.selector +
          '[data-target="' + target + '"],' +
          this.selector + '[href="' + target + '"]'
    
        var active = $(selector)
          .parents('li')
          .addClass('active')
    
        if (active.parent('.dropdown-menu').length) {
          active = active
            .closest('li.dropdown')
            .addClass('active')
        }
    
        active.trigger('activate.bs.scrollspy')
      }
    
      ScrollSpy.prototype.clear = function () {
        $(this.selector)
          .parentsUntil(this.options.target, '.active')
          .removeClass('active')
      }
    
    
      // SCROLLSPY PLUGIN DEFINITION
      // ===========================
    
      function Plugin(option) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.scrollspy')
          var options = typeof option == 'object' && option
    
          if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
          if (typeof option == 'string') data[option]()
        })
      }
    
      var old = $.fn.scrollspy
    
      $.fn.scrollspy             = Plugin
      $.fn.scrollspy.Constructor = ScrollSpy
    
    
      // SCROLLSPY NO CONFLICT
      // =====================
    
      $.fn.scrollspy.noConflict = function () {
        $.fn.scrollspy = old
        return this
      }
    
    
      // SCROLLSPY DATA-API
      // ==================
    
      $(window).on('load.bs.scrollspy.data-api', function () {
        $('[data-spy="scroll"]').each(function () {
          var $spy = $(this)
          Plugin.call($spy, $spy.data())
        })
      })
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: tab.js v3.3.7
     * http://getbootstrap.com/javascript/#tabs
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // TAB CLASS DEFINITION
      // ====================
    
      var Tab = function (element) {
        // jscs:disable requireDollarBeforejQueryAssignment
        this.element = $(element)
        // jscs:enable requireDollarBeforejQueryAssignment
      }
    
      Tab.VERSION = '3.3.7'
    
      Tab.TRANSITION_DURATION = 150
    
      Tab.prototype.show = function () {
        var $this    = this.element
        var $ul      = $this.closest('ul:not(.dropdown-menu)')
        var selector = $this.data('target')
    
        if (!selector) {
          selector = $this.attr('href')
          selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }
    
        if ($this.parent('li').hasClass('active')) return
    
        var $previous = $ul.find('.active:last a')
        var hideEvent = $.Event('hide.bs.tab', {
          relatedTarget: $this[0]
        })
        var showEvent = $.Event('show.bs.tab', {
          relatedTarget: $previous[0]
        })
    
        $previous.trigger(hideEvent)
        $this.trigger(showEvent)
    
        if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
    
        var $target = $(selector)
    
        this.activate($this.closest('li'), $ul)
        this.activate($target, $target.parent(), function () {
          $previous.trigger({
            type: 'hidden.bs.tab',
            relatedTarget: $this[0]
          })
          $this.trigger({
            type: 'shown.bs.tab',
            relatedTarget: $previous[0]
          })
        })
      }
    
      Tab.prototype.activate = function (element, container, callback) {
        var $active    = container.find('> .active')
        var transition = callback
          && $.support.transition
          && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
    
        function next() {
          $active
            .removeClass('active')
            .find('> .dropdown-menu > .active')
              .removeClass('active')
            .end()
            .find('[data-toggle="tab"]')
              .attr('aria-expanded', false)
    
          element
            .addClass('active')
            .find('[data-toggle="tab"]')
              .attr('aria-expanded', true)
    
          if (transition) {
            element[0].offsetWidth // reflow for transition
            element.addClass('in')
          } else {
            element.removeClass('fade')
          }
    
          if (element.parent('.dropdown-menu').length) {
            element
              .closest('li.dropdown')
                .addClass('active')
              .end()
              .find('[data-toggle="tab"]')
                .attr('aria-expanded', true)
          }
    
          callback && callback()
        }
    
        $active.length && transition ?
          $active
            .one('bsTransitionEnd', next)
            .emulateTransitionEnd(Tab.TRANSITION_DURATION) :
          next()
    
        $active.removeClass('in')
      }
    
    
      // TAB PLUGIN DEFINITION
      // =====================
    
      function Plugin(option) {
        return this.each(function () {
          var $this = $(this)
          var data  = $this.data('bs.tab')
    
          if (!data) $this.data('bs.tab', (data = new Tab(this)))
          if (typeof option == 'string') data[option]()
        })
      }
    
      var old = $.fn.tab
    
      $.fn.tab             = Plugin
      $.fn.tab.Constructor = Tab
    
    
      // TAB NO CONFLICT
      // ===============
    
      $.fn.tab.noConflict = function () {
        $.fn.tab = old
        return this
      }
    
    
      // TAB DATA-API
      // ============
    
      var clickHandler = function (e) {
        e.preventDefault()
        Plugin.call($(this), 'show')
      }
    
      $(document)
        .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
        .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
    
    }(jQuery);
    
    /* ========================================================================
     * Bootstrap: affix.js v3.3.7
     * http://getbootstrap.com/javascript/#affix
     * ========================================================================
     * Copyright 2011-2016 Twitter, Inc.
     * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
     * ======================================================================== */
    
    
    +function ($) {
      'use strict';
    
      // AFFIX CLASS DEFINITION
      // ======================
    
      var Affix = function (element, options) {
        this.options = $.extend({}, Affix.DEFAULTS, options)
    
        this.$target = $(this.options.target)
          .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
          .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))
    
        this.$element     = $(element)
        this.affixed      = null
        this.unpin        = null
        this.pinnedOffset = null
    
        this.checkPosition()
      }
    
      Affix.VERSION  = '3.3.7'
    
      Affix.RESET    = 'affix affix-top affix-bottom'
    
      Affix.DEFAULTS = {
        offset: 0,
        target: window
      }
    
      Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
        var scrollTop    = this.$target.scrollTop()
        var position     = this.$element.offset()
        var targetHeight = this.$target.height()
    
        if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
    
        if (this.affixed == 'bottom') {
          if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
          return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
        }
    
        var initializing   = this.affixed == null
        var colliderTop    = initializing ? scrollTop : position.top
        var colliderHeight = initializing ? targetHeight : height
    
        if (offsetTop != null && scrollTop <= offsetTop) return 'top'
        if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
    
        return false
      }
    
      Affix.prototype.getPinnedOffset = function () {
        if (this.pinnedOffset) return this.pinnedOffset
        this.$element.removeClass(Affix.RESET).addClass('affix')
        var scrollTop = this.$target.scrollTop()
        var position  = this.$element.offset()
        return (this.pinnedOffset = position.top - scrollTop)
      }
    
      Affix.prototype.checkPositionWithEventLoop = function () {
        setTimeout($.proxy(this.checkPosition, this), 1)
      }
    
      Affix.prototype.checkPosition = function () {
        if (!this.$element.is(':visible')) return
    
        var height       = this.$element.height()
        var offset       = this.options.offset
        var offsetTop    = offset.top
        var offsetBottom = offset.bottom
        var scrollHeight = Math.max($(document).height(), $(document.body).height())
    
        if (typeof offset != 'object')         offsetBottom = offsetTop = offset
        if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
        if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
    
        var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
    
        if (this.affixed != affix) {
          if (this.unpin != null) this.$element.css('top', '')
    
          var affixType = 'affix' + (affix ? '-' + affix : '')
          var e         = $.Event(affixType + '.bs.affix')
    
          this.$element.trigger(e)
    
          if (e.isDefaultPrevented()) return
    
          this.affixed = affix
          this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
    
          this.$element
            .removeClass(Affix.RESET)
            .addClass(affixType)
            .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
        }
    
        if (affix == 'bottom') {
          this.$element.offset({
            top: scrollHeight - height - offsetBottom
          })
        }
      }
    
    
      // AFFIX PLUGIN DEFINITION
      // =======================
    
      function Plugin(option) {
        return this.each(function () {
          var $this   = $(this)
          var data    = $this.data('bs.affix')
          var options = typeof option == 'object' && option
    
          if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
          if (typeof option == 'string') data[option]()
        })
      }
    
      var old = $.fn.affix
    
      $.fn.affix             = Plugin
      $.fn.affix.Constructor = Affix
    
    
      // AFFIX NO CONFLICT
      // =================
    
      $.fn.affix.noConflict = function () {
        $.fn.affix = old
        return this
      }
    
    
      // AFFIX DATA-API
      // ==============
    
      $(window).on('load', function () {
        $('[data-spy="affix"]').each(function () {
          var $spy = $(this)
          var data = $spy.data()
    
          data.offset = data.offset || {}
    
          if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
          if (data.offsetTop    != null) data.offset.top    = data.offsetTop
    
          Plugin.call($spy, data)
        })
      })
    
    }(jQuery);
    
    /*! jQuery UI - v1.11.4 - 2016-07-15
    * http://jqueryui.com
    * Includes: core.js, widget.js, mouse.js, position.js, draggable.js, droppable.js, resizable.js, selectable.js, sortable.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, menu.js, progressbar.js, selectmenu.js, slider.js, spinner.js, tabs.js, effect.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js
    * Copyright jQuery Foundation and other contributors; Licensed MIT */
    
    (function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(e,s){var n,o,a,r=e.nodeName.toLowerCase();return"area"===r?(n=e.parentNode,o=n.name,e.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap='#"+o+"']")[0],!!a&&i(a)):!1):(/^(input|select|textarea|button|object)$/.test(r)?!e.disabled:"a"===r?e.href||s:s)&&i(e)}function i(e){return t.expr.filters.visible(e)&&!t(e).parents().addBack().filter(function(){return"hidden"===t.css(this,"visibility")}).length}function s(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function n(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=o(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function o(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.delegate(i,"mouseout",function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).delegate(i,"mouseover",a)}function a(){t.datepicker._isDisabledDatepicker(_.inline?_.dpDiv.parent()[0]:_.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function r(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function h(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.extend(t.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),t.fn.extend({scrollParent:function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])},focusable:function(i){return e(i,!isNaN(t.attr(i,"tabindex")))},tabbable:function(i){var s=t.attr(i,"tabindex"),n=isNaN(s);return(n||s>=0)&&e(i,!n)}}),t("<a>").outerWidth(1).jquery||t.each(["Width","Height"],function(e,i){function s(e,i,s,o){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),o&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],o=i.toLowerCase(),a={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?a["inner"+i].call(this):this.each(function(){t(this).css(o,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?a["outer"+i].call(this,e):this.each(function(){t(this).css(o,s(this,e,!0,n)+"px")})}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(t.fn.removeData=function(e){return function(i){return arguments.length?e.call(this,t.camelCase(i)):e.call(this)}}(t.fn.removeData)),t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),t.fn.extend({focus:function(e){return function(i,s){return"number"==typeof i?this.each(function(){var e=this;setTimeout(function(){t(e).focus(),s&&s.call(e)},i)}):e.apply(this,arguments)}}(t.fn.focus),disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(e){if(void 0!==e)return this.css("zIndex",e);if(this.length)for(var i,s,n=t(this[0]);n.length&&n[0]!==document;){if(i=n.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0}}),t.ui.plugin={add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;o.length>n;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}};var l=0,c=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r,h={},l=e.split(".")[0];return e=e.split(".")[1],n=l+"-"+e,s||(s=i,i=t.Widget),t.expr[":"][n.toLowerCase()]=function(e){return!!t.data(e,n)},t[l]=t[l]||{},o=t[l][e],a=t[l][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new a(t,e)},t.extend(a,o,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),r=new i,r.options=t.widget.extend({},r.options),t.each(s,function(e,s){return t.isFunction(s)?(h[e]=function(){var t=function(){return i.prototype[e].apply(this,arguments)},n=function(t){return i.prototype[e].apply(this,t)};return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(h[e]=s,void 0)}),a.prototype=t.widget.extend(r,{widgetEventPrefix:o?r.widgetEventPrefix||e:e},h,{constructor:a,namespace:l,widgetName:e,widgetFullName:n}),o?(t.each(o._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,a,i._proto)}),delete o._childConstructors):i._childConstructors.push(a),t.widget.bridge(e,a),a},t.widget.extend=function(e){for(var i,s,n=c.call(arguments,1),o=0,a=n.length;a>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(e[i]=t.isPlainObject(s)?t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var o="string"==typeof n,a=c.call(arguments,1),r=this;return o?this.each(function(){var i,o=t.data(this,s);return"instance"===n?(r=o,!1):o?t.isFunction(o[n])&&"_"!==n.charAt(0)?(i=o[n].apply(o,a),i!==o&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+n+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+n+"'")}):(a.length&&(n=t.widget.extend.apply(null,[n].concat(a))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=l++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:t.noop,_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(t.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return this.options[t]=e,"disabled"===t&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!e),e&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+o.eventNamespace,c=h[2];c?n.delegate(c,l,r):i.bind(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(i).undelegate(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){t(e.currentTarget).addClass("ui-state-hover")},mouseleave:function(e){t(e.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){t(e.currentTarget).addClass("ui-state-focus")},focusout:function(e){t(e.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget;var u=!1;t(document).mouseup(function(){u=!1}),t.widget("ui.mouse",{version:"1.11.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.bind("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).bind("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){if(!u){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,s=1===e.which,n="string"==typeof this.options.cancel&&e.target.nodeName?t(e.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(e)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(e)!==!1,!this._mouseStarted)?(e.preventDefault(),!0):(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),u=!0,!0)):!0}},_mouseMove:function(e){if(this._mouseMoved){if(t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button)return this._mouseUp(e);if(!e.which)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){return this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),u=!1,!1},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),function(){function e(t,e,i){return[parseFloat(t[0])*(p.test(t[0])?e/100:1),parseFloat(t[1])*(p.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}t.ui=t.ui||{};var n,o,a=Math.max,r=Math.abs,h=Math.round,l=/left|center|right/,c=/top|center|bottom/,u=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,p=/%$/,f=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,o="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:o?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s||n?i.width():i.outerWidth(),height:s||n?i.height():i.outerHeight()}}},t.fn.position=function(n){if(!n||!n.of)return f.apply(this,arguments);n=t.extend({},n);var p,g,m,_,v,b,y=t(n.of),w=t.position.getWithinInfo(n.within),k=t.position.getScrollInfo(w),x=(n.collision||"flip").split(" "),C={};return b=s(y),y[0].preventDefault&&(n.at="left top"),g=b.width,m=b.height,_=b.offset,v=t.extend({},_),t.each(["my","at"],function(){var t,e,i=(n[this]||"").split(" ");1===i.length&&(i=l.test(i[0])?i.concat(["center"]):c.test(i[0])?["center"].concat(i):["center","center"]),i[0]=l.test(i[0])?i[0]:"center",i[1]=c.test(i[1])?i[1]:"center",t=u.exec(i[0]),e=u.exec(i[1]),C[this]=[t?t[0]:0,e?e[0]:0],n[this]=[d.exec(i[0])[0],d.exec(i[1])[0]]}),1===x.length&&(x[1]=x[0]),"right"===n.at[0]?v.left+=g:"center"===n.at[0]&&(v.left+=g/2),"bottom"===n.at[1]?v.top+=m:"center"===n.at[1]&&(v.top+=m/2),p=e(C.at,g,m),v.left+=p[0],v.top+=p[1],this.each(function(){var s,l,c=t(this),u=c.outerWidth(),d=c.outerHeight(),f=i(this,"marginLeft"),b=i(this,"marginTop"),D=u+f+i(this,"marginRight")+k.width,I=d+b+i(this,"marginBottom")+k.height,T=t.extend({},v),P=e(C.my,c.outerWidth(),c.outerHeight());"right"===n.my[0]?T.left-=u:"center"===n.my[0]&&(T.left-=u/2),"bottom"===n.my[1]?T.top-=d:"center"===n.my[1]&&(T.top-=d/2),T.left+=P[0],T.top+=P[1],o||(T.left=h(T.left),T.top=h(T.top)),s={marginLeft:f,marginTop:b},t.each(["left","top"],function(e,i){t.ui.position[x[e]]&&t.ui.position[x[e]][i](T,{targetWidth:g,targetHeight:m,elemWidth:u,elemHeight:d,collisionPosition:s,collisionWidth:D,collisionHeight:I,offset:[p[0]+P[0],p[1]+P[1]],my:n.my,at:n.at,within:w,elem:c})}),n.using&&(l=function(t){var e=_.left-T.left,i=e+g-u,s=_.top-T.top,o=s+m-d,h={target:{element:y,left:_.left,top:_.top,width:g,height:m},element:{element:c,left:T.left,top:T.top,width:u,height:d},horizontal:0>i?"left":e>0?"right":"center",vertical:0>o?"top":s>0?"bottom":"middle"};u>g&&g>r(e+i)&&(h.horizontal="center"),d>m&&m>r(s+o)&&(h.vertical="middle"),h.important=a(r(e),r(i))>a(r(s),r(o))?"horizontal":"vertical",n.using.call(this,t,h)}),c.offset(t.extend(T,{using:l}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,o=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-o-n;e.collisionWidth>o?h>0&&0>=l?(i=t.left+h+e.collisionWidth-o-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+o-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=a(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,o=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-o-n;e.collisionHeight>o?h>0&&0>=l?(i=t.top+h+e.collisionHeight-o-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+o-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=a(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,a=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-a-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-a-o,(0>i||r(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>r(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,a=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-a-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-a-o,(0>s||r(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,(i>0||u>r(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}},function(){var e,i,s,n,a,r=document.getElementsByTagName("body")[0],h=document.createElement("div");e=document.createElement(r?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},r&&t.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(a in s)e.style[a]=s[a];e.appendChild(h),i=r||document.documentElement,i.insertBefore(e,i.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",n=t(h).offset().left,o=n>10&&11>n,e.innerHTML="",i.removeChild(e)}()}(),t.ui.position,t.widget("ui.draggable",t.ui.mouse,{version:"1.11.4",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(e){var i=this.options;return this._blurActiveElement(e),this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("<div>").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=this.document[0];if(this.handleElement.is(e.target))try{i.activeElement&&"body"!==i.activeElement.nodeName.toLowerCase()&&t(i.activeElement).blur()}catch(s){}},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._normalizeRightBottom(),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.focus(),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this.handleElement.addClass("ui-draggable-handle")},_removeHandleClassName:function(){this.handleElement.removeClass("ui-draggable-handle")},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper),n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(h=this.originalPageX),"x"===a.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}
    },_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_normalizeRightBottom:function(){"y"!==this.options.axis&&"auto"!==this.helper.css("right")&&(this.helper.width(this.helper.width()),this.helper.css("right","auto")),"x"!==this.options.axis&&"auto"!==this.helper.css("bottom")&&(this.helper.height(this.helper.height()),this.helper.css("bottom","auto"))},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){var t=this;t.isOver?(t.isOver=0,s.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,o=this;o.positionAbs=s.positionAbs,o.helperProportions=s.helperProportions,o.offset.click=s.offset.click,o._intersectsWith(o.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==o&&this._intersectsWith(this.containerCache)&&t.contains(o.element[0],this.element[0])&&(n=!1),n})),n?(o.isOver||(o.isOver=1,s._parent=i.helper.parent(),o.currentItem=i.helper.appendTo(o.element).data("ui-sortable-item",!0),o.options._helper=o.options.helper,o.options.helper=function(){return i.helper[0]},e.target=o.currentItem[0],o._mouseCapture(e,!0),o._mouseStart(e,!0,!0),o.offset.click.top=s.offset.click.top,o.offset.click.left=s.offset.click.left,o.offset.parent.left-=s.offset.parent.left-o.offset.parent.left,o.offset.parent.top-=s.offset.parent.top-o.offset.parent.top,s._trigger("toSortable",e),s.dropped=o.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,o.fromOutside=s),o.currentItem&&(o._mouseDrag(e),i.position=o.position)):o.isOver&&(o.isOver=0,o.cancelHelperRemoval=!0,o.options._revert=o.options.revert,o.options.revert=!1,o._trigger("out",e,o._uiHash(o)),o._mouseStop(e,!0),o.options.revert=o.options._revert,o.options.helper=o.options._helper,o.placeholder&&o.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),o=s.options;n.css("cursor")&&(o._cursor=n.css("cursor")),n.css("cursor",o.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("opacity")&&(o._opacity=n.css("opacity")),n.css("opacity",o.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(e,i,s){var n=s.options,o=!1,a=s.scrollParentNotHidden[0],r=s.document[0];a!==r&&"HTML"!==a.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+a.offsetHeight-e.pageY<n.scrollSensitivity?a.scrollTop=o=a.scrollTop+n.scrollSpeed:e.pageY-s.overflowOffset.top<n.scrollSensitivity&&(a.scrollTop=o=a.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+a.offsetWidth-e.pageX<n.scrollSensitivity?a.scrollLeft=o=a.scrollLeft+n.scrollSpeed:e.pageX-s.overflowOffset.left<n.scrollSensitivity&&(a.scrollLeft=o=a.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(e.pageY-t(r).scrollTop()<n.scrollSensitivity?o=t(r).scrollTop(t(r).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(r).scrollTop())<n.scrollSensitivity&&(o=t(r).scrollTop(t(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(e.pageX-t(r).scrollLeft()<n.scrollSensitivity?o=t(r).scrollLeft(t(r).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(r).scrollLeft())<n.scrollSensitivity&&(o=t(r).scrollLeft(t(r).scrollLeft()+n.scrollSpeed)))),o!==!1&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(s,e)}}),t.ui.plugin.add("draggable","snap",{start:function(e,i,s){var n=s.options;s.snapElements=[],t(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var e=t(this),i=e.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:e.outerWidth(),height:e.outerHeight(),top:i.top,left:i.left})})},drag:function(e,i,s){var n,o,a,r,h,l,c,u,d,p,f=s.options,g=f.snapTolerance,m=i.offset.left,_=m+s.helperProportions.width,v=i.offset.top,b=v+s.helperProportions.height;for(d=s.snapElements.length-1;d>=0;d--)h=s.snapElements[d].left-s.margins.left,l=h+s.snapElements[d].width,c=s.snapElements[d].top-s.margins.top,u=c+s.snapElements[d].height,h-g>_||m>l+g||c-g>b||v>u+g||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)?(s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(n=g>=Math.abs(c-b),o=g>=Math.abs(u-v),a=g>=Math.abs(h-_),r=g>=Math.abs(l-m),n&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||o||a||r,"outer"!==f.snapMode&&(n=g>=Math.abs(c-v),o=g>=Math.abs(u-b),a=g>=Math.abs(h-m),r=g>=Math.abs(l-_),n&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||o||a||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||o||a||r||p)}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,o=s.options,a=t.makeArray(t(o.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});a.length&&(n=parseInt(t(a[0]).css("zIndex"),10)||0,t(a).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+a.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("zIndex")&&(o._zIndex=n.css("zIndex")),n.css("zIndex",o.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.droppable",{version:"1.11.4",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],void 0):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this.element.addClass("ui-droppable")},_addToManager:function(e){t.ui.ddmanager.droppables[e]=t.ui.ddmanager.droppables[e]||[],t.ui.ddmanager.droppables[e].push(this)},_splice:function(t){for(var e=0;t.length>e;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var e=t.ui.ddmanager.droppables[this.options.scope];this._splice(e),this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(e,i){if("accept"===e)this.accept=t.isFunction(i)?i:function(t){return t.is(i)};else if("scope"===e){var s=t.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(e,i)},_activate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=t(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&t.ui.intersect(s,t.extend(i,{offset:i.element.offset()}),i.options.tolerance,e)?(n=!0,!1):void 0}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}}}),t.ui.intersect=function(){function t(t,e,i){return t>=e&&e+i>t}return function(e,i,s,n){if(!i.offset)return!1;var o=(e.positionAbs||e.position.absolute).left+e.margins.left,a=(e.positionAbs||e.position.absolute).top+e.margins.top,r=o+e.helperProportions.width,h=a+e.helperProportions.height,l=i.offset.left,c=i.offset.top,u=l+i.proportions().width,d=c+i.proportions().height;switch(s){case"fit":return o>=l&&u>=r&&a>=c&&d>=h;case"intersect":return o+e.helperProportions.width/2>l&&u>r-e.helperProportions.width/2&&a+e.helperProportions.height/2>c&&d>h-e.helperProportions.height/2;case"pointer":return t(n.pageY,c,i.proportions().height)&&t(n.pageX,l,i.proportions().width);case"touch":return(a>=c&&d>=a||h>=c&&d>=h||c>a&&h>d)&&(o>=l&&u>=o||r>=l&&u>=r||l>o&&r>u);default:return!1}}}(),t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,o=t.ui.ddmanager.droppables[e.options.scope]||[],a=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;o.length>s;s++)if(!(o[s].options.disabled||e&&!o[s].accept.call(o[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===o[s].element[0]){o[s].proportions().height=0;continue t}o[s].visible="none"!==o[s].element.css("display"),o[s].visible&&("mousedown"===a&&o[s]._activate.call(o[s],i),o[s].offset=o[s].element.offset(),o[s].proportions({width:o[s].element[0].offsetWidth,height:o[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&t.ui.intersect(e,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").bind("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,o,a=t.ui.intersect(e,this,this.options.tolerance,i),r=!a&&this.isover?"isout":a&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,o=this.element.parents(":data(ui-droppable)").filter(function(){return t(this).droppable("instance").options.scope===n}),o.length&&(s=t(o[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").unbind("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}},t.ui.droppable,t.widget("ui.resizable",t.ui.mouse,{version:"1.11.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseInt(t,10)||0},_isNumber:function(t){return!isNaN(parseInt(t,10))},_hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)},_create:function(){var e,i,s,n,o,a=this,r=this.options;if(this.element.addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=r.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),e=this.handles.split(","),this.handles={},i=0;e.length>i;i++)s=t.trim(e[i]),o="ui-resizable-"+s,n=t("<div class='ui-resizable-handle "+o+"'></div>"),n.css({zIndex:r.zIndex}),"se"===s&&n.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(n);this._renderAxis=function(e){var i,s,n,o;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:a._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.mouseover(function(){a.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),a.axis=n&&n[1]?n[1]:"se")}),r.autoHide&&(this._handles.hide(),t(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(t(this).removeClass("ui-resizable-autohide"),a._handles.show())}).mouseleave(function(){r.disabled||a.resizing||(t(this).addClass("ui-resizable-autohide"),a._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,o=this.options,a=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),o.containment&&(i+=t(o.containment).scrollLeft()||0,s+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),a.addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,o=this.axis,a=e.pageX-n.left||0,r=e.pageY-n.top||0,h=this._change[o];return this._updatePrevProperties(),h?(i=h.apply(this,[e,a,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:c.sizeDiff.height,o=s?0:c.sizeDiff.width,a={width:c.helper.width()-o,height:c.helper.height()-n},r=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null,h=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(a,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s,n,o,a=this.options;o={minWidth:this._isNumber(a.minWidth)?a.minWidth:0,maxWidth:this._isNumber(a.maxWidth)?a.maxWidth:1/0,minHeight:this._isNumber(a.minHeight)?a.minHeight:0,maxHeight:this._isNumber(a.maxHeight)?a.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,s=o.minWidth/this.aspectRatio,i=o.maxHeight*this.aspectRatio,n=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),s>o.minHeight&&(o.minHeight=s),o.maxWidth>i&&(o.maxWidth=i),o.maxHeight>n&&(o.maxHeight=n)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,l=/sw|nw|w/.test(i),c=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&l&&(t.left=r-e.minWidth),s&&l&&(t.left=r-e.maxWidth),a&&c&&(t.top=h-e.minHeight),n&&c&&(t.top=h-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];4>e;e++)i[e]=parseInt(s[e],10)||0,i[e]+=parseInt(n[e],10)||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;this._proportionallyResizeElements.length>e;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-a},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,c=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,o,a,r,h=t(this).resizable("instance"),l=h.options,c=h.element,u=l.containment,d=u instanceof t?u.get(0):/parent/.test(u)?c.parent().get(0):u;d&&(h.containerElement=t(d),/document/.test(u)||u===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=h._num(e.css("padding"+s))}),h.containerOffset=e.offset(),h.containerPosition=e.position(),h.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,o=h.containerSize.width,a=h._hasScroll(d,"left")?d.scrollWidth:o,r=h._hasScroll(d)?d.scrollHeight:n,h.parentData={element:d,left:s.left,top:s.top,width:a,height:r}))},resize:function(e){var i,s,n,o,a=t(this).resizable("instance"),r=a.options,h=a.containerOffset,l=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(a._helper?h.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-h.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio,p=!1),a.position.left=r.helper?h.left:0),l.top<(a._helper?h.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-h.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio,p=!1),a.position.top=a._helper?h.top:0),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o?(a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top):(a.offset.left=a.element.offset().left,a.offset.top=a.element.offset().top),i=Math.abs(a.sizeDiff.width+(a._helper?a.offset.left-u.left:a.offset.left-h.left)),s=Math.abs(a.sizeDiff.height+(a._helper?a.offset.top-u.top:a.offset.top-h.top)),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio,p=!1)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio,p=!1)),p||(a.position.left=a.prevPosition.left,a.position.top=a.prevPosition.top,a.size.width=a.prevSize.width,a.size.height=a.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),h=a.outerWidth()-e.sizeDiff.width,l=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance"),i=e.options;t(i.alsoResize).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseInt(e.width(),10),height:parseInt(e.height(),10),left:parseInt(e.css("left"),10),top:parseInt(e.css("top"),10)})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left:s.position.left-a.left||0};t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},o=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.options,s=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof i.ghost?i.ghost:""),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,o=i.originalSize,a=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,c=h[1]||1,u=Math.round((n.width-o.width)/l)*l,d=Math.round((n.height-o.height)/c)*c,p=o.width+u,f=o.height+d,g=s.maxWidth&&p>s.maxWidth,m=s.maxHeight&&f>s.maxHeight,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=h,_&&(p+=l),v&&(f+=c),g&&(p-=l),m&&(f-=c),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=a.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=a.left-u):((0>=f-c||0>=p-l)&&(e=i._getPaddingPlusBorderDimensions(this)),f-c>0?(i.size.height=f,i.position.top=a.top-d):(f=c-e.height,i.size.height=f,i.position.top=a.top+o.height-f),p-l>0?(i.size.width=p,i.position.left=a.left-u):(p=l-e.width,i.size.width=p,i.position.left=a.left+o.width-p))}}),t.ui.resizable,t.widget("ui.selectable",t.ui.mouse,{version:"1.11.4",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e,i=this;
    this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e=t(i.options.filter,i.element[0]),e.addClass("ui-selectee"),e.each(function(){var e=t(this),i=e.offset();t.data(this,"selectable-item",{element:this,$element:e,left:i.left,top:i.top,right:i.left+e.outerWidth(),bottom:i.top+e.outerHeight(),startselected:!1,selected:e.hasClass("ui-selected"),selecting:e.hasClass("ui-selecting"),unselecting:e.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=e.addClass("ui-selectee"),this._mouseInit(),this.helper=t("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),n.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,o=this.opos[0],a=this.opos[1],r=e.pageX,h=e.pageY;return o>r&&(i=r,r=o,o=i),a>h&&(i=h,h=a,a=i),this.helper.css({left:o,top:a,width:r-o,height:h-a}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),l=!1;i&&i.element!==s.element[0]&&("touch"===n.tolerance?l=!(i.left>r||o>i.right||i.top>h||a>i.bottom):"fit"===n.tolerance&&(l=i.left>o&&r>i.right&&i.top>a&&h>i.bottom),l?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),t.widget("ui.sortable",t.ui.mouse,{version:"1.11.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return t>=e&&e+i>t},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){this.element.find(".ui-sortable-handle").removeClass("ui-sortable-handle"),t.each(this.items,function(){(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item).addClass("ui-sortable-handle")})},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").find(".ui-sortable-handle").removeClass("ui-sortable-handle"),this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):void 0}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-this.document.scrollTop()<a.scrollSensitivity?r=this.document.scrollTop(this.document.scrollTop()-a.scrollSpeed):this.window.height()-(e.pageY-this.document.scrollTop())<a.scrollSensitivity&&(r=this.document.scrollTop(this.document.scrollTop()+a.scrollSpeed)),e.pageX-this.document.scrollLeft()<a.scrollSensitivity?r=this.document.scrollLeft(this.document.scrollLeft()-a.scrollSpeed):this.window.width()-(e.pageX-this.document.scrollLeft())<a.scrollSensitivity&&(r=this.document.scrollLeft(this.document.scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var e="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),i="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),s=e&&i,n=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return s?this.floating?o&&"right"===o||"down"===n?2:1:n&&("down"===n?2:1):!1},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,o,a,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(o=t(l[s],this.document[0]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&h.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i],this.document[0]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]).addClass(i||e.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("<tr>",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t("<td>&#160;</td>",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,o,a,r,h,l,c,u,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0);if(d)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,o=null,c=d.floating||this._isFloating(this.currentItem),a=c?"left":"top",r=c?"width":"height",u=c?"clientX":"clientY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[a],l=!1,e[u]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(e[u]-h)&&(n=Math.abs(e[u]-h),o=this.items[s],this.direction=l?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;o?this._rearrange(e,o,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.width():this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.accordion",{version:"1.11.4",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e=this.options.icons;e&&(t("<span>").addClass("ui-accordion-header-icon ui-icon "+e.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(e.header).addClass(e.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").css("display","").removeAttr("role").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),"disabled"===t&&(this.element.toggleClass("ui-state-disabled",!!e).attr("aria-disabled",e),this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!e)),void 0)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),o.focus(),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().focus()},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-state-default ui-corner-all"),this.panels=this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide(),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))
    },_refresh:function(){var e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active).addClass("ui-accordion-header-active ui-state-active ui-corner-top").removeClass("ui-corner-all"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(){var e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){e=Math.max(e,t(this).css("height","").height())}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n[0]===s[0],a=o&&i.collapsible,r=a?t():n.next(),h=s.next(),l={oldHeader:s,oldPanel:h,newHeader:a?t():n,newPanel:r};e.preventDefault(),o&&!i.collapsible||this._trigger("beforeActivate",e,l)===!1||(i.active=a?!1:this.headers.index(n),this.active=o?t():n,this._toggle(l),s.removeClass("ui-accordion-header-active ui-state-active"),i.icons&&s.children(".ui-accordion-header-icon").removeClass(i.icons.activeHeader).addClass(i.icons.header),o||(n.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),i.icons&&n.children(".ui-accordion-header-icon").removeClass(i.icons.header).addClass(i.icons.activeHeader),n.next().addClass("ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,o,a=this,r=0,h=t.css("box-sizing"),l=t.length&&(!e.length||t.index()<e.index()),c=this.options.animate||{},u=l&&c.down||c,d=function(){a._toggleComplete(i)};return"number"==typeof u&&(o=u),"string"==typeof u&&(n=u),n=n||u.easing||c.easing,o=o||u.duration||c.duration,e.length?t.length?(s=t.show().outerHeight(),e.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(this.showProps,{duration:o,easing:n,complete:d,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?"content-box"===h&&(r+=i.now):"content"!==a.options.heightStyle&&(i.now=Math.round(s-e.outerHeight()-r),r=0)}}),void 0):e.animate(this.hideProps,o,n,d):t.animate(this.showProps,o,n,d)},_toggleComplete:function(t){var e=t.oldPanel;e.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}}),t.widget("ui.menu",{version:"1.11.4",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},items:"> *",menus:"ul",position:{my:"left-1 top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target);!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&t(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.currentTarget);i.siblings(".ui-state-active").removeClass("ui-state-active"),this.focus(e,i)}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){t.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var e=t(this);e.data("ui-menu-submenu-carat")&&e.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",n=String.fromCharCode(e.keyCode),o=!1,clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.preventDefault()},_activate:function(t){this.active.is(".ui-state-disabled")||(this.active.is("[aria-haspopup='true']")?this.expand(t):this.select(t))},refresh:function(){var e,i,s=this,n=this.options.icons.submenu,o=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),o.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.parent(),s=t("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),e=o.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);s._isDivider(e)&&e.addClass("ui-widget-content ui-menu-divider")}),i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){"icons"===t&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(e.submenu),"disabled"===t&&this.element.toggleClass("ui-state-disabled",!!e).attr("aria-disabled",e),this._super(t,e)},focus:function(t,e){var i,s;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.addClass("ui-state-focus").removeClass("ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this.active.removeClass("ui-state-focus"),this.active=null,this._trigger("blur",t,{item:this.active}))},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(t.trim(t(this).text()))})}}),t.widget("ui.autocomplete",{version:"1.11.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n;this.isMultiLine=o?!0:a?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];t(e.target).closest(".ui-menu-item").length||this._delay(function(){var e=this;this.document.one("mousedown",function(s){s.target===e.element[0]||s.target===i||t.contains(i,s.target)||e.close()})})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(t,e){var i=e.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",t,{item:i})&&this._value(i.value),this.term=this._value(),this.close(t),this.selectedItem=i}}),this.liveRegion=t("<span>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):void 0},_search:function(t){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(t){t&&(t=this._normalize(t)),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({},e,{label:e.label||e.value,value:e.value||e.label})})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").text(i.label).appendTo(e)},_move:function(t,e){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[t](e),void 0):(this.search(null,e),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(t,e),e.preventDefault())}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.children().hide(),t("<div>").text(i).appendTo(this.liveRegion))}}),t.ui.autocomplete;var d,p="ui-button ui-widget ui-state-default ui-corner-all",f="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",g=function(){var e=t(this);setTimeout(function(){e.find(":ui-button").button("refresh")},1)},m=function(e){var i=e.name,s=e.form,n=t([]);return i&&(i=i.replace(/'/g,"\\'"),n=s?t(s).find("[name='"+i+"'][type=radio]"):t("[name='"+i+"'][type=radio]",e.ownerDocument).filter(function(){return!this.form})),n};t.widget("ui.button",{version:"1.11.4",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,g),"boolean"!=typeof this.options.disabled?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var e=this,i=this.options,s="checkbox"===this.type||"radio"===this.type,n=s?"":"ui-state-active";null===i.label&&(i.label="input"===this.type?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(p).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){i.disabled||this===d&&t(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){i.disabled||t(this).removeClass(n)}).bind("click"+this.eventNamespace,function(t){i.disabled&&(t.preventDefault(),t.stopImmediatePropagation())}),this._on({focus:function(){this.buttonElement.addClass("ui-state-focus")},blur:function(){this.buttonElement.removeClass("ui-state-focus")}}),s&&this.element.bind("change"+this.eventNamespace,function(){e.refresh()}),"checkbox"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){return i.disabled?!1:void 0}):"radio"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){if(i.disabled)return!1;t(this).addClass("ui-state-active"),e.buttonElement.attr("aria-pressed","true");var s=e.element[0];m(s).not(s).map(function(){return t(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){return i.disabled?!1:(t(this).addClass("ui-state-active"),d=this,e.document.one("mouseup",function(){d=null}),void 0)}).bind("mouseup"+this.eventNamespace,function(){return i.disabled?!1:(t(this).removeClass("ui-state-active"),void 0)}).bind("keydown"+this.eventNamespace,function(e){return i.disabled?!1:((e.keyCode===t.ui.keyCode.SPACE||e.keyCode===t.ui.keyCode.ENTER)&&t(this).addClass("ui-state-active"),void 0)}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){t(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(e){e.keyCode===t.ui.keyCode.SPACE&&t(this).click()})),this._setOption("disabled",i.disabled),this._resetButton()},_determineButtonType:function(){var t,e,i;this.type=this.element.is("[type=checkbox]")?"checkbox":this.element.is("[type=radio]")?"radio":this.element.is("input")?"input":"button","checkbox"===this.type||"radio"===this.type?(t=this.element.parents().last(),e="label[for='"+this.element.attr("id")+"']",this.buttonElement=t.find(e),this.buttonElement.length||(t=t.length?t.siblings():this.element.siblings(),this.buttonElement=t.filter(e),this.buttonElement.length||(this.buttonElement=t.find(e))),this.element.addClass("ui-helper-hidden-accessible"),i=this.element.is(":checked"),i&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",i)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(p+" ui-state-active "+f).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(t,e){return this._super(t,e),"disabled"===t?(this.widget().toggleClass("ui-state-disabled",!!e),this.element.prop("disabled",!!e),e&&("checkbox"===this.type||"radio"===this.type?this.buttonElement.removeClass("ui-state-focus"):this.buttonElement.removeClass("ui-state-focus ui-state-active")),void 0):(this._resetButton(),void 0)},refresh:function(){var e=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");e!==this.options.disabled&&this._setOption("disabled",e),"radio"===this.type?m(this.element[0]).each(function(){t(this).is(":checked")?t(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):t(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):"checkbox"===this.type&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if("input"===this.type)return this.options.label&&this.element.val(this.options.label),void 0;var e=this.buttonElement.removeClass(f),i=t("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(e.empty()).text(),s=this.options.icons,n=s.primary&&s.secondary,o=[];s.primary||s.secondary?(this.options.text&&o.push("ui-button-text-icon"+(n?"s":s.primary?"-primary":"-secondary")),s.primary&&e.prepend("<span class='ui-button-icon-primary ui-icon "+s.primary+"'></span>"),s.secondary&&e.append("<span class='ui-button-icon-secondary ui-icon "+s.secondary+"'></span>"),this.options.text||(o.push(n?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||e.attr("title",t.trim(i)))):o.push("ui-button-text-only"),e.addClass(o.join(" "))}}),t.widget("ui.buttonset",{version:"1.11.4",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(t,e){"disabled"===t&&this.buttons.button("option",t,e),this._super(t,e)},refresh:function(){var e="rtl"===this.element.css("direction"),i=this.element.find(this.options.items),s=i.filter(":ui-button");i.not(":ui-button").button(),s.button("refresh"),this.buttons=i.map(function(){return t(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(e?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(e?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return t(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}}),t.ui.button,t.extend(t.ui,{datepicker:{version:"1.11.4"}});var _;t.extend(n.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return r(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,o;s=e.nodeName.toLowerCase(),n="div"===s||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),o=this._newInst(t(e),n),o.settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,o):n&&this._inlineDatepicker(e,o)},_newInst:function(e,i){var s=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?o(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(i),t.data(e,"datepicker",i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,o,a=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),a&&(i.append=t("<span class='"+this._appendClass+"'>"+a+"</span>"),e[r?"before":"after"](i.append)),e.unbind("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&e.focus(this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),o=this._get(i,"buttonImage"),i.trigger=t(this._get(i,"buttonImageOnly")?t("<img/>").addClass(this._triggerClass).attr({src:o,alt:n,title:n}):t("<button type='button'></button>").addClass(this._triggerClass).html(o?t("<img/>").attr({src:o,alt:n,title:n}):n)),e[r?"before":"after"](i.trigger),i.trigger.click(function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]?(t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])):t.datepicker._showDatepicker(e[0]),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,o=new Date(2009,11,20),a=this._get(t,"dateFormat");a.match(/[DM]/)&&(e=function(t){for(i=0,s=0,n=0;t.length>n;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length)}},_inlineDatepicker:function(e,i){var s=t(e);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,n,o){var a,h,l,c,u,d=this._dialogInst;return d||(this.uuid+=1,a="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+a+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),t("body").append(this._dialogInput),d=this._dialogInst=this._newInst(this._dialogInput,!1),d.settings={},t.data(this._dialogInput[0],"datepicker",d)),r(d.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(d,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,c=document.documentElement.scrollLeft||document.body.scrollLeft,u=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+c,l/2-150+u]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),d.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],"datepicker",d),this
    },_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,"datepicker");s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),_===n&&(_=null))},_enableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;this._disabledInputs.length>e;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,i,s){var n,o,a,h,l=this._getInst(e);return 2===arguments.length&&"string"==typeof i?"defaults"===i?t.extend({},t.datepicker._defaults):l?"all"===i?t.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),o=this._getDateDatepicker(e,!0),a=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),r(l.settings,n),null!==a&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,a)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(t(e),l),this._autoSize(l),this._setDate(l,o),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,o=t.datepicker._getInst(e.target),a=!0,r=o.dpDiv.is(".ui-datepicker-rtl");if(o._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),a=!1;break;case 13:return n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",o.dpDiv),n[0]&&t.datepicker._selectDay(e.target,o.selectedMonth,o.selectedYear,n[0]),i=t.datepicker._get(o,"onSelect"),i?(s=t.datepicker._formatDate(o),i.apply(o.input?o.input[0]:null,[s,o])):t.datepicker._hideDatepicker(),!1;case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),a=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),a=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),a=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),a=e.ctrlKey||e.metaKey;break;default:a=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):a=!1;a&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var i,s,n=t.datepicker._getInst(e.target);return t.datepicker._get(n,"constrainInput")?(i=t.datepicker._possibleChars(t.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(e){var i,s=t.datepicker._getInst(e.target);if(s.input.val()!==s.lastVal)try{i=t.datepicker.parseDate(t.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,t.datepicker._getFormatConfig(s)),i&&(t.datepicker._setDateFromField(s),t.datepicker._updateAlternate(s),t.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(e){if(e=e.target||e,"input"!==e.nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e){var i,n,o,a,h,l,c;i=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==i&&(t.datepicker._curInst.dpDiv.stop(!0,!0),i&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),n=t.datepicker._get(i,"beforeShow"),o=n?n.apply(e,[e,i]):{},o!==!1&&(r(i.settings,o),i.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(i),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),a=!1,t(e).parents().each(function(){return a|="fixed"===t(this).css("position"),!a}),h={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(i),h=t.datepicker._checkOffset(i,h,a),i.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":a?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),i.inline||(l=t.datepicker._get(i,"showAnim"),c=t.datepicker._get(i,"duration"),i.dpDiv.css("z-index",s(t(e))+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[l]?i.dpDiv.show(l,t.datepicker._get(i,"showOptions"),c):i.dpDiv[l||"show"](l?c:null),t.datepicker._shouldFocusInput(i)&&i.input.focus(),t.datepicker._curInst=i))}},_updateDatepicker:function(e){this.maxRows=4,_=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],o=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&a.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",o*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.focus(),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;!a||e&&a!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&(t.effects.effect[i]||t.effects[i])?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(a,"onClose"),o&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.focus(),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).each(function(){t(this).val(n)}))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(e,i,s){if(null==e||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,o,a,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,c="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),u=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,d=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,g=-1,m=-1,_=-1,v=-1,b=!1,y=function(t){var i=e.length>n+1&&e.charAt(n+1)===t;return i&&n++,i},w=function(t){var e=y(t),s="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n="y"===t?s:1,o=RegExp("^\\d{"+n+","+s+"}"),a=i.substring(h).match(o);if(!a)throw"Missing number at position "+h;return h+=a[0].length,parseInt(a[0],10)},k=function(e,s,n){var o=-1,a=t.map(y(e)?n:s,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(a,function(t,e){var s=e[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(o=e[0],h+=s.length,!1):void 0}),-1!==o)return o+1;throw"Unknown name at position "+h},x=function(){if(i.charAt(h)!==e.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;e.length>n;n++)if(b)"'"!==e.charAt(n)||y("'")?x():b=!1;else switch(e.charAt(n)){case"d":_=w("d");break;case"D":k("D",u,d);break;case"o":v=w("o");break;case"m":m=w("m");break;case"M":m=k("M",p,f);break;case"y":g=w("y");break;case"@":r=new Date(w("@")),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"!":r=new Date((w("!")-this._ticksTo1970)/1e4),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"'":y("'")?x():b=!0;break;default:x()}if(i.length>h&&(a=i.substr(h),!/^\s+/.test(a)))throw"Extra/unparsed characters found in date: "+a;if(-1===g?g=(new Date).getFullYear():100>g&&(g+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c>=g?0:-100)),v>-1)for(m=1,_=v;;){if(o=this._getDaysInMonth(g,m-1),o>=_)break;m++,_-=o}if(r=this._daylightSavingAdjust(new Date(g,m-1,_)),r.getFullYear()!==g||r.getMonth()+1!==m||r.getDate()!==_)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,o=(i?i.dayNames:null)||this._defaults.dayNames,a=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(e){var i=t.length>s+1&&t.charAt(s+1)===e;return i&&s++,i},l=function(t,e,i){var s=""+e;if(h(t))for(;i>s.length;)s="0"+s;return s},c=function(t,e,i,s){return h(t)?s[e]:i[e]},u="",d=!1;if(e)for(s=0;t.length>s;s++)if(d)"'"!==t.charAt(s)||h("'")?u+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":u+=l("d",e.getDate(),2);break;case"D":u+=c("D",e.getDay(),n,o);break;case"o":u+=l("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=l("m",e.getMonth()+1,2);break;case"M":u+=c("M",e.getMonth(),a,r);break;case"y":u+=h("y")?e.getFullYear():(10>e.getYear()%100?"0":"")+e.getYear()%100;break;case"@":u+=e.getTime();break;case"!":u+=1e4*e.getTime()+this._ticksTo1970;break;case"'":h("'")?u+="'":d=!0;break;default:u+=t.charAt(s)}return u},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=t.length>e+1&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;t.length>e;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,e){return void 0!==t.settings[e]?t.settings[e]:this._defaults[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(r){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(e,i,s){var n=function(t){var e=new Date;return e.setDate(e.getDate()+t),e},o=function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,o=n.getFullYear(),a=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":a+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a));break;case"y":case"Y":o+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a))}l=h.exec(i)}return new Date(o,a,r)},a=null==i||""===i?s:"string"==typeof i?o(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return a=a&&"Invalid Date"==""+a?s:a,a&&(a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)),this._daylightSavingAdjust(a)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,a=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=a.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=a.getMonth(),t.drawYear=t.selectedYear=t.currentYear=a.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){var e=!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return e},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}};t(this).bind(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,h,l,c,u,d,p,f,g,m,_,v,b,y,w,k,x,C,D,I,T,P,M,S,H,z,O,A,N,W,E,F,L,R=new Date,Y=this._daylightSavingAdjust(new Date(R.getFullYear(),R.getMonth(),R.getDate())),B=this._get(t,"isRTL"),j=this._get(t,"showButtonPanel"),q=this._get(t,"hideIfNoPrevNext"),K=this._get(t,"navigationAsDateFormat"),U=this._getNumberOfMonths(t),V=this._get(t,"showCurrentAtPos"),X=this._get(t,"stepMonths"),$=1!==U[0]||1!==U[1],G=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),Q=this._getMinMaxDate(t,"min"),J=this._getMinMaxDate(t,"max"),Z=t.drawMonth-V,te=t.drawYear;if(0>Z&&(Z+=12,te--),J)for(e=this._daylightSavingAdjust(new Date(J.getFullYear(),J.getMonth()-U[0]*U[1]+1,J.getDate())),e=Q&&Q>e?Q:e;this._daylightSavingAdjust(new Date(te,Z,1))>e;)Z--,0>Z&&(Z=11,te--);for(t.drawMonth=Z,t.drawYear=te,i=this._get(t,"prevText"),i=K?this.formatDate(i,this._daylightSavingAdjust(new Date(te,Z-X,1)),this._getFormatConfig(t)):i,s=this._canAdjustMonth(t,-1,te,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(B?"e":"w")+"'>"+i+"</span></a>":q?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(B?"e":"w")+"'>"+i+"</span></a>",n=this._get(t,"nextText"),n=K?this.formatDate(n,this._daylightSavingAdjust(new Date(te,Z+X,1)),this._getFormatConfig(t)):n,o=this._canAdjustMonth(t,1,te,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(B?"w":"e")+"'>"+n+"</span></a>":q?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(B?"w":"e")+"'>"+n+"</span></a>",a=this._get(t,"currentText"),r=this._get(t,"gotoCurrent")&&t.currentDay?G:Y,a=K?this.formatDate(a,r,this._getFormatConfig(t)):a,h=t.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(t,"closeText")+"</button>",l=j?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(B?h:"")+(this._isInRange(t,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+a+"</button>":"")+(B?"":h)+"</div>":"",c=parseInt(this._get(t,"firstDay"),10),c=isNaN(c)?0:c,u=this._get(t,"showWeek"),d=this._get(t,"dayNames"),p=this._get(t,"dayNamesMin"),f=this._get(t,"monthNames"),g=this._get(t,"monthNamesShort"),m=this._get(t,"beforeShowDay"),_=this._get(t,"showOtherMonths"),v=this._get(t,"selectOtherMonths"),b=this._getDefaultDate(t),y="",k=0;U[0]>k;k++){for(x="",this.maxRows=4,C=0;U[1]>C;C++){if(D=this._daylightSavingAdjust(new Date(te,Z,t.selectedDay)),I=" ui-corner-all",T="",$){if(T+="<div class='ui-datepicker-group",U[1]>1)switch(C){case 0:T+=" ui-datepicker-group-first",I=" ui-corner-"+(B?"right":"left");break;case U[1]-1:T+=" ui-datepicker-group-last",I=" ui-corner-"+(B?"left":"right");break;default:T+=" ui-datepicker-group-middle",I=""}T+="'>"}for(T+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+I+"'>"+(/all|left/.test(I)&&0===k?B?o:s:"")+(/all|right/.test(I)&&0===k?B?s:o:"")+this._generateMonthYearHeader(t,Z,te,Q,J,k>0||C>0,f,g)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",P=u?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",w=0;7>w;w++)M=(w+c)%7,P+="<th scope='col'"+((w+c+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[M]+"'>"+p[M]+"</span></th>";for(T+=P+"</tr></thead><tbody>",S=this._getDaysInMonth(te,Z),te===t.selectedYear&&Z===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,S)),H=(this._getFirstDayOfMonth(te,Z)-c+7)%7,z=Math.ceil((H+S)/7),O=$?this.maxRows>z?this.maxRows:z:z,this.maxRows=O,A=this._daylightSavingAdjust(new Date(te,Z,1-H)),N=0;O>N;N++){for(T+="<tr>",W=u?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(A)+"</td>":"",w=0;7>w;w++)E=m?m.apply(t.input?t.input[0]:null,[A]):[!0,""],F=A.getMonth()!==Z,L=F&&!v||!E[0]||Q&&Q>A||J&&A>J,W+="<td class='"+((w+c+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(A.getTime()===D.getTime()&&Z===t.selectedMonth&&t._keyEvent||b.getTime()===A.getTime()&&b.getTime()===D.getTime()?" "+this._dayOverClass:"")+(L?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!_?"":" "+E[1]+(A.getTime()===G.getTime()?" "+this._currentClass:"")+(A.getTime()===Y.getTime()?" ui-datepicker-today":""))+"'"+(F&&!_||!E[2]?"":" title='"+E[2].replace(/'/g,"&#39;")+"'")+(L?"":" data-handler='selectDay' data-event='click' data-month='"+A.getMonth()+"' data-year='"+A.getFullYear()+"'")+">"+(F&&!_?"&#xa0;":L?"<span class='ui-state-default'>"+A.getDate()+"</span>":"<a class='ui-state-default"+(A.getTime()===Y.getTime()?" ui-state-highlight":"")+(A.getTime()===G.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+A.getDate()+"</a>")+"</td>",A.setDate(A.getDate()+1),A=this._daylightSavingAdjust(A);T+=W+"</tr>"}Z++,Z>11&&(Z=0,te++),T+="</tbody></table>"+($?"</div>"+(U[0]>0&&C===U[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=T}y+=x}return y+=l,t._keyEvent=!1,y},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var h,l,c,u,d,p,f,g,m=this._get(t,"changeMonth"),_=this._get(t,"changeYear"),v=this._get(t,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",y="";if(o||!m)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",c=0;12>c;c++)(!h||c>=s.getMonth())&&(!l||n.getMonth()>=c)&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(v||(b+=y+(!o&&m&&_?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!_)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(u=this._get(t,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e},f=p(u[0]),g=Math.max(f,p(u[1]||"")),f=s?Math.max(f,s.getFullYear()):f,g=n?Math.min(g,n.getFullYear()):g,t.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";g>=f;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),v&&(b+=(!o&&m&&_?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.drawYear+("Y"===i?e:0),n=t.drawMonth+("M"===i?e:0),o=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),a=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,o)));t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&i>e?i:e;return s&&n>s?s:n},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),o=this._daylightSavingAdjust(new Date(i,s+(0>e?e:n[0]*n[1]),1));return 0>e&&o.setDate(this._getDaysInMonth(o.getFullYear(),o.getMonth())),this._isInRange(t,o)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),o=this._getMinMaxDate(t,"max"),a=null,r=null,h=this._get(t,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),a=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(a+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!o||e.getTime()<=o.getTime())&&(!a||e.getFullYear()>=a)&&(!r||r>=e.getFullYear())},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),{shortYearCutoff:e,dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);var n=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).mousedown(t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)}):t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i))},t.datepicker=new n,t.datepicker.initialized=!1,t.datepicker.uuid=(new Date).getTime(),t.datepicker.version="1.11.4",t.datepicker,t.widget("ui.dialog",{version:"1.11.4",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"Close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var i=t(this).css(e).offset().top;0>i&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),t=e.parent.children().eq(e.index),t.length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog},disable:t.noop,enable:t.noop,close:function(e){var i,s=this;if(this._isOpen&&this._trigger("beforeClose",e)!==!1){if(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),!this.opener.filter(":focusable").focus().length)try{i=this.document[0].activeElement,i&&"body"!==i.nodeName.toLowerCase()&&t(i).blur()}catch(n){}this._hide(this.uiDialog,this.options.hide,function(){s._trigger("close",e)})}},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;
    return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).focus()},_keepFocus:function(e){function i(){var e=this.document[0].activeElement,i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.focus()}),e.preventDefault()):(this._delay(function(){s.focus()}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(e),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title||t.html("&#160;"),t.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this.uiDialog.removeClass("ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,s.click=function(){n.apply(e.element[0],arguments)},o={icons:s.icons,text:s.showText},delete s.icons,delete s.showText,t("<button></button>",s).button(o).appendTo(e.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){t(this).addClass("ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,e(n))},drag:function(t,s){i._trigger("drag",t,e(s))},stop:function(n,o){var a=o.offset.left-i.document.scrollLeft(),r=o.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(a>=0?"+":"")+a+" "+"top"+(r>=0?"+":"")+r,of:i.window},t(this).removeClass("ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,e(o))}})},_makeResizable:function(){function e(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}var i=this,s=this.options,n=s.resizable,o=this.uiDialog.css("position"),a="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:a,start:function(s,n){t(this).addClass("ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,e(n))},resize:function(t,s){i._trigger("resize",t,e(s))},stop:function(n,o){var a=i.uiDialog.offset(),r=a.left-i.document.scrollLeft(),h=a.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},t(this).removeClass("ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,e(o))}}).css("position",o)},_trackFocus:function(){this._on(this.widget(),{focusin:function(e){this._makeFocusTarget(),this._focusedElement=t(e.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var e=this._trackingInstances(),i=t.inArray(this,e);-1!==i&&e.splice(i,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||(t=[],this.document.data("ui-dialog-instances",t)),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(e){var i=this,s=!1,n={};t.each(e,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(t,e){var i,s,n=this.uiDialog;"dialogClass"===t&&n.removeClass(this.options.dialogClass).addClass(e),"disabled"!==t&&(this._super(t,e),"appendTo"===t&&this.uiDialog.appendTo(this._appendTo()),"buttons"===t&&this._createButtons(),"closeText"===t&&this.uiDialogTitlebarClose.button({label:""+e}),"draggable"===t&&(i=n.is(":data(ui-draggable)"),i&&!e&&n.draggable("destroy"),!i&&e&&this._makeDraggable()),"position"===t&&this._position(),"resizable"===t&&(s=n.is(":data(ui-resizable)"),s&&!e&&n.resizable("destroy"),s&&"string"==typeof e&&n.resizable("option","handles",e),s||e===!1||this._makeResizable()),"title"===t&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var e=t(this);return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return t(e.target).closest(".ui-dialog").length?!0:!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=!0;this._delay(function(){e=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(t){e||this._allowInteraction(t)||(t.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=t("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var t=this.document.data("ui-dialog-overlays")-1;t?this.document.data("ui-dialog-overlays",t):this.document.unbind("focusin").removeData("ui-dialog-overlays"),this.overlay.remove(),this.overlay=null}}}),t.widget("ui.progressbar",{version:"1.11.4",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=t("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(t){return void 0===t?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),void 0)},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),"disabled"===t&&this.element.toggleClass("ui-state-disabled",!!e).attr("aria-disabled",e),this._super(t,e)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).toggleClass("ui-corner-right",e===this.options.max).width(i.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}}),t.widget("ui.selectmenu",{version:"1.11.4",defaultElement:"<select>",options:{appendTo:null,disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:null,change:null,close:null,focus:null,open:null,select:null},_create:function(){var t=this.element.uniqueId().attr("id");this.ids={element:t,button:t+"-button",menu:t+"-menu"},this._drawButton(),this._drawMenu(),this.options.disabled&&this.disable()},_drawButton:function(){var e=this;this.label=t("label[for='"+this.ids.element+"']").attr("for",this.ids.button),this._on(this.label,{click:function(t){this.button.focus(),t.preventDefault()}}),this.element.hide(),this.button=t("<span>",{"class":"ui-selectmenu-button ui-widget ui-state-default ui-corner-all",tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true"}).insertAfter(this.element),t("<span>",{"class":"ui-icon "+this.options.icons.button}).prependTo(this.button),this.buttonText=t("<span>",{"class":"ui-selectmenu-text"}).appendTo(this.button),this._setText(this.buttonText,this.element.find("option:selected").text()),this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){e.menuItems||e._refreshMenu()}),this._hoverable(this.button),this._focusable(this.button)},_drawMenu:function(){var e=this;this.menu=t("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=t("<div>",{"class":"ui-selectmenu-menu ui-front"}).append(this.menu).appendTo(this._appendTo()),this.menuInstance=this.menu.menu({role:"listbox",select:function(t,i){t.preventDefault(),e._setSelection(),e._select(i.item.data("ui-selectmenu-item"),t)},focus:function(t,i){var s=i.item.data("ui-selectmenu-item");null!=e.focusIndex&&s.index!==e.focusIndex&&(e._trigger("focus",t,{item:s}),e.isOpen||e._select(s,t)),e.focusIndex=s.index,e.button.attr("aria-activedescendant",e.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menu.addClass("ui-corner-bottom").removeClass("ui-corner-all"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this._setText(this.buttonText,this._getSelectedItem().text()),this.options.width||this._resizeButton()},_refreshMenu:function(){this.menu.empty();var t,e=this.element.find("option");e.length&&(this._parseOptions(e),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup"),t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){this.options.disabled||(this.menuItems?(this.menu.find(".ui-state-focus").removeClass("ui-state-focus"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t))},_position:function(){this.menuWrap.position(t.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderMenu:function(e,i){var s=this,n="";t.each(i,function(i,o){o.optgroup!==n&&(t("<li>",{"class":"ui-selectmenu-optgroup ui-menu-divider"+(o.element.parent("optgroup").prop("disabled")?" ui-state-disabled":""),text:o.optgroup}).appendTo(e),n=o.optgroup),s._renderItemData(e,o)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(e,i){var s=t("<li>");return i.disabled&&s.addClass("ui-state-disabled"),this._setText(s,i.label),s.appendTo(e)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex):(i=this.menuItems.eq(this.element[0].selectedIndex),n+=":not(.ui-state-disabled)"),s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](n).eq(-1):i[t+"All"](n).eq(0),s.length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex)},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&(window.getSelection?(t=window.getSelection(),t.removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(e){this.isOpen&&(t(e.target).closest(".ui-selectmenu-menu, #"+this.ids.button).length||this.close(e))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection(),t.rangeCount&&(this.range=t.getRangeAt(0))):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(e){var i=!0;switch(e.keyCode){case t.ui.keyCode.TAB:case t.ui.keyCode.ESCAPE:this.close(e),i=!1;break;case t.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(e);break;case t.ui.keyCode.UP:e.altKey?this._toggle(e):this._move("prev",e);break;case t.ui.keyCode.DOWN:e.altKey?this._toggle(e):this._move("next",e);break;case t.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(e):this._toggle(e);break;case t.ui.keyCode.LEFT:this._move("prev",e);break;case t.ui.keyCode.RIGHT:this._move("next",e);break;case t.ui.keyCode.HOME:case t.ui.keyCode.PAGE_UP:this._move("first",e);break;case t.ui.keyCode.END:case t.ui.keyCode.PAGE_DOWN:this._move("last",e);break;default:this.menu.trigger(e),i=!1}i&&e.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex);e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this._setText(this.buttonText,t.label),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){var e=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":e,"aria-activedescendant":e}),this.menu.attr("aria-activedescendant",e)},_setOption:function(t,e){"icons"===t&&this.button.find("span.ui-icon").removeClass(this.options.icons.button).addClass(e.button),this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"disabled"===t&&(this.menuInstance.option("disabled",e),this.button.toggleClass("ui-state-disabled",e).attr("aria-disabled",e),this.element.prop("disabled",e),e?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)),"width"===t&&this._resizeButton()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front")),e.length||(e=this.document[0].body),e},_toggleAttr:function(){this.button.toggleClass("ui-corner-top",this.isOpen).toggleClass("ui-corner-all",!this.isOpen).attr("aria-expanded",this.isOpen),this.menuWrap.toggleClass("ui-selectmenu-open",this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;t||(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){return{disabled:this.element.prop("disabled")}},_parseOptions:function(e){var i=[];e.each(function(e,s){var n=t(s),o=n.parent("optgroup");i.push({element:n,index:e,value:n.val(),label:n.text(),optgroup:o.attr("label")||"",disabled:o.prop("disabled")||n.prop("disabled")})}),this.items=i},_destroy:function(){this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.label.attr("for",this.ids.element)}}),t.widget("ui.slider",t.ui.mouse,{version:"1.11.4",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this._refresh(),this._setOption("disabled",this.options.disabled),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),o="<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e)})},_createRange:function(){var e=this.options,i="";e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=t("<div></div>").appendTo(this.element),i="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(i+("min"===e.range||"max"===e.range?" ui-slider-range-"+e.range:""))):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,o.addClass("ui-state-active").focus(),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_start:function(t,e){var i={handle:this.handles[e],value:this.value()};return this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("start",t,i)},_slide:function(t,e,i){var s,n,o;this.options.values&&this.options.values.length?(s=this.values(e?0:1),2===this.options.values.length&&this.options.range===!0&&(0===e&&i>s||1===e&&s>i)&&(i=s),i!==this.values(e)&&(n=this.values(),n[e]=i,o=this._trigger("slide",t,{handle:this.handles[e],value:i,values:n}),s=this.values(e?0:1),o!==!1&&this.values(e,i))):i!==this.value()&&(o=this._trigger("slide",t,{handle:this.handles[e],value:i}),o!==!1&&this.value(i))},_stop:function(t,e){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("stop",t,i)},_change:function(t,e){if(!this._keySliding&&!this._mouseSliding){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._lastChangedValue=e,this._trigger("change",t,i)}},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!i),this._super(e,i),e){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue(),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=0;n>s;s+=1)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this.options.values&&this.options.values.length){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step,s=Math.floor(+(t-e).toFixed(this._precision())/i)*i;t=s+e,this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshValue:function(){var e,i,s,n,o,a=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,c={};this.options.values&&this.options.values.length?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),c["horizontal"===h.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[l?"animate":"css"](c,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),o=this._valueMax(),i=o!==n?100*((s-n)/(o-n)):0,c["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](c,r.animate),"min"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===a&&"horizontal"===this.orientation&&this.range[l?"animate":"css"]({width:100-i+"%"},{queue:!1,duration:r.animate}),"min"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===a&&"vertical"===this.orientation&&this.range[l?"animate":"css"]({height:100-i+"%"},{queue:!1,duration:r.animate}))},_handleEvents:{keydown:function(e){var i,s,n,o,a=t(e.target).data("ui-slider-handle-index");switch(e.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(e.preventDefault(),!this._keySliding&&(this._keySliding=!0,t(e.target).addClass("ui-state-active"),i=this._start(e,a),i===!1))return}switch(o=this.options.step,s=n=this.options.values&&this.options.values.length?this.values(a):this.value(),e.keyCode){case t.ui.keyCode.HOME:n=this._valueMin();break;case t.ui.keyCode.END:n=this._valueMax();break;case t.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+o);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-o)}this._slide(e,a,n)},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),t(e.target).removeClass("ui-state-active"))}}}),t.widget("ui.spinner",{version:"1.11.4",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e={},i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);void 0!==n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var t=this.element[0]===this.document[0].activeElement;t||(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var t=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=t.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(.5*t.height())&&t.height()>0&&t.height(t.height()),this.options.disabled&&this.disable()
    },_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>&#9650;</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>&#9660;</span>"+"</a>"},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){if("culture"===t||"numberFormat"===t){var i=this._parse(this.element.val());return this.options[t]=e,this.element.val(this._format(i)),void 0}("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(e.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(e.down)),this._super(t,e),"disabled"===t&&(this.widget().toggleClass("ui-state-disabled",!!e),this.element.prop("disabled",!!e),this.buttons.button(e?"disable":"enable"))},_setOptions:h(function(t){this._super(t)}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null===t?!1:t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:h(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:h(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:h(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:h(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(h(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),t.widget("ui.tabs",{version:"1.11.4",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(){var t=/#.*$/;return function(e){var i,s;e=e.cloneNode(!1),i=e.href.replace(t,""),s=location.href.replace(t,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return e.hash.length>1&&i===s}}(),_create:function(){var e=this,i=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",i.collapsible),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var e=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===e&&(s&&this.tabs.each(function(i,n){return t(n).attr("aria-controls")===s?(e=i,!1):void 0}),null===e&&(e=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===e||-1===e)&&(e=this.tabs.length?0:!1)),e!==!1&&(e=this.tabs.index(this.tabs.eq(e)),-1===e&&(e=i?!1:0)),!i&&e===!1&&this.anchors.length&&(e=0),e},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(e){var i=t(this.document[0].activeElement).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(e)){switch(e.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:s++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:n=!1,s--;break;case t.ui.keyCode.END:s=this.anchors.length-1;break;case t.ui.keyCode.HOME:s=0;break;case t.ui.keyCode.SPACE:return e.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case t.ui.keyCode.ENTER:return e.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}e.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),e.ctrlKey||e.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.focus())},_handlePageNav:function(e){return e.altKey&&e.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):e.altKey&&e.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).focus(),t},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):"disabled"===t?(this._setupDisabled(e),void 0):(this._super(t,e),"collapsible"===t&&(this.element.toggleClass("ui-tabs-collapsible",e),e||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e),void 0)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this,i=this.tabs,s=this.anchors,n=this.panels;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist").delegate("> li","mousedown"+this.eventNamespace,function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=t(),this.anchors.each(function(i,s){var n,o,a,r=t(s).uniqueId().attr("id"),h=t(s).closest("li"),l=h.attr("aria-controls");e._isLocal(s)?(n=s.hash,a=n.substring(1),o=e.element.find(e._sanitizeSelector(n))):(a=h.attr("aria-controls")||t({}).uniqueId()[0].id,n="#"+a,o=e.element.find(n),o.length||(o=e._createPanel(a),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":a,"aria-labelledby":r}),o.attr("aria-labelledby",r)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol,ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(e){t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1);for(var i,s=0;i=this.tabs[s];s++)e===!0||-1!==t.inArray(s,e)?t(i).addClass("ui-state-disabled").attr("aria-disabled","true"):t(i).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=e},_setupEvents:function(e){var i={};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n.closest("li"),a=o[0]===s[0],r=a&&i.collapsible,h=r?t():this._getPanelForTab(o),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():o,newPanel:h};e.preventDefault(),o.hasClass("ui-state-disabled")||o.hasClass("ui-tabs-loading")||this.running||a&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(o),this.active=a?t():o,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(o),e),this._toggle(e,c))},_toggle:function(e,i){function s(){o.running=!1,o._trigger("activate",e,i)}function n(){i.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),a.length&&o.options.show?o._show(a,o.options.show,s):(a.show(),s())}var o=this,a=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),n()}):(i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),a.length&&r.length?i.oldTab.attr("tabIndex",-1):a.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),a.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(t){return"string"==typeof t&&(t=this.anchors.index(this.anchors.filter("[href$='"+t+"']"))),t},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tablist.unbind(this.eventNamespace),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(e){var i=this.options.disabled;i!==!1&&(void 0===e?i=!1:(e=this._getIndex(e),i=t.isArray(i)?t.map(i,function(t){return t!==e?t:null}):t.map(this.tabs,function(t,i){return i!==e?i:null})),this._setupDisabled(i))},disable:function(e){var i=this.options.disabled;if(i!==!0){if(void 0===e)i=!0;else{if(e=this._getIndex(e),-1!==t.inArray(e,i))return;i=t.isArray(i)?t.merge([e],i).sort():[e]}this._setupDisabled(i)}},load:function(e,i){e=this._getIndex(e);var s=this,n=this.tabs.eq(e),o=n.find(".ui-tabs-anchor"),a=this._getPanelForTab(n),r={tab:n,panel:a},h=function(t,e){"abort"===e&&s.panels.stop(!1,!0),n.removeClass("ui-tabs-loading"),a.removeAttr("aria-busy"),t===s.xhr&&delete s.xhr};this._isLocal(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(n.addClass("ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,n){setTimeout(function(){a.html(t),s._trigger("load",i,r),h(n,e)},1)}).fail(function(t,e){setTimeout(function(){h(t,e)},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href"),beforeSend:function(e,o){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:o},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}});var v="ui-effects-",b=t;t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(t,o){var a,r=o.re.exec(i),h=r&&o.parse(r),l=o.space||"rgba";return h?(a=s[l](h),s[c[l].cache]=a[c[l].cache],n=s._rgba=a._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,o.transparent),s):o[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var o,a="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],l=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=l.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),l.fn=t.extend(l.prototype,{parse:function(n,a,r,h){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(a),a=e);var u=this,d=t.type(n),p=this._rgba=[];return a!==e&&(n=[n,a,r,h],d="array"),"string"===d?this.parse(s(n)||o._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof l?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var o=s.cache;f(s.props,function(t,e){if(!u[o]&&s.to){if("alpha"===t||null==n[t])return;u[o]=s.to(u._rgba)}u[o][e.idx]=i(n[t],e,!0)}),u[o]&&0>t.inArray(null,u[o].slice(0,3))&&(u[o][3]=1,s.from&&(u._rgba=s.from(u[o])))}),this):e},is:function(t){var i=l(t),s=!0,n=this;return f(c,function(t,o){var a,r=i[o.cache];return r&&(a=n[o.cache]||o.to&&o.to(n._rgba)||[],f(o.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===a[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=l(t),n=s._space(),o=c[n],a=0===this.alpha()?l("transparent"):this,r=a[o.cache]||o.to(a._rgba),h=r.slice();return s=s[o.cache],f(o.props,function(t,n){var o=n.idx,a=r[o],l=s[o],c=u[n.type]||{};null!==l&&(null===a?h[o]=l:(c.mod&&(l-a>c.mod/2?a+=c.mod:a-l>c.mod/2&&(a-=c.mod)),h[o]=i((l-a)*e+a,n)))}),this[n](h)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(e)._rgba;return l(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,o=t[2]/255,a=t[3],r=Math.max(s,n,o),h=Math.min(s,n,o),l=r-h,c=r+h,u=.5*c;return e=h===r?0:s===r?60*(n-o)/l+360:n===r?60*(o-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=u?l/c:l/(2-c),[Math.round(e)%360,i,u,null==a?1:a]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],o=t[3],a=.5>=s?s*(1+i):s+i-s*i,r=2*s-a;return[Math.round(255*n(r,a,e+1/3)),Math.round(255*n(r,a,e)),Math.round(255*n(r,a,e-1/3)),o]},f(c,function(s,n){var o=n.props,a=n.cache,h=n.to,c=n.from;l.fn[s]=function(s){if(h&&!this[a]&&(this[a]=h(this._rgba)),s===e)return this[a].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[a].slice();return f(o,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=l(c(d)),n[a]=d,n):l(d)},f(o,function(e,i){l.fn[e]||(l.fn[e]=function(n){var o,a=t.type(n),h="alpha"===e?this._hsla?"hsla":"rgba":s,l=this[h](),c=l[i.idx];return"undefined"===a?c:("function"===a&&(n=n.call(this,c),a=t.type(n)),null==n&&i.empty?this:("string"===a&&(o=r.exec(n),o&&(n=c+parseFloat(o[2])*("+"===o[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var o,a,r="";if("transparent"!==n&&("string"!==t.type(n)||(o=s(n)))){if(n=l(o||n),!d.rgba&&1!==n._rgba[3]){for(a="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&a&&a.style;)try{r=t.css(a,"backgroundColor"),a=a.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(h){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=l(e.elem,i),e.end=l(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},l.hook(a),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},o=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(b),function(){function e(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,o={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(o[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(o[i]=n[i]);return o}function i(e,i){var s,o,a={};for(s in i)o=i[s],e[s]!==o&&(n[s]||(t.fx.step[s]||!isNaN(parseFloat(o)))&&(a[s]=o));return a}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(b.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(n,o,a,r){var h=t.speed(o,a,r);return this.queue(function(){var o,a=t(this),r=a.attr("class")||"",l=h.children?a.find("*").addBack():a;l=l.map(function(){var i=t(this);return{el:i,start:e(this)}}),o=function(){t.each(s,function(t,e){n[e]&&a[e+"Class"](n[e])})},o(),l=l.map(function(){return this.end=e(this.el[0]),this.diff=i(this.start,this.end),this}),a.attr("class",r),l=l.map(function(){var e=this,i=t.Deferred(),s=t.extend({},h,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,l.get()).done(function(){o(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),h.complete.call(a[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,o):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(e){return function(i,s,n,o,a){return"boolean"==typeof s||void 0===s?n?t.effects.animateClass.call(this,s?{add:i}:{remove:i},n,o,a):e.apply(this,arguments):t.effects.animateClass.call(this,{toggle:i},s,n,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){function e(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function i(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}t.extend(t.effects,{version:"1.11.4",save:function(t,e){for(var i=0;e.length>i;i++)null!==e[i]&&t.data(v+e[i],t[0].style[e[i]])},restore:function(t,e){var i,s;for(s=0;e.length>s;s++)null!==e[s]&&(i=t.data(v+e[s]),void 0===i&&(i=""),t.css(e[s],i))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(a){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).focus(),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).focus()),e},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){function i(e){function i(){t.isFunction(o)&&o.call(n[0]),t.isFunction(e)&&e()}var n=t(this),o=s.complete,r=s.mode;(n.is(":hidden")?"hide"===r:"show"===r)?(n[r](),i()):a.call(n[0],s,i)}var s=e.apply(this,arguments),n=s.mode,o=s.queue,a=t.effects.effect[s.effect];return t.fx.off||!a?n?this[n](s.duration,s.complete):this.each(function(){s.complete&&s.complete.call(this)}):o===!1?this.each(i):this.queue(o||"fx",i)},show:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="show",this.effect.call(this,n)}}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s}})}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}(),t.effects,t.effects.effect.blind=function(e,i){var s,n,o,a=t(this),r=/up|down|vertical/,h=/up|left|vertical|horizontal/,l=["position","top","bottom","left","right","height","width"],c=t.effects.setMode(a,e.mode||"hide"),u=e.direction||"up",d=r.test(u),p=d?"height":"width",f=d?"top":"left",g=h.test(u),m={},_="show"===c;a.parent().is(".ui-effects-wrapper")?t.effects.save(a.parent(),l):t.effects.save(a,l),a.show(),s=t.effects.createWrapper(a).css({overflow:"hidden"}),n=s[p](),o=parseFloat(s.css(f))||0,m[p]=_?n:0,g||(a.css(d?"bottom":"right",0).css(d?"top":"left","auto").css({position:"absolute"}),m[f]=_?o:n+o),_&&(s.css(p,0),g||s.css(f,o+n)),s.animate(m,{duration:e.duration,easing:e.easing,queue:!1,complete:function(){"hide"===c&&a.hide(),t.effects.restore(a,l),t.effects.removeWrapper(a),i()}})},t.effects.effect.bounce=function(e,i){var s,n,o,a=t(this),r=["position","top","bottom","left","right","height","width"],h=t.effects.setMode(a,e.mode||"effect"),l="hide"===h,c="show"===h,u=e.direction||"up",d=e.distance,p=e.times||5,f=2*p+(c||l?1:0),g=e.duration/f,m=e.easing,_="up"===u||"down"===u?"top":"left",v="up"===u||"left"===u,b=a.queue(),y=b.length;for((c||l)&&r.push("opacity"),t.effects.save(a,r),a.show(),t.effects.createWrapper(a),d||(d=a["top"===_?"outerHeight":"outerWidth"]()/3),c&&(o={opacity:1},o[_]=0,a.css("opacity",0).css(_,v?2*-d:2*d).animate(o,g,m)),l&&(d/=Math.pow(2,p-1)),o={},o[_]=0,s=0;p>s;s++)n={},n[_]=(v?"-=":"+=")+d,a.animate(n,g,m).animate(o,g,m),d=l?2*d:d/2;l&&(n={opacity:0},n[_]=(v?"-=":"+=")+d,a.animate(n,g,m)),a.queue(function(){l&&a.hide(),t.effects.restore(a,r),t.effects.removeWrapper(a),i()}),y>1&&b.splice.apply(b,[1,0].concat(b.splice(y,f+1))),a.dequeue()},t.effects.effect.clip=function(e,i){var s,n,o,a=t(this),r=["position","top","bottom","left","right","height","width"],h=t.effects.setMode(a,e.mode||"hide"),l="show"===h,c=e.direction||"vertical",u="vertical"===c,d=u?"height":"width",p=u?"top":"left",f={};t.effects.save(a,r),a.show(),s=t.effects.createWrapper(a).css({overflow:"hidden"}),n="IMG"===a[0].tagName?s:a,o=n[d](),l&&(n.css(d,0),n.css(p,o/2)),f[d]=l?o:0,f[p]=l?0:o/2,n.animate(f,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){l||a.hide(),t.effects.restore(a,r),t.effects.removeWrapper(a),i()}})},t.effects.effect.drop=function(e,i){var s,n=t(this),o=["position","top","bottom","left","right","opacity","height","width"],a=t.effects.setMode(n,e.mode||"hide"),r="show"===a,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h?"pos":"neg",u={opacity:r?1:0};t.effects.save(n,o),n.show(),t.effects.createWrapper(n),s=e.distance||n["top"===l?"outerHeight":"outerWidth"](!0)/2,r&&n.css("opacity",0).css(l,"pos"===c?-s:s),u[l]=(r?"pos"===c?"+=":"-=":"pos"===c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===a&&n.hide(),t.effects.restore(n,o),t.effects.removeWrapper(n),i()}})},t.effects.effect.explode=function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),g||p.hide(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=t.effects.setMode(p,e.mode||"hide"),g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];
    for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacity:g?1:0},e.duration||500,e.easing,s)},t.effects.effect.fade=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"toggle");s.animate({opacity:n},{queue:!1,duration:e.duration,easing:e.easing,complete:i})},t.effects.effect.fold=function(e,i){var s,n,o=t(this),a=["position","top","bottom","left","right","height","width"],r=t.effects.setMode(o,e.mode||"hide"),h="show"===r,l="hide"===r,c=e.size||15,u=/([0-9]+)%/.exec(c),d=!!e.horizFirst,p=h!==d,f=p?["width","height"]:["height","width"],g=e.duration/2,m={},_={};t.effects.save(o,a),o.show(),s=t.effects.createWrapper(o).css({overflow:"hidden"}),n=p?[s.width(),s.height()]:[s.height(),s.width()],u&&(c=parseInt(u[1],10)/100*n[l?0:1]),h&&s.css(d?{height:0,width:c}:{height:c,width:0}),m[f[0]]=h?n[0]:c,_[f[1]]=h?n[1]:0,s.animate(m,g,e.easing).animate(_,g,e.easing,function(){l&&o.hide(),t.effects.restore(o,a),t.effects.removeWrapper(o),i()})},t.effects.effect.highlight=function(e,i){var s=t(this),n=["backgroundImage","backgroundColor","opacity"],o=t.effects.setMode(s,e.mode||"show"),a={backgroundColor:s.css("backgroundColor")};"hide"===o&&(a.opacity=0),t.effects.save(s,n),s.show().css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(a,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===o&&s.hide(),t.effects.restore(s,n),i()}})},t.effects.effect.size=function(e,i){var s,n,o,a=t(this),r=["position","top","bottom","left","right","width","height","overflow","opacity"],h=["position","top","bottom","left","right","overflow","opacity"],l=["width","height","overflow"],c=["fontSize"],u=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],d=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=t.effects.setMode(a,e.mode||"effect"),f=e.restore||"effect"!==p,g=e.scale||"both",m=e.origin||["middle","center"],_=a.css("position"),v=f?r:h,b={height:0,width:0,outerHeight:0,outerWidth:0};"show"===p&&a.show(),s={height:a.height(),width:a.width(),outerHeight:a.outerHeight(),outerWidth:a.outerWidth()},"toggle"===e.mode&&"show"===p?(a.from=e.to||b,a.to=e.from||s):(a.from=e.from||("show"===p?b:s),a.to=e.to||("hide"===p?b:s)),o={from:{y:a.from.height/s.height,x:a.from.width/s.width},to:{y:a.to.height/s.height,x:a.to.width/s.width}},("box"===g||"both"===g)&&(o.from.y!==o.to.y&&(v=v.concat(u),a.from=t.effects.setTransition(a,u,o.from.y,a.from),a.to=t.effects.setTransition(a,u,o.to.y,a.to)),o.from.x!==o.to.x&&(v=v.concat(d),a.from=t.effects.setTransition(a,d,o.from.x,a.from),a.to=t.effects.setTransition(a,d,o.to.x,a.to))),("content"===g||"both"===g)&&o.from.y!==o.to.y&&(v=v.concat(c).concat(l),a.from=t.effects.setTransition(a,c,o.from.y,a.from),a.to=t.effects.setTransition(a,c,o.to.y,a.to)),t.effects.save(a,v),a.show(),t.effects.createWrapper(a),a.css("overflow","hidden").css(a.from),m&&(n=t.effects.getBaseline(m,s),a.from.top=(s.outerHeight-a.outerHeight())*n.y,a.from.left=(s.outerWidth-a.outerWidth())*n.x,a.to.top=(s.outerHeight-a.to.outerHeight)*n.y,a.to.left=(s.outerWidth-a.to.outerWidth)*n.x),a.css(a.from),("content"===g||"both"===g)&&(u=u.concat(["marginTop","marginBottom"]).concat(c),d=d.concat(["marginLeft","marginRight"]),l=r.concat(u).concat(d),a.find("*[width]").each(function(){var i=t(this),s={height:i.height(),width:i.width(),outerHeight:i.outerHeight(),outerWidth:i.outerWidth()};f&&t.effects.save(i,l),i.from={height:s.height*o.from.y,width:s.width*o.from.x,outerHeight:s.outerHeight*o.from.y,outerWidth:s.outerWidth*o.from.x},i.to={height:s.height*o.to.y,width:s.width*o.to.x,outerHeight:s.height*o.to.y,outerWidth:s.width*o.to.x},o.from.y!==o.to.y&&(i.from=t.effects.setTransition(i,u,o.from.y,i.from),i.to=t.effects.setTransition(i,u,o.to.y,i.to)),o.from.x!==o.to.x&&(i.from=t.effects.setTransition(i,d,o.from.x,i.from),i.to=t.effects.setTransition(i,d,o.to.x,i.to)),i.css(i.from),i.animate(i.to,e.duration,e.easing,function(){f&&t.effects.restore(i,l)})})),a.animate(a.to,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){0===a.to.opacity&&a.css("opacity",a.from.opacity),"hide"===p&&a.hide(),t.effects.restore(a,v),f||("static"===_?a.css({position:"relative",top:a.to.top,left:a.to.left}):t.each(["top","left"],function(t,e){a.css(e,function(e,i){var s=parseInt(i,10),n=t?a.to.left:a.to.top;return"auto"===i?n+"px":s+n+"px"})})),t.effects.removeWrapper(a),i()}})},t.effects.effect.scale=function(e,i){var s=t(this),n=t.extend(!0,{},e),o=t.effects.setMode(s,e.mode||"effect"),a=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"hide"===o?0:100),r=e.direction||"both",h=e.origin,l={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()},c={y:"horizontal"!==r?a/100:1,x:"vertical"!==r?a/100:1};n.effect="size",n.queue=!1,n.complete=i,"effect"!==o&&(n.origin=h||["middle","center"],n.restore=!0),n.from=e.from||("show"===o?{height:0,width:0,outerHeight:0,outerWidth:0}:l),n.to={height:l.height*c.y,width:l.width*c.x,outerHeight:l.outerHeight*c.y,outerWidth:l.outerWidth*c.x},n.fade&&("show"===o&&(n.from.opacity=0,n.to.opacity=1),"hide"===o&&(n.from.opacity=1,n.to.opacity=0)),s.effect(n)},t.effects.effect.puff=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"hide"),o="hide"===n,a=parseInt(e.percent,10)||150,r=a/100,h={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()};t.extend(e,{effect:"scale",queue:!1,fade:!0,mode:n,complete:i,percent:o?a:100,from:o?h:{height:h.height*r,width:h.width*r,outerHeight:h.outerHeight*r,outerWidth:h.outerWidth*r}}),s.effect(e)},t.effects.effect.pulsate=function(e,i){var s,n=t(this),o=t.effects.setMode(n,e.mode||"show"),a="show"===o,r="hide"===o,h=a||"hide"===o,l=2*(e.times||5)+(h?1:0),c=e.duration/l,u=0,d=n.queue(),p=d.length;for((a||!n.is(":visible"))&&(n.css("opacity",0).show(),u=1),s=1;l>s;s++)n.animate({opacity:u},c,e.easing),u=1-u;n.animate({opacity:u},c,e.easing),n.queue(function(){r&&n.hide(),i()}),p>1&&d.splice.apply(d,[1,0].concat(d.splice(p,l+1))),n.dequeue()},t.effects.effect.shake=function(e,i){var s,n=t(this),o=["position","top","bottom","left","right","height","width"],a=t.effects.setMode(n,e.mode||"effect"),r=e.direction||"left",h=e.distance||20,l=e.times||3,c=2*l+1,u=Math.round(e.duration/c),d="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},g={},m={},_=n.queue(),v=_.length;for(t.effects.save(n,o),n.show(),t.effects.createWrapper(n),f[d]=(p?"-=":"+=")+h,g[d]=(p?"+=":"-=")+2*h,m[d]=(p?"-=":"+=")+2*h,n.animate(f,u,e.easing),s=1;l>s;s++)n.animate(g,u,e.easing).animate(m,u,e.easing);n.animate(g,u,e.easing).animate(f,u/2,e.easing).queue(function(){"hide"===a&&n.hide(),t.effects.restore(n,o),t.effects.removeWrapper(n),i()}),v>1&&_.splice.apply(_,[1,0].concat(_.splice(v,c+1))),n.dequeue()},t.effects.effect.slide=function(e,i){var s,n=t(this),o=["position","top","bottom","left","right","width","height"],a=t.effects.setMode(n,e.mode||"show"),r="show"===a,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h,u={};t.effects.save(n,o),n.show(),s=e.distance||n["top"===l?"outerHeight":"outerWidth"](!0),t.effects.createWrapper(n).css({overflow:"hidden"}),r&&n.css(l,c?isNaN(s)?"-"+s:-s:s),u[l]=(r?c?"+=":"-=":c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===a&&n.hide(),t.effects.restore(n,o),t.effects.removeWrapper(n),i()}})},t.effects.effect.transfer=function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo(document.body).addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),i()})}});
    /*!
     * Masonry PACKAGED v4.1.1
     * Cascading grid layout library
     * http://masonry.desandro.com
     * MIT License
     * by David DeSandro
     */
    
    !function(t,e){"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,r,a){function h(t,e,n){var o,r="$()."+i+'("'+e+'")';return t.each(function(t,h){var u=a.data(h,i);if(!u)return void s(i+" not initialized. Cannot call methods, i.e. "+r);var d=u[e];if(!d||"_"==e.charAt(0))return void s(r+" is not a valid method");var l=d.apply(u,n);o=void 0===o?l:o}),void 0!==o?o:t}function u(t,e){t.each(function(t,n){var o=a.data(n,i);o?(o.option(e),o._init()):(o=new r(n,e),a.data(n,i,o))})}a=a||e||t.jQuery,a&&(r.prototype.option||(r.prototype.option=function(t){a.isPlainObject(t)&&(this.options=a.extend(!0,this.options,t))}),a.fn[i]=function(t){if("string"==typeof t){var e=o.call(arguments,1);return h(this,t,e)}return u(this,t),this},n(a))}function n(t){!t||t&&t.bridget||(t.bridget=i)}var o=Array.prototype.slice,r=t.console,s="undefined"==typeof r?function(){}:function(t){r.error(t)};return n(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},n=i[t]=i[t]||[];return-1==n.indexOf(e)&&n.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},n=i[t]=i[t]||{};return n[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=i.indexOf(e);return-1!=n&&i.splice(n,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=0,o=i[n];e=e||[];for(var r=this._onceEvents&&this._onceEvents[t];o;){var s=r&&r[o];s&&(this.off(t,o),delete r[o]),o.apply(this,e),n+=s?0:1,o=i[n]}return this}},t}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("get-size/get-size",[],function(){return e()}):"object"==typeof module&&module.exports?module.exports=e():t.getSize=e()}(window,function(){"use strict";function t(t){var e=parseFloat(t),i=-1==t.indexOf("%")&&!isNaN(e);return i&&e}function e(){}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0;u>e;e++){var i=h[e];t[i]=0}return t}function n(t){var e=getComputedStyle(t);return e||a("Style returned "+e+". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"),e}function o(){if(!d){d=!0;var e=document.createElement("div");e.style.width="200px",e.style.padding="1px 2px 3px 4px",e.style.borderStyle="solid",e.style.borderWidth="1px 2px 3px 4px",e.style.boxSizing="border-box";var i=document.body||document.documentElement;i.appendChild(e);var o=n(e);r.isBoxSizeOuter=s=200==t(o.width),i.removeChild(e)}}function r(e){if(o(),"string"==typeof e&&(e=document.querySelector(e)),e&&"object"==typeof e&&e.nodeType){var r=n(e);if("none"==r.display)return i();var a={};a.width=e.offsetWidth,a.height=e.offsetHeight;for(var d=a.isBorderBox="border-box"==r.boxSizing,l=0;u>l;l++){var c=h[l],f=r[c],m=parseFloat(f);a[c]=isNaN(m)?0:m}var p=a.paddingLeft+a.paddingRight,g=a.paddingTop+a.paddingBottom,y=a.marginLeft+a.marginRight,v=a.marginTop+a.marginBottom,_=a.borderLeftWidth+a.borderRightWidth,E=a.borderTopWidth+a.borderBottomWidth,z=d&&s,b=t(r.width);b!==!1&&(a.width=b+(z?0:p+_));var x=t(r.height);return x!==!1&&(a.height=x+(z?0:g+E)),a.innerWidth=a.width-(p+_),a.innerHeight=a.height-(g+E),a.outerWidth=a.width+y,a.outerHeight=a.height+v,a}}var s,a="undefined"==typeof console?e:function(t){console.error(t)},h=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"],u=h.length,d=!1;return r}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("desandro-matches-selector/matches-selector",e):"object"==typeof module&&module.exports?module.exports=e():t.matchesSelector=e()}(window,function(){"use strict";var t=function(){var t=Element.prototype;if(t.matches)return"matches";if(t.matchesSelector)return"matchesSelector";for(var e=["webkit","moz","ms","o"],i=0;i<e.length;i++){var n=e[i],o=n+"MatchesSelector";if(t[o])return o}}();return function(e,i){return e[t](i)}}),function(t,e){"function"==typeof define&&define.amd?define("fizzy-ui-utils/utils",["desandro-matches-selector/matches-selector"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("desandro-matches-selector")):t.fizzyUIUtils=e(t,t.matchesSelector)}(window,function(t,e){var i={};i.extend=function(t,e){for(var i in e)t[i]=e[i];return t},i.modulo=function(t,e){return(t%e+e)%e},i.makeArray=function(t){var e=[];if(Array.isArray(t))e=t;else if(t&&"number"==typeof t.length)for(var i=0;i<t.length;i++)e.push(t[i]);else e.push(t);return e},i.removeFrom=function(t,e){var i=t.indexOf(e);-1!=i&&t.splice(i,1)},i.getParent=function(t,i){for(;t!=document.body;)if(t=t.parentNode,e(t,i))return t},i.getQueryElement=function(t){return"string"==typeof t?document.querySelector(t):t},i.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},i.filterFindElements=function(t,n){t=i.makeArray(t);var o=[];return t.forEach(function(t){if(t instanceof HTMLElement){if(!n)return void o.push(t);e(t,n)&&o.push(t);for(var i=t.querySelectorAll(n),r=0;r<i.length;r++)o.push(i[r])}}),o},i.debounceMethod=function(t,e,i){var n=t.prototype[e],o=e+"Timeout";t.prototype[e]=function(){var t=this[o];t&&clearTimeout(t);var e=arguments,r=this;this[o]=setTimeout(function(){n.apply(r,e),delete r[o]},i||100)}},i.docReady=function(t){var e=document.readyState;"complete"==e||"interactive"==e?t():document.addEventListener("DOMContentLoaded",t)},i.toDashed=function(t){return t.replace(/(.)([A-Z])/g,function(t,e,i){return e+"-"+i}).toLowerCase()};var n=t.console;return i.htmlInit=function(e,o){i.docReady(function(){var r=i.toDashed(o),s="data-"+r,a=document.querySelectorAll("["+s+"]"),h=document.querySelectorAll(".js-"+r),u=i.makeArray(a).concat(i.makeArray(h)),d=s+"-options",l=t.jQuery;u.forEach(function(t){var i,r=t.getAttribute(s)||t.getAttribute(d);try{i=r&&JSON.parse(r)}catch(a){return void(n&&n.error("Error parsing "+s+" on "+t.className+": "+a))}var h=new e(t,i);l&&l.data(t,o,h)})})},i}),function(t,e){"function"==typeof define&&define.amd?define("outlayer/item",["ev-emitter/ev-emitter","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("ev-emitter"),require("get-size")):(t.Outlayer={},t.Outlayer.Item=e(t.EvEmitter,t.getSize))}(window,function(t,e){"use strict";function i(t){for(var e in t)return!1;return e=null,!0}function n(t,e){t&&(this.element=t,this.layout=e,this.position={x:0,y:0},this._create())}function o(t){return t.replace(/([A-Z])/g,function(t){return"-"+t.toLowerCase()})}var r=document.documentElement.style,s="string"==typeof r.transition?"transition":"WebkitTransition",a="string"==typeof r.transform?"transform":"WebkitTransform",h={WebkitTransition:"webkitTransitionEnd",transition:"transitionend"}[s],u={transform:a,transition:s,transitionDuration:s+"Duration",transitionProperty:s+"Property",transitionDelay:s+"Delay"},d=n.prototype=Object.create(t.prototype);d.constructor=n,d._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},d.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},d.getSize=function(){this.size=e(this.element)},d.css=function(t){var e=this.element.style;for(var i in t){var n=u[i]||i;e[n]=t[i]}},d.getPosition=function(){var t=getComputedStyle(this.element),e=this.layout._getOption("originLeft"),i=this.layout._getOption("originTop"),n=t[e?"left":"right"],o=t[i?"top":"bottom"],r=this.layout.size,s=-1!=n.indexOf("%")?parseFloat(n)/100*r.width:parseInt(n,10),a=-1!=o.indexOf("%")?parseFloat(o)/100*r.height:parseInt(o,10);s=isNaN(s)?0:s,a=isNaN(a)?0:a,s-=e?r.paddingLeft:r.paddingRight,a-=i?r.paddingTop:r.paddingBottom,this.position.x=s,this.position.y=a},d.layoutPosition=function(){var t=this.layout.size,e={},i=this.layout._getOption("originLeft"),n=this.layout._getOption("originTop"),o=i?"paddingLeft":"paddingRight",r=i?"left":"right",s=i?"right":"left",a=this.position.x+t[o];e[r]=this.getXValue(a),e[s]="";var h=n?"paddingTop":"paddingBottom",u=n?"top":"bottom",d=n?"bottom":"top",l=this.position.y+t[h];e[u]=this.getYValue(l),e[d]="",this.css(e),this.emitEvent("layout",[this])},d.getXValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&!e?t/this.layout.size.width*100+"%":t+"px"},d.getYValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&e?t/this.layout.size.height*100+"%":t+"px"},d._transitionTo=function(t,e){this.getPosition();var i=this.position.x,n=this.position.y,o=parseInt(t,10),r=parseInt(e,10),s=o===this.position.x&&r===this.position.y;if(this.setPosition(t,e),s&&!this.isTransitioning)return void this.layoutPosition();var a=t-i,h=e-n,u={};u.transform=this.getTranslate(a,h),this.transition({to:u,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},d.getTranslate=function(t,e){var i=this.layout._getOption("originLeft"),n=this.layout._getOption("originTop");return t=i?t:-t,e=n?e:-e,"translate3d("+t+"px, "+e+"px, 0)"},d.goTo=function(t,e){this.setPosition(t,e),this.layoutPosition()},d.moveTo=d._transitionTo,d.setPosition=function(t,e){this.position.x=parseInt(t,10),this.position.y=parseInt(e,10)},d._nonTransition=function(t){this.css(t.to),t.isCleaning&&this._removeStyles(t.to);for(var e in t.onTransitionEnd)t.onTransitionEnd[e].call(this)},d.transition=function(t){if(!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(t);var e=this._transn;for(var i in t.onTransitionEnd)e.onEnd[i]=t.onTransitionEnd[i];for(i in t.to)e.ingProperties[i]=!0,t.isCleaning&&(e.clean[i]=!0);if(t.from){this.css(t.from);var n=this.element.offsetHeight;n=null}this.enableTransition(t.to),this.css(t.to),this.isTransitioning=!0};var l="opacity,"+o(a);d.enableTransition=function(){if(!this.isTransitioning){var t=this.layout.options.transitionDuration;t="number"==typeof t?t+"ms":t,this.css({transitionProperty:l,transitionDuration:t,transitionDelay:this.staggerDelay||0}),this.element.addEventListener(h,this,!1)}},d.onwebkitTransitionEnd=function(t){this.ontransitionend(t)},d.onotransitionend=function(t){this.ontransitionend(t)};var c={"-webkit-transform":"transform"};d.ontransitionend=function(t){if(t.target===this.element){var e=this._transn,n=c[t.propertyName]||t.propertyName;if(delete e.ingProperties[n],i(e.ingProperties)&&this.disableTransition(),n in e.clean&&(this.element.style[t.propertyName]="",delete e.clean[n]),n in e.onEnd){var o=e.onEnd[n];o.call(this),delete e.onEnd[n]}this.emitEvent("transitionEnd",[this])}},d.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(h,this,!1),this.isTransitioning=!1},d._removeStyles=function(t){var e={};for(var i in t)e[i]="";this.css(e)};var f={transitionProperty:"",transitionDuration:"",transitionDelay:""};return d.removeTransitionStyles=function(){this.css(f)},d.stagger=function(t){t=isNaN(t)?0:t,this.staggerDelay=t+"ms"},d.removeElem=function(){this.element.parentNode.removeChild(this.element),this.css({display:""}),this.emitEvent("remove",[this])},d.remove=function(){return s&&parseFloat(this.layout.options.transitionDuration)?(this.once("transitionEnd",function(){this.removeElem()}),void this.hide()):void this.removeElem()},d.reveal=function(){delete this.isHidden,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("visibleStyle");e[i]=this.onRevealTransitionEnd,this.transition({from:t.hiddenStyle,to:t.visibleStyle,isCleaning:!0,onTransitionEnd:e})},d.onRevealTransitionEnd=function(){this.isHidden||this.emitEvent("reveal")},d.getHideRevealTransitionEndProperty=function(t){var e=this.layout.options[t];if(e.opacity)return"opacity";for(var i in e)return i},d.hide=function(){this.isHidden=!0,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("hiddenStyle");e[i]=this.onHideTransitionEnd,this.transition({from:t.visibleStyle,to:t.hiddenStyle,isCleaning:!0,onTransitionEnd:e})},d.onHideTransitionEnd=function(){this.isHidden&&(this.css({display:"none"}),this.emitEvent("hide"))},d.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},n}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("outlayer/outlayer",["ev-emitter/ev-emitter","get-size/get-size","fizzy-ui-utils/utils","./item"],function(i,n,o,r){return e(t,i,n,o,r)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter"),require("get-size"),require("fizzy-ui-utils"),require("./item")):t.Outlayer=e(t,t.EvEmitter,t.getSize,t.fizzyUIUtils,t.Outlayer.Item)}(window,function(t,e,i,n,o){"use strict";function r(t,e){var i=n.getQueryElement(t);if(!i)return void(h&&h.error("Bad element for "+this.constructor.namespace+": "+(i||t)));this.element=i,u&&(this.$element=u(this.element)),this.options=n.extend({},this.constructor.defaults),this.option(e);var o=++l;this.element.outlayerGUID=o,c[o]=this,this._create();var r=this._getOption("initLayout");r&&this.layout()}function s(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e}function a(t){if("number"==typeof t)return t;var e=t.match(/(^\d*\.?\d*)(\w*)/),i=e&&e[1],n=e&&e[2];if(!i.length)return 0;i=parseFloat(i);var o=m[n]||1;return i*o}var h=t.console,u=t.jQuery,d=function(){},l=0,c={};r.namespace="outlayer",r.Item=o,r.defaults={containerStyle:{position:"relative"},initLayout:!0,originLeft:!0,originTop:!0,resize:!0,resizeContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}};var f=r.prototype;n.extend(f,e.prototype),f.option=function(t){n.extend(this.options,t)},f._getOption=function(t){var e=this.constructor.compatOptions[t];return e&&void 0!==this.options[e]?this.options[e]:this.options[t]},r.compatOptions={initLayout:"isInitLayout",horizontal:"isHorizontal",layoutInstant:"isLayoutInstant",originLeft:"isOriginLeft",originTop:"isOriginTop",resize:"isResizeBound",resizeContainer:"isResizingContainer"},f._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),n.extend(this.element.style,this.options.containerStyle);var t=this._getOption("resize");t&&this.bindResize()},f.reloadItems=function(){this.items=this._itemize(this.element.children)},f._itemize=function(t){for(var e=this._filterFindItemElements(t),i=this.constructor.Item,n=[],o=0;o<e.length;o++){var r=e[o],s=new i(r,this);n.push(s)}return n},f._filterFindItemElements=function(t){return n.filterFindElements(t,this.options.itemSelector)},f.getItemElements=function(){return this.items.map(function(t){return t.element})},f.layout=function(){this._resetLayout(),this._manageStamps();var t=this._getOption("layoutInstant"),e=void 0!==t?t:!this._isLayoutInited;this.layoutItems(this.items,e),this._isLayoutInited=!0},f._init=f.layout,f._resetLayout=function(){this.getSize()},f.getSize=function(){this.size=i(this.element)},f._getMeasurement=function(t,e){var n,o=this.options[t];o?("string"==typeof o?n=this.element.querySelector(o):o instanceof HTMLElement&&(n=o),this[t]=n?i(n)[e]:o):this[t]=0},f.layoutItems=function(t,e){t=this._getItemsForLayout(t),this._layoutItems(t,e),this._postLayout()},f._getItemsForLayout=function(t){return t.filter(function(t){return!t.isIgnored})},f._layoutItems=function(t,e){if(this._emitCompleteOnItems("layout",t),t&&t.length){var i=[];t.forEach(function(t){var n=this._getItemLayoutPosition(t);n.item=t,n.isInstant=e||t.isLayoutInstant,i.push(n)},this),this._processLayoutQueue(i)}},f._getItemLayoutPosition=function(){return{x:0,y:0}},f._processLayoutQueue=function(t){this.updateStagger(),t.forEach(function(t,e){this._positionItem(t.item,t.x,t.y,t.isInstant,e)},this)},f.updateStagger=function(){var t=this.options.stagger;return null===t||void 0===t?void(this.stagger=0):(this.stagger=a(t),this.stagger)},f._positionItem=function(t,e,i,n,o){n?t.goTo(e,i):(t.stagger(o*this.stagger),t.moveTo(e,i))},f._postLayout=function(){this.resizeContainer()},f.resizeContainer=function(){var t=this._getOption("resizeContainer");if(t){var e=this._getContainerSize();e&&(this._setContainerMeasure(e.width,!0),this._setContainerMeasure(e.height,!1))}},f._getContainerSize=d,f._setContainerMeasure=function(t,e){if(void 0!==t){var i=this.size;i.isBorderBox&&(t+=e?i.paddingLeft+i.paddingRight+i.borderLeftWidth+i.borderRightWidth:i.paddingBottom+i.paddingTop+i.borderTopWidth+i.borderBottomWidth),t=Math.max(t,0),this.element.style[e?"width":"height"]=t+"px"}},f._emitCompleteOnItems=function(t,e){function i(){o.dispatchEvent(t+"Complete",null,[e])}function n(){s++,s==r&&i()}var o=this,r=e.length;if(!e||!r)return void i();var s=0;e.forEach(function(e){e.once(t,n)})},f.dispatchEvent=function(t,e,i){var n=e?[e].concat(i):i;if(this.emitEvent(t,n),u)if(this.$element=this.$element||u(this.element),e){var o=u.Event(e);o.type=t,this.$element.trigger(o,i)}else this.$element.trigger(t,i)},f.ignore=function(t){var e=this.getItem(t);e&&(e.isIgnored=!0)},f.unignore=function(t){var e=this.getItem(t);e&&delete e.isIgnored},f.stamp=function(t){t=this._find(t),t&&(this.stamps=this.stamps.concat(t),t.forEach(this.ignore,this))},f.unstamp=function(t){t=this._find(t),t&&t.forEach(function(t){n.removeFrom(this.stamps,t),this.unignore(t)},this)},f._find=function(t){return t?("string"==typeof t&&(t=this.element.querySelectorAll(t)),t=n.makeArray(t)):void 0},f._manageStamps=function(){this.stamps&&this.stamps.length&&(this._getBoundingRect(),this.stamps.forEach(this._manageStamp,this))},f._getBoundingRect=function(){var t=this.element.getBoundingClientRect(),e=this.size;this._boundingRect={left:t.left+e.paddingLeft+e.borderLeftWidth,top:t.top+e.paddingTop+e.borderTopWidth,right:t.right-(e.paddingRight+e.borderRightWidth),bottom:t.bottom-(e.paddingBottom+e.borderBottomWidth)}},f._manageStamp=d,f._getElementOffset=function(t){var e=t.getBoundingClientRect(),n=this._boundingRect,o=i(t),r={left:e.left-n.left-o.marginLeft,top:e.top-n.top-o.marginTop,right:n.right-e.right-o.marginRight,bottom:n.bottom-e.bottom-o.marginBottom};return r},f.handleEvent=n.handleEvent,f.bindResize=function(){t.addEventListener("resize",this),this.isResizeBound=!0},f.unbindResize=function(){t.removeEventListener("resize",this),this.isResizeBound=!1},f.onresize=function(){this.resize()},n.debounceMethod(r,"onresize",100),f.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},f.needsResizeLayout=function(){var t=i(this.element),e=this.size&&t;return e&&t.innerWidth!==this.size.innerWidth},f.addItems=function(t){var e=this._itemize(t);return e.length&&(this.items=this.items.concat(e)),e},f.appended=function(t){var e=this.addItems(t);e.length&&(this.layoutItems(e,!0),this.reveal(e))},f.prepended=function(t){var e=this._itemize(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._resetLayout(),this._manageStamps(),this.layoutItems(e,!0),this.reveal(e),this.layoutItems(i)}},f.reveal=function(t){if(this._emitCompleteOnItems("reveal",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.reveal()})}},f.hide=function(t){if(this._emitCompleteOnItems("hide",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.hide()})}},f.revealItemElements=function(t){var e=this.getItems(t);this.reveal(e)},f.hideItemElements=function(t){var e=this.getItems(t);this.hide(e)},f.getItem=function(t){for(var e=0;e<this.items.length;e++){var i=this.items[e];if(i.element==t)return i}},f.getItems=function(t){t=n.makeArray(t);var e=[];return t.forEach(function(t){var i=this.getItem(t);i&&e.push(i)},this),e},f.remove=function(t){var e=this.getItems(t);this._emitCompleteOnItems("remove",e),e&&e.length&&e.forEach(function(t){t.remove(),n.removeFrom(this.items,t)},this)},f.destroy=function(){var t=this.element.style;t.height="",t.position="",t.width="",this.items.forEach(function(t){t.destroy()}),this.unbindResize();var e=this.element.outlayerGUID;delete c[e],delete this.element.outlayerGUID,u&&u.removeData(this.element,this.constructor.namespace)},r.data=function(t){t=n.getQueryElement(t);var e=t&&t.outlayerGUID;return e&&c[e]},r.create=function(t,e){var i=s(r);return i.defaults=n.extend({},r.defaults),n.extend(i.defaults,e),i.compatOptions=n.extend({},r.compatOptions),i.namespace=t,i.data=r.data,i.Item=s(o),n.htmlInit(i,t),u&&u.bridget&&u.bridget(t,i),i};var m={ms:1,s:1e3};return r.Item=o,r}),function(t,e){"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("outlayer"),require("get-size")):t.Masonry=e(t.Outlayer,t.getSize)}(window,function(t,e){var i=t.create("masonry");return i.compatOptions.fitWidth="isFitWidth",i.prototype._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns(),this.colYs=[];for(var t=0;t<this.cols;t++)this.colYs.push(0);this.maxY=0},i.prototype.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var t=this.items[0],i=t&&t.element;this.columnWidth=i&&e(i).outerWidth||this.containerWidth}var n=this.columnWidth+=this.gutter,o=this.containerWidth+this.gutter,r=o/n,s=n-o%n,a=s&&1>s?"round":"floor";r=Math[a](r),this.cols=Math.max(r,1)},i.prototype.getContainerWidth=function(){var t=this._getOption("fitWidth"),i=t?this.element.parentNode:this.element,n=e(i);this.containerWidth=n&&n.innerWidth},i.prototype._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth%this.columnWidth,i=e&&1>e?"round":"ceil",n=Math[i](t.size.outerWidth/this.columnWidth);n=Math.min(n,this.cols);for(var o=this._getColGroup(n),r=Math.min.apply(Math,o),s=o.indexOf(r),a={x:this.columnWidth*s,y:r},h=r+t.size.outerHeight,u=this.cols+1-o.length,d=0;u>d;d++)this.colYs[s+d]=h;return a},i.prototype._getColGroup=function(t){if(2>t)return this.colYs;for(var e=[],i=this.cols+1-t,n=0;i>n;n++){var o=this.colYs.slice(n,n+t);e[n]=Math.max.apply(Math,o)}return e},i.prototype._manageStamp=function(t){var i=e(t),n=this._getElementOffset(t),o=this._getOption("originLeft"),r=o?n.left:n.right,s=r+i.outerWidth,a=Math.floor(r/this.columnWidth);a=Math.max(0,a);var h=Math.floor(s/this.columnWidth);h-=s%this.columnWidth?0:1,h=Math.min(this.cols-1,h);for(var u=this._getOption("originTop"),d=(u?n.top:n.bottom)+i.outerHeight,l=a;h>=l;l++)this.colYs[l]=Math.max(d,this.colYs[l])},i.prototype._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var t={height:this.maxY};return this._getOption("fitWidth")&&(t.width=this._getContainerFitWidth()),t},i.prototype._getContainerFitWidth=function(){for(var t=0,e=this.cols;--e&&0===this.colYs[e];)t++;return(this.cols-t)*this.columnWidth-this.gutter},i.prototype.needsResizeLayout=function(){var t=this.containerWidth;return this.getContainerWidth(),t!=this.containerWidth},i});
    /**
     * microplugin.js
     * Copyright (c) 2013 Brian Reavis & contributors
     *
     * 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.
     *
     * @author Brian Reavis <brian@thirdroute.com>
     */
    
    (function(root, factory) {
        if (typeof define === 'function' && define.amd) {
            define(factory);
        } else if (typeof exports === 'object') {
            module.exports = factory();
        } else {
            root.MicroPlugin = factory();
        }
    }(this, function() {
        var MicroPlugin = {};
    
        MicroPlugin.mixin = function(Interface) {
            Interface.plugins = {};
    
            /**
             * Initializes the listed plugins (with options).
             * Acceptable formats:
             *
             * List (without options):
             *   ['a', 'b', 'c']
             *
             * List (with options):
             *   [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
             *
             * Hash (with options):
             *   {'a': { ... }, 'b': { ... }, 'c': { ... }}
             *
             * @param {mixed} plugins
             */
            Interface.prototype.initializePlugins = function(plugins) {
                var i, n, key;
                var self  = this;
                var queue = [];
    
                self.plugins = {
                    names     : [],
                    settings  : {},
                    requested : {},
                    loaded    : {}
                };
    
                if (utils.isArray(plugins)) {
                    for (i = 0, n = plugins.length; i < n; i++) {
                        if (typeof plugins[i] === 'string') {
                            queue.push(plugins[i]);
                        } else {
                            self.plugins.settings[plugins[i].name] = plugins[i].options;
                            queue.push(plugins[i].name);
                        }
                    }
                } else if (plugins) {
                    for (key in plugins) {
                        if (plugins.hasOwnProperty(key)) {
                            self.plugins.settings[key] = plugins[key];
                            queue.push(key);
                        }
                    }
                }
    
                while (queue.length) {
                    self.require(queue.shift());
                }
            };
    
            Interface.prototype.loadPlugin = function(name) {
                var self    = this;
                var plugins = self.plugins;
                var plugin  = Interface.plugins[name];
    
                if (!Interface.plugins.hasOwnProperty(name)) {
                    throw new Error('Unable to find "' +  name + '" plugin');
                }
    
                plugins.requested[name] = true;
                plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
                plugins.names.push(name);
            };
    
            /**
             * Initializes a plugin.
             *
             * @param {string} name
             */
            Interface.prototype.require = function(name) {
                var self = this;
                var plugins = self.plugins;
    
                if (!self.plugins.loaded.hasOwnProperty(name)) {
                    if (plugins.requested[name]) {
                        throw new Error('Plugin has circular dependency ("' + name + '")');
                    }
                    self.loadPlugin(name);
                }
    
                return plugins.loaded[name];
            };
    
            /**
             * Registers a plugin.
             *
             * @param {string} name
             * @param {function} fn
             */
            Interface.define = function(name, fn) {
                Interface.plugins[name] = {
                    'name' : name,
                    'fn'   : fn
                };
            };
        };
    
        var utils = {
            isArray: Array.isArray || function(vArg) {
                return Object.prototype.toString.call(vArg) === '[object Array]';
            }
        };
    
        return MicroPlugin;
    }));
    /**
     * sifter.js
     * Copyright (c) 2013 Brian Reavis & contributors
     *
     * 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.
     *
     * @author Brian Reavis <brian@thirdroute.com>
     */
    
    (function(root, factory) {
        if (typeof define === 'function' && define.amd) {
            define(factory);
        } else if (typeof exports === 'object') {
            module.exports = factory();
        } else {
            root.Sifter = factory();
        }
    }(this, function() {
    
        /**
         * Textually searches arrays and hashes of objects
         * by property (or multiple properties). Designed
         * specifically for autocomplete.
         *
         * @constructor
         * @param {array|object} items
         * @param {object} items
         */
        var Sifter = function(items, settings) {
            this.items = items;
            this.settings = settings || {diacritics: true};
        };
    
        /**
         * Splits a search string into an array of individual
         * regexps to be used to match results.
         *
         * @param {string} query
         * @returns {array}
         */
        Sifter.prototype.tokenize = function(query) {
            query = trim(String(query || '').toLowerCase());
            if (!query || !query.length) return [];
    
            var i, n, regex, letter;
            var tokens = [];
            var words = query.split(/ +/);
    
            for (i = 0, n = words.length; i < n; i++) {
                regex = escape_regex(words[i]);
                if (this.settings.diacritics) {
                    for (letter in DIACRITICS) {
                        if (DIACRITICS.hasOwnProperty(letter)) {
                            regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
                        }
                    }
                }
                tokens.push({
                    string : words[i],
                    regex  : new RegExp(regex, 'i')
                });
            }
    
            return tokens;
        };
    
        /**
         * Iterates over arrays and hashes.
         *
         * ```
         * this.iterator(this.items, function(item, id) {
         *    // invoked for each item
         * });
         * ```
         *
         * @param {array|object} object
         */
        Sifter.prototype.iterator = function(object, callback) {
            var iterator;
            if (is_array(object)) {
                iterator = Array.prototype.forEach || function(callback) {
                    for (var i = 0, n = this.length; i < n; i++) {
                        callback(this[i], i, this);
                    }
                };
            } else {
                iterator = function(callback) {
                    for (var key in this) {
                        if (this.hasOwnProperty(key)) {
                            callback(this[key], key, this);
                        }
                    }
                };
            }
    
            iterator.apply(object, [callback]);
        };
    
        /**
         * Returns a function to be used to score individual results.
         *
         * Good matches will have a higher score than poor matches.
         * If an item is not a match, 0 will be returned by the function.
         *
         * @param {object|string} search
         * @param {object} options (optional)
         * @returns {function}
         */
        Sifter.prototype.getScoreFunction = function(search, options) {
            var self, fields, tokens, token_count, nesting;
    
            self        = this;
            search      = self.prepareSearch(search, options);
            tokens      = search.tokens;
            fields      = search.options.fields;
            token_count = tokens.length;
            nesting     = search.options.nesting;
    
            /**
             * Calculates how close of a match the
             * given value is against a search token.
             *
             * @param {mixed} value
             * @param {object} token
             * @return {number}
             */
            var scoreValue = function(value, token) {
                var score, pos;
    
                if (!value) return 0;
                value = String(value || '');
                pos = value.search(token.regex);
                if (pos === -1) return 0;
                score = token.string.length / value.length;
                if (pos === 0) score += 0.5;
                return score;
            };
    
            /**
             * Calculates the score of an object
             * against the search query.
             *
             * @param {object} token
             * @param {object} data
             * @return {number}
             */
            var scoreObject = (function() {
                var field_count = fields.length;
                if (!field_count) {
                    return function() { return 0; };
                }
                if (field_count === 1) {
                    return function(token, data) {
                        return scoreValue(getattr(data, fields[0], nesting), token);
                    };
                }
                return function(token, data) {
                    for (var i = 0, sum = 0; i < field_count; i++) {
                        sum += scoreValue(getattr(data, fields[i], nesting), token);
                    }
                    return sum / field_count;
                };
            })();
    
            if (!token_count) {
                return function() { return 0; };
            }
            if (token_count === 1) {
                return function(data) {
                    return scoreObject(tokens[0], data);
                };
            }
    
            if (search.options.conjunction === 'and') {
                return function(data) {
                    var score;
                    for (var i = 0, sum = 0; i < token_count; i++) {
                        score = scoreObject(tokens[i], data);
                        if (score <= 0) return 0;
                        sum += score;
                    }
                    return sum / token_count;
                };
            } else {
                return function(data) {
                    for (var i = 0, sum = 0; i < token_count; i++) {
                        sum += scoreObject(tokens[i], data);
                    }
                    return sum / token_count;
                };
            }
        };
    
        /**
         * Returns a function that can be used to compare two
         * results, for sorting purposes. If no sorting should
         * be performed, `null` will be returned.
         *
         * @param {string|object} search
         * @param {object} options
         * @return function(a,b)
         */
        Sifter.prototype.getSortFunction = function(search, options) {
            var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort;
    
            self   = this;
            search = self.prepareSearch(search, options);
            sort   = (!search.query && options.sort_empty) || options.sort;
    
            /**
             * Fetches the specified sort field value
             * from a search result item.
             *
             * @param  {string} name
             * @param  {object} result
             * @return {mixed}
             */
            get_field = function(name, result) {
                if (name === '$score') return result.score;
                return getattr(self.items[result.id], name, options.nesting);
            };
    
            // parse options
            fields = [];
            if (sort) {
                for (i = 0, n = sort.length; i < n; i++) {
                    if (search.query || sort[i].field !== '$score') {
                        fields.push(sort[i]);
                    }
                }
            }
    
            // the "$score" field is implied to be the primary
            // sort field, unless it's manually specified
            if (search.query) {
                implicit_score = true;
                for (i = 0, n = fields.length; i < n; i++) {
                    if (fields[i].field === '$score') {
                        implicit_score = false;
                        break;
                    }
                }
                if (implicit_score) {
                    fields.unshift({field: '$score', direction: 'desc'});
                }
            } else {
                for (i = 0, n = fields.length; i < n; i++) {
                    if (fields[i].field === '$score') {
                        fields.splice(i, 1);
                        break;
                    }
                }
            }
    
            multipliers = [];
            for (i = 0, n = fields.length; i < n; i++) {
                multipliers.push(fields[i].direction === 'desc' ? -1 : 1);
            }
    
            // build function
            fields_count = fields.length;
            if (!fields_count) {
                return null;
            } else if (fields_count === 1) {
                field = fields[0].field;
                multiplier = multipliers[0];
                return function(a, b) {
                    return multiplier * cmp(
                        get_field(field, a),
                        get_field(field, b)
                    );
                };
            } else {
                return function(a, b) {
                    var i, result, a_value, b_value, field;
                    for (i = 0; i < fields_count; i++) {
                        field = fields[i].field;
                        result = multipliers[i] * cmp(
                            get_field(field, a),
                            get_field(field, b)
                        );
                        if (result) return result;
                    }
                    return 0;
                };
            }
        };
    
        /**
         * Parses a search query and returns an object
         * with tokens and fields ready to be populated
         * with results.
         *
         * @param {string} query
         * @param {object} options
         * @returns {object}
         */
        Sifter.prototype.prepareSearch = function(query, options) {
            if (typeof query === 'object') return query;
    
            options = extend({}, options);
    
            var option_fields     = options.fields;
            var option_sort       = options.sort;
            var option_sort_empty = options.sort_empty;
    
            if (option_fields && !is_array(option_fields)) options.fields = [option_fields];
            if (option_sort && !is_array(option_sort)) options.sort = [option_sort];
            if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty];
    
            return {
                options : options,
                query   : String(query || '').toLowerCase(),
                tokens  : this.tokenize(query),
                total   : 0,
                items   : []
            };
        };
    
        /**
         * Searches through all items and returns a sorted array of matches.
         *
         * The `options` parameter can contain:
         *
         *   - fields {string|array}
         *   - sort {array}
         *   - score {function}
         *   - filter {bool}
         *   - limit {integer}
         *
         * Returns an object containing:
         *
         *   - options {object}
         *   - query {string}
         *   - tokens {array}
         *   - total {int}
         *   - items {array}
         *
         * @param {string} query
         * @param {object} options
         * @returns {object}
         */
        Sifter.prototype.search = function(query, options) {
            var self = this, value, score, search, calculateScore;
            var fn_sort;
            var fn_score;
    
            search  = this.prepareSearch(query, options);
            options = search.options;
            query   = search.query;
    
            // generate result scoring function
            fn_score = options.score || self.getScoreFunction(search);
    
            // perform search and sort
            if (query.length) {
                self.iterator(self.items, function(item, id) {
                    score = fn_score(item);
                    if (options.filter === false || score > 0) {
                        search.items.push({'score': score, 'id': id});
                    }
                });
            } else {
                self.iterator(self.items, function(item, id) {
                    search.items.push({'score': 1, 'id': id});
                });
            }
    
            fn_sort = self.getSortFunction(search, options);
            if (fn_sort) search.items.sort(fn_sort);
    
            // apply limits
            search.total = search.items.length;
            if (typeof options.limit === 'number') {
                search.items = search.items.slice(0, options.limit);
            }
    
            return search;
        };
    
        // utilities
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
        var cmp = function(a, b) {
            if (typeof a === 'number' && typeof b === 'number') {
                return a > b ? 1 : (a < b ? -1 : 0);
            }
            a = asciifold(String(a || ''));
            b = asciifold(String(b || ''));
            if (a > b) return 1;
            if (b > a) return -1;
            return 0;
        };
    
        var extend = function(a, b) {
            var i, n, k, object;
            for (i = 1, n = arguments.length; i < n; i++) {
                object = arguments[i];
                if (!object) continue;
                for (k in object) {
                    if (object.hasOwnProperty(k)) {
                        a[k] = object[k];
                    }
                }
            }
            return a;
        };
    
        /**
         * A property getter resolving dot-notation
         * @param  {Object}  obj     The root object to fetch property on
         * @param  {String}  name    The optionally dotted property name to fetch
         * @param  {Boolean} nesting Handle nesting or not
         * @return {Object}          The resolved property value
         */
        var getattr = function(obj, name, nesting) {
            if (!obj || !name) return;
            if (!nesting) return obj[name];
            var names = name.split(".");
            while(names.length && (obj = obj[names.shift()]));
            return obj;
        };
    
        var trim = function(str) {
            return (str + '').replace(/^\s+|\s+$|/g, '');
        };
    
        var escape_regex = function(str) {
            return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
        };
    
        var is_array = Array.isArray || (typeof $ !== 'undefined' && $.isArray) || function(object) {
            return Object.prototype.toString.call(object) === '[object Array]';
        };
    
        var DIACRITICS = {
            'a': '[aá¸€á¸Ä‚ÄƒÃ‚Ã¢ÇÇŽÈºâ±¥È¦È§áº áº¡Ã„Ã¤Ã€Ã ÃÃ¡Ä€ÄÃƒÃ£Ã…Ã¥Ä…Ä„ÃƒÄ…Ä„]',
            'b': '[bâ¢Î²Î’Bà¸¿ðŒá›’]',
            'c': '[cÄ†Ä‡ÄˆÄ‰ÄŒÄÄŠÄ‹CÌ„cÌ„Ã‡Ã§á¸ˆá¸‰È»È¼Æ‡ÆˆÉ•á´„ï¼£ï½ƒ]',
            'd': '[dÄŽÄá¸Šá¸‹á¸á¸‘á¸Œá¸á¸’á¸“á¸Žá¸ÄÄ‘DÌ¦dÌ¦Æ‰É–ÆŠÉ—Æ‹ÆŒáµ­á¶á¶‘È¡á´…ï¼¤ï½„Ã°]',
            'e': '[eÃ‰Ã©ÃˆÃ¨ÃŠÃªá¸˜á¸™ÄšÄ›Ä”Ä•áº¼áº½á¸šá¸›áººáº»Ä–Ä—Ã‹Ã«Ä’Ä“È¨È©Ä˜Ä™á¶’É†É‡È„È…áº¾áº¿á»€á»á»„á»…á»‚á»ƒá¸œá¸á¸–á¸—á¸”á¸•È†È‡áº¸áº¹á»†á»‡â±¸á´‡ï¼¥ï½…É˜ÇÆÆÎµ]',
            'f': '[fÆ‘Æ’á¸žá¸Ÿ]',
            'g': '[gÉ¢â‚²Ç¤Ç¥ÄœÄÄžÄŸÄ¢Ä£Æ“É Ä Ä¡]',
            'h': '[hÄ¤Ä¥Ä¦Ä§á¸¨á¸©áº–áº–á¸¤á¸¥á¸¢á¸£É¦Ê°Ç¶Æ•]',
            'i': '[iÃÃ­ÃŒÃ¬Ä¬Ä­ÃŽÃ®ÇÇÃÃ¯á¸®á¸¯Ä¨Ä©Ä®Ä¯ÄªÄ«á»ˆá»‰ÈˆÈ‰ÈŠÈ‹á»Šá»‹á¸¬á¸­Æ—É¨É¨Ì†áµ»á¶–Ä°iIÄ±Éªï¼©ï½‰]',
            'j': '[jÈ·Ä´ÄµÉˆÉ‰ÊÉŸÊ²]',
            'k': '[kÆ˜Æ™ê€êá¸°á¸±Ç¨Ç©á¸²á¸³á¸´á¸µÎºÏ°â‚­]',
            'l': '[lÅÅ‚Ä½Ä¾Ä»Ä¼Ä¹Äºá¸¶á¸·á¸¸á¸¹á¸¼á¸½á¸ºá¸»Ä¿Å€È½Æšâ± â±¡â±¢É«É¬á¶…É­È´ÊŸï¼¬ï½Œ]',
            'n': '[nÅƒÅ„Ç¸Ç¹Å‡ÅˆÃ‘Ã±á¹„á¹…Å…Å†á¹†á¹‡á¹Šá¹‹á¹ˆá¹‰NÌˆnÌˆÆÉ²È Æžáµ°á¶‡É³ÈµÉ´ï¼®ï½ŽÅŠÅ‹]',
            'o': '[oÃ˜Ã¸Ã–Ã¶Ã“Ã³Ã’Ã²Ã”Ã´Ç‘Ç’ÅÅ‘ÅŽÅÈ®È¯á»Œá»ÆŸÉµÆ Æ¡á»Žá»ÅŒÅÃ•ÃµÇªÇ«ÈŒÈÕ•Ö…]',
            'p': '[pá¹”á¹•á¹–á¹—â±£áµ½Æ¤Æ¥áµ±]',
            'q': '[qê–ê—Ê ÉŠÉ‹ê˜ê™qÌƒ]',
            'r': '[rÅ”Å•ÉŒÉÅ˜Å™Å–Å—á¹˜á¹™ÈÈ‘È’È“á¹šá¹›â±¤É½]',
            's': '[sÅšÅ›á¹ á¹¡á¹¢á¹£êž¨êž©ÅœÅÅ Å¡ÅžÅŸÈ˜È™SÌˆsÌˆ]',
            't': '[tÅ¤Å¥á¹ªá¹«Å¢Å£á¹¬á¹­Æ®ÊˆÈšÈ›á¹°á¹±á¹®á¹¯Æ¬Æ­]',
            'u': '[uÅ¬Å­É„Ê‰á»¤á»¥ÃœÃ¼ÃšÃºÃ™Ã¹Ã›Ã»Ç“Ç”Å°Å±Å¬Å­Æ¯Æ°á»¦á»§ÅªÅ«Å¨Å©Å²Å³È”È•âˆª]',
            'v': '[vá¹¼á¹½á¹¾á¹¿Æ²Ê‹êžêŸâ±±Ê‹]',
            'w': '[wáº‚áºƒáº€áºÅ´Åµáº„áº…áº†áº‡áºˆáº‰]',
            'x': '[xáºŒáºáºŠáº‹Ï‡]',
            'y': '[yÃÃ½á»²á»³Å¶Å·Å¸Ã¿á»¸á»¹áºŽáºá»´á»µÉŽÉÆ³Æ´]',
            'z': '[zÅ¹Åºáºáº‘Å½Å¾Å»Å¼áº’áº“áº”áº•ÆµÆ¶]'
        };
    
        var asciifold = (function() {
            var i, n, k, chunk;
            var foreignletters = '';
            var lookup = {};
            for (k in DIACRITICS) {
                if (DIACRITICS.hasOwnProperty(k)) {
                    chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1);
                    foreignletters += chunk;
                    for (i = 0, n = chunk.length; i < n; i++) {
                        lookup[chunk.charAt(i)] = k;
                    }
                }
            }
            var regexp = new RegExp('[' +  foreignletters + ']', 'g');
            return function(str) {
                return str.replace(regexp, function(foreignletter) {
                    return lookup[foreignletter];
                }).toLowerCase();
            };
        })();
    
    
        // export
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
        return Sifter;
    }));
    
    
    /**
     * selectize.js (v0.12.4)
     * Copyright (c) 2013â€“2015 Brian Reavis & contributors
     *
     * 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.
     *
     * @author Brian Reavis <brian@thirdroute.com>
     */
    
    /*jshint curly:false */
    /*jshint browser:true */
    
    (function(root, factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery','sifter','microplugin'], factory);
        } else if (typeof exports === 'object') {
            module.exports = factory(require('jquery'), require('sifter'), require('microplugin'));
        } else {
            root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin);
        }
    }(this, function($, Sifter, MicroPlugin) {
        'use strict';
    
        var highlight = function($element, pattern) {
            if (typeof pattern === 'string' && !pattern.length) return;
            var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
        
            var highlight = function(node) {
                var skip = 0;
                if (node.nodeType === 3) {
                    var pos = node.data.search(regex);
                    if (pos >= 0 && node.data.length > 0) {
                        var match = node.data.match(regex);
                        var spannode = document.createElement('span');
                        spannode.className = 'highlight';
                        var middlebit = node.splitText(pos);
                        var endbit = middlebit.splitText(match[0].length);
                        var middleclone = middlebit.cloneNode(true);
                        spannode.appendChild(middleclone);
                        middlebit.parentNode.replaceChild(spannode, middlebit);
                        skip = 1;
                    }
                } else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
                    for (var i = 0; i < node.childNodes.length; ++i) {
                        i += highlight(node.childNodes[i]);
                    }
                }
                return skip;
            };
        
            return $element.each(function() {
                highlight(this);
            });
        };
        
        /**
         * removeHighlight fn copied from highlight v5 and
         * edited to remove with() and pass js strict mode
         */
        $.fn.removeHighlight = function() {
            return this.find("span.highlight").each(function() {
                this.parentNode.firstChild.nodeName;
                var parent = this.parentNode;
                parent.replaceChild(this.firstChild, this);
                parent.normalize();
            }).end();
        };
        
        
        var MicroEvent = function() {};
        MicroEvent.prototype = {
            on: function(event, fct){
                this._events = this._events || {};
                this._events[event] = this._events[event] || [];
                this._events[event].push(fct);
            },
            off: function(event, fct){
                var n = arguments.length;
                if (n === 0) return delete this._events;
                if (n === 1) return delete this._events[event];
        
                this._events = this._events || {};
                if (event in this._events === false) return;
                this._events[event].splice(this._events[event].indexOf(fct), 1);
            },
            trigger: function(event /* , args... */){
                this._events = this._events || {};
                if (event in this._events === false) return;
                for (var i = 0; i < this._events[event].length; i++){
                    this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
                }
            }
        };
        
        /**
         * Mixin will delegate all MicroEvent.js function in the destination object.
         *
         * - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent
         *
         * @param {object} the object which will support MicroEvent
         */
        MicroEvent.mixin = function(destObject){
            var props = ['on', 'off', 'trigger'];
            for (var i = 0; i < props.length; i++){
                destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
            }
        };
        
        var IS_MAC        = /Mac/.test(navigator.userAgent);
        
        var KEY_A         = 65;
        var KEY_COMMA     = 188;
        var KEY_RETURN    = 13;
        var KEY_ESC       = 27;
        var KEY_LEFT      = 37;
        var KEY_UP        = 38;
        var KEY_P         = 80;
        var KEY_RIGHT     = 39;
        var KEY_DOWN      = 40;
        var KEY_N         = 78;
        var KEY_BACKSPACE = 8;
        var KEY_DELETE    = 46;
        var KEY_SHIFT     = 16;
        var KEY_CMD       = IS_MAC ? 91 : 17;
        var KEY_CTRL      = IS_MAC ? 18 : 17;
        var KEY_TAB       = 9;
        
        var TAG_SELECT    = 1;
        var TAG_INPUT     = 2;
        
        // for now, android support in general is too spotty to support validity
        var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('input').validity;
        
        
        var isset = function(object) {
            return typeof object !== 'undefined';
        };
        
        /**
         * Converts a scalar to its best string representation
         * for hash keys and HTML attribute values.
         *
         * Transformations:
         *   'str'     -> 'str'
         *   null      -> ''
         *   undefined -> ''
         *   true      -> '1'
         *   false     -> '0'
         *   0         -> '0'
         *   1         -> '1'
         *
         * @param {string} value
         * @returns {string|null}
         */
        var hash_key = function(value) {
            if (typeof value === 'undefined' || value === null) return null;
            if (typeof value === 'boolean') return value ? '1' : '0';
            return value + '';
        };
        
        /**
         * Escapes a string for use within HTML.
         *
         * @param {string} str
         * @returns {string}
         */
        var escape_html = function(str) {
            return (str + '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;');
        };
        
        /**
         * Escapes "$" characters in replacement strings.
         *
         * @param {string} str
         * @returns {string}
         */
        var escape_replace = function(str) {
            return (str + '').replace(/\$/g, '$$$$');
        };
        
        var hook = {};
        
        /**
         * Wraps `method` on `self` so that `fn`
         * is invoked before the original method.
         *
         * @param {object} self
         * @param {string} method
         * @param {function} fn
         */
        hook.before = function(self, method, fn) {
            var original = self[method];
            self[method] = function() {
                fn.apply(self, arguments);
                return original.apply(self, arguments);
            };
        };
        
        /**
         * Wraps `method` on `self` so that `fn`
         * is invoked after the original method.
         *
         * @param {object} self
         * @param {string} method
         * @param {function} fn
         */
        hook.after = function(self, method, fn) {
            var original = self[method];
            self[method] = function() {
                var result = original.apply(self, arguments);
                fn.apply(self, arguments);
                return result;
            };
        };
        
        /**
         * Wraps `fn` so that it can only be invoked once.
         *
         * @param {function} fn
         * @returns {function}
         */
        var once = function(fn) {
            var called = false;
            return function() {
                if (called) return;
                called = true;
                fn.apply(this, arguments);
            };
        };
        
        /**
         * Wraps `fn` so that it can only be called once
         * every `delay` milliseconds (invoked on the falling edge).
         *
         * @param {function} fn
         * @param {int} delay
         * @returns {function}
         */
        var debounce = function(fn, delay) {
            var timeout;
            return function() {
                var self = this;
                var args = arguments;
                window.clearTimeout(timeout);
                timeout = window.setTimeout(function() {
                    fn.apply(self, args);
                }, delay);
            };
        };
        
        /**
         * Debounce all fired events types listed in `types`
         * while executing the provided `fn`.
         *
         * @param {object} self
         * @param {array} types
         * @param {function} fn
         */
        var debounce_events = function(self, types, fn) {
            var type;
            var trigger = self.trigger;
            var event_args = {};
        
            // override trigger method
            self.trigger = function() {
                var type = arguments[0];
                if (types.indexOf(type) !== -1) {
                    event_args[type] = arguments;
                } else {
                    return trigger.apply(self, arguments);
                }
            };
        
            // invoke provided function
            fn.apply(self, []);
            self.trigger = trigger;
        
            // trigger queued events
            for (type in event_args) {
                if (event_args.hasOwnProperty(type)) {
                    trigger.apply(self, event_args[type]);
                }
            }
        };
        
        /**
         * A workaround for http://bugs.jquery.com/ticket/6696
         *
         * @param {object} $parent - Parent element to listen on.
         * @param {string} event - Event name.
         * @param {string} selector - Descendant selector to filter by.
         * @param {function} fn - Event handler.
         */
        var watchChildEvent = function($parent, event, selector, fn) {
            $parent.on(event, selector, function(e) {
                var child = e.target;
                while (child && child.parentNode !== $parent[0]) {
                    child = child.parentNode;
                }
                e.currentTarget = child;
                return fn.apply(this, [e]);
            });
        };
        
        /**
         * Determines the current selection within a text input control.
         * Returns an object containing:
         *   - start
         *   - length
         *
         * @param {object} input
         * @returns {object}
         */
        var getSelection = function(input) {
            var result = {};
            if ('selectionStart' in input) {
                result.start = input.selectionStart;
                result.length = input.selectionEnd - result.start;
            } else if (document.selection) {
                input.focus();
                var sel = document.selection.createRange();
                var selLen = document.selection.createRange().text.length;
                sel.moveStart('character', -input.value.length);
                result.start = sel.text.length - selLen;
                result.length = selLen;
            }
            return result;
        };
        
        /**
         * Copies CSS properties from one element to another.
         *
         * @param {object} $from
         * @param {object} $to
         * @param {array} properties
         */
        var transferStyles = function($from, $to, properties) {
            var i, n, styles = {};
            if (properties) {
                for (i = 0, n = properties.length; i < n; i++) {
                    styles[properties[i]] = $from.css(properties[i]);
                }
            } else {
                styles = $from.css();
            }
            $to.css(styles);
        };
        
        /**
         * Measures the width of a string within a
         * parent element (in pixels).
         *
         * @param {string} str
         * @param {object} $parent
         * @returns {int}
         */
        var measureString = function(str, $parent) {
            if (!str) {
                return 0;
            }
        
            var $test = $('<test>').css({
                position: 'absolute',
                top: -99999,
                left: -99999,
                width: 'auto',
                padding: 0,
                whiteSpace: 'pre'
            }).text(str).appendTo('body');
        
            transferStyles($parent, $test, [
                'letterSpacing',
                'fontSize',
                'fontFamily',
                'fontWeight',
                'textTransform'
            ]);
        
            var width = $test.width();
            $test.remove();
        
            return width;
        };
        
        /**
         * Sets up an input to grow horizontally as the user
         * types. If the value is changed manually, you can
         * trigger the "update" handler to resize:
         *
         * $input.trigger('update');
         *
         * @param {object} $input
         */
        var autoGrow = function($input) {
            var currentWidth = null;
        
            var update = function(e, options) {
                var value, keyCode, printable, placeholder, width;
                var shift, character, selection;
                e = e || window.event || {};
                options = options || {};
        
                if (e.metaKey || e.altKey) return;
                if (!options.force && $input.data('grow') === false) return;
        
                value = $input.val();
                if (e.type && e.type.toLowerCase() === 'keydown') {
                    keyCode = e.keyCode;
                    printable = (
                        (keyCode >= 97 && keyCode <= 122) || // a-z
                        (keyCode >= 65 && keyCode <= 90)  || // A-Z
                        (keyCode >= 48 && keyCode <= 57)  || // 0-9
                        keyCode === 32 // space
                    );
        
                    if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) {
                        selection = getSelection($input[0]);
                        if (selection.length) {
                            value = value.substring(0, selection.start) + value.substring(selection.start + selection.length);
                        } else if (keyCode === KEY_BACKSPACE && selection.start) {
                            value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1);
                        } else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') {
                            value = value.substring(0, selection.start) + value.substring(selection.start + 1);
                        }
                    } else if (printable) {
                        shift = e.shiftKey;
                        character = String.fromCharCode(e.keyCode);
                        if (shift) character = character.toUpperCase();
                        else character = character.toLowerCase();
                        value += character;
                    }
                }
        
                placeholder = $input.attr('placeholder');
                if (!value && placeholder) {
                    value = placeholder;
                }
        
                width = measureString(value, $input) + 4;
                if (width !== currentWidth) {
                    currentWidth = width;
                    $input.width(width);
                    $input.triggerHandler('resize');
                }
            };
        
            $input.on('keydown keyup update blur', update);
            update();
        };
        
        var domToString = function(d) {
            var tmp = document.createElement('div');
        
            tmp.appendChild(d.cloneNode(true));
        
            return tmp.innerHTML;
        };
        
        var logError = function(message, options){
            if(!options) options = {};
            var component = "Selectize";
        
            console.error(component + ": " + message)
        
            if(options.explanation){
                // console.group is undefined in <IE11
                if(console.group) console.group();
                console.error(options.explanation);
                if(console.group) console.groupEnd();
            }
        }
        
        
        var Selectize = function($input, settings) {
            var key, i, n, dir, input, self = this;
            input = $input[0];
            input.selectize = self;
        
            // detect rtl environment
            var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
            dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction;
            dir = dir || $input.parents('[dir]:first').attr('dir') || '';
        
            // setup default state
            $.extend(self, {
                order            : 0,
                settings         : settings,
                $input           : $input,
                tabIndex         : $input.attr('tabindex') || '',
                tagType          : input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT,
                rtl              : /rtl/i.test(dir),
        
                eventNS          : '.selectize' + (++Selectize.count),
                highlightedValue : null,
                isOpen           : false,
                isDisabled       : false,
                isRequired       : $input.is('[required]'),
                isInvalid        : false,
                isLocked         : false,
                isFocused        : false,
                isInputHidden    : false,
                isSetup          : false,
                isShiftDown      : false,
                isCmdDown        : false,
                isCtrlDown       : false,
                ignoreFocus      : false,
                ignoreBlur       : false,
                ignoreHover      : false,
                hasOptions       : false,
                currentResults   : null,
                lastValue        : '',
                caretPos         : 0,
                loading          : 0,
                loadedSearches   : {},
        
                $activeOption    : null,
                $activeItems     : [],
        
                optgroups        : {},
                options          : {},
                userOptions      : {},
                items            : [],
                renderCache      : {},
                onSearchChange   : settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle)
            });
        
            // search system
            self.sifter = new Sifter(this.options, {diacritics: settings.diacritics});
        
            // build options table
            if (self.settings.options) {
                for (i = 0, n = self.settings.options.length; i < n; i++) {
                    self.registerOption(self.settings.options[i]);
                }
                delete self.settings.options;
            }
        
            // build optgroup table
            if (self.settings.optgroups) {
                for (i = 0, n = self.settings.optgroups.length; i < n; i++) {
                    self.registerOptionGroup(self.settings.optgroups[i]);
                }
                delete self.settings.optgroups;
            }
        
            // option-dependent defaults
            self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi');
            if (typeof self.settings.hideSelected !== 'boolean') {
                self.settings.hideSelected = self.settings.mode === 'multi';
            }
        
            self.initializePlugins(self.settings.plugins);
            self.setupCallbacks();
            self.setupTemplates();
            self.setup();
        };
        
        // mixins
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        
        MicroEvent.mixin(Selectize);
        
        if(typeof MicroPlugin !== "undefined"){
            MicroPlugin.mixin(Selectize);
        }else{
            logError("Dependency MicroPlugin is missing",
                {explanation:
                    "Make sure you either: (1) are using the \"standalone\" "+
                    "version of Selectize, or (2) require MicroPlugin before you "+
                    "load Selectize."}
            );
        }
        
        
        // methods
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        
        $.extend(Selectize.prototype, {
        
            /**
             * Creates all elements and sets up event bindings.
             */
            setup: function() {
                var self      = this;
                var settings  = self.settings;
                var eventNS   = self.eventNS;
                var $window   = $(window);
                var $document = $(document);
                var $input    = self.$input;
        
                var $wrapper;
                var $control;
                var $control_input;
                var $dropdown;
                var $dropdown_content;
                var $dropdown_parent;
                var inputMode;
                var timeout_blur;
                var timeout_focus;
                var classes;
                var classes_plugins;
                var inputId;
        
                inputMode         = self.settings.mode;
                classes           = $input.attr('class') || '';
        
                $wrapper          = $('<div>').addClass(settings.wrapperClass).addClass(classes).addClass(inputMode);
                $control          = $('<div>').addClass(settings.inputClass).addClass('items').appendTo($wrapper);
                $control_input    = $('<input type="text" autocomplete="off" />').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex);
                $dropdown_parent  = $(settings.dropdownParent || $wrapper);
                $dropdown         = $('<div>').addClass(settings.dropdownClass).addClass(inputMode).hide().appendTo($dropdown_parent);
                $dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);
        
                if(inputId = $input.attr('id')) {
                    $control_input.attr('id', inputId + '-selectized');
                    $("label[for='"+inputId+"']").attr('for', inputId + '-selectized');
                }
        
                if(self.settings.copyClassesToDropdown) {
                    $dropdown.addClass(classes);
                }
        
                $wrapper.css({
                    width: $input[0].style.width
                });
        
                if (self.plugins.names.length) {
                    classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
                    $wrapper.addClass(classes_plugins);
                    $dropdown.addClass(classes_plugins);
                }
        
                if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) {
                    $input.attr('multiple', 'multiple');
                }
        
                if (self.settings.placeholder) {
                    $control_input.attr('placeholder', settings.placeholder);
                }
        
                // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
                if (!self.settings.splitOn && self.settings.delimiter) {
                    var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
                    self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*');
                }
        
                if ($input.attr('autocorrect')) {
                    $control_input.attr('autocorrect', $input.attr('autocorrect'));
                }
        
                if ($input.attr('autocapitalize')) {
                    $control_input.attr('autocapitalize', $input.attr('autocapitalize'));
                }
        
                self.$wrapper          = $wrapper;
                self.$control          = $control;
                self.$control_input    = $control_input;
                self.$dropdown         = $dropdown;
                self.$dropdown_content = $dropdown_content;
        
                $dropdown.on('mouseenter', '[data-selectable]', function() { return self.onOptionHover.apply(self, arguments); });
                $dropdown.on('mousedown click', '[data-selectable]', function() { return self.onOptionSelect.apply(self, arguments); });
                watchChildEvent($control, 'mousedown', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); });
                autoGrow($control_input);
        
                $control.on({
                    mousedown : function() { return self.onMouseDown.apply(self, arguments); },
                    click     : function() { return self.onClick.apply(self, arguments); }
                });
        
                $control_input.on({
                    mousedown : function(e) { e.stopPropagation(); },
                    keydown   : function() { return self.onKeyDown.apply(self, arguments); },
                    keyup     : function() { return self.onKeyUp.apply(self, arguments); },
                    keypress  : function() { return self.onKeyPress.apply(self, arguments); },
                    resize    : function() { self.positionDropdown.apply(self, []); },
                    blur      : function() { return self.onBlur.apply(self, arguments); },
                    focus     : function() { self.ignoreBlur = false; return self.onFocus.apply(self, arguments); },
                    paste     : function() { return self.onPaste.apply(self, arguments); }
                });
        
                $document.on('keydown' + eventNS, function(e) {
                    self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey'];
                    self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
                    self.isShiftDown = e.shiftKey;
                });
        
                $document.on('keyup' + eventNS, function(e) {
                    if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
                    if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
                    if (e.keyCode === KEY_CMD) self.isCmdDown = false;
                });
        
                $document.on('mousedown' + eventNS, function(e) {
                    if (self.isFocused) {
                        // prevent events on the dropdown scrollbar from causing the control to blur
                        if (e.target === self.$dropdown[0] || e.target.parentNode === self.$dropdown[0]) {
                            return false;
                        }
                        // blur on click outside
                        if (!self.$control.has(e.target).length && e.target !== self.$control[0]) {
                            self.blur(e.target);
                        }
                    }
                });
        
                $window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function() {
                    if (self.isOpen) {
                        self.positionDropdown.apply(self, arguments);
                    }
                });
                $window.on('mousemove' + eventNS, function() {
                    self.ignoreHover = false;
                });
        
                // store original children and tab index so that they can be
                // restored when the destroy() method is called.
                this.revertSettings = {
                    $children : $input.children().detach(),
                    tabindex  : $input.attr('tabindex')
                };
        
                $input.attr('tabindex', -1).hide().after(self.$wrapper);
        
                if ($.isArray(settings.items)) {
                    self.setValue(settings.items);
                    delete settings.items;
                }
        
                // feature detect for the validation API
                if (SUPPORTS_VALIDITY_API) {
                    $input.on('invalid' + eventNS, function(e) {
                        e.preventDefault();
                        self.isInvalid = true;
                        self.refreshState();
                    });
                }
        
                self.updateOriginalInput();
                self.refreshItems();
                self.refreshState();
                self.updatePlaceholder();
                self.isSetup = true;
        
                if ($input.is(':disabled')) {
                    self.disable();
                }
        
                self.on('change', this.onChange);
        
                $input.data('selectize', self);
                $input.addClass('selectized');
                self.trigger('initialize');
        
                // preload options
                if (settings.preload === true) {
                    self.onSearchChange('');
                }
        
            },
        
            /**
             * Sets up default rendering functions.
             */
            setupTemplates: function() {
                var self = this;
                var field_label = self.settings.labelField;
                var field_optgroup = self.settings.optgroupLabelField;
        
                var templates = {
                    'optgroup': function(data) {
                        return '<div class="optgroup">' + data.html + '</div>';
                    },
                    'optgroup_header': function(data, escape) {
                        return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
                    },
                    'option': function(data, escape) {
                        return '<div class="option">' + escape(data[field_label]) + '</div>';
                    },
                    'item': function(data, escape) {
                        return '<div class="item">' + escape(data[field_label]) + '</div>';
                    },
                    'option_create': function(data, escape) {
                        return '<div class="create">Add <strong>' + escape(data.input) + '</strong>&hellip;</div>';
                    }
                };
        
                self.settings.render = $.extend({}, templates, self.settings.render);
            },
        
            /**
             * Maps fired events to callbacks provided
             * in the settings used when creating the control.
             */
            setupCallbacks: function() {
                var key, fn, callbacks = {
                    'initialize'      : 'onInitialize',
                    'change'          : 'onChange',
                    'item_add'        : 'onItemAdd',
                    'item_remove'     : 'onItemRemove',
                    'clear'           : 'onClear',
                    'option_add'      : 'onOptionAdd',
                    'option_remove'   : 'onOptionRemove',
                    'option_clear'    : 'onOptionClear',
                    'optgroup_add'    : 'onOptionGroupAdd',
                    'optgroup_remove' : 'onOptionGroupRemove',
                    'optgroup_clear'  : 'onOptionGroupClear',
                    'dropdown_open'   : 'onDropdownOpen',
                    'dropdown_close'  : 'onDropdownClose',
                    'type'            : 'onType',
                    'load'            : 'onLoad',
                    'focus'           : 'onFocus',
                    'blur'            : 'onBlur'
                };
        
                for (key in callbacks) {
                    if (callbacks.hasOwnProperty(key)) {
                        fn = this.settings[callbacks[key]];
                        if (fn) this.on(key, fn);
                    }
                }
            },
        
            /**
             * Triggered when the main control element
             * has a click event.
             *
             * @param {object} e
             * @return {boolean}
             */
            onClick: function(e) {
                var self = this;
        
                // necessary for mobile webkit devices (manual focus triggering
                // is ignored unless invoked within a click event)
                if (!self.isFocused) {
                    self.focus();
                    e.preventDefault();
                }
            },
        
            /**
             * Triggered when the main control element
             * has a mouse down event.
             *
             * @param {object} e
             * @return {boolean}
             */
            onMouseDown: function(e) {
                var self = this;
                var defaultPrevented = e.isDefaultPrevented();
                var $target = $(e.target);
        
                if (self.isFocused) {
                    // retain focus by preventing native handling. if the
                    // event target is the input it should not be modified.
                    // otherwise, text selection within the input won't work.
                    if (e.target !== self.$control_input[0]) {
                        if (self.settings.mode === 'single') {
                            // toggle dropdown
                            self.isOpen ? self.close() : self.open();
                        } else if (!defaultPrevented) {
                            self.setActiveItem(null);
                        }
                        return false;
                    }
                } else {
                    // give control focus
                    if (!defaultPrevented) {
                        window.setTimeout(function() {
                            self.focus();
                        }, 0);
                    }
                }
            },
        
            /**
             * Triggered when the value of the control has been changed.
             * This should propagate the event to the original DOM
             * input / select element.
             */
            onChange: function() {
                this.$input.trigger('change');
            },
        
            /**
             * Triggered on <input> paste.
             *
             * @param {object} e
             * @returns {boolean}
             */
            onPaste: function(e) {
                var self = this;
        
                if (self.isFull() || self.isInputHidden || self.isLocked) {
                    e.preventDefault();
                    return;
                }
        
                // If a regex or string is included, this will split the pasted
                // input and create Items for each separate value
                if (self.settings.splitOn) {
        
                    // Wait for pasted text to be recognized in value
                    setTimeout(function() {
                        var pastedText = self.$control_input.val();
                        if(!pastedText.match(self.settings.splitOn)){ return }
        
                        var splitInput = $.trim(pastedText).split(self.settings.splitOn);
                        for (var i = 0, n = splitInput.length; i < n; i++) {
                            self.createItem(splitInput[i]);
                        }
                    }, 0);
                }
            },
        
            /**
             * Triggered on <input> keypress.
             *
             * @param {object} e
             * @returns {boolean}
             */
            onKeyPress: function(e) {
                if (this.isLocked) return e && e.preventDefault();
                var character = String.fromCharCode(e.keyCode || e.which);
                if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) {
                    this.createItem();
                    e.preventDefault();
                    return false;
                }
            },
        
            /**
             * Triggered on <input> keydown.
             *
             * @param {object} e
             * @returns {boolean}
             */
            onKeyDown: function(e) {
                var isInput = e.target === this.$control_input[0];
                var self = this;
        
                if (self.isLocked) {
                    if (e.keyCode !== KEY_TAB) {
                        e.preventDefault();
                    }
                    return;
                }
        
                switch (e.keyCode) {
                    case KEY_A:
                        if (self.isCmdDown) {
                            self.selectAll();
                            return;
                        }
                        break;
                    case KEY_ESC:
                        if (self.isOpen) {
                            e.preventDefault();
                            e.stopPropagation();
                            self.close();
                        }
                        return;
                    case KEY_N:
                        if (!e.ctrlKey || e.altKey) break;
                    case KEY_DOWN:
                        if (!self.isOpen && self.hasOptions) {
                            self.open();
                        } else if (self.$activeOption) {
                            self.ignoreHover = true;
                            var $next = self.getAdjacentOption(self.$activeOption, 1);
                            if ($next.length) self.setActiveOption($next, true, true);
                        }
                        e.preventDefault();
                        return;
                    case KEY_P:
                        if (!e.ctrlKey || e.altKey) break;
                    case KEY_UP:
                        if (self.$activeOption) {
                            self.ignoreHover = true;
                            var $prev = self.getAdjacentOption(self.$activeOption, -1);
                            if ($prev.length) self.setActiveOption($prev, true, true);
                        }
                        e.preventDefault();
                        return;
                    case KEY_RETURN:
                        if (self.isOpen && self.$activeOption) {
                            self.onOptionSelect({currentTarget: self.$activeOption});
                            e.preventDefault();
                        }
                        return;
                    case KEY_LEFT:
                        self.advanceSelection(-1, e);
                        return;
                    case KEY_RIGHT:
                        self.advanceSelection(1, e);
                        return;
                    case KEY_TAB:
                        if (self.settings.selectOnTab && self.isOpen && self.$activeOption) {
                            self.onOptionSelect({currentTarget: self.$activeOption});
        
                            // Default behaviour is to jump to the next field, we only want this
                            // if the current field doesn't accept any more entries
                            if (!self.isFull()) {
                                e.preventDefault();
                            }
                        }
                        if (self.settings.create && self.createItem()) {
                            e.preventDefault();
                        }
                        return;
                    case KEY_BACKSPACE:
                    case KEY_DELETE:
                        self.deleteSelection(e);
                        return;
                }
        
                if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) {
                    e.preventDefault();
                    return;
                }
            },
        
            /**
             * Triggered on <input> keyup.
             *
             * @param {object} e
             * @returns {boolean}
             */
            onKeyUp: function(e) {
                var self = this;
        
                if (self.isLocked) return e && e.preventDefault();
                var value = self.$control_input.val() || '';
                if (self.lastValue !== value) {
                    self.lastValue = value;
                    self.onSearchChange(value);
                    self.refreshOptions();
                    self.trigger('type', value);
                }
            },
        
            /**
             * Invokes the user-provide option provider / loader.
             *
             * Note: this function is debounced in the Selectize
             * constructor (by `settings.loadThrottle` milliseconds)
             *
             * @param {string} value
             */
            onSearchChange: function(value) {
                var self = this;
                var fn = self.settings.load;
                if (!fn) return;
                if (self.loadedSearches.hasOwnProperty(value)) return;
                self.loadedSearches[value] = true;
                self.load(function(callback) {
                    fn.apply(self, [value, callback]);
                });
            },
        
            /**
             * Triggered on <input> focus.
             *
             * @param {object} e (optional)
             * @returns {boolean}
             */
            onFocus: function(e) {
                var self = this;
                var wasFocused = self.isFocused;
        
                if (self.isDisabled) {
                    self.blur();
                    e && e.preventDefault();
                    return false;
                }
        
                if (self.ignoreFocus) return;
                self.isFocused = true;
                if (self.settings.preload === 'focus') self.onSearchChange('');
        
                if (!wasFocused) self.trigger('focus');
        
                if (!self.$activeItems.length) {
                    self.showInput();
                    self.setActiveItem(null);
                    self.refreshOptions(!!self.settings.openOnFocus);
                }
        
                self.refreshState();
            },
        
            /**
             * Triggered on <input> blur.
             *
             * @param {object} e
             * @param {Element} dest
             */
            onBlur: function(e, dest) {
                var self = this;
                if (!self.isFocused) return;
                self.isFocused = false;
        
                if (self.ignoreFocus) {
                    return;
                } else if (!self.ignoreBlur && document.activeElement === self.$dropdown_content[0]) {
                    // necessary to prevent IE closing the dropdown when the scrollbar is clicked
                    self.ignoreBlur = true;
                    self.onFocus(e);
                    return;
                }
        
                var deactivate = function() {
                    self.close();
                    self.setTextboxValue('');
                    self.setActiveItem(null);
                    self.setActiveOption(null);
                    self.setCaret(self.items.length);
                    self.refreshState();
        
                    // IE11 bug: element still marked as active
                    dest && dest.focus && dest.focus();
        
                    self.ignoreFocus = false;
                    self.trigger('blur');
                };
        
                self.ignoreFocus = true;
                if (self.settings.create && self.settings.createOnBlur) {
                    self.createItem(null, false, deactivate);
                } else {
                    deactivate();
                }
            },
        
            /**
             * Triggered when the user rolls over
             * an option in the autocomplete dropdown menu.
             *
             * @param {object} e
             * @returns {boolean}
             */
            onOptionHover: function(e) {
                if (this.ignoreHover) return;
                this.setActiveOption(e.currentTarget, false);
            },
        
            /**
             * Triggered when the user clicks on an option
             * in the autocomplete dropdown menu.
             *
             * @param {object} e
             * @returns {boolean}
             */
            onOptionSelect: function(e) {
                var value, $target, $option, self = this;
        
                if (e.preventDefault) {
                    e.preventDefault();
                    e.stopPropagation();
                }
        
                $target = $(e.currentTarget);
                if ($target.hasClass('create')) {
                    self.createItem(null, function() {
                        if (self.settings.closeAfterSelect) {
                            self.close();
                        }
                    });
                } else {
                    value = $target.attr('data-value');
                    if (typeof value !== 'undefined') {
                        self.lastQuery = null;
                        self.setTextboxValue('');
                        self.addItem(value);
                        if (self.settings.closeAfterSelect) {
                            self.close();
                        } else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) {
                            self.setActiveOption(self.getOption(value));
                        }
                    }
                }
            },
        
            /**
             * Triggered when the user clicks on an item
             * that has been selected.
             *
             * @param {object} e
             * @returns {boolean}
             */
            onItemSelect: function(e) {
                var self = this;
        
                if (self.isLocked) return;
                if (self.settings.mode === 'multi') {
                    e.preventDefault();
                    self.setActiveItem(e.currentTarget, e);
                }
            },
        
            /**
             * Invokes the provided method that provides
             * results to a callback---which are then added
             * as options to the control.
             *
             * @param {function} fn
             */
            load: function(fn) {
                var self = this;
                var $wrapper = self.$wrapper.addClass(self.settings.loadingClass);
        
                self.loading++;
                fn.apply(self, [function(results) {
                    self.loading = Math.max(self.loading - 1, 0);
                    if (results && results.length) {
                        self.addOption(results);
                        self.refreshOptions(self.isFocused && !self.isInputHidden);
                    }
                    if (!self.loading) {
                        $wrapper.removeClass(self.settings.loadingClass);
                    }
                    self.trigger('load', results);
                }]);
            },
        
            /**
             * Sets the input field of the control to the specified value.
             *
             * @param {string} value
             */
            setTextboxValue: function(value) {
                var $input = this.$control_input;
                var changed = $input.val() !== value;
                if (changed) {
                    $input.val(value).triggerHandler('update');
                    this.lastValue = value;
                }
            },
        
            /**
             * Returns the value of the control. If multiple items
             * can be selected (e.g. <select multiple>), this returns
             * an array. If only one item can be selected, this
             * returns a string.
             *
             * @returns {mixed}
             */
            getValue: function() {
                if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
                    return this.items;
                } else {
                    return this.items.join(this.settings.delimiter);
                }
            },
        
            /**
             * Resets the selected items to the given value.
             *
             * @param {mixed} value
             */
            setValue: function(value, silent) {
                var events = silent ? [] : ['change'];
        
                debounce_events(this, events, function() {
                    this.clear(silent);
                    this.addItems(value, silent);
                });
            },
        
            /**
             * Sets the selected item.
             *
             * @param {object} $item
             * @param {object} e (optional)
             */
            setActiveItem: function($item, e) {
                var self = this;
                var eventName;
                var i, idx, begin, end, item, swap;
                var $last;
        
                if (self.settings.mode === 'single') return;
                $item = $($item);
        
                // clear the active selection
                if (!$item.length) {
                    $(self.$activeItems).removeClass('active');
                    self.$activeItems = [];
                    if (self.isFocused) {
                        self.showInput();
                    }
                    return;
                }
        
                // modify selection
                eventName = e && e.type.toLowerCase();
        
                if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) {
                    $last = self.$control.children('.active:last');
                    begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]);
                    end   = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]);
                    if (begin > end) {
                        swap  = begin;
                        begin = end;
                        end   = swap;
                    }
                    for (i = begin; i <= end; i++) {
                        item = self.$control[0].childNodes[i];
                        if (self.$activeItems.indexOf(item) === -1) {
                            $(item).addClass('active');
                            self.$activeItems.push(item);
                        }
                    }
                    e.preventDefault();
                } else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
                    if ($item.hasClass('active')) {
                        idx = self.$activeItems.indexOf($item[0]);
                        self.$activeItems.splice(idx, 1);
                        $item.removeClass('active');
                    } else {
                        self.$activeItems.push($item.addClass('active')[0]);
                    }
                } else {
                    $(self.$activeItems).removeClass('active');
                    self.$activeItems = [$item.addClass('active')[0]];
                }
        
                // ensure control has focus
                self.hideInput();
                if (!this.isFocused) {
                    self.focus();
                }
            },
        
            /**
             * Sets the selected item in the dropdown menu
             * of available options.
             *
             * @param {object} $object
             * @param {boolean} scroll
             * @param {boolean} animate
             */
            setActiveOption: function($option, scroll, animate) {
                var height_menu, height_item, y;
                var scroll_top, scroll_bottom;
                var self = this;
        
                if (self.$activeOption) self.$activeOption.removeClass('active');
                self.$activeOption = null;
        
                $option = $($option);
                if (!$option.length) return;
        
                self.$activeOption = $option.addClass('active');
        
                if (scroll || !isset(scroll)) {
        
                    height_menu   = self.$dropdown_content.height();
                    height_item   = self.$activeOption.outerHeight(true);
                    scroll        = self.$dropdown_content.scrollTop() || 0;
                    y             = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll;
                    scroll_top    = y;
                    scroll_bottom = y - height_menu + height_item;
        
                    if (y + height_item > height_menu + scroll) {
                        self.$dropdown_content.stop().animate({scrollTop: scroll_bottom}, animate ? self.settings.scrollDuration : 0);
                    } else if (y < scroll) {
                        self.$dropdown_content.stop().animate({scrollTop: scroll_top}, animate ? self.settings.scrollDuration : 0);
                    }
        
                }
            },
        
            /**
             * Selects all items (CTRL + A).
             */
            selectAll: function() {
                var self = this;
                if (self.settings.mode === 'single') return;
        
                self.$activeItems = Array.prototype.slice.apply(self.$control.children(':not(input)').addClass('active'));
                if (self.$activeItems.length) {
                    self.hideInput();
                    self.close();
                }
                self.focus();
            },
        
            /**
             * Hides the input element out of view, while
             * retaining its focus.
             */
            hideInput: function() {
                var self = this;
        
                self.setTextboxValue('');
                self.$control_input.css({opacity: 0, position: 'absolute', left: self.rtl ? 10000 : -10000});
                self.isInputHidden = true;
            },
        
            /**
             * Restores input visibility.
             */
            showInput: function() {
                this.$control_input.css({opacity: 1, position: 'relative', left: 0});
                this.isInputHidden = false;
            },
        
            /**
             * Gives the control focus.
             */
            focus: function() {
                var self = this;
                if (self.isDisabled) return;
        
                self.ignoreFocus = true;
                self.$control_input[0].focus();
                window.setTimeout(function() {
                    self.ignoreFocus = false;
                    self.onFocus();
                }, 0);
            },
        
            /**
             * Forces the control out of focus.
             *
             * @param {Element} dest
             */
            blur: function(dest) {
                this.$control_input[0].blur();
                this.onBlur(null, dest);
            },
        
            /**
             * Returns a function that scores an object
             * to show how good of a match it is to the
             * provided query.
             *
             * @param {string} query
             * @param {object} options
             * @return {function}
             */
            getScoreFunction: function(query) {
                return this.sifter.getScoreFunction(query, this.getSearchOptions());
            },
        
            /**
             * Returns search options for sifter (the system
             * for scoring and sorting results).
             *
             * @see https://github.com/brianreavis/sifter.js
             * @return {object}
             */
            getSearchOptions: function() {
                var settings = this.settings;
                var sort = settings.sortField;
                if (typeof sort === 'string') {
                    sort = [{field: sort}];
                }
        
                return {
                    fields      : settings.searchField,
                    conjunction : settings.searchConjunction,
                    sort        : sort
                };
            },
        
            /**
             * Searches through available options and returns
             * a sorted array of matches.
             *
             * Returns an object containing:
             *
             *   - query {string}
             *   - tokens {array}
             *   - total {int}
             *   - items {array}
             *
             * @param {string} query
             * @returns {object}
             */
            search: function(query) {
                var i, value, score, result, calculateScore;
                var self     = this;
                var settings = self.settings;
                var options  = this.getSearchOptions();
        
                // validate user-provided result scoring function
                if (settings.score) {
                    calculateScore = self.settings.score.apply(this, [query]);
                    if (typeof calculateScore !== 'function') {
                        throw new Error('Selectize "score" setting must be a function that returns a function');
                    }
                }
        
                // perform search
                if (query !== self.lastQuery) {
                    self.lastQuery = query;
                    result = self.sifter.search(query, $.extend(options, {score: calculateScore}));
                    self.currentResults = result;
                } else {
                    result = $.extend(true, {}, self.currentResults);
                }
        
                // filter out selected items
                if (settings.hideSelected) {
                    for (i = result.items.length - 1; i >= 0; i--) {
                        if (self.items.indexOf(hash_key(result.items[i].id)) !== -1) {
                            result.items.splice(i, 1);
                        }
                    }
                }
        
                return result;
            },
        
            /**
             * Refreshes the list of available options shown
             * in the autocomplete dropdown menu.
             *
             * @param {boolean} triggerDropdown
             */
            refreshOptions: function(triggerDropdown) {
                var i, j, k, n, groups, groups_order, option, option_html, optgroup, optgroups, html, html_children, has_create_option;
                var $active, $active_before, $create;
        
                if (typeof triggerDropdown === 'undefined') {
                    triggerDropdown = true;
                }
        
                var self              = this;
                var query             = $.trim(self.$control_input.val());
                var results           = self.search(query);
                var $dropdown_content = self.$dropdown_content;
                var active_before     = self.$activeOption && hash_key(self.$activeOption.attr('data-value'));
        
                // build markup
                n = results.items.length;
                if (typeof self.settings.maxOptions === 'number') {
                    n = Math.min(n, self.settings.maxOptions);
                }
        
                // render and group available options individually
                groups = {};
                groups_order = [];
        
                for (i = 0; i < n; i++) {
                    option      = self.options[results.items[i].id];
                    option_html = self.render('option', option);
                    optgroup    = option[self.settings.optgroupField] || '';
                    optgroups   = $.isArray(optgroup) ? optgroup : [optgroup];
        
                    for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
                        optgroup = optgroups[j];
                        if (!self.optgroups.hasOwnProperty(optgroup)) {
                            optgroup = '';
                        }
                        if (!groups.hasOwnProperty(optgroup)) {
                            groups[optgroup] = document.createDocumentFragment();
                            groups_order.push(optgroup);
                        }
                        groups[optgroup].appendChild(option_html);
                    }
                }
        
                // sort optgroups
                if (this.settings.lockOptgroupOrder) {
                    groups_order.sort(function(a, b) {
                        var a_order = self.optgroups[a].$order || 0;
                        var b_order = self.optgroups[b].$order || 0;
                        return a_order - b_order;
                    });
                }
        
                // render optgroup headers & join groups
                html = document.createDocumentFragment();
                for (i = 0, n = groups_order.length; i < n; i++) {
                    optgroup = groups_order[i];
                    if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].childNodes.length) {
                        // render the optgroup header and options within it,
                        // then pass it to the wrapper template
                        html_children = document.createDocumentFragment();
                        html_children.appendChild(self.render('optgroup_header', self.optgroups[optgroup]));
                        html_children.appendChild(groups[optgroup]);
        
                        html.appendChild(self.render('optgroup', $.extend({}, self.optgroups[optgroup], {
                            html: domToString(html_children),
                            dom:  html_children
                        })));
                    } else {
                        html.appendChild(groups[optgroup]);
                    }
                }
        
                $dropdown_content.html(html);
        
                // highlight matching terms inline
                if (self.settings.highlight && results.query.length && results.tokens.length) {
                    $dropdown_content.removeHighlight();
                    for (i = 0, n = results.tokens.length; i < n; i++) {
                        highlight($dropdown_content, results.tokens[i].regex);
                    }
                }
        
                // add "selected" class to selected options
                if (!self.settings.hideSelected) {
                    for (i = 0, n = self.items.length; i < n; i++) {
                        self.getOption(self.items[i]).addClass('selected');
                    }
                }
        
                // add create option
                has_create_option = self.canCreate(query);
                if (has_create_option) {
                    $dropdown_content.prepend(self.render('option_create', {input: query}));
                    $create = $($dropdown_content[0].childNodes[0]);
                }
        
                // activate
                self.hasOptions = results.items.length > 0 || has_create_option;
                if (self.hasOptions) {
                    if (results.items.length > 0) {
                        $active_before = active_before && self.getOption(active_before);
                        if ($active_before && $active_before.length) {
                            $active = $active_before;
                        } else if (self.settings.mode === 'single' && self.items.length) {
                            $active = self.getOption(self.items[0]);
                        }
                        if (!$active || !$active.length) {
                            if ($create && !self.settings.addPrecedence) {
                                $active = self.getAdjacentOption($create, 1);
                            } else {
                                $active = $dropdown_content.find('[data-selectable]:first');
                            }
                        }
                    } else {
                        $active = $create;
                    }
                    self.setActiveOption($active);
                    if (triggerDropdown && !self.isOpen) { self.open(); }
                } else {
                    self.setActiveOption(null);
                    if (triggerDropdown && self.isOpen) { self.close(); }
                }
            },
        
            /**
             * Adds an available option. If it already exists,
             * nothing will happen. Note: this does not refresh
             * the options list dropdown (use `refreshOptions`
             * for that).
             *
             * Usage:
             *
             *   this.addOption(data)
             *
             * @param {object|array} data
             */
            addOption: function(data) {
                var i, n, value, self = this;
        
                if ($.isArray(data)) {
                    for (i = 0, n = data.length; i < n; i++) {
                        self.addOption(data[i]);
                    }
                    return;
                }
        
                if (value = self.registerOption(data)) {
                    self.userOptions[value] = true;
                    self.lastQuery = null;
                    self.trigger('option_add', value, data);
                }
            },
        
            /**
             * Registers an option to the pool of options.
             *
             * @param {object} data
             * @return {boolean|string}
             */
            registerOption: function(data) {
                var key = hash_key(data[this.settings.valueField]);
                if (typeof key === 'undefined' || key === null || this.options.hasOwnProperty(key)) return false;
                data.$order = data.$order || ++this.order;
                this.options[key] = data;
                return key;
            },
        
            /**
             * Registers an option group to the pool of option groups.
             *
             * @param {object} data
             * @return {boolean|string}
             */
            registerOptionGroup: function(data) {
                var key = hash_key(data[this.settings.optgroupValueField]);
                if (!key) return false;
        
                data.$order = data.$order || ++this.order;
                this.optgroups[key] = data;
                return key;
            },
        
            /**
             * Registers a new optgroup for options
             * to be bucketed into.
             *
             * @param {string} id
             * @param {object} data
             */
            addOptionGroup: function(id, data) {
                data[this.settings.optgroupValueField] = id;
                if (id = this.registerOptionGroup(data)) {
                    this.trigger('optgroup_add', id, data);
                }
            },
        
            /**
             * Removes an existing option group.
             *
             * @param {string} id
             */
            removeOptionGroup: function(id) {
                if (this.optgroups.hasOwnProperty(id)) {
                    delete this.optgroups[id];
                    this.renderCache = {};
                    this.trigger('optgroup_remove', id);
                }
            },
        
            /**
             * Clears all existing option groups.
             */
            clearOptionGroups: function() {
                this.optgroups = {};
                this.renderCache = {};
                this.trigger('optgroup_clear');
            },
        
            /**
             * Updates an option available for selection. If
             * it is visible in the selected items or options
             * dropdown, it will be re-rendered automatically.
             *
             * @param {string} value
             * @param {object} data
             */
            updateOption: function(value, data) {
                var self = this;
                var $item, $item_new;
                var value_new, index_item, cache_items, cache_options, order_old;
        
                value     = hash_key(value);
                value_new = hash_key(data[self.settings.valueField]);
        
                // sanity checks
                if (value === null) return;
                if (!self.options.hasOwnProperty(value)) return;
                if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
        
                order_old = self.options[value].$order;
        
                // update references
                if (value_new !== value) {
                    delete self.options[value];
                    index_item = self.items.indexOf(value);
                    if (index_item !== -1) {
                        self.items.splice(index_item, 1, value_new);
                    }
                }
                data.$order = data.$order || order_old;
                self.options[value_new] = data;
        
                // invalidate render cache
                cache_items = self.renderCache['item'];
                cache_options = self.renderCache['option'];
        
                if (cache_items) {
                    delete cache_items[value];
                    delete cache_items[value_new];
                }
                if (cache_options) {
                    delete cache_options[value];
                    delete cache_options[value_new];
                }
        
                // update the item if it's selected
                if (self.items.indexOf(value_new) !== -1) {
                    $item = self.getItem(value);
                    $item_new = $(self.render('item', data));
                    if ($item.hasClass('active')) $item_new.addClass('active');
                    $item.replaceWith($item_new);
                }
        
                // invalidate last query because we might have updated the sortField
                self.lastQuery = null;
        
                // update dropdown contents
                if (self.isOpen) {
                    self.refreshOptions(false);
                }
            },
        
            /**
             * Removes a single option.
             *
             * @param {string} value
             * @param {boolean} silent
             */
            removeOption: function(value, silent) {
                var self = this;
                value = hash_key(value);
        
                var cache_items = self.renderCache['item'];
                var cache_options = self.renderCache['option'];
                if (cache_items) delete cache_items[value];
                if (cache_options) delete cache_options[value];
        
                delete self.userOptions[value];
                delete self.options[value];
                self.lastQuery = null;
                self.trigger('option_remove', value);
                self.removeItem(value, silent);
            },
        
            /**
             * Clears all options.
             */
            clearOptions: function() {
                var self = this;
        
                self.loadedSearches = {};
                self.userOptions = {};
                self.renderCache = {};
                self.options = self.sifter.items = {};
                self.lastQuery = null;
                self.trigger('option_clear');
                self.clear();
            },
        
            /**
             * Returns the jQuery element of the option
             * matching the given value.
             *
             * @param {string} value
             * @returns {object}
             */
            getOption: function(value) {
                return this.getElementWithValue(value, this.$dropdown_content.find('[data-selectable]'));
            },
        
            /**
             * Returns the jQuery element of the next or
             * previous selectable option.
             *
             * @param {object} $option
             * @param {int} direction  can be 1 for next or -1 for previous
             * @return {object}
             */
            getAdjacentOption: function($option, direction) {
                var $options = this.$dropdown.find('[data-selectable]');
                var index    = $options.index($option) + direction;
        
                return index >= 0 && index < $options.length ? $options.eq(index) : $();
            },
        
            /**
             * Finds the first element with a "data-value" attribute
             * that matches the given value.
             *
             * @param {mixed} value
             * @param {object} $els
             * @return {object}
             */
            getElementWithValue: function(value, $els) {
                value = hash_key(value);
        
                if (typeof value !== 'undefined' && value !== null) {
                    for (var i = 0, n = $els.length; i < n; i++) {
                        if ($els[i].getAttribute('data-value') === value) {
                            return $($els[i]);
                        }
                    }
                }
        
                return $();
            },
        
            /**
             * Returns the jQuery element of the item
             * matching the given value.
             *
             * @param {string} value
             * @returns {object}
             */
            getItem: function(value) {
                return this.getElementWithValue(value, this.$control.children());
            },
        
            /**
             * "Selects" multiple items at once. Adds them to the list
             * at the current caret position.
             *
             * @param {string} value
             * @param {boolean} silent
             */
            addItems: function(values, silent) {
                var items = $.isArray(values) ? values : [values];
                for (var i = 0, n = items.length; i < n; i++) {
                    this.isPending = (i < n - 1);
                    this.addItem(items[i], silent);
                }
            },
        
            /**
             * "Selects" an item. Adds it to the list
             * at the current caret position.
             *
             * @param {string} value
             * @param {boolean} silent
             */
            addItem: function(value, silent) {
                var events = silent ? [] : ['change'];
        
                debounce_events(this, events, function() {
                    var $item, $option, $options;
                    var self = this;
                    var inputMode = self.settings.mode;
                    var i, active, value_next, wasFull;
                    value = hash_key(value);
        
                    if (self.items.indexOf(value) !== -1) {
                        if (inputMode === 'single') self.close();
                        return;
                    }
        
                    if (!self.options.hasOwnProperty(value)) return;
                    if (inputMode === 'single') self.clear(silent);
                    if (inputMode === 'multi' && self.isFull()) return;
        
                    $item = $(self.render('item', self.options[value]));
                    wasFull = self.isFull();
                    self.items.splice(self.caretPos, 0, value);
                    self.insertAtCaret($item);
                    if (!self.isPending || (!wasFull && self.isFull())) {
                        self.refreshState();
                    }
        
                    if (self.isSetup) {
                        $options = self.$dropdown_content.find('[data-selectable]');
        
                        // update menu / remove the option (if this is not one item being added as part of series)
                        if (!self.isPending) {
                            $option = self.getOption(value);
                            value_next = self.getAdjacentOption($option, 1).attr('data-value');
                            self.refreshOptions(self.isFocused && inputMode !== 'single');
                            if (value_next) {
                                self.setActiveOption(self.getOption(value_next));
                            }
                        }
        
                        // hide the menu if the maximum number of items have been selected or no options are left
                        if (!$options.length || self.isFull()) {
                            self.close();
                        } else {
                            self.positionDropdown();
                        }
        
                        self.updatePlaceholder();
                        self.trigger('item_add', value, $item);
                        self.updateOriginalInput({silent: silent});
                    }
                });
            },
        
            /**
             * Removes the selected item matching
             * the provided value.
             *
             * @param {string} value
             */
            removeItem: function(value, silent) {
                var self = this;
                var $item, i, idx;
        
                $item = (value instanceof $) ? value : self.getItem(value);
                value = hash_key($item.attr('data-value'));
                i = self.items.indexOf(value);
        
                if (i !== -1) {
                    $item.remove();
                    if ($item.hasClass('active')) {
                        idx = self.$activeItems.indexOf($item[0]);
                        self.$activeItems.splice(idx, 1);
                    }
        
                    self.items.splice(i, 1);
                    self.lastQuery = null;
                    if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
                        self.removeOption(value, silent);
                    }
        
                    if (i < self.caretPos) {
                        self.setCaret(self.caretPos - 1);
                    }
        
                    self.refreshState();
                    self.updatePlaceholder();
                    self.updateOriginalInput({silent: silent});
                    self.positionDropdown();
                    self.trigger('item_remove', value, $item);
                }
            },
        
            /**
             * Invokes the `create` method provided in the
             * selectize options that should provide the data
             * for the new item, given the user input.
             *
             * Once this completes, it will be added
             * to the item list.
             *
             * @param {string} value
             * @param {boolean} [triggerDropdown]
             * @param {function} [callback]
             * @return {boolean}
             */
            createItem: function(input, triggerDropdown) {
                var self  = this;
                var caret = self.caretPos;
                input = input || $.trim(self.$control_input.val() || '');
        
                var callback = arguments[arguments.length - 1];
                if (typeof callback !== 'function') callback = function() {};
        
                if (typeof triggerDropdown !== 'boolean') {
                    triggerDropdown = true;
                }
        
                if (!self.canCreate(input)) {
                    callback();
                    return false;
                }
        
                self.lock();
        
                var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
                    var data = {};
                    data[self.settings.labelField] = input;
                    data[self.settings.valueField] = input;
                    return data;
                };
        
                var create = once(function(data) {
                    self.unlock();
        
                    if (!data || typeof data !== 'object') return callback();
                    var value = hash_key(data[self.settings.valueField]);
                    if (typeof value !== 'string') return callback();
        
                    self.setTextboxValue('');
                    self.addOption(data);
                    self.setCaret(caret);
                    self.addItem(value);
                    self.refreshOptions(triggerDropdown && self.settings.mode !== 'single');
                    callback(data);
                });
        
                var output = setup.apply(this, [input, create]);
                if (typeof output !== 'undefined') {
                    create(output);
                }
        
                return true;
            },
        
            /**
             * Re-renders the selected item lists.
             */
            refreshItems: function() {
                this.lastQuery = null;
        
                if (this.isSetup) {
                    this.addItem(this.items);
                }
        
                this.refreshState();
                this.updateOriginalInput();
            },
        
            /**
             * Updates all state-dependent attributes
             * and CSS classes.
             */
            refreshState: function() {
                this.refreshValidityState();
                this.refreshClasses();
            },
        
            /**
             * Update the `required` attribute of both input and control input.
             *
             * The `required` property needs to be activated on the control input
             * for the error to be displayed at the right place. `required` also
             * needs to be temporarily deactivated on the input since the input is
             * hidden and can't show errors.
             */
            refreshValidityState: function() {
                if (!this.isRequired) return false;
        
                var invalid = !this.items.length;
        
                this.isInvalid = invalid;
                this.$control_input.prop('required', invalid);
                this.$input.prop('required', !invalid);
            },
        
            /**
             * Updates all state-dependent CSS classes.
             */
            refreshClasses: function() {
                var self     = this;
                var isFull   = self.isFull();
                var isLocked = self.isLocked;
        
                self.$wrapper
                    .toggleClass('rtl', self.rtl);
        
                self.$control
                    .toggleClass('focus', self.isFocused)
                    .toggleClass('disabled', self.isDisabled)
                    .toggleClass('required', self.isRequired)
                    .toggleClass('invalid', self.isInvalid)
                    .toggleClass('locked', isLocked)
                    .toggleClass('full', isFull).toggleClass('not-full', !isFull)
                    .toggleClass('input-active', self.isFocused && !self.isInputHidden)
                    .toggleClass('dropdown-active', self.isOpen)
                    .toggleClass('has-options', !$.isEmptyObject(self.options))
                    .toggleClass('has-items', self.items.length > 0);
        
                self.$control_input.data('grow', !isFull && !isLocked);
            },
        
            /**
             * Determines whether or not more items can be added
             * to the control without exceeding the user-defined maximum.
             *
             * @returns {boolean}
             */
            isFull: function() {
                return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
            },
        
            /**
             * Refreshes the original <select> or <input>
             * element to reflect the current state.
             */
            updateOriginalInput: function(opts) {
                var i, n, options, label, self = this;
                opts = opts || {};
        
                if (self.tagType === TAG_SELECT) {
                    options = [];
                    for (i = 0, n = self.items.length; i < n; i++) {
                        label = self.options[self.items[i]][self.settings.labelField] || '';
                        options.push('<option value="' + escape_html(self.items[i]) + '" selected="selected">' + escape_html(label) + '</option>');
                    }
                    if (!options.length && !this.$input.attr('multiple')) {
                        options.push('<option value="" selected="selected"></option>');
                    }
                    self.$input.html(options.join(''));
                } else {
                    self.$input.val(self.getValue());
                    self.$input.attr('value',self.$input.val());
                }
        
                if (self.isSetup) {
                    if (!opts.silent) {
                        self.trigger('change', self.$input.val());
                    }
                }
            },
        
            /**
             * Shows/hide the input placeholder depending
             * on if there items in the list already.
             */
            updatePlaceholder: function() {
                if (!this.settings.placeholder) return;
                var $input = this.$control_input;
        
                if (this.items.length) {
                    $input.removeAttr('placeholder');
                } else {
                    $input.attr('placeholder', this.settings.placeholder);
                }
                $input.triggerHandler('update', {force: true});
            },
        
            /**
             * Shows the autocomplete dropdown containing
             * the available options.
             */
            open: function() {
                var self = this;
        
                if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return;
                self.focus();
                self.isOpen = true;
                self.refreshState();
                self.$dropdown.css({visibility: 'hidden', display: 'block'});
                self.positionDropdown();
                self.$dropdown.css({visibility: 'visible'});
                self.trigger('dropdown_open', self.$dropdown);
            },
        
            /**
             * Closes the autocomplete dropdown menu.
             */
            close: function() {
                var self = this;
                var trigger = self.isOpen;
        
                if (self.settings.mode === 'single' && self.items.length) {
                    self.hideInput();
                    self.$control_input.blur(); // close keyboard on iOS
                }
        
                self.isOpen = false;
                self.$dropdown.hide();
                self.setActiveOption(null);
                self.refreshState();
        
                if (trigger) self.trigger('dropdown_close', self.$dropdown);
            },
        
            /**
             * Calculates and applies the appropriate
             * position of the dropdown.
             */
            positionDropdown: function() {
                var $control = this.$control;
                var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
                offset.top += $control.outerHeight(true);
        
                this.$dropdown.css({
                    width : $control.outerWidth(),
                    top   : offset.top,
                    left  : offset.left
                });
            },
        
            /**
             * Resets / clears all selected items
             * from the control.
             *
             * @param {boolean} silent
             */
            clear: function(silent) {
                var self = this;
        
                if (!self.items.length) return;
                self.$control.children(':not(input)').remove();
                self.items = [];
                self.lastQuery = null;
                self.setCaret(0);
                self.setActiveItem(null);
                self.updatePlaceholder();
                self.updateOriginalInput({silent: silent});
                self.refreshState();
                self.showInput();
                self.trigger('clear');
            },
        
            /**
             * A helper method for inserting an element
             * at the current caret position.
             *
             * @param {object} $el
             */
            insertAtCaret: function($el) {
                var caret = Math.min(this.caretPos, this.items.length);
                if (caret === 0) {
                    this.$control.prepend($el);
                } else {
                    $(this.$control[0].childNodes[caret]).before($el);
                }
                this.setCaret(caret + 1);
            },
        
            /**
             * Removes the current selected item(s).
             *
             * @param {object} e (optional)
             * @returns {boolean}
             */
            deleteSelection: function(e) {
                var i, n, direction, selection, values, caret, option_select, $option_select, $tail;
                var self = this;
        
                direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1;
                selection = getSelection(self.$control_input[0]);
        
                if (self.$activeOption && !self.settings.hideSelected) {
                    option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value');
                }
        
                // determine items that will be removed
                values = [];
        
                if (self.$activeItems.length) {
                    $tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
                    caret = self.$control.children(':not(input)').index($tail);
                    if (direction > 0) { caret++; }
        
                    for (i = 0, n = self.$activeItems.length; i < n; i++) {
                        values.push($(self.$activeItems[i]).attr('data-value'));
                    }
                    if (e) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
                    if (direction < 0 && selection.start === 0 && selection.length === 0) {
                        values.push(self.items[self.caretPos - 1]);
                    } else if (direction > 0 && selection.start === self.$control_input.val().length) {
                        values.push(self.items[self.caretPos]);
                    }
                }
        
                // allow the callback to abort
                if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false)) {
                    return false;
                }
        
                // perform removal
                if (typeof caret !== 'undefined') {
                    self.setCaret(caret);
                }
                while (values.length) {
                    self.removeItem(values.pop());
                }
        
                self.showInput();
                self.positionDropdown();
                self.refreshOptions(true);
        
                // select previous option
                if (option_select) {
                    $option_select = self.getOption(option_select);
                    if ($option_select.length) {
                        self.setActiveOption($option_select);
                    }
                }
        
                return true;
            },
        
            /**
             * Selects the previous / next item (depending
             * on the `direction` argument).
             *
             * > 0 - right
             * < 0 - left
             *
             * @param {int} direction
             * @param {object} e (optional)
             */
            advanceSelection: function(direction, e) {
                var tail, selection, idx, valueLength, cursorAtEdge, $tail;
                var self = this;
        
                if (direction === 0) return;
                if (self.rtl) direction *= -1;
        
                tail = direction > 0 ? 'last' : 'first';
                selection = getSelection(self.$control_input[0]);
        
                if (self.isFocused && !self.isInputHidden) {
                    valueLength = self.$control_input.val().length;
                    cursorAtEdge = direction < 0
                        ? selection.start === 0 && selection.length === 0
                        : selection.start === valueLength;
        
                    if (cursorAtEdge && !valueLength) {
                        self.advanceCaret(direction, e);
                    }
                } else {
                    $tail = self.$control.children('.active:' + tail);
                    if ($tail.length) {
                        idx = self.$control.children(':not(input)').index($tail);
                        self.setActiveItem(null);
                        self.setCaret(direction > 0 ? idx + 1 : idx);
                    }
                }
            },
        
            /**
             * Moves the caret left / right.
             *
             * @param {int} direction
             * @param {object} e (optional)
             */
            advanceCaret: function(direction, e) {
                var self = this, fn, $adj;
        
                if (direction === 0) return;
        
                fn = direction > 0 ? 'next' : 'prev';
                if (self.isShiftDown) {
                    $adj = self.$control_input[fn]();
                    if ($adj.length) {
                        self.hideInput();
                        self.setActiveItem($adj);
                        e && e.preventDefault();
                    }
                } else {
                    self.setCaret(self.caretPos + direction);
                }
            },
        
            /**
             * Moves the caret to the specified index.
             *
             * @param {int} i
             */
            setCaret: function(i) {
                var self = this;
        
                if (self.settings.mode === 'single') {
                    i = self.items.length;
                } else {
                    i = Math.max(0, Math.min(self.items.length, i));
                }
        
                if(!self.isPending) {
                    // the input must be moved by leaving it in place and moving the
                    // siblings, due to the fact that focus cannot be restored once lost
                    // on mobile webkit devices
                    var j, n, fn, $children, $child;
                    $children = self.$control.children(':not(input)');
                    for (j = 0, n = $children.length; j < n; j++) {
                        $child = $($children[j]).detach();
                        if (j <  i) {
                            self.$control_input.before($child);
                        } else {
                            self.$control.append($child);
                        }
                    }
                }
        
                self.caretPos = i;
            },
        
            /**
             * Disables user input on the control. Used while
             * items are being asynchronously created.
             */
            lock: function() {
                this.close();
                this.isLocked = true;
                this.refreshState();
            },
        
            /**
             * Re-enables user input on the control.
             */
            unlock: function() {
                this.isLocked = false;
                this.refreshState();
            },
        
            /**
             * Disables user input on the control completely.
             * While disabled, it cannot receive focus.
             */
            disable: function() {
                var self = this;
                self.$input.prop('disabled', true);
                self.$control_input.prop('disabled', true).prop('tabindex', -1);
                self.isDisabled = true;
                self.lock();
            },
        
            /**
             * Enables the control so that it can respond
             * to focus and user input.
             */
            enable: function() {
                var self = this;
                self.$input.prop('disabled', false);
                self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex);
                self.isDisabled = false;
                self.unlock();
            },
        
            /**
             * Completely destroys the control and
             * unbinds all event listeners so that it can
             * be garbage collected.
             */
            destroy: function() {
                var self = this;
                var eventNS = self.eventNS;
                var revertSettings = self.revertSettings;
        
                self.trigger('destroy');
                self.off();
                self.$wrapper.remove();
                self.$dropdown.remove();
        
                self.$input
                    .html('')
                    .append(revertSettings.$children)
                    .removeAttr('tabindex')
                    .removeClass('selectized')
                    .attr({tabindex: revertSettings.tabindex})
                    .show();
        
                self.$control_input.removeData('grow');
                self.$input.removeData('selectize');
        
                $(window).off(eventNS);
                $(document).off(eventNS);
                $(document.body).off(eventNS);
        
                delete self.$input[0].selectize;
            },
        
            /**
             * A helper method for rendering "item" and
             * "option" templates, given the data.
             *
             * @param {string} templateName
             * @param {object} data
             * @returns {string}
             */
            render: function(templateName, data) {
                var value, id, label;
                var html = '';
                var cache = false;
                var self = this;
                var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;
        
                if (templateName === 'option' || templateName === 'item') {
                    value = hash_key(data[self.settings.valueField]);
                    cache = !!value;
                }
        
                // pull markup from cache if it exists
                if (cache) {
                    if (!isset(self.renderCache[templateName])) {
                        self.renderCache[templateName] = {};
                    }
                    if (self.renderCache[templateName].hasOwnProperty(value)) {
                        return self.renderCache[templateName][value];
                    }
                }
        
                // render markup
                html = $(self.settings.render[templateName].apply(this, [data, escape_html]));
        
                // add mandatory attributes
                if (templateName === 'option' || templateName === 'option_create') {
                    html.attr('data-selectable', '');
                }
                else if (templateName === 'optgroup') {
                    id = data[self.settings.optgroupValueField] || '';
                    html.attr('data-group', id);
                }
                if (templateName === 'option' || templateName === 'item') {
                    html.attr('data-value', value || '');
                }
        
                // update cache
                if (cache) {
                    self.renderCache[templateName][value] = html[0];
                }
        
                return html[0];
            },
        
            /**
             * Clears the render cache for a template. If
             * no template is given, clears all render
             * caches.
             *
             * @param {string} templateName
             */
            clearCache: function(templateName) {
                var self = this;
                if (typeof templateName === 'undefined') {
                    self.renderCache = {};
                } else {
                    delete self.renderCache[templateName];
                }
            },
        
            /**
             * Determines whether or not to display the
             * create item prompt, given a user input.
             *
             * @param {string} input
             * @return {boolean}
             */
            canCreate: function(input) {
                var self = this;
                if (!self.settings.create) return false;
                var filter = self.settings.createFilter;
                return input.length
                    && (typeof filter !== 'function' || filter.apply(self, [input]))
                    && (typeof filter !== 'string' || new RegExp(filter).test(input))
                    && (!(filter instanceof RegExp) || filter.test(input));
            }
        
        });
        
        
        Selectize.count = 0;
        Selectize.defaults = {
            options: [],
            optgroups: [],
        
            plugins: [],
            delimiter: ',',
            splitOn: null, // regexp or string for splitting up values from a paste command
            persist: true,
            diacritics: true,
            create: false,
            createOnBlur: false,
            createFilter: null,
            highlight: true,
            openOnFocus: true,
            maxOptions: 1000,
            maxItems: null,
            hideSelected: null,
            addPrecedence: false,
            selectOnTab: false,
            preload: false,
            allowEmptyOption: false,
            closeAfterSelect: false,
        
            scrollDuration: 60,
            loadThrottle: 300,
            loadingClass: 'loading',
        
            dataAttr: 'data-data',
            optgroupField: 'optgroup',
            valueField: 'value',
            labelField: 'text',
            optgroupLabelField: 'label',
            optgroupValueField: 'value',
            lockOptgroupOrder: false,
        
            sortField: '$order',
            searchField: ['text'],
            searchConjunction: 'and',
        
            mode: null,
            wrapperClass: 'selectize-control',
            inputClass: 'selectize-input',
            dropdownClass: 'selectize-dropdown',
            dropdownContentClass: 'selectize-dropdown-content',
        
            dropdownParent: null,
        
            copyClassesToDropdown: true,
        
            /*
            load                 : null, // function(query, callback) { ... }
            score                : null, // function(search) { ... }
            onInitialize         : null, // function() { ... }
            onChange             : null, // function(value) { ... }
            onItemAdd            : null, // function(value, $item) { ... }
            onItemRemove         : null, // function(value) { ... }
            onClear              : null, // function() { ... }
            onOptionAdd          : null, // function(value, data) { ... }
            onOptionRemove       : null, // function(value) { ... }
            onOptionClear        : null, // function() { ... }
            onOptionGroupAdd     : null, // function(id, data) { ... }
            onOptionGroupRemove  : null, // function(id) { ... }
            onOptionGroupClear   : null, // function() { ... }
            onDropdownOpen       : null, // function($dropdown) { ... }
            onDropdownClose      : null, // function($dropdown) { ... }
            onType               : null, // function(str) { ... }
            onDelete             : null, // function(values) { ... }
            */
        
            render: {
                /*
                item: null,
                optgroup: null,
                optgroup_header: null,
                option: null,
                option_create: null
                */
            }
        };
        
        
        $.fn.selectize = function(settings_user) {
            var defaults             = $.fn.selectize.defaults;
            var settings             = $.extend({}, defaults, settings_user);
            var attr_data            = settings.dataAttr;
            var field_label          = settings.labelField;
            var field_value          = settings.valueField;
            var field_optgroup       = settings.optgroupField;
            var field_optgroup_label = settings.optgroupLabelField;
            var field_optgroup_value = settings.optgroupValueField;
        
            /**
             * Initializes selectize from a <input type="text"> element.
             *
             * @param {object} $input
             * @param {object} settings_element
             */
            var init_textbox = function($input, settings_element) {
                var i, n, values, option;
        
                var data_raw = $input.attr(attr_data);
        
                if (!data_raw) {
                    var value = $.trim($input.val() || '');
                    if (!settings.allowEmptyOption && !value.length) return;
                    values = value.split(settings.delimiter);
                    for (i = 0, n = values.length; i < n; i++) {
                        option = {};
                        option[field_label] = values[i];
                        option[field_value] = values[i];
                        settings_element.options.push(option);
                    }
                    settings_element.items = values;
                } else {
                    settings_element.options = JSON.parse(data_raw);
                    for (i = 0, n = settings_element.options.length; i < n; i++) {
                        settings_element.items.push(settings_element.options[i][field_value]);
                    }
                }
            };
        
            /**
             * Initializes selectize from a <select> element.
             *
             * @param {object} $input
             * @param {object} settings_element
             */
            var init_select = function($input, settings_element) {
                var i, n, tagName, $children, order = 0;
                var options = settings_element.options;
                var optionsMap = {};
        
                var readData = function($el) {
                    var data = attr_data && $el.attr(attr_data);
                    if (typeof data === 'string' && data.length) {
                        return JSON.parse(data);
                    }
                    return null;
                };
        
                var addOption = function($option, group) {
                    $option = $($option);
        
                    var value = hash_key($option.val());
                    if (!value && !settings.allowEmptyOption) return;
        
                    // if the option already exists, it's probably been
                    // duplicated in another optgroup. in this case, push
                    // the current group to the "optgroup" property on the
                    // existing option so that it's rendered in both places.
                    if (optionsMap.hasOwnProperty(value)) {
                        if (group) {
                            var arr = optionsMap[value][field_optgroup];
                            if (!arr) {
                                optionsMap[value][field_optgroup] = group;
                            } else if (!$.isArray(arr)) {
                                optionsMap[value][field_optgroup] = [arr, group];
                            } else {
                                arr.push(group);
                            }
                        }
                        return;
                    }
        
                    var option             = readData($option) || {};
                    option[field_label]    = option[field_label] || $option.text();
                    option[field_value]    = option[field_value] || value;
                    option[field_optgroup] = option[field_optgroup] || group;
        
                    optionsMap[value] = option;
                    options.push(option);
        
                    if ($option.is(':selected')) {
                        settings_element.items.push(value);
                    }
                };
        
                var addGroup = function($optgroup) {
                    var i, n, id, optgroup, $options;
        
                    $optgroup = $($optgroup);
                    id = $optgroup.attr('label');
        
                    if (id) {
                        optgroup = readData($optgroup) || {};
                        optgroup[field_optgroup_label] = id;
                        optgroup[field_optgroup_value] = id;
                        settings_element.optgroups.push(optgroup);
                    }
        
                    $options = $('option', $optgroup);
                    for (i = 0, n = $options.length; i < n; i++) {
                        addOption($options[i], id);
                    }
                };
        
                settings_element.maxItems = $input.attr('multiple') ? null : 1;
        
                $children = $input.children();
                for (i = 0, n = $children.length; i < n; i++) {
                    tagName = $children[i].tagName.toLowerCase();
                    if (tagName === 'optgroup') {
                        addGroup($children[i]);
                    } else if (tagName === 'option') {
                        addOption($children[i]);
                    }
                }
            };
        
            return this.each(function() {
                if (this.selectize) return;
        
                var instance;
                var $input = $(this);
                var tag_name = this.tagName.toLowerCase();
                var placeholder = $input.attr('placeholder') || $input.attr('data-placeholder');
                if (!placeholder && !settings.allowEmptyOption) {
                    placeholder = $input.children('option[value=""]').text();
                }
        
                var settings_element = {
                    'placeholder' : placeholder,
                    'options'     : [],
                    'optgroups'   : [],
                    'items'       : []
                };
        
                if (tag_name === 'select') {
                    init_select($input, settings_element);
                } else {
                    init_textbox($input, settings_element);
                }
        
                instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings_user));
            });
        };
        
        $.fn.selectize.defaults = Selectize.defaults;
        $.fn.selectize.support = {
            validity: SUPPORTS_VALIDITY_API
        };
        
        
        Selectize.define('drag_drop', function(options) {
            if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');
            if (this.settings.mode !== 'multi') return;
            var self = this;
        
            self.lock = (function() {
                var original = self.lock;
                return function() {
                    var sortable = self.$control.data('sortable');
                    if (sortable) sortable.disable();
                    return original.apply(self, arguments);
                };
            })();
        
            self.unlock = (function() {
                var original = self.unlock;
                return function() {
                    var sortable = self.$control.data('sortable');
                    if (sortable) sortable.enable();
                    return original.apply(self, arguments);
                };
            })();
        
            self.setup = (function() {
                var original = self.setup;
                return function() {
                    original.apply(this, arguments);
        
                    var $control = self.$control.sortable({
                        items: '[data-value]',
                        forcePlaceholderSize: true,
                        disabled: self.isLocked,
                        start: function(e, ui) {
                            ui.placeholder.css('width', ui.helper.css('width'));
                            $control.css({overflow: 'visible'});
                        },
                        stop: function() {
                            $control.css({overflow: 'hidden'});
                            var active = self.$activeItems ? self.$activeItems.slice() : null;
                            var values = [];
                            $control.children('[data-value]').each(function() {
                                values.push($(this).attr('data-value'));
                            });
                            self.setValue(values);
                            self.setActiveItem(active);
                        }
                    });
                };
            })();
        
        });
        
        Selectize.define('dropdown_header', function(options) {
            var self = this;
        
            options = $.extend({
                title         : 'Untitled',
                headerClass   : 'selectize-dropdown-header',
                titleRowClass : 'selectize-dropdown-header-title',
                labelClass    : 'selectize-dropdown-header-label',
                closeClass    : 'selectize-dropdown-header-close',
        
                html: function(data) {
                    return (
                        '<div class="' + data.headerClass + '">' +
                            '<div class="' + data.titleRowClass + '">' +
                                '<span class="' + data.labelClass + '">' + data.title + '</span>' +
                                '<a href="javascript:void(0)" class="' + data.closeClass + '">&times;</a>' +
                            '</div>' +
                        '</div>'
                    );
                }
            }, options);
        
            self.setup = (function() {
                var original = self.setup;
                return function() {
                    original.apply(self, arguments);
                    self.$dropdown_header = $(options.html(options));
                    self.$dropdown.prepend(self.$dropdown_header);
                };
            })();
        
        });
        
        Selectize.define('optgroup_columns', function(options) {
            var self = this;
        
            options = $.extend({
                equalizeWidth  : true,
                equalizeHeight : true
            }, options);
        
            this.getAdjacentOption = function($option, direction) {
                var $options = $option.closest('[data-group]').find('[data-selectable]');
                var index    = $options.index($option) + direction;
        
                return index >= 0 && index < $options.length ? $options.eq(index) : $();
            };
        
            this.onKeyDown = (function() {
                var original = self.onKeyDown;
                return function(e) {
                    var index, $option, $options, $optgroup;
        
                    if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) {
                        self.ignoreHover = true;
                        $optgroup = this.$activeOption.closest('[data-group]');
                        index = $optgroup.find('[data-selectable]').index(this.$activeOption);
        
                        if(e.keyCode === KEY_LEFT) {
                            $optgroup = $optgroup.prev('[data-group]');
                        } else {
                            $optgroup = $optgroup.next('[data-group]');
                        }
        
                        $options = $optgroup.find('[data-selectable]');
                        $option  = $options.eq(Math.min($options.length - 1, index));
                        if ($option.length) {
                            this.setActiveOption($option);
                        }
                        return;
                    }
        
                    return original.apply(this, arguments);
                };
            })();
        
            var getScrollbarWidth = function() {
                var div;
                var width = getScrollbarWidth.width;
                var doc = document;
        
                if (typeof width === 'undefined') {
                    div = doc.createElement('div');
                    div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
                    div = div.firstChild;
                    doc.body.appendChild(div);
                    width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth;
                    doc.body.removeChild(div);
                }
                return width;
            };
        
            var equalizeSizes = function() {
                var i, n, height_max, width, width_last, width_parent, $optgroups;
        
                $optgroups = $('[data-group]', self.$dropdown_content);
                n = $optgroups.length;
                if (!n || !self.$dropdown_content.width()) return;
        
                if (options.equalizeHeight) {
                    height_max = 0;
                    for (i = 0; i < n; i++) {
                        height_max = Math.max(height_max, $optgroups.eq(i).height());
                    }
                    $optgroups.css({height: height_max});
                }
        
                if (options.equalizeWidth) {
                    width_parent = self.$dropdown_content.innerWidth() - getScrollbarWidth();
                    width = Math.round(width_parent / n);
                    $optgroups.css({width: width});
                    if (n > 1) {
                        width_last = width_parent - width * (n - 1);
                        $optgroups.eq(n - 1).css({width: width_last});
                    }
                }
            };
        
            if (options.equalizeHeight || options.equalizeWidth) {
                hook.after(this, 'positionDropdown', equalizeSizes);
                hook.after(this, 'refreshOptions', equalizeSizes);
            }
        
        
        });
        
        Selectize.define('remove_button', function(options) {
            options = $.extend({
                    label     : '&times;',
                    title     : 'Remove',
                    className : 'remove',
                    append    : true
                }, options);
        
                var singleClose = function(thisRef, options) {
        
                    options.className = 'remove-single';
        
                    var self = thisRef;
                    var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
        
                    /**
                     * Appends an element as a child (with raw HTML).
                     *
                     * @param {string} html_container
                     * @param {string} html_element
                     * @return {string}
                     */
                    var append = function(html_container, html_element) {
                        return html_container + html_element;
                    };
        
                    thisRef.setup = (function() {
                        var original = self.setup;
                        return function() {
                            // override the item rendering method to add the button to each
                            if (options.append) {
                                var id = $(self.$input.context).attr('id');
                                var selectizer = $('#'+id);
        
                                var render_item = self.settings.render.item;
                                self.settings.render.item = function(data) {
                                    return append(render_item.apply(thisRef, arguments), html);
                                };
                            }
        
                            original.apply(thisRef, arguments);
        
                            // add event listener
                            thisRef.$control.on('click', '.' + options.className, function(e) {
                                e.preventDefault();
                                if (self.isLocked) return;
        
                                self.clear();
                            });
        
                        };
                    })();
                };
        
                var multiClose = function(thisRef, options) {
        
                    var self = thisRef;
                    var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
        
                    /**
                     * Appends an element as a child (with raw HTML).
                     *
                     * @param {string} html_container
                     * @param {string} html_element
                     * @return {string}
                     */
                    var append = function(html_container, html_element) {
                        var pos = html_container.search(/(<\/[^>]+>\s*)$/);
                        return html_container.substring(0, pos) + html_element + html_container.substring(pos);
                    };
        
                    thisRef.setup = (function() {
                        var original = self.setup;
                        return function() {
                            // override the item rendering method to add the button to each
                            if (options.append) {
                                var render_item = self.settings.render.item;
                                self.settings.render.item = function(data) {
                                    return append(render_item.apply(thisRef, arguments), html);
                                };
                            }
        
                            original.apply(thisRef, arguments);
        
                            // add event listener
                            thisRef.$control.on('click', '.' + options.className, function(e) {
                                e.preventDefault();
                                if (self.isLocked) return;
        
                                var $item = $(e.currentTarget).parent();
                                self.setActiveItem($item);
                                if (self.deleteSelection()) {
                                    self.setCaret(self.items.length);
                                }
                            });
        
                        };
                    })();
                };
        
                if (this.settings.mode === 'single') {
                    singleClose(this, options);
                    return;
                } else {
                    multiClose(this, options);
                }
        });
        
        
        Selectize.define('restore_on_backspace', function(options) {
            var self = this;
        
            options.text = options.text || function(option) {
                return option[this.settings.labelField];
            };
        
            this.onKeyDown = (function() {
                var original = self.onKeyDown;
                return function(e) {
                    var index, option;
                    if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) {
                        index = this.caretPos - 1;
                        if (index >= 0 && index < this.items.length) {
                            option = this.options[this.items[index]];
                            if (this.deleteSelection(e)) {
                                this.setTextboxValue(options.text.apply(this, [option]));
                                this.refreshOptions(true);
                            }
                            e.preventDefault();
                            return;
                        }
                    }
                    return original.apply(this, arguments);
                };
            })();
        });
        
    
        return Selectize;
    }));
    // Generated by CoffeeScript 1.10.0
    
    /*
    jQuery Growl
    Copyright 2015 Kevin Sylvestre
    1.3.2
     */
    
    (function() {
      "use strict";
      var $, Animation, Growl,
        bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
    
      $ = jQuery;
    
      Animation = (function() {
        function Animation() {}
    
        Animation.transitions = {
          "webkitTransition": "webkitTransitionEnd",
          "mozTransition": "mozTransitionEnd",
          "oTransition": "oTransitionEnd",
          "transition": "transitionend"
        };
    
        Animation.transition = function($el) {
          var el, ref, result, type;
          el = $el[0];
          ref = this.transitions;
          for (type in ref) {
            result = ref[type];
            if (el.style[type] != null) {
              return result;
            }
          }
        };
    
        return Animation;
    
      })();
    
      Growl = (function() {
        Growl.settings = {
          namespace: 'growl',
          duration: 3200,
          close: "&#215;",
          location: "default",
          style: "default",
          size: "medium",
          delayOnHover: true
        };
    
        Growl.growl = function(settings) {
          if (settings == null) {
            settings = {};
          }
          this.initialize();
          return new Growl(settings);
        };
    
        Growl.initialize = function() {
          return $("body:not(:has(#growls))").append('<div id="growls" />');
        };
    
        function Growl(settings) {
          if (settings == null) {
            settings = {};
          }
          this.container = bind(this.container, this);
          this.content = bind(this.content, this);
          this.html = bind(this.html, this);
          this.$growl = bind(this.$growl, this);
          this.$growls = bind(this.$growls, this);
          this.animate = bind(this.animate, this);
          this.remove = bind(this.remove, this);
          this.dismiss = bind(this.dismiss, this);
          this.present = bind(this.present, this);
          this.waitAndDismiss = bind(this.waitAndDismiss, this);
          this.cycle = bind(this.cycle, this);
          this.close = bind(this.close, this);
          this.click = bind(this.click, this);
          this.mouseLeave = bind(this.mouseLeave, this);
          this.mouseEnter = bind(this.mouseEnter, this);
          this.unbind = bind(this.unbind, this);
          this.bind = bind(this.bind, this);
          this.render = bind(this.render, this);
          this.settings = $.extend({}, Growl.settings, settings);
          this.$growls().attr('class', this.settings.location);
          this.render();
        }
    
        Growl.prototype.render = function() {
          var $growl;
          $growl = this.$growl();
          this.$growls().append($growl);
          if (this.settings.fixed) {
            this.present();
          } else {
            this.cycle();
          }
        };
    
        Growl.prototype.bind = function($growl) {
          if ($growl == null) {
            $growl = this.$growl();
          }
          $growl.on("click", this.click);
          if (this.settings.delayOnHover) {
            $growl.on("mouseenter", this.mouseEnter);
            $growl.on("mouseleave", this.mouseLeave);
          }
          return $growl.on("contextmenu", this.close).find("." + this.settings.namespace + "-close").on("click", this.close);
        };
    
        Growl.prototype.unbind = function($growl) {
          if ($growl == null) {
            $growl = this.$growl();
          }
          $growl.off("click", this.click);
          if (this.settings.delayOnHover) {
            $growl.off("mouseenter", this.mouseEnter);
            $growl.off("mouseleave", this.mouseLeave);
          }
          return $growl.off("contextmenu", this.close).find("." + this.settings.namespace + "-close").off("click", this.close);
        };
    
        Growl.prototype.mouseEnter = function(event) {
          var $growl;
          $growl = this.$growl();
          return $growl.stop(true, true);
        };
    
        Growl.prototype.mouseLeave = function(event) {
          return this.waitAndDismiss();
        };
    
        Growl.prototype.click = function(event) {
          if (this.settings.url != null) {
            event.preventDefault();
            event.stopPropagation();
            return window.open(this.settings.url);
          }
        };
    
        Growl.prototype.close = function(event) {
          var $growl;
          event.preventDefault();
          event.stopPropagation();
          $growl = this.$growl();
          return $growl.stop().queue(this.dismiss).queue(this.remove);
        };
    
        Growl.prototype.cycle = function() {
          var $growl;
          $growl = this.$growl();
          return $growl.queue(this.present).queue(this.waitAndDismiss());
        };
    
        Growl.prototype.waitAndDismiss = function() {
          var $growl;
          $growl = this.$growl();
          return $growl.delay(this.settings.duration).queue(this.dismiss).queue(this.remove);
        };
    
        Growl.prototype.present = function(callback) {
          var $growl;
          $growl = this.$growl();
          this.bind($growl);
          return this.animate($growl, this.settings.namespace + "-incoming", 'out', callback);
        };
    
        Growl.prototype.dismiss = function(callback) {
          var $growl;
          $growl = this.$growl();
          this.unbind($growl);
          return this.animate($growl, this.settings.namespace + "-outgoing", 'in', callback);
        };
    
        Growl.prototype.remove = function(callback) {
          this.$growl().remove();
          return typeof callback === "function" ? callback() : void 0;
        };
    
        Growl.prototype.animate = function($element, name, direction, callback) {
          var transition;
          if (direction == null) {
            direction = 'in';
          }
          transition = Animation.transition($element);
          $element[direction === 'in' ? 'removeClass' : 'addClass'](name);
          $element.offset().position;
          $element[direction === 'in' ? 'addClass' : 'removeClass'](name);
          if (callback == null) {
            return;
          }
          if (transition != null) {
            $element.one(transition, callback);
          } else {
            callback();
          }
        };
    
        Growl.prototype.$growls = function() {
          return this.$_growls != null ? this.$_growls : this.$_growls = $('#growls');
        };
    
        Growl.prototype.$growl = function() {
          return this.$_growl != null ? this.$_growl : this.$_growl = $(this.html());
        };
    
        Growl.prototype.html = function() {
          return this.container(this.content());
        };
    
        Growl.prototype.content = function() {
          return "<div class='" + this.settings.namespace + "-close'>" + this.settings.close + "</div>\n<div class='" + this.settings.namespace + "-title'>" + this.settings.title + "</div>\n<div class='" + this.settings.namespace + "-message'>" + this.settings.message + "</div>";
        };
    
        Growl.prototype.container = function(content) {
          return "<div class='" + this.settings.namespace + " " + this.settings.namespace + "-" + this.settings.style + " " + this.settings.namespace + "-" + this.settings.size + "'>\n  " + content + "\n</div>";
        };
    
        return Growl;
    
      })();
    
      this.Growl = Growl;
    
      $.growl = function(options) {
        if (options == null) {
          options = {};
        }
        return Growl.growl(options);
      };
    
      $.growl.error = function(options) {
        var settings;
        if (options == null) {
          options = {};
        }
        settings = {
          title: "Error!",
          style: "error"
        };
        return $.growl($.extend(settings, options));
      };
    
      $.growl.notice = function(options) {
        var settings;
        if (options == null) {
          options = {};
        }
        settings = {
          title: "Notice!",
          style: "notice"
        };
        return $.growl($.extend(settings, options));
      };
    
      $.growl.warning = function(options) {
        var settings;
        if (options == null) {
          options = {};
        }
        settings = {
          title: "Warning!",
          style: "warning"
        };
        return $.growl($.extend(settings, options));
      };
    
    }).call(this);
    
    /* ========================================================================
     * bootstrap-switch - v3.3.2
     * http://www.bootstrap-switch.org
     * ========================================================================
     * Copyright 2012-2013 Mattia Larentis
     *
     * ========================================================================
     * 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.
     * ========================================================================
     */
    
    (function() {
      var __slice = [].slice;
    
      (function($, window) {
        "use strict";
        var BootstrapSwitch;
        BootstrapSwitch = (function() {
          function BootstrapSwitch(element, options) {
            if (options == null) {
              options = {};
            }
            this.$element = $(element);
            this.options = $.extend({}, $.fn.bootstrapSwitch.defaults, {
              state: this.$element.is(":checked"),
              size: this.$element.data("size"),
              animate: this.$element.data("animate"),
              disabled: this.$element.is(":disabled"),
              readonly: this.$element.is("[readonly]"),
              indeterminate: this.$element.data("indeterminate"),
              inverse: this.$element.data("inverse"),
              radioAllOff: this.$element.data("radio-all-off"),
              onColor: this.$element.data("on-color"),
              offColor: this.$element.data("off-color"),
              onText: this.$element.data("on-text"),
              offText: this.$element.data("off-text"),
              labelText: this.$element.data("label-text"),
              handleWidth: this.$element.data("handle-width"),
              labelWidth: this.$element.data("label-width"),
              baseClass: this.$element.data("base-class"),
              wrapperClass: this.$element.data("wrapper-class")
            }, options);
            this.$wrapper = $("<div>", {
              "class": (function(_this) {
                return function() {
                  var classes;
                  classes = ["" + _this.options.baseClass].concat(_this._getClasses(_this.options.wrapperClass));
                  classes.push(_this.options.state ? "" + _this.options.baseClass + "-on" : "" + _this.options.baseClass + "-off");
                  if (_this.options.size != null) {
                    classes.push("" + _this.options.baseClass + "-" + _this.options.size);
                  }
                  if (_this.options.disabled) {
                    classes.push("" + _this.options.baseClass + "-disabled");
                  }
                  if (_this.options.readonly) {
                    classes.push("" + _this.options.baseClass + "-readonly");
                  }
                  if (_this.options.indeterminate) {
                    classes.push("" + _this.options.baseClass + "-indeterminate");
                  }
                  if (_this.options.inverse) {
                    classes.push("" + _this.options.baseClass + "-inverse");
                  }
                  if (_this.$element.attr("id")) {
                    classes.push("" + _this.options.baseClass + "-id-" + (_this.$element.attr("id")));
                  }
                  return classes.join(" ");
                };
              })(this)()
            });
            this.$container = $("<div>", {
              "class": "" + this.options.baseClass + "-container"
            });
            this.$on = $("<span>", {
              html: this.options.onText,
              "class": "" + this.options.baseClass + "-handle-on " + this.options.baseClass + "-" + this.options.onColor
            });
            this.$off = $("<span>", {
              html: this.options.offText,
              "class": "" + this.options.baseClass + "-handle-off " + this.options.baseClass + "-" + this.options.offColor
            });
            this.$label = $("<span>", {
              html: this.options.labelText,
              "class": "" + this.options.baseClass + "-label"
            });
            this.$element.on("init.bootstrapSwitch", (function(_this) {
              return function() {
                return _this.options.onInit.apply(element, arguments);
              };
            })(this));
            this.$element.on("switchChange.bootstrapSwitch", (function(_this) {
              return function() {
                return _this.options.onSwitchChange.apply(element, arguments);
              };
            })(this));
            this.$container = this.$element.wrap(this.$container).parent();
            this.$wrapper = this.$container.wrap(this.$wrapper).parent();
            this.$element.before(this.options.inverse ? this.$off : this.$on).before(this.$label).before(this.options.inverse ? this.$on : this.$off);
            if (this.options.indeterminate) {
              this.$element.prop("indeterminate", true);
            }
            this._init();
            this._elementHandlers();
            this._handleHandlers();
            this._labelHandlers();
            this._formHandler();
            this._externalLabelHandler();
            this.$element.trigger("init.bootstrapSwitch");
          }
    
          BootstrapSwitch.prototype._constructor = BootstrapSwitch;
    
          BootstrapSwitch.prototype.state = function(value, skip) {
            if (typeof value === "undefined") {
              return this.options.state;
            }
            if (this.options.disabled || this.options.readonly) {
              return this.$element;
            }
            if (this.options.state && !this.options.radioAllOff && this.$element.is(":radio")) {
              return this.$element;
            }
            if (this.options.indeterminate) {
              this.indeterminate(false);
            }
            value = !!value;
            this.$element.prop("checked", value).trigger("change.bootstrapSwitch", skip);
            return this.$element;
          };
    
          BootstrapSwitch.prototype.toggleState = function(skip) {
            if (this.options.disabled || this.options.readonly) {
              return this.$element;
            }
            if (this.options.indeterminate) {
              this.indeterminate(false);
              return this.state(true);
            } else {
              return this.$element.prop("checked", !this.options.state).trigger("change.bootstrapSwitch", skip);
            }
          };
    
          BootstrapSwitch.prototype.size = function(value) {
            if (typeof value === "undefined") {
              return this.options.size;
            }
            if (this.options.size != null) {
              this.$wrapper.removeClass("" + this.options.baseClass + "-" + this.options.size);
            }
            if (value) {
              this.$wrapper.addClass("" + this.options.baseClass + "-" + value);
            }
            this._width();
            this._containerPosition();
            this.options.size = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.animate = function(value) {
            if (typeof value === "undefined") {
              return this.options.animate;
            }
            value = !!value;
            if (value === this.options.animate) {
              return this.$element;
            }
            return this.toggleAnimate();
          };
    
          BootstrapSwitch.prototype.toggleAnimate = function() {
            this.options.animate = !this.options.animate;
            this.$wrapper.toggleClass("" + this.options.baseClass + "-animate");
            return this.$element;
          };
    
          BootstrapSwitch.prototype.disabled = function(value) {
            if (typeof value === "undefined") {
              return this.options.disabled;
            }
            value = !!value;
            if (value === this.options.disabled) {
              return this.$element;
            }
            return this.toggleDisabled();
          };
    
          BootstrapSwitch.prototype.toggleDisabled = function() {
            this.options.disabled = !this.options.disabled;
            this.$element.prop("disabled", this.options.disabled);
            this.$wrapper.toggleClass("" + this.options.baseClass + "-disabled");
            return this.$element;
          };
    
          BootstrapSwitch.prototype.readonly = function(value) {
            if (typeof value === "undefined") {
              return this.options.readonly;
            }
            value = !!value;
            if (value === this.options.readonly) {
              return this.$element;
            }
            return this.toggleReadonly();
          };
    
          BootstrapSwitch.prototype.toggleReadonly = function() {
            this.options.readonly = !this.options.readonly;
            this.$element.prop("readonly", this.options.readonly);
            this.$wrapper.toggleClass("" + this.options.baseClass + "-readonly");
            return this.$element;
          };
    
          BootstrapSwitch.prototype.indeterminate = function(value) {
            if (typeof value === "undefined") {
              return this.options.indeterminate;
            }
            value = !!value;
            if (value === this.options.indeterminate) {
              return this.$element;
            }
            return this.toggleIndeterminate();
          };
    
          BootstrapSwitch.prototype.toggleIndeterminate = function() {
            this.options.indeterminate = !this.options.indeterminate;
            this.$element.prop("indeterminate", this.options.indeterminate);
            this.$wrapper.toggleClass("" + this.options.baseClass + "-indeterminate");
            this._containerPosition();
            return this.$element;
          };
    
          BootstrapSwitch.prototype.inverse = function(value) {
            if (typeof value === "undefined") {
              return this.options.inverse;
            }
            value = !!value;
            if (value === this.options.inverse) {
              return this.$element;
            }
            return this.toggleInverse();
          };
    
          BootstrapSwitch.prototype.toggleInverse = function() {
            var $off, $on;
            this.$wrapper.toggleClass("" + this.options.baseClass + "-inverse");
            $on = this.$on.clone(true);
            $off = this.$off.clone(true);
            this.$on.replaceWith($off);
            this.$off.replaceWith($on);
            this.$on = $off;
            this.$off = $on;
            this.options.inverse = !this.options.inverse;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.onColor = function(value) {
            var color;
            color = this.options.onColor;
            if (typeof value === "undefined") {
              return color;
            }
            if (color != null) {
              this.$on.removeClass("" + this.options.baseClass + "-" + color);
            }
            this.$on.addClass("" + this.options.baseClass + "-" + value);
            this.options.onColor = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.offColor = function(value) {
            var color;
            color = this.options.offColor;
            if (typeof value === "undefined") {
              return color;
            }
            if (color != null) {
              this.$off.removeClass("" + this.options.baseClass + "-" + color);
            }
            this.$off.addClass("" + this.options.baseClass + "-" + value);
            this.options.offColor = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.onText = function(value) {
            if (typeof value === "undefined") {
              return this.options.onText;
            }
            this.$on.html(value);
            this._width();
            this._containerPosition();
            this.options.onText = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.offText = function(value) {
            if (typeof value === "undefined") {
              return this.options.offText;
            }
            this.$off.html(value);
            this._width();
            this._containerPosition();
            this.options.offText = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.labelText = function(value) {
            if (typeof value === "undefined") {
              return this.options.labelText;
            }
            this.$label.html(value);
            this._width();
            this.options.labelText = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.handleWidth = function(value) {
            if (typeof value === "undefined") {
              return this.options.handleWidth;
            }
            this.options.handleWidth = value;
            this._width();
            this._containerPosition();
            return this.$element;
          };
    
          BootstrapSwitch.prototype.labelWidth = function(value) {
            if (typeof value === "undefined") {
              return this.options.labelWidth;
            }
            this.options.labelWidth = value;
            this._width();
            this._containerPosition();
            return this.$element;
          };
    
          BootstrapSwitch.prototype.baseClass = function(value) {
            return this.options.baseClass;
          };
    
          BootstrapSwitch.prototype.wrapperClass = function(value) {
            if (typeof value === "undefined") {
              return this.options.wrapperClass;
            }
            if (!value) {
              value = $.fn.bootstrapSwitch.defaults.wrapperClass;
            }
            this.$wrapper.removeClass(this._getClasses(this.options.wrapperClass).join(" "));
            this.$wrapper.addClass(this._getClasses(value).join(" "));
            this.options.wrapperClass = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.radioAllOff = function(value) {
            if (typeof value === "undefined") {
              return this.options.radioAllOff;
            }
            value = !!value;
            if (value === this.options.radioAllOff) {
              return this.$element;
            }
            this.options.radioAllOff = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.onInit = function(value) {
            if (typeof value === "undefined") {
              return this.options.onInit;
            }
            if (!value) {
              value = $.fn.bootstrapSwitch.defaults.onInit;
            }
            this.options.onInit = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.onSwitchChange = function(value) {
            if (typeof value === "undefined") {
              return this.options.onSwitchChange;
            }
            if (!value) {
              value = $.fn.bootstrapSwitch.defaults.onSwitchChange;
            }
            this.options.onSwitchChange = value;
            return this.$element;
          };
    
          BootstrapSwitch.prototype.destroy = function() {
            var $form;
            $form = this.$element.closest("form");
            if ($form.length) {
              $form.off("reset.bootstrapSwitch").removeData("bootstrap-switch");
            }
            this.$container.children().not(this.$element).remove();
            this.$element.unwrap().unwrap().off(".bootstrapSwitch").removeData("bootstrap-switch");
            return this.$element;
          };
    
          BootstrapSwitch.prototype._width = function() {
            var $handles, handleWidth;
            $handles = this.$on.add(this.$off);
            $handles.add(this.$label).css("width", "");
            handleWidth = this.options.handleWidth === "auto" ? Math.max(this.$on.width(), this.$off.width()) : this.options.handleWidth;
            $handles.width(handleWidth);
            this.$label.width((function(_this) {
              return function(index, width) {
                if (_this.options.labelWidth !== "auto") {
                  return _this.options.labelWidth;
                }
                if (width < handleWidth) {
                  return handleWidth;
                } else {
                  return width;
                }
              };
            })(this));
            this._handleWidth = this.$on.outerWidth();
            this._labelWidth = this.$label.outerWidth();
            this.$container.width((this._handleWidth * 2) + this._labelWidth);
            return this.$wrapper.width(this._handleWidth + this._labelWidth);
          };
    
          BootstrapSwitch.prototype._containerPosition = function(state, callback) {
            if (state == null) {
              state = this.options.state;
            }
            this.$container.css("margin-left", (function(_this) {
              return function() {
                var values;
                values = [0, "-" + _this._handleWidth + "px"];
                if (_this.options.indeterminate) {
                  return "-" + (_this._handleWidth / 2) + "px";
                }
                if (state) {
                  if (_this.options.inverse) {
                    return values[1];
                  } else {
                    return values[0];
                  }
                } else {
                  if (_this.options.inverse) {
                    return values[0];
                  } else {
                    return values[1];
                  }
                }
              };
            })(this));
            if (!callback) {
              return;
            }
            return setTimeout(function() {
              return callback();
            }, 50);
          };
    
          BootstrapSwitch.prototype._init = function() {
            var init, initInterval;
            init = (function(_this) {
              return function() {
                _this._width();
                return _this._containerPosition(null, function() {
                  if (_this.options.animate) {
                    return _this.$wrapper.addClass("" + _this.options.baseClass + "-animate");
                  }
                });
              };
            })(this);
            if (this.$wrapper.is(":visible")) {
              return init();
            }
            return initInterval = window.setInterval((function(_this) {
              return function() {
                if (_this.$wrapper.is(":visible")) {
                  init();
                  return window.clearInterval(initInterval);
                }
              };
            })(this), 50);
          };
    
          BootstrapSwitch.prototype._elementHandlers = function() {
            return this.$element.on({
              "change.bootstrapSwitch": (function(_this) {
                return function(e, skip) {
                  var state;
                  e.preventDefault();
                  e.stopImmediatePropagation();
                  state = _this.$element.is(":checked");
                  _this._containerPosition(state);
                  if (state === _this.options.state) {
                    return;
                  }
                  _this.options.state = state;
                  _this.$wrapper.toggleClass("" + _this.options.baseClass + "-off").toggleClass("" + _this.options.baseClass + "-on");
                  if (!skip) {
                    if (_this.$element.is(":radio")) {
                      $("[name='" + (_this.$element.attr('name')) + "']").not(_this.$element).prop("checked", false).trigger("change.bootstrapSwitch", true);
                    }
                    return _this.$element.trigger("switchChange.bootstrapSwitch", [state]);
                  }
                };
              })(this),
              "focus.bootstrapSwitch": (function(_this) {
                return function(e) {
                  e.preventDefault();
                  return _this.$wrapper.addClass("" + _this.options.baseClass + "-focused");
                };
              })(this),
              "blur.bootstrapSwitch": (function(_this) {
                return function(e) {
                  e.preventDefault();
                  return _this.$wrapper.removeClass("" + _this.options.baseClass + "-focused");
                };
              })(this),
              "keydown.bootstrapSwitch": (function(_this) {
                return function(e) {
                  if (!e.which || _this.options.disabled || _this.options.readonly) {
                    return;
                  }
                  switch (e.which) {
                    case 37:
                      e.preventDefault();
                      e.stopImmediatePropagation();
                      return _this.state(false);
                    case 39:
                      e.preventDefault();
                      e.stopImmediatePropagation();
                      return _this.state(true);
                  }
                };
              })(this)
            });
          };
    
          BootstrapSwitch.prototype._handleHandlers = function() {
            this.$on.on("click.bootstrapSwitch", (function(_this) {
              return function(event) {
                event.preventDefault();
                event.stopPropagation();
                _this.state(false);
                return _this.$element.trigger("focus.bootstrapSwitch");
              };
            })(this));
            return this.$off.on("click.bootstrapSwitch", (function(_this) {
              return function(event) {
                event.preventDefault();
                event.stopPropagation();
                _this.state(true);
                return _this.$element.trigger("focus.bootstrapSwitch");
              };
            })(this));
          };
    
          BootstrapSwitch.prototype._labelHandlers = function() {
            return this.$label.on({
              "mousedown.bootstrapSwitch touchstart.bootstrapSwitch": (function(_this) {
                return function(e) {
                  if (_this._dragStart || _this.options.disabled || _this.options.readonly) {
                    return;
                  }
                  e.preventDefault();
                  e.stopPropagation();
                  _this._dragStart = (e.pageX || e.originalEvent.touches[0].pageX) - parseInt(_this.$container.css("margin-left"), 10);
                  if (_this.options.animate) {
                    _this.$wrapper.removeClass("" + _this.options.baseClass + "-animate");
                  }
                  return _this.$element.trigger("focus.bootstrapSwitch");
                };
              })(this),
              "mousemove.bootstrapSwitch touchmove.bootstrapSwitch": (function(_this) {
                return function(e) {
                  var difference;
                  if (_this._dragStart == null) {
                    return;
                  }
                  e.preventDefault();
                  difference = (e.pageX || e.originalEvent.touches[0].pageX) - _this._dragStart;
                  if (difference < -_this._handleWidth || difference > 0) {
                    return;
                  }
                  _this._dragEnd = difference;
                  return _this.$container.css("margin-left", "" + _this._dragEnd + "px");
                };
              })(this),
              "mouseup.bootstrapSwitch touchend.bootstrapSwitch": (function(_this) {
                return function(e) {
                  var state;
                  if (!_this._dragStart) {
                    return;
                  }
                  e.preventDefault();
                  if (_this.options.animate) {
                    _this.$wrapper.addClass("" + _this.options.baseClass + "-animate");
                  }
                  if (_this._dragEnd) {
                    state = _this._dragEnd > -(_this._handleWidth / 2);
                    _this._dragEnd = false;
                    _this.state(_this.options.inverse ? !state : state);
                  } else {
                    _this.state(!_this.options.state);
                  }
                  return _this._dragStart = false;
                };
              })(this),
              "mouseleave.bootstrapSwitch": (function(_this) {
                return function(e) {
                  return _this.$label.trigger("mouseup.bootstrapSwitch");
                };
              })(this)
            });
          };
    
          BootstrapSwitch.prototype._externalLabelHandler = function() {
            var $externalLabel;
            $externalLabel = this.$element.closest("label");
            return $externalLabel.on("click", (function(_this) {
              return function(event) {
                event.preventDefault();
                event.stopImmediatePropagation();
                if (event.target === $externalLabel[0]) {
                  return _this.toggleState();
                }
              };
            })(this));
          };
    
          BootstrapSwitch.prototype._formHandler = function() {
            var $form;
            $form = this.$element.closest("form");
            if ($form.data("bootstrap-switch")) {
              return;
            }
            return $form.on("reset.bootstrapSwitch", function() {
              return window.setTimeout(function() {
                return $form.find("input").filter(function() {
                  return $(this).data("bootstrap-switch");
                }).each(function() {
                  return $(this).bootstrapSwitch("state", this.checked);
                });
              }, 1);
            }).data("bootstrap-switch", true);
          };
    
          BootstrapSwitch.prototype._getClasses = function(classes) {
            var c, cls, _i, _len;
            if (!$.isArray(classes)) {
              return ["" + this.options.baseClass + "-" + classes];
            }
            cls = [];
            for (_i = 0, _len = classes.length; _i < _len; _i++) {
              c = classes[_i];
              cls.push("" + this.options.baseClass + "-" + c);
            }
            return cls;
          };
    
          return BootstrapSwitch;
    
        })();
        $.fn.bootstrapSwitch = function() {
          var args, option, ret;
          option = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
          ret = this;
          this.each(function() {
            var $this, data;
            $this = $(this);
            data = $this.data("bootstrap-switch");
            if (!data) {
              $this.data("bootstrap-switch", data = new BootstrapSwitch(this, option));
            }
            if (typeof option === "string") {
              return ret = data[option].apply(data, args);
            }
          });
          return ret;
        };
        $.fn.bootstrapSwitch.Constructor = BootstrapSwitch;
        return $.fn.bootstrapSwitch.defaults = {
          state: true,
          size: null,
          animate: true,
          disabled: false,
          readonly: false,
          indeterminate: false,
          inverse: false,
          radioAllOff: false,
          onColor: "primary",
          offColor: "default",
          onText: "ON",
          offText: "OFF",
          labelText: "&nbsp;",
          handleWidth: "auto",
          labelWidth: "auto",
          baseClass: "bootstrap-switch",
          wrapperClass: "wrapper",
          onInit: function() {},
          onSwitchChange: function() {}
        };
      })(window.jQuery, window);
    
    }).call(this);
    
    //! moment.js
    //! version : 2.17.1
    //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
    //! license : MIT
    //! momentjs.com
    
    ;(function (global, factory) {
        typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
        global.moment = factory()
    }(this, (function () { 'use strict';
    
    var hookCallback;
    
    function hooks () {
        return hookCallback.apply(null, arguments);
    }
    
    // This is done to register the method called with moment()
    // without creating circular dependencies.
    function setHookCallback (callback) {
        hookCallback = callback;
    }
    
    function isArray(input) {
        return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
    }
    
    function isObject(input) {
        // IE8 will treat undefined and null as object if it wasn't for
        // input != null
        return input != null && Object.prototype.toString.call(input) === '[object Object]';
    }
    
    function isObjectEmpty(obj) {
        var k;
        for (k in obj) {
            // even if its not own property I'd still call it non-empty
            return false;
        }
        return true;
    }
    
    function isNumber(input) {
        return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
    }
    
    function isDate(input) {
        return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
    }
    
    function map(arr, fn) {
        var res = [], i;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }
    
    function hasOwnProp(a, b) {
        return Object.prototype.hasOwnProperty.call(a, b);
    }
    
    function extend(a, b) {
        for (var i in b) {
            if (hasOwnProp(b, i)) {
                a[i] = b[i];
            }
        }
    
        if (hasOwnProp(b, 'toString')) {
            a.toString = b.toString;
        }
    
        if (hasOwnProp(b, 'valueOf')) {
            a.valueOf = b.valueOf;
        }
    
        return a;
    }
    
    function createUTC (input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, true).utc();
    }
    
    function defaultParsingFlags() {
        // We need to deep clone this object.
        return {
            empty           : false,
            unusedTokens    : [],
            unusedInput     : [],
            overflow        : -2,
            charsLeftOver   : 0,
            nullInput       : false,
            invalidMonth    : null,
            invalidFormat   : false,
            userInvalidated : false,
            iso             : false,
            parsedDateParts : [],
            meridiem        : null
        };
    }
    
    function getParsingFlags(m) {
        if (m._pf == null) {
            m._pf = defaultParsingFlags();
        }
        return m._pf;
    }
    
    var some;
    if (Array.prototype.some) {
        some = Array.prototype.some;
    } else {
        some = function (fun) {
            var t = Object(this);
            var len = t.length >>> 0;
    
            for (var i = 0; i < len; i++) {
                if (i in t && fun.call(this, t[i], i, t)) {
                    return true;
                }
            }
    
            return false;
        };
    }
    
    var some$1 = some;
    
    function isValid(m) {
        if (m._isValid == null) {
            var flags = getParsingFlags(m);
            var parsedParts = some$1.call(flags.parsedDateParts, function (i) {
                return i != null;
            });
            var isNowValid = !isNaN(m._d.getTime()) &&
                flags.overflow < 0 &&
                !flags.empty &&
                !flags.invalidMonth &&
                !flags.invalidWeekday &&
                !flags.nullInput &&
                !flags.invalidFormat &&
                !flags.userInvalidated &&
                (!flags.meridiem || (flags.meridiem && parsedParts));
    
            if (m._strict) {
                isNowValid = isNowValid &&
                    flags.charsLeftOver === 0 &&
                    flags.unusedTokens.length === 0 &&
                    flags.bigHour === undefined;
            }
    
            if (Object.isFrozen == null || !Object.isFrozen(m)) {
                m._isValid = isNowValid;
            }
            else {
                return isNowValid;
            }
        }
        return m._isValid;
    }
    
    function createInvalid (flags) {
        var m = createUTC(NaN);
        if (flags != null) {
            extend(getParsingFlags(m), flags);
        }
        else {
            getParsingFlags(m).userInvalidated = true;
        }
    
        return m;
    }
    
    function isUndefined(input) {
        return input === void 0;
    }
    
    // Plugins that add properties should also add the key here (null value),
    // so we can properly clone ourselves.
    var momentProperties = hooks.momentProperties = [];
    
    function copyConfig(to, from) {
        var i, prop, val;
    
        if (!isUndefined(from._isAMomentObject)) {
            to._isAMomentObject = from._isAMomentObject;
        }
        if (!isUndefined(from._i)) {
            to._i = from._i;
        }
        if (!isUndefined(from._f)) {
            to._f = from._f;
        }
        if (!isUndefined(from._l)) {
            to._l = from._l;
        }
        if (!isUndefined(from._strict)) {
            to._strict = from._strict;
        }
        if (!isUndefined(from._tzm)) {
            to._tzm = from._tzm;
        }
        if (!isUndefined(from._isUTC)) {
            to._isUTC = from._isUTC;
        }
        if (!isUndefined(from._offset)) {
            to._offset = from._offset;
        }
        if (!isUndefined(from._pf)) {
            to._pf = getParsingFlags(from);
        }
        if (!isUndefined(from._locale)) {
            to._locale = from._locale;
        }
    
        if (momentProperties.length > 0) {
            for (i in momentProperties) {
                prop = momentProperties[i];
                val = from[prop];
                if (!isUndefined(val)) {
                    to[prop] = val;
                }
            }
        }
    
        return to;
    }
    
    var updateInProgress = false;
    
    // Moment prototype object
    function Moment(config) {
        copyConfig(this, config);
        this._d = new Date(config._d != null ? config._d.getTime() : NaN);
        if (!this.isValid()) {
            this._d = new Date(NaN);
        }
        // Prevent infinite loop in case updateOffset creates new moment
        // objects.
        if (updateInProgress === false) {
            updateInProgress = true;
            hooks.updateOffset(this);
            updateInProgress = false;
        }
    }
    
    function isMoment (obj) {
        return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
    }
    
    function absFloor (number) {
        if (number < 0) {
            // -0 -> 0
            return Math.ceil(number) || 0;
        } else {
            return Math.floor(number);
        }
    }
    
    function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion,
            value = 0;
    
        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
            value = absFloor(coercedNumber);
        }
    
        return value;
    }
    
    // compare two arrays, return the number of differences
    function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }
    
    function warn(msg) {
        if (hooks.suppressDeprecationWarnings === false &&
                (typeof console !==  'undefined') && console.warn) {
            console.warn('Deprecation warning: ' + msg);
        }
    }
    
    function deprecate(msg, fn) {
        var firstTime = true;
    
        return extend(function () {
            if (hooks.deprecationHandler != null) {
                hooks.deprecationHandler(null, msg);
            }
            if (firstTime) {
                var args = [];
                var arg;
                for (var i = 0; i < arguments.length; i++) {
                    arg = '';
                    if (typeof arguments[i] === 'object') {
                        arg += '\n[' + i + '] ';
                        for (var key in arguments[0]) {
                            arg += key + ': ' + arguments[0][key] + ', ';
                        }
                        arg = arg.slice(0, -2); // Remove trailing comma and space
                    } else {
                        arg = arguments[i];
                    }
                    args.push(arg);
                }
                warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
                firstTime = false;
            }
            return fn.apply(this, arguments);
        }, fn);
    }
    
    var deprecations = {};
    
    function deprecateSimple(name, msg) {
        if (hooks.deprecationHandler != null) {
            hooks.deprecationHandler(name, msg);
        }
        if (!deprecations[name]) {
            warn(msg);
            deprecations[name] = true;
        }
    }
    
    hooks.suppressDeprecationWarnings = false;
    hooks.deprecationHandler = null;
    
    function isFunction(input) {
        return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
    }
    
    function set (config) {
        var prop, i;
        for (i in config) {
            prop = config[i];
            if (isFunction(prop)) {
                this[i] = prop;
            } else {
                this['_' + i] = prop;
            }
        }
        this._config = config;
        // Lenient ordinal parsing accepts just a number in addition to
        // number + (possibly) stuff coming from _ordinalParseLenient.
        this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
    }
    
    function mergeConfigs(parentConfig, childConfig) {
        var res = extend({}, parentConfig), prop;
        for (prop in childConfig) {
            if (hasOwnProp(childConfig, prop)) {
                if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
                    res[prop] = {};
                    extend(res[prop], parentConfig[prop]);
                    extend(res[prop], childConfig[prop]);
                } else if (childConfig[prop] != null) {
                    res[prop] = childConfig[prop];
                } else {
                    delete res[prop];
                }
            }
        }
        for (prop in parentConfig) {
            if (hasOwnProp(parentConfig, prop) &&
                    !hasOwnProp(childConfig, prop) &&
                    isObject(parentConfig[prop])) {
                // make sure changes to properties don't modify parent config
                res[prop] = extend({}, res[prop]);
            }
        }
        return res;
    }
    
    function Locale(config) {
        if (config != null) {
            this.set(config);
        }
    }
    
    var keys;
    
    if (Object.keys) {
        keys = Object.keys;
    } else {
        keys = function (obj) {
            var i, res = [];
            for (i in obj) {
                if (hasOwnProp(obj, i)) {
                    res.push(i);
                }
            }
            return res;
        };
    }
    
    var keys$1 = keys;
    
    var defaultCalendar = {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    };
    
    function calendar (key, mom, now) {
        var output = this._calendar[key] || this._calendar['sameElse'];
        return isFunction(output) ? output.call(mom, now) : output;
    }
    
    var defaultLongDateFormat = {
        LTS  : 'h:mm:ss A',
        LT   : 'h:mm A',
        L    : 'MM/DD/YYYY',
        LL   : 'MMMM D, YYYY',
        LLL  : 'MMMM D, YYYY h:mm A',
        LLLL : 'dddd, MMMM D, YYYY h:mm A'
    };
    
    function longDateFormat (key) {
        var format = this._longDateFormat[key],
            formatUpper = this._longDateFormat[key.toUpperCase()];
    
        if (format || !formatUpper) {
            return format;
        }
    
        this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
            return val.slice(1);
        });
    
        return this._longDateFormat[key];
    }
    
    var defaultInvalidDate = 'Invalid date';
    
    function invalidDate () {
        return this._invalidDate;
    }
    
    var defaultOrdinal = '%d';
    var defaultOrdinalParse = /\d{1,2}/;
    
    function ordinal (number) {
        return this._ordinal.replace('%d', number);
    }
    
    var defaultRelativeTime = {
        future : 'in %s',
        past   : '%s ago',
        s  : 'a few seconds',
        m  : 'a minute',
        mm : '%d minutes',
        h  : 'an hour',
        hh : '%d hours',
        d  : 'a day',
        dd : '%d days',
        M  : 'a month',
        MM : '%d months',
        y  : 'a year',
        yy : '%d years'
    };
    
    function relativeTime (number, withoutSuffix, string, isFuture) {
        var output = this._relativeTime[string];
        return (isFunction(output)) ?
            output(number, withoutSuffix, string, isFuture) :
            output.replace(/%d/i, number);
    }
    
    function pastFuture (diff, output) {
        var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
        return isFunction(format) ? format(output) : format.replace(/%s/i, output);
    }
    
    var aliases = {};
    
    function addUnitAlias (unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
    }
    
    function normalizeUnits(units) {
        return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
    }
    
    function normalizeObjectUnits(inputObject) {
        var normalizedInput = {},
            normalizedProp,
            prop;
    
        for (prop in inputObject) {
            if (hasOwnProp(inputObject, prop)) {
                normalizedProp = normalizeUnits(prop);
                if (normalizedProp) {
                    normalizedInput[normalizedProp] = inputObject[prop];
                }
            }
        }
    
        return normalizedInput;
    }
    
    var priorities = {};
    
    function addUnitPriority(unit, priority) {
        priorities[unit] = priority;
    }
    
    function getPrioritizedUnits(unitsObj) {
        var units = [];
        for (var u in unitsObj) {
            units.push({unit: u, priority: priorities[u]});
        }
        units.sort(function (a, b) {
            return a.priority - b.priority;
        });
        return units;
    }
    
    function makeGetSet (unit, keepTime) {
        return function (value) {
            if (value != null) {
                set$1(this, unit, value);
                hooks.updateOffset(this, keepTime);
                return this;
            } else {
                return get(this, unit);
            }
        };
    }
    
    function get (mom, unit) {
        return mom.isValid() ?
            mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
    }
    
    function set$1 (mom, unit, value) {
        if (mom.isValid()) {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }
    
    // MOMENTS
    
    function stringGet (units) {
        units = normalizeUnits(units);
        if (isFunction(this[units])) {
            return this[units]();
        }
        return this;
    }
    
    
    function stringSet (units, value) {
        if (typeof units === 'object') {
            units = normalizeObjectUnits(units);
            var prioritized = getPrioritizedUnits(units);
            for (var i = 0; i < prioritized.length; i++) {
                this[prioritized[i].unit](units[prioritized[i].unit]);
            }
        } else {
            units = normalizeUnits(units);
            if (isFunction(this[units])) {
                return this[units](value);
            }
        }
        return this;
    }
    
    function zeroFill(number, targetLength, forceSign) {
        var absNumber = '' + Math.abs(number),
            zerosToFill = targetLength - absNumber.length,
            sign = number >= 0;
        return (sign ? (forceSign ? '+' : '') : '-') +
            Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
    }
    
    var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
    
    var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
    
    var formatFunctions = {};
    
    var formatTokenFunctions = {};
    
    // token:    'M'
    // padded:   ['MM', 2]
    // ordinal:  'Mo'
    // callback: function () { this.month() + 1 }
    function addFormatToken (token, padded, ordinal, callback) {
        var func = callback;
        if (typeof callback === 'string') {
            func = function () {
                return this[callback]();
            };
        }
        if (token) {
            formatTokenFunctions[token] = func;
        }
        if (padded) {
            formatTokenFunctions[padded[0]] = function () {
                return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
            };
        }
        if (ordinal) {
            formatTokenFunctions[ordinal] = function () {
                return this.localeData().ordinal(func.apply(this, arguments), token);
            };
        }
    }
    
    function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
            return input.replace(/^\[|\]$/g, '');
        }
        return input.replace(/\\/g, '');
    }
    
    function makeFormatFunction(format) {
        var array = format.match(formattingTokens), i, length;
    
        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }
    
        return function (mom) {
            var output = '', i;
            for (i = 0; i < length; i++) {
                output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
            }
            return output;
        };
    }
    
    // format date using native date object
    function formatMoment(m, format) {
        if (!m.isValid()) {
            return m.localeData().invalidDate();
        }
    
        format = expandFormat(format, m.localeData());
        formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
    
        return formatFunctions[format](m);
    }
    
    function expandFormat(format, locale) {
        var i = 5;
    
        function replaceLongDateFormatTokens(input) {
            return locale.longDateFormat(input) || input;
        }
    
        localFormattingTokens.lastIndex = 0;
        while (i >= 0 && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
            localFormattingTokens.lastIndex = 0;
            i -= 1;
        }
    
        return format;
    }
    
    var match1         = /\d/;            //       0 - 9
    var match2         = /\d\d/;          //      00 - 99
    var match3         = /\d{3}/;         //     000 - 999
    var match4         = /\d{4}/;         //    0000 - 9999
    var match6         = /[+-]?\d{6}/;    // -999999 - 999999
    var match1to2      = /\d\d?/;         //       0 - 99
    var match3to4      = /\d\d\d\d?/;     //     999 - 9999
    var match5to6      = /\d\d\d\d\d\d?/; //   99999 - 999999
    var match1to3      = /\d{1,3}/;       //       0 - 999
    var match1to4      = /\d{1,4}/;       //       0 - 9999
    var match1to6      = /[+-]?\d{1,6}/;  // -999999 - 999999
    
    var matchUnsigned  = /\d+/;           //       0 - inf
    var matchSigned    = /[+-]?\d+/;      //    -inf - inf
    
    var matchOffset    = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
    var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
    
    var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
    
    // any word (or two) characters or numbers including two/three word month in arabic.
    // includes scottish gaelic two word and hyphenated months
    var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
    
    
    var regexes = {};
    
    function addRegexToken (token, regex, strictRegex) {
        regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
            return (isStrict && strictRegex) ? strictRegex : regex;
        };
    }
    
    function getParseRegexForToken (token, config) {
        if (!hasOwnProp(regexes, token)) {
            return new RegExp(unescapeFormat(token));
        }
    
        return regexes[token](config._strict, config._locale);
    }
    
    // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    function unescapeFormat(s) {
        return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
            return p1 || p2 || p3 || p4;
        }));
    }
    
    function regexEscape(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }
    
    var tokens = {};
    
    function addParseToken (token, callback) {
        var i, func = callback;
        if (typeof token === 'string') {
            token = [token];
        }
        if (isNumber(callback)) {
            func = function (input, array) {
                array[callback] = toInt(input);
            };
        }
        for (i = 0; i < token.length; i++) {
            tokens[token[i]] = func;
        }
    }
    
    function addWeekParseToken (token, callback) {
        addParseToken(token, function (input, array, config, token) {
            config._w = config._w || {};
            callback(input, config._w, config, token);
        });
    }
    
    function addTimeToArrayFromToken(token, input, config) {
        if (input != null && hasOwnProp(tokens, token)) {
            tokens[token](input, config._a, config, token);
        }
    }
    
    var YEAR = 0;
    var MONTH = 1;
    var DATE = 2;
    var HOUR = 3;
    var MINUTE = 4;
    var SECOND = 5;
    var MILLISECOND = 6;
    var WEEK = 7;
    var WEEKDAY = 8;
    
    var indexOf;
    
    if (Array.prototype.indexOf) {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function (o) {
            // I know
            var i;
            for (i = 0; i < this.length; ++i) {
                if (this[i] === o) {
                    return i;
                }
            }
            return -1;
        };
    }
    
    var indexOf$1 = indexOf;
    
    function daysInMonth(year, month) {
        return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    }
    
    // FORMATTING
    
    addFormatToken('M', ['MM', 2], 'Mo', function () {
        return this.month() + 1;
    });
    
    addFormatToken('MMM', 0, 0, function (format) {
        return this.localeData().monthsShort(this, format);
    });
    
    addFormatToken('MMMM', 0, 0, function (format) {
        return this.localeData().months(this, format);
    });
    
    // ALIASES
    
    addUnitAlias('month', 'M');
    
    // PRIORITY
    
    addUnitPriority('month', 8);
    
    // PARSING
    
    addRegexToken('M',    match1to2);
    addRegexToken('MM',   match1to2, match2);
    addRegexToken('MMM',  function (isStrict, locale) {
        return locale.monthsShortRegex(isStrict);
    });
    addRegexToken('MMMM', function (isStrict, locale) {
        return locale.monthsRegex(isStrict);
    });
    
    addParseToken(['M', 'MM'], function (input, array) {
        array[MONTH] = toInt(input) - 1;
    });
    
    addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
        var month = config._locale.monthsParse(input, token, config._strict);
        // if we didn't find a month name, mark the date as invalid.
        if (month != null) {
            array[MONTH] = month;
        } else {
            getParsingFlags(config).invalidMonth = input;
        }
    });
    
    // LOCALES
    
    var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
    var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
    function localeMonths (m, format) {
        if (!m) {
            return this._months;
        }
        return isArray(this._months) ? this._months[m.month()] :
            this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
    }
    
    var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
    function localeMonthsShort (m, format) {
        if (!m) {
            return this._monthsShort;
        }
        return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
            this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
    }
    
    function handleStrictParse(monthName, format, strict) {
        var i, ii, mom, llc = monthName.toLocaleLowerCase();
        if (!this._monthsParse) {
            // this is not used
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
            for (i = 0; i < 12; ++i) {
                mom = createUTC([2000, i]);
                this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
                this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
            }
        }
    
        if (strict) {
            if (format === 'MMM') {
                ii = indexOf$1.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'MMM') {
                ii = indexOf$1.call(this._shortMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._longMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }
    
    function localeMonthsParse (monthName, format, strict) {
        var i, mom, regex;
    
        if (this._monthsParseExact) {
            return handleStrictParse.call(this, monthName, format, strict);
        }
    
        if (!this._monthsParse) {
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
        }
    
        // TODO: add sorting
        // Sorting makes sure if one month (or abbr) is a prefix of another
        // see sorting in computeMonthsParse
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, i]);
            if (strict && !this._longMonthsParse[i]) {
                this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
                this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
            }
            if (!strict && !this._monthsParse[i]) {
                regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
                return i;
            } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
                return i;
            } else if (!strict && this._monthsParse[i].test(monthName)) {
                return i;
            }
        }
    }
    
    // MOMENTS
    
    function setMonth (mom, value) {
        var dayOfMonth;
    
        if (!mom.isValid()) {
            // No op
            return mom;
        }
    
        if (typeof value === 'string') {
            if (/^\d+$/.test(value)) {
                value = toInt(value);
            } else {
                value = mom.localeData().monthsParse(value);
                // TODO: Another silent failure?
                if (!isNumber(value)) {
                    return mom;
                }
            }
        }
    
        dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        return mom;
    }
    
    function getSetMonth (value) {
        if (value != null) {
            setMonth(this, value);
            hooks.updateOffset(this, true);
            return this;
        } else {
            return get(this, 'Month');
        }
    }
    
    function getDaysInMonth () {
        return daysInMonth(this.year(), this.month());
    }
    
    var defaultMonthsShortRegex = matchWord;
    function monthsShortRegex (isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsShortStrictRegex;
            } else {
                return this._monthsShortRegex;
            }
        } else {
            if (!hasOwnProp(this, '_monthsShortRegex')) {
                this._monthsShortRegex = defaultMonthsShortRegex;
            }
            return this._monthsShortStrictRegex && isStrict ?
                this._monthsShortStrictRegex : this._monthsShortRegex;
        }
    }
    
    var defaultMonthsRegex = matchWord;
    function monthsRegex (isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsStrictRegex;
            } else {
                return this._monthsRegex;
            }
        } else {
            if (!hasOwnProp(this, '_monthsRegex')) {
                this._monthsRegex = defaultMonthsRegex;
            }
            return this._monthsStrictRegex && isStrict ?
                this._monthsStrictRegex : this._monthsRegex;
        }
    }
    
    function computeMonthsParse () {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }
    
        var shortPieces = [], longPieces = [], mixedPieces = [],
            i, mom;
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, i]);
            shortPieces.push(this.monthsShort(mom, ''));
            longPieces.push(this.months(mom, ''));
            mixedPieces.push(this.months(mom, ''));
            mixedPieces.push(this.monthsShort(mom, ''));
        }
        // Sorting makes sure if one month (or abbr) is a prefix of another it
        // will match the longer piece.
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 12; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
        }
        for (i = 0; i < 24; i++) {
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }
    
        this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._monthsShortRegex = this._monthsRegex;
        this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
    }
    
    // FORMATTING
    
    addFormatToken('Y', 0, 0, function () {
        var y = this.year();
        return y <= 9999 ? '' + y : '+' + y;
    });
    
    addFormatToken(0, ['YY', 2], 0, function () {
        return this.year() % 100;
    });
    
    addFormatToken(0, ['YYYY',   4],       0, 'year');
    addFormatToken(0, ['YYYYY',  5],       0, 'year');
    addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
    
    // ALIASES
    
    addUnitAlias('year', 'y');
    
    // PRIORITIES
    
    addUnitPriority('year', 1);
    
    // PARSING
    
    addRegexToken('Y',      matchSigned);
    addRegexToken('YY',     match1to2, match2);
    addRegexToken('YYYY',   match1to4, match4);
    addRegexToken('YYYYY',  match1to6, match6);
    addRegexToken('YYYYYY', match1to6, match6);
    
    addParseToken(['YYYYY', 'YYYYYY'], YEAR);
    addParseToken('YYYY', function (input, array) {
        array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
    });
    addParseToken('YY', function (input, array) {
        array[YEAR] = hooks.parseTwoDigitYear(input);
    });
    addParseToken('Y', function (input, array) {
        array[YEAR] = parseInt(input, 10);
    });
    
    // HELPERS
    
    function daysInYear(year) {
        return isLeapYear(year) ? 366 : 365;
    }
    
    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }
    
    // HOOKS
    
    hooks.parseTwoDigitYear = function (input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
    };
    
    // MOMENTS
    
    var getSetYear = makeGetSet('FullYear', true);
    
    function getIsLeapYear () {
        return isLeapYear(this.year());
    }
    
    function createDate (y, m, d, h, M, s, ms) {
        //can't just apply() to create a date:
        //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
        var date = new Date(y, m, d, h, M, s, ms);
    
        //the date constructor remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
            date.setFullYear(y);
        }
        return date;
    }
    
    function createUTCDate (y) {
        var date = new Date(Date.UTC.apply(null, arguments));
    
        //the Date.UTC function remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
            date.setUTCFullYear(y);
        }
        return date;
    }
    
    // start-of-first-week - start-of-year
    function firstWeekOffset(year, dow, doy) {
        var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
            fwd = 7 + dow - doy,
            // first-week day local weekday -- which local weekday is fwd
            fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
    
        return -fwdlw + fwd - 1;
    }
    
    //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
    function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
        var localWeekday = (7 + weekday - dow) % 7,
            weekOffset = firstWeekOffset(year, dow, doy),
            dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
            resYear, resDayOfYear;
    
        if (dayOfYear <= 0) {
            resYear = year - 1;
            resDayOfYear = daysInYear(resYear) + dayOfYear;
        } else if (dayOfYear > daysInYear(year)) {
            resYear = year + 1;
            resDayOfYear = dayOfYear - daysInYear(year);
        } else {
            resYear = year;
            resDayOfYear = dayOfYear;
        }
    
        return {
            year: resYear,
            dayOfYear: resDayOfYear
        };
    }
    
    function weekOfYear(mom, dow, doy) {
        var weekOffset = firstWeekOffset(mom.year(), dow, doy),
            week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
            resWeek, resYear;
    
        if (week < 1) {
            resYear = mom.year() - 1;
            resWeek = week + weeksInYear(resYear, dow, doy);
        } else if (week > weeksInYear(mom.year(), dow, doy)) {
            resWeek = week - weeksInYear(mom.year(), dow, doy);
            resYear = mom.year() + 1;
        } else {
            resYear = mom.year();
            resWeek = week;
        }
    
        return {
            week: resWeek,
            year: resYear
        };
    }
    
    function weeksInYear(year, dow, doy) {
        var weekOffset = firstWeekOffset(year, dow, doy),
            weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
        return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
    }
    
    // FORMATTING
    
    addFormatToken('w', ['ww', 2], 'wo', 'week');
    addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
    
    // ALIASES
    
    addUnitAlias('week', 'w');
    addUnitAlias('isoWeek', 'W');
    
    // PRIORITIES
    
    addUnitPriority('week', 5);
    addUnitPriority('isoWeek', 5);
    
    // PARSING
    
    addRegexToken('w',  match1to2);
    addRegexToken('ww', match1to2, match2);
    addRegexToken('W',  match1to2);
    addRegexToken('WW', match1to2, match2);
    
    addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
        week[token.substr(0, 1)] = toInt(input);
    });
    
    // HELPERS
    
    // LOCALES
    
    function localeWeek (mom) {
        return weekOfYear(mom, this._week.dow, this._week.doy).week;
    }
    
    var defaultLocaleWeek = {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    };
    
    function localeFirstDayOfWeek () {
        return this._week.dow;
    }
    
    function localeFirstDayOfYear () {
        return this._week.doy;
    }
    
    // MOMENTS
    
    function getSetWeek (input) {
        var week = this.localeData().week(this);
        return input == null ? week : this.add((input - week) * 7, 'd');
    }
    
    function getSetISOWeek (input) {
        var week = weekOfYear(this, 1, 4).week;
        return input == null ? week : this.add((input - week) * 7, 'd');
    }
    
    // FORMATTING
    
    addFormatToken('d', 0, 'do', 'day');
    
    addFormatToken('dd', 0, 0, function (format) {
        return this.localeData().weekdaysMin(this, format);
    });
    
    addFormatToken('ddd', 0, 0, function (format) {
        return this.localeData().weekdaysShort(this, format);
    });
    
    addFormatToken('dddd', 0, 0, function (format) {
        return this.localeData().weekdays(this, format);
    });
    
    addFormatToken('e', 0, 0, 'weekday');
    addFormatToken('E', 0, 0, 'isoWeekday');
    
    // ALIASES
    
    addUnitAlias('day', 'd');
    addUnitAlias('weekday', 'e');
    addUnitAlias('isoWeekday', 'E');
    
    // PRIORITY
    addUnitPriority('day', 11);
    addUnitPriority('weekday', 11);
    addUnitPriority('isoWeekday', 11);
    
    // PARSING
    
    addRegexToken('d',    match1to2);
    addRegexToken('e',    match1to2);
    addRegexToken('E',    match1to2);
    addRegexToken('dd',   function (isStrict, locale) {
        return locale.weekdaysMinRegex(isStrict);
    });
    addRegexToken('ddd',   function (isStrict, locale) {
        return locale.weekdaysShortRegex(isStrict);
    });
    addRegexToken('dddd',   function (isStrict, locale) {
        return locale.weekdaysRegex(isStrict);
    });
    
    addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
        var weekday = config._locale.weekdaysParse(input, token, config._strict);
        // if we didn't get a weekday name, mark the date as invalid
        if (weekday != null) {
            week.d = weekday;
        } else {
            getParsingFlags(config).invalidWeekday = input;
        }
    });
    
    addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
        week[token] = toInt(input);
    });
    
    // HELPERS
    
    function parseWeekday(input, locale) {
        if (typeof input !== 'string') {
            return input;
        }
    
        if (!isNaN(input)) {
            return parseInt(input, 10);
        }
    
        input = locale.weekdaysParse(input);
        if (typeof input === 'number') {
            return input;
        }
    
        return null;
    }
    
    function parseIsoWeekday(input, locale) {
        if (typeof input === 'string') {
            return locale.weekdaysParse(input) % 7 || 7;
        }
        return isNaN(input) ? null : input;
    }
    
    // LOCALES
    
    var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
    function localeWeekdays (m, format) {
        if (!m) {
            return this._weekdays;
        }
        return isArray(this._weekdays) ? this._weekdays[m.day()] :
            this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
    }
    
    var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
    function localeWeekdaysShort (m) {
        return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
    }
    
    var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
    function localeWeekdaysMin (m) {
        return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
    }
    
    function handleStrictParse$1(weekdayName, format, strict) {
        var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._minWeekdaysParse = [];
    
            for (i = 0; i < 7; ++i) {
                mom = createUTC([2000, 1]).day(i);
                this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
                this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
                this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
            }
        }
    
        if (strict) {
            if (format === 'dddd') {
                ii = indexOf$1.call(this._weekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'dddd') {
                ii = indexOf$1.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf$1.call(this._minWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf$1.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }
    
    function localeWeekdaysParse (weekdayName, format, strict) {
        var i, mom, regex;
    
        if (this._weekdaysParseExact) {
            return handleStrictParse$1.call(this, weekdayName, format, strict);
        }
    
        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._minWeekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._fullWeekdaysParse = [];
        }
    
        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already
    
            mom = createUTC([2000, 1]).day(i);
            if (strict && !this._fullWeekdaysParse[i]) {
                this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
                this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
                this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
            }
            if (!this._weekdaysParse[i]) {
                regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
                this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
                return i;
            }
        }
    }
    
    // MOMENTS
    
    function getSetDayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        if (input != null) {
            input = parseWeekday(input, this.localeData());
            return this.add(input - day, 'd');
        } else {
            return day;
        }
    }
    
    function getSetLocaleDayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
        return input == null ? weekday : this.add(input - weekday, 'd');
    }
    
    function getSetISODayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
    
        // behaves the same as moment#day except
        // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
        // as a setter, sunday should belong to the previous week.
    
        if (input != null) {
            var weekday = parseIsoWeekday(input, this.localeData());
            return this.day(this.day() % 7 ? weekday : weekday - 7);
        } else {
            return this.day() || 7;
        }
    }
    
    var defaultWeekdaysRegex = matchWord;
    function weekdaysRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysStrictRegex;
            } else {
                return this._weekdaysRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                this._weekdaysRegex = defaultWeekdaysRegex;
            }
            return this._weekdaysStrictRegex && isStrict ?
                this._weekdaysStrictRegex : this._weekdaysRegex;
        }
    }
    
    var defaultWeekdaysShortRegex = matchWord;
    function weekdaysShortRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysShortStrictRegex;
            } else {
                return this._weekdaysShortRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysShortRegex')) {
                this._weekdaysShortRegex = defaultWeekdaysShortRegex;
            }
            return this._weekdaysShortStrictRegex && isStrict ?
                this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
        }
    }
    
    var defaultWeekdaysMinRegex = matchWord;
    function weekdaysMinRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysMinStrictRegex;
            } else {
                return this._weekdaysMinRegex;
            }
        } else {
            if (!hasOwnProp(this, '_weekdaysMinRegex')) {
                this._weekdaysMinRegex = defaultWeekdaysMinRegex;
            }
            return this._weekdaysMinStrictRegex && isStrict ?
                this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
        }
    }
    
    
    function computeWeekdaysParse () {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }
    
        var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
            i, mom, minp, shortp, longp;
        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, 1]).day(i);
            minp = this.weekdaysMin(mom, '');
            shortp = this.weekdaysShort(mom, '');
            longp = this.weekdays(mom, '');
            minPieces.push(minp);
            shortPieces.push(shortp);
            longPieces.push(longp);
            mixedPieces.push(minp);
            mixedPieces.push(shortp);
            mixedPieces.push(longp);
        }
        // Sorting makes sure if one weekday (or abbr) is a prefix of another it
        // will match the longer piece.
        minPieces.sort(cmpLenRev);
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 7; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }
    
        this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._weekdaysShortRegex = this._weekdaysRegex;
        this._weekdaysMinRegex = this._weekdaysRegex;
    
        this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
        this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
    }
    
    // FORMATTING
    
    function hFormat() {
        return this.hours() % 12 || 12;
    }
    
    function kFormat() {
        return this.hours() || 24;
    }
    
    addFormatToken('H', ['HH', 2], 0, 'hour');
    addFormatToken('h', ['hh', 2], 0, hFormat);
    addFormatToken('k', ['kk', 2], 0, kFormat);
    
    addFormatToken('hmm', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
    });
    
    addFormatToken('hmmss', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
            zeroFill(this.seconds(), 2);
    });
    
    addFormatToken('Hmm', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2);
    });
    
    addFormatToken('Hmmss', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2) +
            zeroFill(this.seconds(), 2);
    });
    
    function meridiem (token, lowercase) {
        addFormatToken(token, 0, 0, function () {
            return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
        });
    }
    
    meridiem('a', true);
    meridiem('A', false);
    
    // ALIASES
    
    addUnitAlias('hour', 'h');
    
    // PRIORITY
    addUnitPriority('hour', 13);
    
    // PARSING
    
    function matchMeridiem (isStrict, locale) {
        return locale._meridiemParse;
    }
    
    addRegexToken('a',  matchMeridiem);
    addRegexToken('A',  matchMeridiem);
    addRegexToken('H',  match1to2);
    addRegexToken('h',  match1to2);
    addRegexToken('HH', match1to2, match2);
    addRegexToken('hh', match1to2, match2);
    
    addRegexToken('hmm', match3to4);
    addRegexToken('hmmss', match5to6);
    addRegexToken('Hmm', match3to4);
    addRegexToken('Hmmss', match5to6);
    
    addParseToken(['H', 'HH'], HOUR);
    addParseToken(['a', 'A'], function (input, array, config) {
        config._isPm = config._locale.isPM(input);
        config._meridiem = input;
    });
    addParseToken(['h', 'hh'], function (input, array, config) {
        array[HOUR] = toInt(input);
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('Hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
    });
    addParseToken('Hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
    });
    
    // LOCALES
    
    function localeIsPM (input) {
        // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
        // Using charAt should be more compatible.
        return ((input + '').toLowerCase().charAt(0) === 'p');
    }
    
    var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
    function localeMeridiem (hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'pm' : 'PM';
        } else {
            return isLower ? 'am' : 'AM';
        }
    }
    
    
    // MOMENTS
    
    // Setting the hour should keep the time, because the user explicitly
    // specified which hour he wants. So trying to maintain the same hour (in
    // a new timezone) makes sense. Adding/subtracting hours does not follow
    // this rule.
    var getSetHour = makeGetSet('Hours', true);
    
    // months
    // week
    // weekdays
    // meridiem
    var baseConfig = {
        calendar: defaultCalendar,
        longDateFormat: defaultLongDateFormat,
        invalidDate: defaultInvalidDate,
        ordinal: defaultOrdinal,
        ordinalParse: defaultOrdinalParse,
        relativeTime: defaultRelativeTime,
    
        months: defaultLocaleMonths,
        monthsShort: defaultLocaleMonthsShort,
    
        week: defaultLocaleWeek,
    
        weekdays: defaultLocaleWeekdays,
        weekdaysMin: defaultLocaleWeekdaysMin,
        weekdaysShort: defaultLocaleWeekdaysShort,
    
        meridiemParse: defaultLocaleMeridiemParse
    };
    
    // internal storage for locale config files
    var locales = {};
    var localeFamilies = {};
    var globalLocale;
    
    function normalizeLocale(key) {
        return key ? key.toLowerCase().replace('_', '-') : key;
    }
    
    // pick the locale from the array
    // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
    // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
    function chooseLocale(names) {
        var i = 0, j, next, locale, split;
    
        while (i < names.length) {
            split = normalizeLocale(names[i]).split('-');
            j = split.length;
            next = normalizeLocale(names[i + 1]);
            next = next ? next.split('-') : null;
            while (j > 0) {
                locale = loadLocale(split.slice(0, j).join('-'));
                if (locale) {
                    return locale;
                }
                if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return null;
    }
    
    function loadLocale(name) {
        var oldLocale = null;
        // TODO: Find a better way to register and load all the locales in Node
        if (!locales[name] && (typeof module !== 'undefined') &&
                module && module.exports) {
            try {
                oldLocale = globalLocale._abbr;
                require('./locale/' + name);
                // because defineLocale currently also sets the global locale, we
                // want to undo that for lazy loaded locales
                getSetGlobalLocale(oldLocale);
            } catch (e) { }
        }
        return locales[name];
    }
    
    // This function will load locale and then set the global locale.  If
    // no arguments are passed in, it will simply return the current global
    // locale key.
    function getSetGlobalLocale (key, values) {
        var data;
        if (key) {
            if (isUndefined(values)) {
                data = getLocale(key);
            }
            else {
                data = defineLocale(key, values);
            }
    
            if (data) {
                // moment.duration._locale = moment._locale = data;
                globalLocale = data;
            }
        }
    
        return globalLocale._abbr;
    }
    
    function defineLocale (name, config) {
        if (config !== null) {
            var parentConfig = baseConfig;
            config.abbr = name;
            if (locales[name] != null) {
                deprecateSimple('defineLocaleOverride',
                        'use moment.updateLocale(localeName, config) to change ' +
                        'an existing locale. moment.defineLocale(localeName, ' +
                        'config) should only be used for creating a new locale ' +
                        'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
                parentConfig = locales[name]._config;
            } else if (config.parentLocale != null) {
                if (locales[config.parentLocale] != null) {
                    parentConfig = locales[config.parentLocale]._config;
                } else {
                    if (!localeFamilies[config.parentLocale]) {
                        localeFamilies[config.parentLocale] = [];
                    }
                    localeFamilies[config.parentLocale].push({
                        name: name,
                        config: config
                    });
                    return null;
                }
            }
            locales[name] = new Locale(mergeConfigs(parentConfig, config));
    
            if (localeFamilies[name]) {
                localeFamilies[name].forEach(function (x) {
                    defineLocale(x.name, x.config);
                });
            }
    
            // backwards compat for now: also set the locale
            // make sure we set the locale AFTER all child locales have been
            // created, so we won't end up with the child locale set.
            getSetGlobalLocale(name);
    
    
            return locales[name];
        } else {
            // useful for testing
            delete locales[name];
            return null;
        }
    }
    
    function updateLocale(name, config) {
        if (config != null) {
            var locale, parentConfig = baseConfig;
            // MERGE
            if (locales[name] != null) {
                parentConfig = locales[name]._config;
            }
            config = mergeConfigs(parentConfig, config);
            locale = new Locale(config);
            locale.parentLocale = locales[name];
            locales[name] = locale;
    
            // backwards compat for now: also set the locale
            getSetGlobalLocale(name);
        } else {
            // pass null for config to unupdate, useful for tests
            if (locales[name] != null) {
                if (locales[name].parentLocale != null) {
                    locales[name] = locales[name].parentLocale;
                } else if (locales[name] != null) {
                    delete locales[name];
                }
            }
        }
        return locales[name];
    }
    
    // returns locale data
    function getLocale (key) {
        var locale;
    
        if (key && key._locale && key._locale._abbr) {
            key = key._locale._abbr;
        }
    
        if (!key) {
            return globalLocale;
        }
    
        if (!isArray(key)) {
            //short-circuit everything else
            locale = loadLocale(key);
            if (locale) {
                return locale;
            }
            key = [key];
        }
    
        return chooseLocale(key);
    }
    
    function listLocales() {
        return keys$1(locales);
    }
    
    function checkOverflow (m) {
        var overflow;
        var a = m._a;
    
        if (a && getParsingFlags(m).overflow === -2) {
            overflow =
                a[MONTH]       < 0 || a[MONTH]       > 11  ? MONTH :
                a[DATE]        < 1 || a[DATE]        > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
                a[HOUR]        < 0 || a[HOUR]        > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
                a[MINUTE]      < 0 || a[MINUTE]      > 59  ? MINUTE :
                a[SECOND]      < 0 || a[SECOND]      > 59  ? SECOND :
                a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
                -1;
    
            if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
                overflow = DATE;
            }
            if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
                overflow = WEEK;
            }
            if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
                overflow = WEEKDAY;
            }
    
            getParsingFlags(m).overflow = overflow;
        }
    
        return m;
    }
    
    // iso 8601 regex
    // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
    var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
    var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
    
    var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
    
    var isoDates = [
        ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
        ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
        ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
        ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
        ['YYYY-DDD', /\d{4}-\d{3}/],
        ['YYYY-MM', /\d{4}-\d\d/, false],
        ['YYYYYYMMDD', /[+-]\d{10}/],
        ['YYYYMMDD', /\d{8}/],
        // YYYYMM is NOT allowed by the standard
        ['GGGG[W]WWE', /\d{4}W\d{3}/],
        ['GGGG[W]WW', /\d{4}W\d{2}/, false],
        ['YYYYDDD', /\d{7}/]
    ];
    
    // iso time formats and regexes
    var isoTimes = [
        ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
        ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
        ['HH:mm:ss', /\d\d:\d\d:\d\d/],
        ['HH:mm', /\d\d:\d\d/],
        ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
        ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
        ['HHmmss', /\d\d\d\d\d\d/],
        ['HHmm', /\d\d\d\d/],
        ['HH', /\d\d/]
    ];
    
    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
    
    // date from iso format
    function configFromISO(config) {
        var i, l,
            string = config._i,
            match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
            allowTime, dateFormat, timeFormat, tzFormat;
    
        if (match) {
            getParsingFlags(config).iso = true;
    
            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(match[1])) {
                    dateFormat = isoDates[i][0];
                    allowTime = isoDates[i][2] !== false;
                    break;
                }
            }
            if (dateFormat == null) {
                config._isValid = false;
                return;
            }
            if (match[3]) {
                for (i = 0, l = isoTimes.length; i < l; i++) {
                    if (isoTimes[i][1].exec(match[3])) {
                        // match[2] should be 'T' or space
                        timeFormat = (match[2] || ' ') + isoTimes[i][0];
                        break;
                    }
                }
                if (timeFormat == null) {
                    config._isValid = false;
                    return;
                }
            }
            if (!allowTime && timeFormat != null) {
                config._isValid = false;
                return;
            }
            if (match[4]) {
                if (tzRegex.exec(match[4])) {
                    tzFormat = 'Z';
                } else {
                    config._isValid = false;
                    return;
                }
            }
            config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
            configFromStringAndFormat(config);
        } else {
            config._isValid = false;
        }
    }
    
    // date from iso format or fallback
    function configFromString(config) {
        var matched = aspNetJsonRegex.exec(config._i);
    
        if (matched !== null) {
            config._d = new Date(+matched[1]);
            return;
        }
    
        configFromISO(config);
        if (config._isValid === false) {
            delete config._isValid;
            hooks.createFromInputFallback(config);
        }
    }
    
    hooks.createFromInputFallback = deprecate(
        'value provided is not in a recognized ISO format. moment construction falls back to js Date(), ' +
        'which is not reliable across all browsers and versions. Non ISO date formats are ' +
        'discouraged and will be removed in an upcoming major release. Please refer to ' +
        'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
        function (config) {
            config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
        }
    );
    
    // Pick the first defined of two or three arguments.
    function defaults(a, b, c) {
        if (a != null) {
            return a;
        }
        if (b != null) {
            return b;
        }
        return c;
    }
    
    function currentDateArray(config) {
        // hooks is actually the exported moment object
        var nowValue = new Date(hooks.now());
        if (config._useUTC) {
            return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
        }
        return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
    }
    
    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function configFromArray (config) {
        var i, date, input = [], currentDate, yearToUse;
    
        if (config._d) {
            return;
        }
    
        currentDate = currentDateArray(config);
    
        //compute day of the year from weeks and weekdays
        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
            dayOfYearFromWeekInfo(config);
        }
    
        //if the day of the year is set, figure out what it is
        if (config._dayOfYear) {
            yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
    
            if (config._dayOfYear > daysInYear(yearToUse)) {
                getParsingFlags(config)._overflowDayOfYear = true;
            }
    
            date = createUTCDate(yearToUse, 0, config._dayOfYear);
            config._a[MONTH] = date.getUTCMonth();
            config._a[DATE] = date.getUTCDate();
        }
    
        // Default to current date.
        // * if no year, month, day of month are given, default to today
        // * if day of month is given, default month and year
        // * if month is given, default only year
        // * if year is given, don't default anything
        for (i = 0; i < 3 && config._a[i] == null; ++i) {
            config._a[i] = input[i] = currentDate[i];
        }
    
        // Zero out whatever was not defaulted, including time
        for (; i < 7; i++) {
            config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
        }
    
        // Check for 24:00:00.000
        if (config._a[HOUR] === 24 &&
                config._a[MINUTE] === 0 &&
                config._a[SECOND] === 0 &&
                config._a[MILLISECOND] === 0) {
            config._nextDay = true;
            config._a[HOUR] = 0;
        }
    
        config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
        // Apply timezone offset from input. The actual utcOffset can be changed
        // with parseZone.
        if (config._tzm != null) {
            config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
        }
    
        if (config._nextDay) {
            config._a[HOUR] = 24;
        }
    }
    
    function dayOfYearFromWeekInfo(config) {
        var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
    
        w = config._w;
        if (w.GG != null || w.W != null || w.E != null) {
            dow = 1;
            doy = 4;
    
            // TODO: We need to take the current isoWeekYear, but that depends on
            // how we interpret now (local, utc, fixed offset). So create
            // a now version of current config (take local/utc/offset flags, and
            // create now).
            weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
            week = defaults(w.W, 1);
            weekday = defaults(w.E, 1);
            if (weekday < 1 || weekday > 7) {
                weekdayOverflow = true;
            }
        } else {
            dow = config._locale._week.dow;
            doy = config._locale._week.doy;
    
            var curWeek = weekOfYear(createLocal(), dow, doy);
    
            weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
    
            // Default to current week.
            week = defaults(w.w, curWeek.week);
    
            if (w.d != null) {
                // weekday -- low day numbers are considered next week
                weekday = w.d;
                if (weekday < 0 || weekday > 6) {
                    weekdayOverflow = true;
                }
            } else if (w.e != null) {
                // local weekday -- counting starts from begining of week
                weekday = w.e + dow;
                if (w.e < 0 || w.e > 6) {
                    weekdayOverflow = true;
                }
            } else {
                // default to begining of week
                weekday = dow;
            }
        }
        if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
            getParsingFlags(config)._overflowWeeks = true;
        } else if (weekdayOverflow != null) {
            getParsingFlags(config)._overflowWeekday = true;
        } else {
            temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
            config._a[YEAR] = temp.year;
            config._dayOfYear = temp.dayOfYear;
        }
    }
    
    // constant that refers to the ISO standard
    hooks.ISO_8601 = function () {};
    
    // date from string and format string
    function configFromStringAndFormat(config) {
        // TODO: Move this to another part of the creation flow to prevent circular deps
        if (config._f === hooks.ISO_8601) {
            configFromISO(config);
            return;
        }
    
        config._a = [];
        getParsingFlags(config).empty = true;
    
        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var string = '' + config._i,
            i, parsedInput, tokens, token, skipped,
            stringLength = string.length,
            totalParsedInputLength = 0;
    
        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
    
        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            // console.log('token', token, 'parsedInput', parsedInput,
            //         'regex', getParseRegexForToken(token, config));
            if (parsedInput) {
                skipped = string.substr(0, string.indexOf(parsedInput));
                if (skipped.length > 0) {
                    getParsingFlags(config).unusedInput.push(skipped);
                }
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
                totalParsedInputLength += parsedInput.length;
            }
            // don't parse if it's not a known token
            if (formatTokenFunctions[token]) {
                if (parsedInput) {
                    getParsingFlags(config).empty = false;
                }
                else {
                    getParsingFlags(config).unusedTokens.push(token);
                }
                addTimeToArrayFromToken(token, parsedInput, config);
            }
            else if (config._strict && !parsedInput) {
                getParsingFlags(config).unusedTokens.push(token);
            }
        }
    
        // add remaining unparsed input length to the string
        getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
            getParsingFlags(config).unusedInput.push(string);
        }
    
        // clear _12h flag if hour is <= 12
        if (config._a[HOUR] <= 12 &&
            getParsingFlags(config).bigHour === true &&
            config._a[HOUR] > 0) {
            getParsingFlags(config).bigHour = undefined;
        }
    
        getParsingFlags(config).parsedDateParts = config._a.slice(0);
        getParsingFlags(config).meridiem = config._meridiem;
        // handle meridiem
        config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
    
        configFromArray(config);
        checkOverflow(config);
    }
    
    
    function meridiemFixWrap (locale, hour, meridiem) {
        var isPm;
    
        if (meridiem == null) {
            // nothing to do
            return hour;
        }
        if (locale.meridiemHour != null) {
            return locale.meridiemHour(hour, meridiem);
        } else if (locale.isPM != null) {
            // Fallback
            isPm = locale.isPM(meridiem);
            if (isPm && hour < 12) {
                hour += 12;
            }
            if (!isPm && hour === 12) {
                hour = 0;
            }
            return hour;
        } else {
            // this is not supposed to happen
            return hour;
        }
    }
    
    // date from string and array of format strings
    function configFromStringAndArray(config) {
        var tempConfig,
            bestMoment,
    
            scoreToBeat,
            i,
            currentScore;
    
        if (config._f.length === 0) {
            getParsingFlags(config).invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }
    
        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._f = config._f[i];
            configFromStringAndFormat(tempConfig);
    
            if (!isValid(tempConfig)) {
                continue;
            }
    
            // if there is any input that was not parsed add a penalty for that format
            currentScore += getParsingFlags(tempConfig).charsLeftOver;
    
            //or tokens
            currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
    
            getParsingFlags(tempConfig).score = currentScore;
    
            if (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }
    
        extend(config, bestMoment || tempConfig);
    }
    
    function configFromObject(config) {
        if (config._d) {
            return;
        }
    
        var i = normalizeObjectUnits(config._i);
        config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
            return obj && parseInt(obj, 10);
        });
    
        configFromArray(config);
    }
    
    function createFromConfig (config) {
        var res = new Moment(checkOverflow(prepareConfig(config)));
        if (res._nextDay) {
            // Adding is smart enough around DST
            res.add(1, 'd');
            res._nextDay = undefined;
        }
    
        return res;
    }
    
    function prepareConfig (config) {
        var input = config._i,
            format = config._f;
    
        config._locale = config._locale || getLocale(config._l);
    
        if (input === null || (format === undefined && input === '')) {
            return createInvalid({nullInput: true});
        }
    
        if (typeof input === 'string') {
            config._i = input = config._locale.preparse(input);
        }
    
        if (isMoment(input)) {
            return new Moment(checkOverflow(input));
        } else if (isDate(input)) {
            config._d = input;
        } else if (isArray(format)) {
            configFromStringAndArray(config);
        } else if (format) {
            configFromStringAndFormat(config);
        }  else {
            configFromInput(config);
        }
    
        if (!isValid(config)) {
            config._d = null;
        }
    
        return config;
    }
    
    function configFromInput(config) {
        var input = config._i;
        if (input === undefined) {
            config._d = new Date(hooks.now());
        } else if (isDate(input)) {
            config._d = new Date(input.valueOf());
        } else if (typeof input === 'string') {
            configFromString(config);
        } else if (isArray(input)) {
            config._a = map(input.slice(0), function (obj) {
                return parseInt(obj, 10);
            });
            configFromArray(config);
        } else if (typeof(input) === 'object') {
            configFromObject(config);
        } else if (isNumber(input)) {
            // from milliseconds
            config._d = new Date(input);
        } else {
            hooks.createFromInputFallback(config);
        }
    }
    
    function createLocalOrUTC (input, format, locale, strict, isUTC) {
        var c = {};
    
        if (locale === true || locale === false) {
            strict = locale;
            locale = undefined;
        }
    
        if ((isObject(input) && isObjectEmpty(input)) ||
                (isArray(input) && input.length === 0)) {
            input = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c._isAMomentObject = true;
        c._useUTC = c._isUTC = isUTC;
        c._l = locale;
        c._i = input;
        c._f = format;
        c._strict = strict;
    
        return createFromConfig(c);
    }
    
    function createLocal (input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, false);
    }
    
    var prototypeMin = deprecate(
        'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
        function () {
            var other = createLocal.apply(null, arguments);
            if (this.isValid() && other.isValid()) {
                return other < this ? this : other;
            } else {
                return createInvalid();
            }
        }
    );
    
    var prototypeMax = deprecate(
        'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
        function () {
            var other = createLocal.apply(null, arguments);
            if (this.isValid() && other.isValid()) {
                return other > this ? this : other;
            } else {
                return createInvalid();
            }
        }
    );
    
    // Pick a moment m from moments so that m[fn](other) is true for all
    // other. This relies on the function fn to be transitive.
    //
    // moments should either be an array of moment objects or an array, whose
    // first element is an array of moment objects.
    function pickBy(fn, moments) {
        var res, i;
        if (moments.length === 1 && isArray(moments[0])) {
            moments = moments[0];
        }
        if (!moments.length) {
            return createLocal();
        }
        res = moments[0];
        for (i = 1; i < moments.length; ++i) {
            if (!moments[i].isValid() || moments[i][fn](res)) {
                res = moments[i];
            }
        }
        return res;
    }
    
    // TODO: Use [].sort instead?
    function min () {
        var args = [].slice.call(arguments, 0);
    
        return pickBy('isBefore', args);
    }
    
    function max () {
        var args = [].slice.call(arguments, 0);
    
        return pickBy('isAfter', args);
    }
    
    var now = function () {
        return Date.now ? Date.now() : +(new Date());
    };
    
    function Duration (duration) {
        var normalizedInput = normalizeObjectUnits(duration),
            years = normalizedInput.year || 0,
            quarters = normalizedInput.quarter || 0,
            months = normalizedInput.month || 0,
            weeks = normalizedInput.week || 0,
            days = normalizedInput.day || 0,
            hours = normalizedInput.hour || 0,
            minutes = normalizedInput.minute || 0,
            seconds = normalizedInput.second || 0,
            milliseconds = normalizedInput.millisecond || 0;
    
        // representation for dateAddRemove
        this._milliseconds = +milliseconds +
            seconds * 1e3 + // 1000
            minutes * 6e4 + // 1000 * 60
            hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = +days +
            weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = +months +
            quarters * 3 +
            years * 12;
    
        this._data = {};
    
        this._locale = getLocale();
    
        this._bubble();
    }
    
    function isDuration (obj) {
        return obj instanceof Duration;
    }
    
    function absRound (number) {
        if (number < 0) {
            return Math.round(-1 * number) * -1;
        } else {
            return Math.round(number);
        }
    }
    
    // FORMATTING
    
    function offset (token, separator) {
        addFormatToken(token, 0, 0, function () {
            var offset = this.utcOffset();
            var sign = '+';
            if (offset < 0) {
                offset = -offset;
                sign = '-';
            }
            return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
        });
    }
    
    offset('Z', ':');
    offset('ZZ', '');
    
    // PARSING
    
    addRegexToken('Z',  matchShortOffset);
    addRegexToken('ZZ', matchShortOffset);
    addParseToken(['Z', 'ZZ'], function (input, array, config) {
        config._useUTC = true;
        config._tzm = offsetFromString(matchShortOffset, input);
    });
    
    // HELPERS
    
    // timezone chunker
    // '+10:00' > ['10',  '00']
    // '-1530'  > ['-15', '30']
    var chunkOffset = /([\+\-]|\d\d)/gi;
    
    function offsetFromString(matcher, string) {
        var matches = (string || '').match(matcher);
    
        if (matches === null) {
            return null;
        }
    
        var chunk   = matches[matches.length - 1] || [];
        var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
        var minutes = +(parts[1] * 60) + toInt(parts[2]);
    
        return minutes === 0 ?
          0 :
          parts[0] === '+' ? minutes : -minutes;
    }
    
    // Return a moment from input, that is local/utc/zone equivalent to model.
    function cloneWithOffset(input, model) {
        var res, diff;
        if (model._isUTC) {
            res = model.clone();
            diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
            // Use low-level api, because this fn is low-level api.
            res._d.setTime(res._d.valueOf() + diff);
            hooks.updateOffset(res, false);
            return res;
        } else {
            return createLocal(input).local();
        }
    }
    
    function getDateOffset (m) {
        // On Firefox.24 Date#getTimezoneOffset returns a floating point.
        // https://github.com/moment/moment/pull/1871
        return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
    }
    
    // HOOKS
    
    // This function will be called whenever a moment is mutated.
    // It is intended to keep the offset in sync with the timezone.
    hooks.updateOffset = function () {};
    
    // MOMENTS
    
    // keepLocalTime = true means only change the timezone, without
    // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
    // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
    // +0200, so we adjust the time as needed, to be valid.
    //
    // Keeping the time actually adds/subtracts (one hour)
    // from the actual represented time. That is why we call updateOffset
    // a second time. In case it wants us to change the offset again
    // _changeInProgress == true case, then we have to adjust, because
    // there is no such time in the given timezone.
    function getSetOffset (input, keepLocalTime) {
        var offset = this._offset || 0,
            localAdjust;
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        if (input != null) {
            if (typeof input === 'string') {
                input = offsetFromString(matchShortOffset, input);
                if (input === null) {
                    return this;
                }
            } else if (Math.abs(input) < 16) {
                input = input * 60;
            }
            if (!this._isUTC && keepLocalTime) {
                localAdjust = getDateOffset(this);
            }
            this._offset = input;
            this._isUTC = true;
            if (localAdjust != null) {
                this.add(localAdjust, 'm');
            }
            if (offset !== input) {
                if (!keepLocalTime || this._changeInProgress) {
                    addSubtract(this, createDuration(input - offset, 'm'), 1, false);
                } else if (!this._changeInProgress) {
                    this._changeInProgress = true;
                    hooks.updateOffset(this, true);
                    this._changeInProgress = null;
                }
            }
            return this;
        } else {
            return this._isUTC ? offset : getDateOffset(this);
        }
    }
    
    function getSetZone (input, keepLocalTime) {
        if (input != null) {
            if (typeof input !== 'string') {
                input = -input;
            }
    
            this.utcOffset(input, keepLocalTime);
    
            return this;
        } else {
            return -this.utcOffset();
        }
    }
    
    function setOffsetToUTC (keepLocalTime) {
        return this.utcOffset(0, keepLocalTime);
    }
    
    function setOffsetToLocal (keepLocalTime) {
        if (this._isUTC) {
            this.utcOffset(0, keepLocalTime);
            this._isUTC = false;
    
            if (keepLocalTime) {
                this.subtract(getDateOffset(this), 'm');
            }
        }
        return this;
    }
    
    function setOffsetToParsedOffset () {
        if (this._tzm != null) {
            this.utcOffset(this._tzm);
        } else if (typeof this._i === 'string') {
            var tZone = offsetFromString(matchOffset, this._i);
            if (tZone != null) {
                this.utcOffset(tZone);
            }
            else {
                this.utcOffset(0, true);
            }
        }
        return this;
    }
    
    function hasAlignedHourOffset (input) {
        if (!this.isValid()) {
            return false;
        }
        input = input ? createLocal(input).utcOffset() : 0;
    
        return (this.utcOffset() - input) % 60 === 0;
    }
    
    function isDaylightSavingTime () {
        return (
            this.utcOffset() > this.clone().month(0).utcOffset() ||
            this.utcOffset() > this.clone().month(5).utcOffset()
        );
    }
    
    function isDaylightSavingTimeShifted () {
        if (!isUndefined(this._isDSTShifted)) {
            return this._isDSTShifted;
        }
    
        var c = {};
    
        copyConfig(c, this);
        c = prepareConfig(c);
    
        if (c._a) {
            var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
            this._isDSTShifted = this.isValid() &&
                compareArrays(c._a, other.toArray()) > 0;
        } else {
            this._isDSTShifted = false;
        }
    
        return this._isDSTShifted;
    }
    
    function isLocal () {
        return this.isValid() ? !this._isUTC : false;
    }
    
    function isUtcOffset () {
        return this.isValid() ? this._isUTC : false;
    }
    
    function isUtc () {
        return this.isValid() ? this._isUTC && this._offset === 0 : false;
    }
    
    // ASP.NET json date format regex
    var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
    
    // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
    // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
    // and further modified to allow for strings containing both week and day
    var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
    
    function createDuration (input, key) {
        var duration = input,
            // matching against regexp is expensive, do it on demand
            match = null,
            sign,
            ret,
            diffRes;
    
        if (isDuration(input)) {
            duration = {
                ms : input._milliseconds,
                d  : input._days,
                M  : input._months
            };
        } else if (isNumber(input)) {
            duration = {};
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        } else if (!!(match = aspNetRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y  : 0,
                d  : toInt(match[DATE])                         * sign,
                h  : toInt(match[HOUR])                         * sign,
                m  : toInt(match[MINUTE])                       * sign,
                s  : toInt(match[SECOND])                       * sign,
                ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
            };
        } else if (!!(match = isoRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y : parseIso(match[2], sign),
                M : parseIso(match[3], sign),
                w : parseIso(match[4], sign),
                d : parseIso(match[5], sign),
                h : parseIso(match[6], sign),
                m : parseIso(match[7], sign),
                s : parseIso(match[8], sign)
            };
        } else if (duration == null) {// checks for null or undefined
            duration = {};
        } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
            diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
    
            duration = {};
            duration.ms = diffRes.milliseconds;
            duration.M = diffRes.months;
        }
    
        ret = new Duration(duration);
    
        if (isDuration(input) && hasOwnProp(input, '_locale')) {
            ret._locale = input._locale;
        }
    
        return ret;
    }
    
    createDuration.fn = Duration.prototype;
    
    function parseIso (inp, sign) {
        // We'd normally use ~~inp for this, but unfortunately it also
        // converts floats to ints.
        // inp may be undefined, so careful calling replace on it.
        var res = inp && parseFloat(inp.replace(',', '.'));
        // apply sign while we're at it
        return (isNaN(res) ? 0 : res) * sign;
    }
    
    function positiveMomentsDifference(base, other) {
        var res = {milliseconds: 0, months: 0};
    
        res.months = other.month() - base.month() +
            (other.year() - base.year()) * 12;
        if (base.clone().add(res.months, 'M').isAfter(other)) {
            --res.months;
        }
    
        res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
    
        return res;
    }
    
    function momentsDifference(base, other) {
        var res;
        if (!(base.isValid() && other.isValid())) {
            return {milliseconds: 0, months: 0};
        }
    
        other = cloneWithOffset(other, base);
        if (base.isBefore(other)) {
            res = positiveMomentsDifference(base, other);
        } else {
            res = positiveMomentsDifference(other, base);
            res.milliseconds = -res.milliseconds;
            res.months = -res.months;
        }
    
        return res;
    }
    
    // TODO: remove 'name' arg after deprecation is removed
    function createAdder(direction, name) {
        return function (val, period) {
            var dur, tmp;
            //invert the arguments, but complain about it
            if (period !== null && !isNaN(+period)) {
                deprecateSimple(name, 'moment().' + name  + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
                'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
                tmp = val; val = period; period = tmp;
            }
    
            val = typeof val === 'string' ? +val : val;
            dur = createDuration(val, period);
            addSubtract(this, dur, direction);
            return this;
        };
    }
    
    function addSubtract (mom, duration, isAdding, updateOffset) {
        var milliseconds = duration._milliseconds,
            days = absRound(duration._days),
            months = absRound(duration._months);
    
        if (!mom.isValid()) {
            // No op
            return;
        }
    
        updateOffset = updateOffset == null ? true : updateOffset;
    
        if (milliseconds) {
            mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
        }
        if (days) {
            set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
        }
        if (months) {
            setMonth(mom, get(mom, 'Month') + months * isAdding);
        }
        if (updateOffset) {
            hooks.updateOffset(mom, days || months);
        }
    }
    
    var add      = createAdder(1, 'add');
    var subtract = createAdder(-1, 'subtract');
    
    function getCalendarFormat(myMoment, now) {
        var diff = myMoment.diff(now, 'days', true);
        return diff < -6 ? 'sameElse' :
                diff < -1 ? 'lastWeek' :
                diff < 0 ? 'lastDay' :
                diff < 1 ? 'sameDay' :
                diff < 2 ? 'nextDay' :
                diff < 7 ? 'nextWeek' : 'sameElse';
    }
    
    function calendar$1 (time, formats) {
        // We want to compare the start of today, vs this.
        // Getting start-of-today depends on whether we're local/utc/offset or not.
        var now = time || createLocal(),
            sod = cloneWithOffset(now, this).startOf('day'),
            format = hooks.calendarFormat(this, sod) || 'sameElse';
    
        var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
    
        return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
    }
    
    function clone () {
        return new Moment(this);
    }
    
    function isAfter (input, units) {
        var localInput = isMoment(input) ? input : createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() > localInput.valueOf();
        } else {
            return localInput.valueOf() < this.clone().startOf(units).valueOf();
        }
    }
    
    function isBefore (input, units) {
        var localInput = isMoment(input) ? input : createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() < localInput.valueOf();
        } else {
            return this.clone().endOf(units).valueOf() < localInput.valueOf();
        }
    }
    
    function isBetween (from, to, units, inclusivity) {
        inclusivity = inclusivity || '()';
        return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
            (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
    }
    
    function isSame (input, units) {
        var localInput = isMoment(input) ? input : createLocal(input),
            inputMs;
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(units || 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() === localInput.valueOf();
        } else {
            inputMs = localInput.valueOf();
            return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
        }
    }
    
    function isSameOrAfter (input, units) {
        return this.isSame(input, units) || this.isAfter(input,units);
    }
    
    function isSameOrBefore (input, units) {
        return this.isSame(input, units) || this.isBefore(input,units);
    }
    
    function diff (input, units, asFloat) {
        var that,
            zoneDelta,
            delta, output;
    
        if (!this.isValid()) {
            return NaN;
        }
    
        that = cloneWithOffset(input, this);
    
        if (!that.isValid()) {
            return NaN;
        }
    
        zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
    
        units = normalizeUnits(units);
    
        if (units === 'year' || units === 'month' || units === 'quarter') {
            output = monthDiff(this, that);
            if (units === 'quarter') {
                output = output / 3;
            } else if (units === 'year') {
                output = output / 12;
            }
        } else {
            delta = this - that;
            output = units === 'second' ? delta / 1e3 : // 1000
                units === 'minute' ? delta / 6e4 : // 1000 * 60
                units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
                units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
                units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
                delta;
        }
        return asFloat ? output : absFloor(output);
    }
    
    function monthDiff (a, b) {
        // difference in months
        var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
            // b is in (anchor - 1 month, anchor + 1 month)
            anchor = a.clone().add(wholeMonthDiff, 'months'),
            anchor2, adjust;
    
        if (b - anchor < 0) {
            anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor - anchor2);
        } else {
            anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor2 - anchor);
        }
    
        //check for negative zero, return zero if negative zero
        return -(wholeMonthDiff + adjust) || 0;
    }
    
    hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
    hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
    
    function toString () {
        return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
    }
    
    function toISOString () {
        var m = this.clone().utc();
        if (0 < m.year() && m.year() <= 9999) {
            if (isFunction(Date.prototype.toISOString)) {
                // native implementation is ~50x faster, use it when we can
                return this.toDate().toISOString();
            } else {
                return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            }
        } else {
            return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
        }
    }
    
    /**
     * Return a human readable representation of a moment that can
     * also be evaluated to get a new moment which is the same
     *
     * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
     */
    function inspect () {
        if (!this.isValid()) {
            return 'moment.invalid(/* ' + this._i + ' */)';
        }
        var func = 'moment';
        var zone = '';
        if (!this.isLocal()) {
            func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
            zone = 'Z';
        }
        var prefix = '[' + func + '("]';
        var year = (0 < this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
        var datetime = '-MM-DD[T]HH:mm:ss.SSS';
        var suffix = zone + '[")]';
    
        return this.format(prefix + year + datetime + suffix);
    }
    
    function format (inputString) {
        if (!inputString) {
            inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
        }
        var output = formatMoment(this, inputString);
        return this.localeData().postformat(output);
    }
    
    function from (time, withoutSuffix) {
        if (this.isValid() &&
                ((isMoment(time) && time.isValid()) ||
                 createLocal(time).isValid())) {
            return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }
    
    function fromNow (withoutSuffix) {
        return this.from(createLocal(), withoutSuffix);
    }
    
    function to (time, withoutSuffix) {
        if (this.isValid() &&
                ((isMoment(time) && time.isValid()) ||
                 createLocal(time).isValid())) {
            return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }
    
    function toNow (withoutSuffix) {
        return this.to(createLocal(), withoutSuffix);
    }
    
    // If passed a locale key, it will set the locale for this
    // instance.  Otherwise, it will return the locale configuration
    // variables for this instance.
    function locale (key) {
        var newLocaleData;
    
        if (key === undefined) {
            return this._locale._abbr;
        } else {
            newLocaleData = getLocale(key);
            if (newLocaleData != null) {
                this._locale = newLocaleData;
            }
            return this;
        }
    }
    
    var lang = deprecate(
        'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
        function (key) {
            if (key === undefined) {
                return this.localeData();
            } else {
                return this.locale(key);
            }
        }
    );
    
    function localeData () {
        return this._locale;
    }
    
    function startOf (units) {
        units = normalizeUnits(units);
        // the following switch intentionally omits break keywords
        // to utilize falling through the cases.
        switch (units) {
            case 'year':
                this.month(0);
                /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
                /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
            case 'date':
                this.hours(0);
                /* falls through */
            case 'hour':
                this.minutes(0);
                /* falls through */
            case 'minute':
                this.seconds(0);
                /* falls through */
            case 'second':
                this.milliseconds(0);
        }
    
        // weeks are a special case
        if (units === 'week') {
            this.weekday(0);
        }
        if (units === 'isoWeek') {
            this.isoWeekday(1);
        }
    
        // quarters are also special
        if (units === 'quarter') {
            this.month(Math.floor(this.month() / 3) * 3);
        }
    
        return this;
    }
    
    function endOf (units) {
        units = normalizeUnits(units);
        if (units === undefined || units === 'millisecond') {
            return this;
        }
    
        // 'date' is an alias for 'day', so it should be considered as such.
        if (units === 'date') {
            units = 'day';
        }
    
        return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
    }
    
    function valueOf () {
        return this._d.valueOf() - ((this._offset || 0) * 60000);
    }
    
    function unix () {
        return Math.floor(this.valueOf() / 1000);
    }
    
    function toDate () {
        return new Date(this.valueOf());
    }
    
    function toArray () {
        var m = this;
        return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
    }
    
    function toObject () {
        var m = this;
        return {
            years: m.year(),
            months: m.month(),
            date: m.date(),
            hours: m.hours(),
            minutes: m.minutes(),
            seconds: m.seconds(),
            milliseconds: m.milliseconds()
        };
    }
    
    function toJSON () {
        // new Date(NaN).toJSON() === null
        return this.isValid() ? this.toISOString() : null;
    }
    
    function isValid$1 () {
        return isValid(this);
    }
    
    function parsingFlags () {
        return extend({}, getParsingFlags(this));
    }
    
    function invalidAt () {
        return getParsingFlags(this).overflow;
    }
    
    function creationData() {
        return {
            input: this._i,
            format: this._f,
            locale: this._locale,
            isUTC: this._isUTC,
            strict: this._strict
        };
    }
    
    // FORMATTING
    
    addFormatToken(0, ['gg', 2], 0, function () {
        return this.weekYear() % 100;
    });
    
    addFormatToken(0, ['GG', 2], 0, function () {
        return this.isoWeekYear() % 100;
    });
    
    function addWeekYearFormatToken (token, getter) {
        addFormatToken(0, [token, token.length], 0, getter);
    }
    
    addWeekYearFormatToken('gggg',     'weekYear');
    addWeekYearFormatToken('ggggg',    'weekYear');
    addWeekYearFormatToken('GGGG',  'isoWeekYear');
    addWeekYearFormatToken('GGGGG', 'isoWeekYear');
    
    // ALIASES
    
    addUnitAlias('weekYear', 'gg');
    addUnitAlias('isoWeekYear', 'GG');
    
    // PRIORITY
    
    addUnitPriority('weekYear', 1);
    addUnitPriority('isoWeekYear', 1);
    
    
    // PARSING
    
    addRegexToken('G',      matchSigned);
    addRegexToken('g',      matchSigned);
    addRegexToken('GG',     match1to2, match2);
    addRegexToken('gg',     match1to2, match2);
    addRegexToken('GGGG',   match1to4, match4);
    addRegexToken('gggg',   match1to4, match4);
    addRegexToken('GGGGG',  match1to6, match6);
    addRegexToken('ggggg',  match1to6, match6);
    
    addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
        week[token.substr(0, 2)] = toInt(input);
    });
    
    addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
        week[token] = hooks.parseTwoDigitYear(input);
    });
    
    // MOMENTS
    
    function getSetWeekYear (input) {
        return getSetWeekYearHelper.call(this,
                input,
                this.week(),
                this.weekday(),
                this.localeData()._week.dow,
                this.localeData()._week.doy);
    }
    
    function getSetISOWeekYear (input) {
        return getSetWeekYearHelper.call(this,
                input, this.isoWeek(), this.isoWeekday(), 1, 4);
    }
    
    function getISOWeeksInYear () {
        return weeksInYear(this.year(), 1, 4);
    }
    
    function getWeeksInYear () {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
    }
    
    function getSetWeekYearHelper(input, week, weekday, dow, doy) {
        var weeksTarget;
        if (input == null) {
            return weekOfYear(this, dow, doy).year;
        } else {
            weeksTarget = weeksInYear(input, dow, doy);
            if (week > weeksTarget) {
                week = weeksTarget;
            }
            return setWeekAll.call(this, input, week, weekday, dow, doy);
        }
    }
    
    function setWeekAll(weekYear, week, weekday, dow, doy) {
        var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
            date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
    
        this.year(date.getUTCFullYear());
        this.month(date.getUTCMonth());
        this.date(date.getUTCDate());
        return this;
    }
    
    // FORMATTING
    
    addFormatToken('Q', 0, 'Qo', 'quarter');
    
    // ALIASES
    
    addUnitAlias('quarter', 'Q');
    
    // PRIORITY
    
    addUnitPriority('quarter', 7);
    
    // PARSING
    
    addRegexToken('Q', match1);
    addParseToken('Q', function (input, array) {
        array[MONTH] = (toInt(input) - 1) * 3;
    });
    
    // MOMENTS
    
    function getSetQuarter (input) {
        return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
    }
    
    // FORMATTING
    
    addFormatToken('D', ['DD', 2], 'Do', 'date');
    
    // ALIASES
    
    addUnitAlias('date', 'D');
    
    // PRIOROITY
    addUnitPriority('date', 9);
    
    // PARSING
    
    addRegexToken('D',  match1to2);
    addRegexToken('DD', match1to2, match2);
    addRegexToken('Do', function (isStrict, locale) {
        return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
    });
    
    addParseToken(['D', 'DD'], DATE);
    addParseToken('Do', function (input, array) {
        array[DATE] = toInt(input.match(match1to2)[0], 10);
    });
    
    // MOMENTS
    
    var getSetDayOfMonth = makeGetSet('Date', true);
    
    // FORMATTING
    
    addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
    
    // ALIASES
    
    addUnitAlias('dayOfYear', 'DDD');
    
    // PRIORITY
    addUnitPriority('dayOfYear', 4);
    
    // PARSING
    
    addRegexToken('DDD',  match1to3);
    addRegexToken('DDDD', match3);
    addParseToken(['DDD', 'DDDD'], function (input, array, config) {
        config._dayOfYear = toInt(input);
    });
    
    // HELPERS
    
    // MOMENTS
    
    function getSetDayOfYear (input) {
        var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
        return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
    }
    
    // FORMATTING
    
    addFormatToken('m', ['mm', 2], 0, 'minute');
    
    // ALIASES
    
    addUnitAlias('minute', 'm');
    
    // PRIORITY
    
    addUnitPriority('minute', 14);
    
    // PARSING
    
    addRegexToken('m',  match1to2);
    addRegexToken('mm', match1to2, match2);
    addParseToken(['m', 'mm'], MINUTE);
    
    // MOMENTS
    
    var getSetMinute = makeGetSet('Minutes', false);
    
    // FORMATTING
    
    addFormatToken('s', ['ss', 2], 0, 'second');
    
    // ALIASES
    
    addUnitAlias('second', 's');
    
    // PRIORITY
    
    addUnitPriority('second', 15);
    
    // PARSING
    
    addRegexToken('s',  match1to2);
    addRegexToken('ss', match1to2, match2);
    addParseToken(['s', 'ss'], SECOND);
    
    // MOMENTS
    
    var getSetSecond = makeGetSet('Seconds', false);
    
    // FORMATTING
    
    addFormatToken('S', 0, 0, function () {
        return ~~(this.millisecond() / 100);
    });
    
    addFormatToken(0, ['SS', 2], 0, function () {
        return ~~(this.millisecond() / 10);
    });
    
    addFormatToken(0, ['SSS', 3], 0, 'millisecond');
    addFormatToken(0, ['SSSS', 4], 0, function () {
        return this.millisecond() * 10;
    });
    addFormatToken(0, ['SSSSS', 5], 0, function () {
        return this.millisecond() * 100;
    });
    addFormatToken(0, ['SSSSSS', 6], 0, function () {
        return this.millisecond() * 1000;
    });
    addFormatToken(0, ['SSSSSSS', 7], 0, function () {
        return this.millisecond() * 10000;
    });
    addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
        return this.millisecond() * 100000;
    });
    addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
        return this.millisecond() * 1000000;
    });
    
    
    // ALIASES
    
    addUnitAlias('millisecond', 'ms');
    
    // PRIORITY
    
    addUnitPriority('millisecond', 16);
    
    // PARSING
    
    addRegexToken('S',    match1to3, match1);
    addRegexToken('SS',   match1to3, match2);
    addRegexToken('SSS',  match1to3, match3);
    
    var token;
    for (token = 'SSSS'; token.length <= 9; token += 'S') {
        addRegexToken(token, matchUnsigned);
    }
    
    function parseMs(input, array) {
        array[MILLISECOND] = toInt(('0.' + input) * 1000);
    }
    
    for (token = 'S'; token.length <= 9; token += 'S') {
        addParseToken(token, parseMs);
    }
    // MOMENTS
    
    var getSetMillisecond = makeGetSet('Milliseconds', false);
    
    // FORMATTING
    
    addFormatToken('z',  0, 0, 'zoneAbbr');
    addFormatToken('zz', 0, 0, 'zoneName');
    
    // MOMENTS
    
    function getZoneAbbr () {
        return this._isUTC ? 'UTC' : '';
    }
    
    function getZoneName () {
        return this._isUTC ? 'Coordinated Universal Time' : '';
    }
    
    var proto = Moment.prototype;
    
    proto.add               = add;
    proto.calendar          = calendar$1;
    proto.clone             = clone;
    proto.diff              = diff;
    proto.endOf             = endOf;
    proto.format            = format;
    proto.from              = from;
    proto.fromNow           = fromNow;
    proto.to                = to;
    proto.toNow             = toNow;
    proto.get               = stringGet;
    proto.invalidAt         = invalidAt;
    proto.isAfter           = isAfter;
    proto.isBefore          = isBefore;
    proto.isBetween         = isBetween;
    proto.isSame            = isSame;
    proto.isSameOrAfter     = isSameOrAfter;
    proto.isSameOrBefore    = isSameOrBefore;
    proto.isValid           = isValid$1;
    proto.lang              = lang;
    proto.locale            = locale;
    proto.localeData        = localeData;
    proto.max               = prototypeMax;
    proto.min               = prototypeMin;
    proto.parsingFlags      = parsingFlags;
    proto.set               = stringSet;
    proto.startOf           = startOf;
    proto.subtract          = subtract;
    proto.toArray           = toArray;
    proto.toObject          = toObject;
    proto.toDate            = toDate;
    proto.toISOString       = toISOString;
    proto.inspect           = inspect;
    proto.toJSON            = toJSON;
    proto.toString          = toString;
    proto.unix              = unix;
    proto.valueOf           = valueOf;
    proto.creationData      = creationData;
    
    // Year
    proto.year       = getSetYear;
    proto.isLeapYear = getIsLeapYear;
    
    // Week Year
    proto.weekYear    = getSetWeekYear;
    proto.isoWeekYear = getSetISOWeekYear;
    
    // Quarter
    proto.quarter = proto.quarters = getSetQuarter;
    
    // Month
    proto.month       = getSetMonth;
    proto.daysInMonth = getDaysInMonth;
    
    // Week
    proto.week           = proto.weeks        = getSetWeek;
    proto.isoWeek        = proto.isoWeeks     = getSetISOWeek;
    proto.weeksInYear    = getWeeksInYear;
    proto.isoWeeksInYear = getISOWeeksInYear;
    
    // Day
    proto.date       = getSetDayOfMonth;
    proto.day        = proto.days             = getSetDayOfWeek;
    proto.weekday    = getSetLocaleDayOfWeek;
    proto.isoWeekday = getSetISODayOfWeek;
    proto.dayOfYear  = getSetDayOfYear;
    
    // Hour
    proto.hour = proto.hours = getSetHour;
    
    // Minute
    proto.minute = proto.minutes = getSetMinute;
    
    // Second
    proto.second = proto.seconds = getSetSecond;
    
    // Millisecond
    proto.millisecond = proto.milliseconds = getSetMillisecond;
    
    // Offset
    proto.utcOffset            = getSetOffset;
    proto.utc                  = setOffsetToUTC;
    proto.local                = setOffsetToLocal;
    proto.parseZone            = setOffsetToParsedOffset;
    proto.hasAlignedHourOffset = hasAlignedHourOffset;
    proto.isDST                = isDaylightSavingTime;
    proto.isLocal              = isLocal;
    proto.isUtcOffset          = isUtcOffset;
    proto.isUtc                = isUtc;
    proto.isUTC                = isUtc;
    
    // Timezone
    proto.zoneAbbr = getZoneAbbr;
    proto.zoneName = getZoneName;
    
    // Deprecations
    proto.dates  = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
    proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
    proto.years  = deprecate('years accessor is deprecated. Use year instead', getSetYear);
    proto.zone   = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
    proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
    
    function createUnix (input) {
        return createLocal(input * 1000);
    }
    
    function createInZone () {
        return createLocal.apply(null, arguments).parseZone();
    }
    
    function preParsePostFormat (string) {
        return string;
    }
    
    var proto$1 = Locale.prototype;
    
    proto$1.calendar        = calendar;
    proto$1.longDateFormat  = longDateFormat;
    proto$1.invalidDate     = invalidDate;
    proto$1.ordinal         = ordinal;
    proto$1.preparse        = preParsePostFormat;
    proto$1.postformat      = preParsePostFormat;
    proto$1.relativeTime    = relativeTime;
    proto$1.pastFuture      = pastFuture;
    proto$1.set             = set;
    
    // Month
    proto$1.months            =        localeMonths;
    proto$1.monthsShort       =        localeMonthsShort;
    proto$1.monthsParse       =        localeMonthsParse;
    proto$1.monthsRegex       = monthsRegex;
    proto$1.monthsShortRegex  = monthsShortRegex;
    
    // Week
    proto$1.week = localeWeek;
    proto$1.firstDayOfYear = localeFirstDayOfYear;
    proto$1.firstDayOfWeek = localeFirstDayOfWeek;
    
    // Day of Week
    proto$1.weekdays       =        localeWeekdays;
    proto$1.weekdaysMin    =        localeWeekdaysMin;
    proto$1.weekdaysShort  =        localeWeekdaysShort;
    proto$1.weekdaysParse  =        localeWeekdaysParse;
    
    proto$1.weekdaysRegex       =        weekdaysRegex;
    proto$1.weekdaysShortRegex  =        weekdaysShortRegex;
    proto$1.weekdaysMinRegex    =        weekdaysMinRegex;
    
    // Hours
    proto$1.isPM = localeIsPM;
    proto$1.meridiem = localeMeridiem;
    
    function get$1 (format, index, field, setter) {
        var locale = getLocale();
        var utc = createUTC().set(setter, index);
        return locale[field](utc, format);
    }
    
    function listMonthsImpl (format, index, field) {
        if (isNumber(format)) {
            index = format;
            format = undefined;
        }
    
        format = format || '';
    
        if (index != null) {
            return get$1(format, index, field, 'month');
        }
    
        var i;
        var out = [];
        for (i = 0; i < 12; i++) {
            out[i] = get$1(format, i, field, 'month');
        }
        return out;
    }
    
    // ()
    // (5)
    // (fmt, 5)
    // (fmt)
    // (true)
    // (true, 5)
    // (true, fmt, 5)
    // (true, fmt)
    function listWeekdaysImpl (localeSorted, format, index, field) {
        if (typeof localeSorted === 'boolean') {
            if (isNumber(format)) {
                index = format;
                format = undefined;
            }
    
            format = format || '';
        } else {
            format = localeSorted;
            index = format;
            localeSorted = false;
    
            if (isNumber(format)) {
                index = format;
                format = undefined;
            }
    
            format = format || '';
        }
    
        var locale = getLocale(),
            shift = localeSorted ? locale._week.dow : 0;
    
        if (index != null) {
            return get$1(format, (index + shift) % 7, field, 'day');
        }
    
        var i;
        var out = [];
        for (i = 0; i < 7; i++) {
            out[i] = get$1(format, (i + shift) % 7, field, 'day');
        }
        return out;
    }
    
    function listMonths (format, index) {
        return listMonthsImpl(format, index, 'months');
    }
    
    function listMonthsShort (format, index) {
        return listMonthsImpl(format, index, 'monthsShort');
    }
    
    function listWeekdays (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
    }
    
    function listWeekdaysShort (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
    }
    
    function listWeekdaysMin (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
    }
    
    getSetGlobalLocale('en', {
        ordinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal : function (number) {
            var b = number % 10,
                output = (toInt(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });
    
    // Side effect imports
    hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
    hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
    
    var mathAbs = Math.abs;
    
    function abs () {
        var data           = this._data;
    
        this._milliseconds = mathAbs(this._milliseconds);
        this._days         = mathAbs(this._days);
        this._months       = mathAbs(this._months);
    
        data.milliseconds  = mathAbs(data.milliseconds);
        data.seconds       = mathAbs(data.seconds);
        data.minutes       = mathAbs(data.minutes);
        data.hours         = mathAbs(data.hours);
        data.months        = mathAbs(data.months);
        data.years         = mathAbs(data.years);
    
        return this;
    }
    
    function addSubtract$1 (duration, input, value, direction) {
        var other = createDuration(input, value);
    
        duration._milliseconds += direction * other._milliseconds;
        duration._days         += direction * other._days;
        duration._months       += direction * other._months;
    
        return duration._bubble();
    }
    
    // supports only 2.0-style add(1, 's') or add(duration)
    function add$1 (input, value) {
        return addSubtract$1(this, input, value, 1);
    }
    
    // supports only 2.0-style subtract(1, 's') or subtract(duration)
    function subtract$1 (input, value) {
        return addSubtract$1(this, input, value, -1);
    }
    
    function absCeil (number) {
        if (number < 0) {
            return Math.floor(number);
        } else {
            return Math.ceil(number);
        }
    }
    
    function bubble () {
        var milliseconds = this._milliseconds;
        var days         = this._days;
        var months       = this._months;
        var data         = this._data;
        var seconds, minutes, hours, years, monthsFromDays;
    
        // if we have a mix of positive and negative values, bubble down first
        // check: https://github.com/moment/moment/issues/2166
        if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
                (milliseconds <= 0 && days <= 0 && months <= 0))) {
            milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
            days = 0;
            months = 0;
        }
    
        // The following code bubbles up values, see the tests for
        // examples of what that means.
        data.milliseconds = milliseconds % 1000;
    
        seconds           = absFloor(milliseconds / 1000);
        data.seconds      = seconds % 60;
    
        minutes           = absFloor(seconds / 60);
        data.minutes      = minutes % 60;
    
        hours             = absFloor(minutes / 60);
        data.hours        = hours % 24;
    
        days += absFloor(hours / 24);
    
        // convert days to months
        monthsFromDays = absFloor(daysToMonths(days));
        months += monthsFromDays;
        days -= absCeil(monthsToDays(monthsFromDays));
    
        // 12 months -> 1 year
        years = absFloor(months / 12);
        months %= 12;
    
        data.days   = days;
        data.months = months;
        data.years  = years;
    
        return this;
    }
    
    function daysToMonths (days) {
        // 400 years have 146097 days (taking into account leap year rules)
        // 400 years have 12 months === 4800
        return days * 4800 / 146097;
    }
    
    function monthsToDays (months) {
        // the reverse of daysToMonths
        return months * 146097 / 4800;
    }
    
    function as (units) {
        var days;
        var months;
        var milliseconds = this._milliseconds;
    
        units = normalizeUnits(units);
    
        if (units === 'month' || units === 'year') {
            days   = this._days   + milliseconds / 864e5;
            months = this._months + daysToMonths(days);
            return units === 'month' ? months : months / 12;
        } else {
            // handle milliseconds separately because of floating point math errors (issue #1867)
            days = this._days + Math.round(monthsToDays(this._months));
            switch (units) {
                case 'week'   : return days / 7     + milliseconds / 6048e5;
                case 'day'    : return days         + milliseconds / 864e5;
                case 'hour'   : return days * 24    + milliseconds / 36e5;
                case 'minute' : return days * 1440  + milliseconds / 6e4;
                case 'second' : return days * 86400 + milliseconds / 1000;
                // Math.floor prevents floating point math errors here
                case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
                default: throw new Error('Unknown unit ' + units);
            }
        }
    }
    
    // TODO: Use this.as('ms')?
    function valueOf$1 () {
        return (
            this._milliseconds +
            this._days * 864e5 +
            (this._months % 12) * 2592e6 +
            toInt(this._months / 12) * 31536e6
        );
    }
    
    function makeAs (alias) {
        return function () {
            return this.as(alias);
        };
    }
    
    var asMilliseconds = makeAs('ms');
    var asSeconds      = makeAs('s');
    var asMinutes      = makeAs('m');
    var asHours        = makeAs('h');
    var asDays         = makeAs('d');
    var asWeeks        = makeAs('w');
    var asMonths       = makeAs('M');
    var asYears        = makeAs('y');
    
    function get$2 (units) {
        units = normalizeUnits(units);
        return this[units + 's']();
    }
    
    function makeGetter(name) {
        return function () {
            return this._data[name];
        };
    }
    
    var milliseconds = makeGetter('milliseconds');
    var seconds      = makeGetter('seconds');
    var minutes      = makeGetter('minutes');
    var hours        = makeGetter('hours');
    var days         = makeGetter('days');
    var months       = makeGetter('months');
    var years        = makeGetter('years');
    
    function weeks () {
        return absFloor(this.days() / 7);
    }
    
    var round = Math.round;
    var thresholds = {
        s: 45,  // seconds to minute
        m: 45,  // minutes to hour
        h: 22,  // hours to day
        d: 26,  // days to month
        M: 11   // months to year
    };
    
    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
        return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }
    
    function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
        var duration = createDuration(posNegDuration).abs();
        var seconds  = round(duration.as('s'));
        var minutes  = round(duration.as('m'));
        var hours    = round(duration.as('h'));
        var days     = round(duration.as('d'));
        var months   = round(duration.as('M'));
        var years    = round(duration.as('y'));
    
        var a = seconds < thresholds.s && ['s', seconds]  ||
                minutes <= 1           && ['m']           ||
                minutes < thresholds.m && ['mm', minutes] ||
                hours   <= 1           && ['h']           ||
                hours   < thresholds.h && ['hh', hours]   ||
                days    <= 1           && ['d']           ||
                days    < thresholds.d && ['dd', days]    ||
                months  <= 1           && ['M']           ||
                months  < thresholds.M && ['MM', months]  ||
                years   <= 1           && ['y']           || ['yy', years];
    
        a[2] = withoutSuffix;
        a[3] = +posNegDuration > 0;
        a[4] = locale;
        return substituteTimeAgo.apply(null, a);
    }
    
    // This function allows you to set the rounding function for relative time strings
    function getSetRelativeTimeRounding (roundingFunction) {
        if (roundingFunction === undefined) {
            return round;
        }
        if (typeof(roundingFunction) === 'function') {
            round = roundingFunction;
            return true;
        }
        return false;
    }
    
    // This function allows you to set a threshold for relative time strings
    function getSetRelativeTimeThreshold (threshold, limit) {
        if (thresholds[threshold] === undefined) {
            return false;
        }
        if (limit === undefined) {
            return thresholds[threshold];
        }
        thresholds[threshold] = limit;
        return true;
    }
    
    function humanize (withSuffix) {
        var locale = this.localeData();
        var output = relativeTime$1(this, !withSuffix, locale);
    
        if (withSuffix) {
            output = locale.pastFuture(+this, output);
        }
    
        return locale.postformat(output);
    }
    
    var abs$1 = Math.abs;
    
    function toISOString$1() {
        // for ISO strings we do not use the normal bubbling rules:
        //  * milliseconds bubble up until they become hours
        //  * days do not bubble at all
        //  * months bubble up until they become years
        // This is because there is no context-free conversion between hours and days
        // (think of clock changes)
        // and also not between days and months (28-31 days per month)
        var seconds = abs$1(this._milliseconds) / 1000;
        var days         = abs$1(this._days);
        var months       = abs$1(this._months);
        var minutes, hours, years;
    
        // 3600 seconds -> 60 minutes -> 1 hour
        minutes           = absFloor(seconds / 60);
        hours             = absFloor(minutes / 60);
        seconds %= 60;
        minutes %= 60;
    
        // 12 months -> 1 year
        years  = absFloor(months / 12);
        months %= 12;
    
    
        // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
        var Y = years;
        var M = months;
        var D = days;
        var h = hours;
        var m = minutes;
        var s = seconds;
        var total = this.asSeconds();
    
        if (!total) {
            // this is the same as C#'s (Noda) and python (isodate)...
            // but not other JS (goog.date)
            return 'P0D';
        }
    
        return (total < 0 ? '-' : '') +
            'P' +
            (Y ? Y + 'Y' : '') +
            (M ? M + 'M' : '') +
            (D ? D + 'D' : '') +
            ((h || m || s) ? 'T' : '') +
            (h ? h + 'H' : '') +
            (m ? m + 'M' : '') +
            (s ? s + 'S' : '');
    }
    
    var proto$2 = Duration.prototype;
    
    proto$2.abs            = abs;
    proto$2.add            = add$1;
    proto$2.subtract       = subtract$1;
    proto$2.as             = as;
    proto$2.asMilliseconds = asMilliseconds;
    proto$2.asSeconds      = asSeconds;
    proto$2.asMinutes      = asMinutes;
    proto$2.asHours        = asHours;
    proto$2.asDays         = asDays;
    proto$2.asWeeks        = asWeeks;
    proto$2.asMonths       = asMonths;
    proto$2.asYears        = asYears;
    proto$2.valueOf        = valueOf$1;
    proto$2._bubble        = bubble;
    proto$2.get            = get$2;
    proto$2.milliseconds   = milliseconds;
    proto$2.seconds        = seconds;
    proto$2.minutes        = minutes;
    proto$2.hours          = hours;
    proto$2.days           = days;
    proto$2.weeks          = weeks;
    proto$2.months         = months;
    proto$2.years          = years;
    proto$2.humanize       = humanize;
    proto$2.toISOString    = toISOString$1;
    proto$2.toString       = toISOString$1;
    proto$2.toJSON         = toISOString$1;
    proto$2.locale         = locale;
    proto$2.localeData     = localeData;
    
    // Deprecations
    proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
    proto$2.lang = lang;
    
    // Side effect imports
    
    // FORMATTING
    
    addFormatToken('X', 0, 0, 'unix');
    addFormatToken('x', 0, 0, 'valueOf');
    
    // PARSING
    
    addRegexToken('x', matchSigned);
    addRegexToken('X', matchTimestamp);
    addParseToken('X', function (input, array, config) {
        config._d = new Date(parseFloat(input, 10) * 1000);
    });
    addParseToken('x', function (input, array, config) {
        config._d = new Date(toInt(input));
    });
    
    // Side effect imports
    
    
    hooks.version = '2.17.1';
    
    setHookCallback(createLocal);
    
    hooks.fn                    = proto;
    hooks.min                   = min;
    hooks.max                   = max;
    hooks.now                   = now;
    hooks.utc                   = createUTC;
    hooks.unix                  = createUnix;
    hooks.months                = listMonths;
    hooks.isDate                = isDate;
    hooks.locale                = getSetGlobalLocale;
    hooks.invalid               = createInvalid;
    hooks.duration              = createDuration;
    hooks.isMoment              = isMoment;
    hooks.weekdays              = listWeekdays;
    hooks.parseZone             = createInZone;
    hooks.localeData            = getLocale;
    hooks.isDuration            = isDuration;
    hooks.monthsShort           = listMonthsShort;
    hooks.weekdaysMin           = listWeekdaysMin;
    hooks.defineLocale          = defineLocale;
    hooks.updateLocale          = updateLocale;
    hooks.locales               = listLocales;
    hooks.weekdaysShort         = listWeekdaysShort;
    hooks.normalizeUnits        = normalizeUnits;
    hooks.relativeTimeRounding = getSetRelativeTimeRounding;
    hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
    hooks.calendarFormat        = getCalendarFormat;
    hooks.prototype             = proto;
    
    return hooks;
    
    })));
    
    /*!
     * Chart.js
     * http://chartjs.org/
     * Version: 2.3.0
     *
     * Copyright 2016 Nick Downie
     * Released under the MIT license
     * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
     */
    !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Chart=t()}}(function(){return function t(e,a,i){function n(r,l){if(!a[r]){if(!e[r]){var s="function"==typeof require&&require;if(!l&&s)return s(r,!0);if(o)return o(r,!0);var d=new Error("Cannot find module '"+r+"'");throw d.code="MODULE_NOT_FOUND",d}var u=a[r]={exports:{}};e[r][0].call(u.exports,function(t){var a=e[r][1][t];return n(a?a:t)},u,u.exports,t,e,a,i)}return a[r].exports}for(var o="function"==typeof require&&require,r=0;r<i.length;r++)n(i[r]);return n}({1:[function(t,e,a){},{}],2:[function(t,e,a){function i(t){if(t){var e=/^#([a-fA-F0-9]{3})$/,a=/^#([a-fA-F0-9]{6})$/,i=/^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,n=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,o=/(\w+)/,r=[0,0,0],l=1,s=t.match(e);if(s){s=s[1];for(var d=0;d<r.length;d++)r[d]=parseInt(s[d]+s[d],16)}else if(s=t.match(a)){s=s[1];for(var d=0;d<r.length;d++)r[d]=parseInt(s.slice(2*d,2*d+2),16)}else if(s=t.match(i)){for(var d=0;d<r.length;d++)r[d]=parseInt(s[d+1]);l=parseFloat(s[4])}else if(s=t.match(n)){for(var d=0;d<r.length;d++)r[d]=Math.round(2.55*parseFloat(s[d+1]));l=parseFloat(s[4])}else if(s=t.match(o)){if("transparent"==s[1])return[0,0,0,0];if(r=y[s[1]],!r)return}for(var d=0;d<r.length;d++)r[d]=v(r[d],0,255);return l=l||0==l?v(l,0,1):1,r[3]=l,r}}function n(t){if(t){var e=/^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/,a=t.match(e);if(a){var i=parseFloat(a[4]),n=v(parseInt(a[1]),0,360),o=v(parseFloat(a[2]),0,100),r=v(parseFloat(a[3]),0,100),l=v(isNaN(i)?1:i,0,1);return[n,o,r,l]}}}function o(t){if(t){var e=/^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/,a=t.match(e);if(a){var i=parseFloat(a[4]),n=v(parseInt(a[1]),0,360),o=v(parseFloat(a[2]),0,100),r=v(parseFloat(a[3]),0,100),l=v(isNaN(i)?1:i,0,1);return[n,o,r,l]}}}function r(t){var e=i(t);return e&&e.slice(0,3)}function l(t){var e=n(t);return e&&e.slice(0,3)}function s(t){var e=i(t);return e?e[3]:(e=n(t))?e[3]:(e=o(t))?e[3]:void 0}function d(t){return"#"+x(t[0])+x(t[1])+x(t[2])}function u(t,e){return 1>e||t[3]&&t[3]<1?c(t,e):"rgb("+t[0]+", "+t[1]+", "+t[2]+")"}function c(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"rgba("+t[0]+", "+t[1]+", "+t[2]+", "+e+")"}function h(t,e){if(1>e||t[3]&&t[3]<1)return f(t,e);var a=Math.round(t[0]/255*100),i=Math.round(t[1]/255*100),n=Math.round(t[2]/255*100);return"rgb("+a+"%, "+i+"%, "+n+"%)"}function f(t,e){var a=Math.round(t[0]/255*100),i=Math.round(t[1]/255*100),n=Math.round(t[2]/255*100);return"rgba("+a+"%, "+i+"%, "+n+"%, "+(e||t[3]||1)+")"}function g(t,e){return 1>e||t[3]&&t[3]<1?p(t,e):"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)"}function p(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+e+")"}function m(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+(void 0!==e&&1!==e?", "+e:"")+")"}function b(t){return k[t.slice(0,3)]}function v(t,e,a){return Math.min(Math.max(e,t),a)}function x(t){var e=t.toString(16).toUpperCase();return e.length<2?"0"+e:e}var y=t(6);e.exports={getRgba:i,getHsla:n,getRgb:r,getHsl:l,getHwb:o,getAlpha:s,hexString:d,rgbString:u,rgbaString:c,percentString:h,percentaString:f,hslString:g,hslaString:p,hwbString:m,keyword:b};var k={};for(var S in y)k[y[S]]=S},{6:6}],3:[function(t,e,a){var i=t(5),n=t(2),o=function(t){if(t instanceof o)return t;if(!(this instanceof o))return new o(t);this.values={rgb:[0,0,0],hsl:[0,0,0],hsv:[0,0,0],hwb:[0,0,0],cmyk:[0,0,0,0],alpha:1};var e;if("string"==typeof t)if(e=n.getRgba(t))this.setValues("rgb",e);else if(e=n.getHsla(t))this.setValues("hsl",e);else{if(!(e=n.getHwb(t)))throw new Error('Unable to parse color from string "'+t+'"');this.setValues("hwb",e)}else if("object"==typeof t)if(e=t,void 0!==e.r||void 0!==e.red)this.setValues("rgb",e);else if(void 0!==e.l||void 0!==e.lightness)this.setValues("hsl",e);else if(void 0!==e.v||void 0!==e.value)this.setValues("hsv",e);else if(void 0!==e.w||void 0!==e.whiteness)this.setValues("hwb",e);else{if(void 0===e.c&&void 0===e.cyan)throw new Error("Unable to parse color from object "+JSON.stringify(t));this.setValues("cmyk",e)}};o.prototype={rgb:function(){return this.setSpace("rgb",arguments)},hsl:function(){return this.setSpace("hsl",arguments)},hsv:function(){return this.setSpace("hsv",arguments)},hwb:function(){return this.setSpace("hwb",arguments)},cmyk:function(){return this.setSpace("cmyk",arguments)},rgbArray:function(){return this.values.rgb},hslArray:function(){return this.values.hsl},hsvArray:function(){return this.values.hsv},hwbArray:function(){var t=this.values;return 1!==t.alpha?t.hwb.concat([t.alpha]):t.hwb},cmykArray:function(){return this.values.cmyk},rgbaArray:function(){var t=this.values;return t.rgb.concat([t.alpha])},hslaArray:function(){var t=this.values;return t.hsl.concat([t.alpha])},alpha:function(t){return void 0===t?this.values.alpha:(this.setValues("alpha",t),this)},red:function(t){return this.setChannel("rgb",0,t)},green:function(t){return this.setChannel("rgb",1,t)},blue:function(t){return this.setChannel("rgb",2,t)},hue:function(t){return t&&(t%=360,t=0>t?360+t:t),this.setChannel("hsl",0,t)},saturation:function(t){return this.setChannel("hsl",1,t)},lightness:function(t){return this.setChannel("hsl",2,t)},saturationv:function(t){return this.setChannel("hsv",1,t)},whiteness:function(t){return this.setChannel("hwb",1,t)},blackness:function(t){return this.setChannel("hwb",2,t)},value:function(t){return this.setChannel("hsv",2,t)},cyan:function(t){return this.setChannel("cmyk",0,t)},magenta:function(t){return this.setChannel("cmyk",1,t)},yellow:function(t){return this.setChannel("cmyk",2,t)},black:function(t){return this.setChannel("cmyk",3,t)},hexString:function(){return n.hexString(this.values.rgb)},rgbString:function(){return n.rgbString(this.values.rgb,this.values.alpha)},rgbaString:function(){return n.rgbaString(this.values.rgb,this.values.alpha)},percentString:function(){return n.percentString(this.values.rgb,this.values.alpha)},hslString:function(){return n.hslString(this.values.hsl,this.values.alpha)},hslaString:function(){return n.hslaString(this.values.hsl,this.values.alpha)},hwbString:function(){return n.hwbString(this.values.hwb,this.values.alpha)},keyword:function(){return n.keyword(this.values.rgb,this.values.alpha)},rgbNumber:function(){var t=this.values.rgb;return t[0]<<16|t[1]<<8|t[2]},luminosity:function(){for(var t=this.values.rgb,e=[],a=0;a<t.length;a++){var i=t[a]/255;e[a]=.03928>=i?i/12.92:Math.pow((i+.055)/1.055,2.4)}return.2126*e[0]+.7152*e[1]+.0722*e[2]},contrast:function(t){var e=this.luminosity(),a=t.luminosity();return e>a?(e+.05)/(a+.05):(a+.05)/(e+.05)},level:function(t){var e=this.contrast(t);return e>=7.1?"AAA":e>=4.5?"AA":""},dark:function(){var t=this.values.rgb,e=(299*t[0]+587*t[1]+114*t[2])/1e3;return 128>e},light:function(){return!this.dark()},negate:function(){for(var t=[],e=0;3>e;e++)t[e]=255-this.values.rgb[e];return this.setValues("rgb",t),this},lighten:function(t){var e=this.values.hsl;return e[2]+=e[2]*t,this.setValues("hsl",e),this},darken:function(t){var e=this.values.hsl;return e[2]-=e[2]*t,this.setValues("hsl",e),this},saturate:function(t){var e=this.values.hsl;return e[1]+=e[1]*t,this.setValues("hsl",e),this},desaturate:function(t){var e=this.values.hsl;return e[1]-=e[1]*t,this.setValues("hsl",e),this},whiten:function(t){var e=this.values.hwb;return e[1]+=e[1]*t,this.setValues("hwb",e),this},blacken:function(t){var e=this.values.hwb;return e[2]+=e[2]*t,this.setValues("hwb",e),this},greyscale:function(){var t=this.values.rgb,e=.3*t[0]+.59*t[1]+.11*t[2];return this.setValues("rgb",[e,e,e]),this},clearer:function(t){var e=this.values.alpha;return this.setValues("alpha",e-e*t),this},opaquer:function(t){var e=this.values.alpha;return this.setValues("alpha",e+e*t),this},rotate:function(t){var e=this.values.hsl,a=(e[0]+t)%360;return e[0]=0>a?360+a:a,this.setValues("hsl",e),this},mix:function(t,e){var a=this,i=t,n=void 0===e?.5:e,o=2*n-1,r=a.alpha()-i.alpha(),l=((o*r===-1?o:(o+r)/(1+o*r))+1)/2,s=1-l;return this.rgb(l*a.red()+s*i.red(),l*a.green()+s*i.green(),l*a.blue()+s*i.blue()).alpha(a.alpha()*n+i.alpha()*(1-n))},toJSON:function(){return this.rgb()},clone:function(){var t,e,a=new o,i=this.values,n=a.values;for(var r in i)i.hasOwnProperty(r)&&(t=i[r],e={}.toString.call(t),"[object Array]"===e?n[r]=t.slice(0):"[object Number]"===e?n[r]=t:console.error("unexpected color value:",t));return a}},o.prototype.spaces={rgb:["red","green","blue"],hsl:["hue","saturation","lightness"],hsv:["hue","saturation","value"],hwb:["hue","whiteness","blackness"],cmyk:["cyan","magenta","yellow","black"]},o.prototype.maxes={rgb:[255,255,255],hsl:[360,100,100],hsv:[360,100,100],hwb:[360,100,100],cmyk:[100,100,100,100]},o.prototype.getValues=function(t){for(var e=this.values,a={},i=0;i<t.length;i++)a[t.charAt(i)]=e[t][i];return 1!==e.alpha&&(a.a=e.alpha),a},o.prototype.setValues=function(t,e){var a,n=this.values,o=this.spaces,r=this.maxes,l=1;if("alpha"===t)l=e;else if(e.length)n[t]=e.slice(0,t.length),l=e[t.length];else if(void 0!==e[t.charAt(0)]){for(a=0;a<t.length;a++)n[t][a]=e[t.charAt(a)];l=e.a}else if(void 0!==e[o[t][0]]){var s=o[t];for(a=0;a<t.length;a++)n[t][a]=e[s[a]];l=e.alpha}if(n.alpha=Math.max(0,Math.min(1,void 0===l?n.alpha:l)),"alpha"===t)return!1;var d;for(a=0;a<t.length;a++)d=Math.max(0,Math.min(r[t][a],n[t][a])),n[t][a]=Math.round(d);for(var u in o)u!==t&&(n[u]=i[t][u](n[t]));return!0},o.prototype.setSpace=function(t,e){var a=e[0];return void 0===a?this.getValues(t):("number"==typeof a&&(a=Array.prototype.slice.call(e)),this.setValues(t,a),this)},o.prototype.setChannel=function(t,e,a){var i=this.values[t];return void 0===a?i[e]:a===i[e]?this:(i[e]=a,this.setValues(t,i),this)},"undefined"!=typeof window&&(window.Color=o),e.exports=o},{2:2,5:5}],4:[function(t,e,a){function i(t){var e,a,i,n=t[0]/255,o=t[1]/255,r=t[2]/255,l=Math.min(n,o,r),s=Math.max(n,o,r),d=s-l;return s==l?e=0:n==s?e=(o-r)/d:o==s?e=2+(r-n)/d:r==s&&(e=4+(n-o)/d),e=Math.min(60*e,360),0>e&&(e+=360),i=(l+s)/2,a=s==l?0:.5>=i?d/(s+l):d/(2-s-l),[e,100*a,100*i]}function n(t){var e,a,i,n=t[0],o=t[1],r=t[2],l=Math.min(n,o,r),s=Math.max(n,o,r),d=s-l;return a=0==s?0:d/s*1e3/10,s==l?e=0:n==s?e=(o-r)/d:o==s?e=2+(r-n)/d:r==s&&(e=4+(n-o)/d),e=Math.min(60*e,360),0>e&&(e+=360),i=s/255*1e3/10,[e,a,i]}function o(t){var e=t[0],a=t[1],n=t[2],o=i(t)[0],r=1/255*Math.min(e,Math.min(a,n)),n=1-1/255*Math.max(e,Math.max(a,n));return[o,100*r,100*n]}function l(t){var e,a,i,n,o=t[0]/255,r=t[1]/255,l=t[2]/255;return n=Math.min(1-o,1-r,1-l),e=(1-o-n)/(1-n)||0,a=(1-r-n)/(1-n)||0,i=(1-l-n)/(1-n)||0,[100*e,100*a,100*i,100*n]}function s(t){return G[JSON.stringify(t)]}function d(t){var e=t[0]/255,a=t[1]/255,i=t[2]/255;e=e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92,a=a>.04045?Math.pow((a+.055)/1.055,2.4):a/12.92,i=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92;var n=.4124*e+.3576*a+.1805*i,o=.2126*e+.7152*a+.0722*i,r=.0193*e+.1192*a+.9505*i;return[100*n,100*o,100*r]}function u(t){var e,a,i,n=d(t),o=n[0],r=n[1],l=n[2];return o/=95.047,r/=100,l/=108.883,o=o>.008856?Math.pow(o,1/3):7.787*o+16/116,r=r>.008856?Math.pow(r,1/3):7.787*r+16/116,l=l>.008856?Math.pow(l,1/3):7.787*l+16/116,e=116*r-16,a=500*(o-r),i=200*(r-l),[e,a,i]}function c(t){return W(u(t))}function h(t){var e,a,i,n,o,r=t[0]/360,l=t[1]/100,s=t[2]/100;if(0==l)return o=255*s,[o,o,o];a=.5>s?s*(1+l):s+l-s*l,e=2*s-a,n=[0,0,0];for(var d=0;3>d;d++)i=r+1/3*-(d-1),0>i&&i++,i>1&&i--,o=1>6*i?e+6*(a-e)*i:1>2*i?a:2>3*i?e+(a-e)*(2/3-i)*6:e,n[d]=255*o;return n}function f(t){var e,a,i=t[0],n=t[1]/100,o=t[2]/100;return 0===o?[0,0,0]:(o*=2,n*=1>=o?o:2-o,a=(o+n)/2,e=2*n/(o+n),[i,100*e,100*a])}function p(t){return o(h(t))}function m(t){return l(h(t))}function v(t){return s(h(t))}function x(t){var e=t[0]/60,a=t[1]/100,i=t[2]/100,n=Math.floor(e)%6,o=e-Math.floor(e),r=255*i*(1-a),l=255*i*(1-a*o),s=255*i*(1-a*(1-o)),i=255*i;switch(n){case 0:return[i,s,r];case 1:return[l,i,r];case 2:return[r,i,s];case 3:return[r,l,i];case 4:return[s,r,i];case 5:return[i,r,l]}}function y(t){var e,a,i=t[0],n=t[1]/100,o=t[2]/100;return a=(2-n)*o,e=n*o,e/=1>=a?a:2-a,e=e||0,a/=2,[i,100*e,100*a]}function k(t){return o(x(t))}function S(t){return l(x(t))}function w(t){return s(x(t))}function C(t){var e,a,i,n,o=t[0]/360,l=t[1]/100,s=t[2]/100,d=l+s;switch(d>1&&(l/=d,s/=d),e=Math.floor(6*o),a=1-s,i=6*o-e,0!=(1&e)&&(i=1-i),n=l+i*(a-l),e){default:case 6:case 0:r=a,g=n,b=l;break;case 1:r=n,g=a,b=l;break;case 2:r=l,g=a,b=n;break;case 3:r=l,g=n,b=a;break;case 4:r=n,g=l,b=a;break;case 5:r=a,g=l,b=n}return[255*r,255*g,255*b]}function M(t){return i(C(t))}function D(t){return n(C(t))}function I(t){return l(C(t))}function A(t){return s(C(t))}function T(t){var e,a,i,n=t[0]/100,o=t[1]/100,r=t[2]/100,l=t[3]/100;return e=1-Math.min(1,n*(1-l)+l),a=1-Math.min(1,o*(1-l)+l),i=1-Math.min(1,r*(1-l)+l),[255*e,255*a,255*i]}function P(t){return i(T(t))}function F(t){return n(T(t))}function R(t){return o(T(t))}function _(t){return s(T(t))}function V(t){var e,a,i,n=t[0]/100,o=t[1]/100,r=t[2]/100;return e=3.2406*n+-1.5372*o+r*-.4986,a=n*-.9689+1.8758*o+.0415*r,i=.0557*n+o*-.204+1.057*r,e=e>.0031308?1.055*Math.pow(e,1/2.4)-.055:e=12.92*e,a=a>.0031308?1.055*Math.pow(a,1/2.4)-.055:a=12.92*a,i=i>.0031308?1.055*Math.pow(i,1/2.4)-.055:i=12.92*i,e=Math.min(Math.max(0,e),1),a=Math.min(Math.max(0,a),1),i=Math.min(Math.max(0,i),1),[255*e,255*a,255*i]}function L(t){var e,a,i,n=t[0],o=t[1],r=t[2];return n/=95.047,o/=100,r/=108.883,n=n>.008856?Math.pow(n,1/3):7.787*n+16/116,o=o>.008856?Math.pow(o,1/3):7.787*o+16/116,r=r>.008856?Math.pow(r,1/3):7.787*r+16/116,e=116*o-16,a=500*(n-o),i=200*(o-r),[e,a,i]}function O(t){return W(L(t))}function B(t){var e,a,i,n,o=t[0],r=t[1],l=t[2];return 8>=o?(a=100*o/903.3,n=7.787*(a/100)+16/116):(a=100*Math.pow((o+16)/116,3),n=Math.pow(a/100,1/3)),e=.008856>=e/95.047?e=95.047*(r/500+n-16/116)/7.787:95.047*Math.pow(r/500+n,3),i=.008859>=i/108.883?i=108.883*(n-l/200-16/116)/7.787:108.883*Math.pow(n-l/200,3),[e,a,i]}function W(t){var e,a,i,n=t[0],o=t[1],r=t[2];return e=Math.atan2(r,o),a=360*e/2/Math.PI,0>a&&(a+=360),i=Math.sqrt(o*o+r*r),[n,i,a]}function z(t){return V(B(t))}function N(t){var e,a,i,n=t[0],o=t[1],r=t[2];return i=r/360*2*Math.PI,e=o*Math.cos(i),a=o*Math.sin(i),[n,e,a]}function H(t){return B(N(t))}function E(t){return z(N(t))}function U(t){return Z[t]}function q(t){return i(U(t))}function j(t){return n(U(t))}function Y(t){return o(U(t))}function K(t){return l(U(t))}function X(t){return u(U(t))}function J(t){return d(U(t))}e.exports={rgb2hsl:i,rgb2hsv:n,rgb2hwb:o,rgb2cmyk:l,rgb2keyword:s,rgb2xyz:d,rgb2lab:u,rgb2lch:c,hsl2rgb:h,hsl2hsv:f,hsl2hwb:p,hsl2cmyk:m,hsl2keyword:v,hsv2rgb:x,hsv2hsl:y,hsv2hwb:k,hsv2cmyk:S,hsv2keyword:w,hwb2rgb:C,hwb2hsl:M,hwb2hsv:D,hwb2cmyk:I,hwb2keyword:A,cmyk2rgb:T,cmyk2hsl:P,cmyk2hsv:F,cmyk2hwb:R,cmyk2keyword:_,keyword2rgb:U,keyword2hsl:q,keyword2hsv:j,keyword2hwb:Y,keyword2cmyk:K,keyword2lab:X,keyword2xyz:J,xyz2rgb:V,xyz2lab:L,xyz2lch:O,lab2xyz:B,lab2rgb:z,lab2lch:W,lch2lab:N,lch2xyz:H,lch2rgb:E};var Z={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},G={};for(var Q in Z)G[JSON.stringify(Z[Q])]=Q},{}],5:[function(t,e,a){var i=t(4),n=function(){return new d};for(var o in i){n[o+"Raw"]=function(t){return function(e){return"number"==typeof e&&(e=Array.prototype.slice.call(arguments)),i[t](e)}}(o);var r=/(\w+)2(\w+)/.exec(o),l=r[1],s=r[2];n[l]=n[l]||{},n[l][s]=n[o]=function(t){return function(e){"number"==typeof e&&(e=Array.prototype.slice.call(arguments));var a=i[t](e);if("string"==typeof a||void 0===a)return a;for(var n=0;n<a.length;n++)a[n]=Math.round(a[n]);return a}}(o)}var d=function(){this.convs={}};d.prototype.routeSpace=function(t,e){var a=e[0];return void 0===a?this.getValues(t):("number"==typeof a&&(a=Array.prototype.slice.call(e)),this.setValues(t,a))},d.prototype.setValues=function(t,e){return this.space=t,this.convs={},this.convs[t]=e,this},d.prototype.getValues=function(t){var e=this.convs[t];if(!e){var a=this.space,i=this.convs[a];e=n[a][t](i),this.convs[t]=e}return e},["rgb","hsl","hsv","cmyk","keyword"].forEach(function(t){d.prototype[t]=function(e){return this.routeSpace(t,arguments)}}),e.exports=n},{4:4}],6:[function(t,e,a){e.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},{}],7:[function(t,e,a){var i=t(27)();t(26)(i),t(22)(i),t(25)(i),t(21)(i),t(23)(i),t(24)(i),t(28)(i),t(32)(i),t(30)(i),t(31)(i),t(33)(i),t(29)(i),t(34)(i),t(35)(i),t(36)(i),t(37)(i),t(38)(i),t(41)(i),t(39)(i),t(40)(i),t(42)(i),t(43)(i),t(44)(i),t(15)(i),t(16)(i),t(17)(i),t(18)(i),t(19)(i),t(20)(i),t(8)(i),t(9)(i),t(10)(i),t(11)(i),t(12)(i),t(13)(i),t(14)(i),window.Chart=e.exports=i},{10:10,11:11,12:12,13:13,14:14,15:15,16:16,17:17,18:18,19:19,20:20,21:21,22:22,23:23,24:24,25:25,26:26,27:27,28:28,29:29,30:30,31:31,32:32,33:33,34:34,35:35,36:36,37:37,38:38,39:39,40:40,41:41,42:42,43:43,44:44,8:8,9:9}],8:[function(t,e,a){"use strict";e.exports=function(t){t.Bar=function(e,a){return a.type="bar",new t(e,a)}}},{}],9:[function(t,e,a){"use strict";e.exports=function(t){t.Bubble=function(e,a){return a.type="bubble",new t(e,a)}}},{}],10:[function(t,e,a){"use strict";e.exports=function(t){t.Doughnut=function(e,a){return a.type="doughnut",new t(e,a)}}},{}],11:[function(t,e,a){"use strict";e.exports=function(t){t.Line=function(e,a){return a.type="line",new t(e,a)}}},{}],12:[function(t,e,a){"use strict";e.exports=function(t){t.PolarArea=function(e,a){return a.type="polarArea",new t(e,a)}}},{}],13:[function(t,e,a){"use strict";e.exports=function(t){t.Radar=function(e,a){return a.options=t.helpers.configMerge({aspectRatio:1},a.options),a.type="radar",new t(e,a)}}},{}],14:[function(t,e,a){"use strict";e.exports=function(t){var e={hover:{mode:"single"},scales:{xAxes:[{type:"linear",position:"bottom",id:"x-axis-1"}],yAxes:[{type:"linear",position:"left",id:"y-axis-1"}]},tooltips:{callbacks:{title:function(){return""},label:function(t){return"("+t.xLabel+", "+t.yLabel+")"}}}};t.defaults.scatter=e,t.controllers.scatter=t.controllers.line,t.Scatter=function(e,a){return a.type="scatter",new t(e,a)}}},{}],15:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.bar={hover:{mode:"label"},scales:{xAxes:[{type:"category",categoryPercentage:.8,barPercentage:.9,gridLines:{offsetGridLines:!0}}],yAxes:[{type:"linear"}]}},t.controllers.bar=t.DatasetController.extend({dataElementType:t.elements.Rectangle,initialize:function(e,a){t.DatasetController.prototype.initialize.call(this,e,a),this.getMeta().bar=!0},getBarCount:function(){var t=this,a=0;return e.each(t.chart.data.datasets,function(e,i){var n=t.chart.getDatasetMeta(i);n.bar&&t.chart.isDatasetVisible(i)&&++a},t),a},update:function(t){var a=this;e.each(a.getMeta().data,function(e,i){a.updateElement(e,i,t)},a)},updateElement:function(t,a,i){var n=this,o=n.getMeta(),r=n.getScaleForId(o.xAxisID),l=n.getScaleForId(o.yAxisID),s=l.getBasePixel(),d=n.chart.options.elements.rectangle,u=t.custom||{},c=n.getDataset();e.extend(t,{_xScale:r,_yScale:l,_datasetIndex:n.index,_index:a,_model:{x:n.calculateBarX(a,n.index),y:i?s:n.calculateBarY(a,n.index),label:n.chart.data.labels[a],datasetLabel:c.label,base:i?s:n.calculateBarBase(n.index,a),width:n.calculateBarWidth(a),backgroundColor:u.backgroundColor?u.backgroundColor:e.getValueAtIndexOrDefault(c.backgroundColor,a,d.backgroundColor),borderSkipped:u.borderSkipped?u.borderSkipped:d.borderSkipped,borderColor:u.borderColor?u.borderColor:e.getValueAtIndexOrDefault(c.borderColor,a,d.borderColor),borderWidth:u.borderWidth?u.borderWidth:e.getValueAtIndexOrDefault(c.borderWidth,a,d.borderWidth)}}),t.pivot()},calculateBarBase:function(t,e){var a=this,i=a.getMeta(),n=a.getScaleForId(i.yAxisID),o=0;if(n.options.stacked){for(var r=a.chart,l=r.data.datasets,s=Number(l[t].data[e]),d=0;t>d;d++){var u=l[d],c=r.getDatasetMeta(d);if(c.bar&&c.yAxisID===n.id&&r.isDatasetVisible(d)){var h=Number(u.data[e]);o+=0>s?Math.min(h,0):Math.max(h,0)}}return n.getPixelForValue(o)}return n.getBasePixel()},getRuler:function(t){var e,a=this,i=a.getMeta(),n=a.getScaleForId(i.xAxisID),o=a.getBarCount();e="category"===n.options.type?n.getPixelForTick(t+1)-n.getPixelForTick(t):n.width/n.ticks.length;var r=e*n.options.categoryPercentage,l=(e-e*n.options.categoryPercentage)/2,s=r/o;if(n.ticks.length!==a.chart.data.labels.length){var d=n.ticks.length/a.chart.data.labels.length;s*=d}var u=s*n.options.barPercentage,c=s-s*n.options.barPercentage;return{datasetCount:o,tickWidth:e,categoryWidth:r,categorySpacing:l,fullBarWidth:s,barWidth:u,barSpacing:c}},calculateBarWidth:function(t){var e=this.getScaleForId(this.getMeta().xAxisID);if(e.options.barThickness)return e.options.barThickness;var a=this.getRuler(t);return e.options.stacked?a.categoryWidth:a.barWidth},getBarIndex:function(t){var e,a,i=0;for(a=0;t>a;++a)e=this.chart.getDatasetMeta(a),e.bar&&this.chart.isDatasetVisible(a)&&++i;return i},calculateBarX:function(t,e){var a=this,i=a.getMeta(),n=a.getScaleForId(i.xAxisID),o=a.getBarIndex(e),r=a.getRuler(t),l=n.getPixelForValue(null,t,e,a.chart.isCombo);return l-=a.chart.isCombo?r.tickWidth/2:0,n.options.stacked?l+r.categoryWidth/2+r.categorySpacing:l+r.barWidth/2+r.categorySpacing+r.barWidth*o+r.barSpacing/2+r.barSpacing*o},calculateBarY:function(t,e){var a=this,i=a.getMeta(),n=a.getScaleForId(i.yAxisID),o=Number(a.getDataset().data[t]);if(n.options.stacked){for(var r=0,l=0,s=0;e>s;s++){var d=a.chart.data.datasets[s],u=a.chart.getDatasetMeta(s);if(u.bar&&u.yAxisID===n.id&&a.chart.isDatasetVisible(s)){var c=Number(d.data[t]);0>c?l+=c||0:r+=c||0}}return 0>o?n.getPixelForValue(l+o):n.getPixelForValue(r+o)}return n.getPixelForValue(o)},draw:function(t){var a=this,i=t||1;e.each(a.getMeta().data,function(t,e){var n=a.getDataset().data[e];null===n||void 0===n||isNaN(n)||t.transition(i).draw()},a)},setHoverStyle:function(t){var a=this.chart.data.datasets[t._datasetIndex],i=t._index,n=t.custom||{},o=t._model;o.backgroundColor=n.hoverBackgroundColor?n.hoverBackgroundColor:e.getValueAtIndexOrDefault(a.hoverBackgroundColor,i,e.getHoverColor(o.backgroundColor)),o.borderColor=n.hoverBorderColor?n.hoverBorderColor:e.getValueAtIndexOrDefault(a.hoverBorderColor,i,e.getHoverColor(o.borderColor)),o.borderWidth=n.hoverBorderWidth?n.hoverBorderWidth:e.getValueAtIndexOrDefault(a.hoverBorderWidth,i,o.borderWidth)},removeHoverStyle:function(t){var a=this.chart.data.datasets[t._datasetIndex],i=t._index,n=t.custom||{},o=t._model,r=this.chart.options.elements.rectangle;o.backgroundColor=n.backgroundColor?n.backgroundColor:e.getValueAtIndexOrDefault(a.backgroundColor,i,r.backgroundColor),o.borderColor=n.borderColor?n.borderColor:e.getValueAtIndexOrDefault(a.borderColor,i,r.borderColor),o.borderWidth=n.borderWidth?n.borderWidth:e.getValueAtIndexOrDefault(a.borderWidth,i,r.borderWidth)}}),t.defaults.horizontalBar={hover:{mode:"label"},scales:{xAxes:[{type:"linear",position:"bottom"}],yAxes:[{position:"left",type:"category",categoryPercentage:.8,barPercentage:.9,gridLines:{offsetGridLines:!0}}]},elements:{rectangle:{borderSkipped:"left"}},tooltips:{callbacks:{title:function(t,e){var a="";return t.length>0&&(t[0].yLabel?a=t[0].yLabel:e.labels.length>0&&t[0].index<e.labels.length&&(a=e.labels[t[0].index])),a},label:function(t,e){var a=e.datasets[t.datasetIndex].label||"";return a+": "+t.xLabel}}}},t.controllers.horizontalBar=t.controllers.bar.extend({updateElement:function(t,a,i){var n=this,o=n.getMeta(),r=n.getScaleForId(o.xAxisID),l=n.getScaleForId(o.yAxisID),s=r.getBasePixel(),d=t.custom||{},u=n.getDataset(),c=n.chart.options.elements.rectangle;e.extend(t,{_xScale:r,_yScale:l,_datasetIndex:n.index,_index:a,_model:{x:i?s:n.calculateBarX(a,n.index),y:n.calculateBarY(a,n.index),label:n.chart.data.labels[a],datasetLabel:u.label,base:i?s:n.calculateBarBase(n.index,a),height:n.calculateBarHeight(a),backgroundColor:d.backgroundColor?d.backgroundColor:e.getValueAtIndexOrDefault(u.backgroundColor,a,c.backgroundColor),borderSkipped:d.borderSkipped?d.borderSkipped:c.borderSkipped,borderColor:d.borderColor?d.borderColor:e.getValueAtIndexOrDefault(u.borderColor,a,c.borderColor),borderWidth:d.borderWidth?d.borderWidth:e.getValueAtIndexOrDefault(u.borderWidth,a,c.borderWidth)},draw:function(){function t(t){return s[(u+t)%4]}var e=this._chart.ctx,a=this._view,i=a.height/2,n=a.y-i,o=a.y+i,r=a.base-(a.base-a.x),l=a.borderWidth/2;a.borderWidth&&(n+=l,o-=l,r+=l),e.beginPath(),e.fillStyle=a.backgroundColor,e.strokeStyle=a.borderColor,e.lineWidth=a.borderWidth;var s=[[a.base,o],[a.base,n],[r,n],[r,o]],d=["bottom","left","top","right"],u=d.indexOf(a.borderSkipped,0);-1===u&&(u=0),e.moveTo.apply(e,t(0));for(var c=1;4>c;c++)e.lineTo.apply(e,t(c));e.fill(),a.borderWidth&&e.stroke()},inRange:function(t,e){var a=this._view,i=!1;return a&&(i=a.x<a.base?e>=a.y-a.height/2&&e<=a.y+a.height/2&&t>=a.x&&t<=a.base:e>=a.y-a.height/2&&e<=a.y+a.height/2&&t>=a.base&&t<=a.x),i}}),t.pivot()},calculateBarBase:function(t,e){var a=this,i=a.getMeta(),n=a.getScaleForId(i.xAxisID),o=0;
    if(n.options.stacked){for(var r=a.chart,l=r.data.datasets,s=Number(l[t].data[e]),d=0;t>d;d++){var u=l[d],c=r.getDatasetMeta(d);if(c.bar&&c.xAxisID===n.id&&r.isDatasetVisible(d)){var h=Number(u.data[e]);o+=0>s?Math.min(h,0):Math.max(h,0)}}return n.getPixelForValue(o)}return n.getBasePixel()},getRuler:function(t){var e,a=this,i=a.getMeta(),n=a.getScaleForId(i.yAxisID),o=a.getBarCount();e="category"===n.options.type?n.getPixelForTick(t+1)-n.getPixelForTick(t):n.width/n.ticks.length;var r=e*n.options.categoryPercentage,l=(e-e*n.options.categoryPercentage)/2,s=r/o;if(n.ticks.length!==a.chart.data.labels.length){var d=n.ticks.length/a.chart.data.labels.length;s*=d}var u=s*n.options.barPercentage,c=s-s*n.options.barPercentage;return{datasetCount:o,tickHeight:e,categoryHeight:r,categorySpacing:l,fullBarHeight:s,barHeight:u,barSpacing:c}},calculateBarHeight:function(t){var e=this,a=e.getScaleForId(e.getMeta().yAxisID);if(a.options.barThickness)return a.options.barThickness;var i=e.getRuler(t);return a.options.stacked?i.categoryHeight:i.barHeight},calculateBarX:function(t,e){var a=this,i=a.getMeta(),n=a.getScaleForId(i.xAxisID),o=Number(a.getDataset().data[t]);if(n.options.stacked){for(var r=0,l=0,s=0;e>s;s++){var d=a.chart.data.datasets[s],u=a.chart.getDatasetMeta(s);if(u.bar&&u.xAxisID===n.id&&a.chart.isDatasetVisible(s)){var c=Number(d.data[t]);0>c?l+=c||0:r+=c||0}}return 0>o?n.getPixelForValue(l+o):n.getPixelForValue(r+o)}return n.getPixelForValue(o)},calculateBarY:function(t,e){var a=this,i=a.getMeta(),n=a.getScaleForId(i.yAxisID),o=a.getBarIndex(e),r=a.getRuler(t),l=n.getPixelForValue(null,t,e,a.chart.isCombo);return l-=a.chart.isCombo?r.tickHeight/2:0,n.options.stacked?l+r.categoryHeight/2+r.categorySpacing:l+r.barHeight/2+r.categorySpacing+r.barHeight*o+r.barSpacing/2+r.barSpacing*o}})}},{}],16:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.bubble={hover:{mode:"single"},scales:{xAxes:[{type:"linear",position:"bottom",id:"x-axis-0"}],yAxes:[{type:"linear",position:"left",id:"y-axis-0"}]},tooltips:{callbacks:{title:function(){return""},label:function(t,e){var a=e.datasets[t.datasetIndex].label||"",i=e.datasets[t.datasetIndex].data[t.index];return a+": ("+i.x+", "+i.y+", "+i.r+")"}}}},t.controllers.bubble=t.DatasetController.extend({dataElementType:t.elements.Point,update:function(t){var a=this,i=a.getMeta(),n=i.data;e.each(n,function(e,i){a.updateElement(e,i,t)})},updateElement:function(a,i,n){var o=this,r=o.getMeta(),l=o.getScaleForId(r.xAxisID),s=o.getScaleForId(r.yAxisID),d=a.custom||{},u=o.getDataset(),c=u.data[i],h=o.chart.options.elements.point,f=o.index;e.extend(a,{_xScale:l,_yScale:s,_datasetIndex:f,_index:i,_model:{x:n?l.getPixelForDecimal(.5):l.getPixelForValue("object"==typeof c?c:NaN,i,f,o.chart.isCombo),y:n?s.getBasePixel():s.getPixelForValue(c,i,f),radius:n?0:d.radius?d.radius:o.getRadius(c),hitRadius:d.hitRadius?d.hitRadius:e.getValueAtIndexOrDefault(u.hitRadius,i,h.hitRadius)}}),t.DatasetController.prototype.removeHoverStyle.call(o,a,h);var g=a._model;g.skip=d.skip?d.skip:isNaN(g.x)||isNaN(g.y),a.pivot()},getRadius:function(t){return t.r||this.chart.options.elements.point.radius},setHoverStyle:function(a){var i=this;t.DatasetController.prototype.setHoverStyle.call(i,a);var n=i.chart.data.datasets[a._datasetIndex],o=a._index,r=a.custom||{},l=a._model;l.radius=r.hoverRadius?r.hoverRadius:e.getValueAtIndexOrDefault(n.hoverRadius,o,i.chart.options.elements.point.hoverRadius)+i.getRadius(n.data[o])},removeHoverStyle:function(e){var a=this;t.DatasetController.prototype.removeHoverStyle.call(a,e,a.chart.options.elements.point);var i=a.chart.data.datasets[e._datasetIndex].data[e._index],n=e.custom||{},o=e._model;o.radius=n.radius?n.radius:a.getRadius(i)}})}},{}],17:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=t.defaults;a.doughnut={animation:{animateRotate:!0,animateScale:!1},aspectRatio:1,hover:{mode:"single"},legendCallback:function(t){var e=[];e.push('<ul class="'+t.id+'-legend">');var a=t.data,i=a.datasets,n=a.labels;if(i.length)for(var o=0;o<i[0].data.length;++o)e.push('<li><span style="background-color:'+i[0].backgroundColor[o]+'"></span>'),n[o]&&e.push(n[o]),e.push("</li>");return e.push("</ul>"),e.join("")},legend:{labels:{generateLabels:function(t){var a=t.data;return a.labels.length&&a.datasets.length?a.labels.map(function(i,n){var o=t.getDatasetMeta(0),r=a.datasets[0],l=o.data[n],s=l&&l.custom||{},d=e.getValueAtIndexOrDefault,u=t.options.elements.arc,c=s.backgroundColor?s.backgroundColor:d(r.backgroundColor,n,u.backgroundColor),h=s.borderColor?s.borderColor:d(r.borderColor,n,u.borderColor),f=s.borderWidth?s.borderWidth:d(r.borderWidth,n,u.borderWidth);return{text:i,fillStyle:c,strokeStyle:h,lineWidth:f,hidden:isNaN(r.data[n])||o.data[n].hidden,index:n}}):[]}},onClick:function(t,e){var a,i,n,o=e.index,r=this.chart;for(a=0,i=(r.data.datasets||[]).length;i>a;++a)n=r.getDatasetMeta(a),n.data[o]&&(n.data[o].hidden=!n.data[o].hidden);r.update()}},cutoutPercentage:50,rotation:Math.PI*-.5,circumference:2*Math.PI,tooltips:{callbacks:{title:function(){return""},label:function(t,e){return e.labels[t.index]+": "+e.datasets[t.datasetIndex].data[t.index]}}}},a.pie=e.clone(a.doughnut),e.extend(a.pie,{cutoutPercentage:0}),t.controllers.doughnut=t.controllers.pie=t.DatasetController.extend({dataElementType:t.elements.Arc,linkScales:e.noop,getRingIndex:function(t){for(var e=0,a=0;t>a;++a)this.chart.isDatasetVisible(a)&&++e;return e},update:function(t){var a=this,i=a.chart,n=i.chartArea,o=i.options,r=o.elements.arc,l=n.right-n.left-r.borderWidth,s=n.bottom-n.top-r.borderWidth,d=Math.min(l,s),u={x:0,y:0},c=a.getMeta(),h=o.cutoutPercentage,f=o.circumference;if(f<2*Math.PI){var g=o.rotation%(2*Math.PI);g+=2*Math.PI*(g>=Math.PI?-1:g<-Math.PI?1:0);var p=g+f,m={x:Math.cos(g),y:Math.sin(g)},b={x:Math.cos(p),y:Math.sin(p)},v=0>=g&&p>=0||g<=2*Math.PI&&2*Math.PI<=p,x=g<=.5*Math.PI&&.5*Math.PI<=p||g<=2.5*Math.PI&&2.5*Math.PI<=p,y=g<=-Math.PI&&-Math.PI<=p||g<=Math.PI&&Math.PI<=p,k=g<=.5*-Math.PI&&.5*-Math.PI<=p||g<=1.5*Math.PI&&1.5*Math.PI<=p,S=h/100,w={x:y?-1:Math.min(m.x*(m.x<0?1:S),b.x*(b.x<0?1:S)),y:k?-1:Math.min(m.y*(m.y<0?1:S),b.y*(b.y<0?1:S))},C={x:v?1:Math.max(m.x*(m.x>0?1:S),b.x*(b.x>0?1:S)),y:x?1:Math.max(m.y*(m.y>0?1:S),b.y*(b.y>0?1:S))},M={width:.5*(C.x-w.x),height:.5*(C.y-w.y)};d=Math.min(l/M.width,s/M.height),u={x:(C.x+w.x)*-.5,y:(C.y+w.y)*-.5}}i.borderWidth=a.getMaxBorderWidth(c.data),i.outerRadius=Math.max((d-i.borderWidth)/2,0),i.innerRadius=Math.max(h?i.outerRadius/100*h:1,0),i.radiusLength=(i.outerRadius-i.innerRadius)/i.getVisibleDatasetCount(),i.offsetX=u.x*i.outerRadius,i.offsetY=u.y*i.outerRadius,c.total=a.calculateTotal(),a.outerRadius=i.outerRadius-i.radiusLength*a.getRingIndex(a.index),a.innerRadius=a.outerRadius-i.radiusLength,e.each(c.data,function(e,i){a.updateElement(e,i,t)})},updateElement:function(t,a,i){var n=this,o=n.chart,r=o.chartArea,l=o.options,s=l.animation,d=(r.left+r.right)/2,u=(r.top+r.bottom)/2,c=l.rotation,h=l.rotation,f=n.getDataset(),g=i&&s.animateRotate?0:t.hidden?0:n.calculateCircumference(f.data[a])*(l.circumference/(2*Math.PI)),p=i&&s.animateScale?0:n.innerRadius,m=i&&s.animateScale?0:n.outerRadius,b=e.getValueAtIndexOrDefault;e.extend(t,{_datasetIndex:n.index,_index:a,_model:{x:d+o.offsetX,y:u+o.offsetY,startAngle:c,endAngle:h,circumference:g,outerRadius:m,innerRadius:p,label:b(f.label,a,o.data.labels[a])}});var v=t._model;this.removeHoverStyle(t),i&&s.animateRotate||(0===a?v.startAngle=l.rotation:v.startAngle=n.getMeta().data[a-1]._model.endAngle,v.endAngle=v.startAngle+v.circumference),t.pivot()},removeHoverStyle:function(e){t.DatasetController.prototype.removeHoverStyle.call(this,e,this.chart.options.elements.arc)},calculateTotal:function(){var t,a=this.getDataset(),i=this.getMeta(),n=0;return e.each(i.data,function(e,i){t=a.data[i],isNaN(t)||e.hidden||(n+=Math.abs(t))}),n},calculateCircumference:function(t){var e=this.getMeta().total;return e>0&&!isNaN(t)?2*Math.PI*(t/e):0},getMaxBorderWidth:function(t){for(var e,a,i=0,n=this.index,o=t.length,r=0;o>r;r++)e=t[r]._model?t[r]._model.borderWidth:0,a=t[r]._chart?t[r]._chart.config.data.datasets[n].hoverBorderWidth:0,i=e>i?e:i,i=a>i?a:i;return i}})}},{}],18:[function(t,e,a){"use strict";e.exports=function(t){function e(t,e){return a.getValueOrDefault(t.showLine,e.showLines)}var a=t.helpers;t.defaults.line={showLines:!0,spanGaps:!1,hover:{mode:"label"},scales:{xAxes:[{type:"category",id:"x-axis-0"}],yAxes:[{type:"linear",id:"y-axis-0"}]}},t.controllers.line=t.DatasetController.extend({datasetElementType:t.elements.Line,dataElementType:t.elements.Point,addElementAndReset:function(a){var i=this,n=i.chart.options,o=i.getMeta();t.DatasetController.prototype.addElementAndReset.call(i,a),e(i.getDataset(),n)&&0!==o.dataset._model.tension&&i.updateBezierControlPoints()},update:function(t){var i,n,o,r=this,l=r.getMeta(),s=l.dataset,d=l.data||[],u=r.chart.options,c=u.elements.line,h=r.getScaleForId(l.yAxisID),f=r.getDataset(),g=e(f,u);for(g&&(o=s.custom||{},void 0!==f.tension&&void 0===f.lineTension&&(f.lineTension=f.tension),s._scale=h,s._datasetIndex=r.index,s._children=d,s._model={spanGaps:f.spanGaps?f.spanGaps:u.spanGaps,tension:o.tension?o.tension:a.getValueOrDefault(f.lineTension,c.tension),backgroundColor:o.backgroundColor?o.backgroundColor:f.backgroundColor||c.backgroundColor,borderWidth:o.borderWidth?o.borderWidth:f.borderWidth||c.borderWidth,borderColor:o.borderColor?o.borderColor:f.borderColor||c.borderColor,borderCapStyle:o.borderCapStyle?o.borderCapStyle:f.borderCapStyle||c.borderCapStyle,borderDash:o.borderDash?o.borderDash:f.borderDash||c.borderDash,borderDashOffset:o.borderDashOffset?o.borderDashOffset:f.borderDashOffset||c.borderDashOffset,borderJoinStyle:o.borderJoinStyle?o.borderJoinStyle:f.borderJoinStyle||c.borderJoinStyle,fill:o.fill?o.fill:void 0!==f.fill?f.fill:c.fill,steppedLine:o.steppedLine?o.steppedLine:a.getValueOrDefault(f.steppedLine,c.stepped),cubicInterpolationMode:o.cubicInterpolationMode?o.cubicInterpolationMode:a.getValueOrDefault(f.cubicInterpolationMode,c.cubicInterpolationMode),scaleTop:h.top,scaleBottom:h.bottom,scaleZero:h.getBasePixel()},s.pivot()),i=0,n=d.length;n>i;++i)r.updateElement(d[i],i,t);for(g&&0!==s._model.tension&&r.updateBezierControlPoints(),i=0,n=d.length;n>i;++i)d[i].pivot()},getPointBackgroundColor:function(t,e){var i=this.chart.options.elements.point.backgroundColor,n=this.getDataset(),o=t.custom||{};return o.backgroundColor?i=o.backgroundColor:n.pointBackgroundColor?i=a.getValueAtIndexOrDefault(n.pointBackgroundColor,e,i):n.backgroundColor&&(i=n.backgroundColor),i},getPointBorderColor:function(t,e){var i=this.chart.options.elements.point.borderColor,n=this.getDataset(),o=t.custom||{};return o.borderColor?i=o.borderColor:n.pointBorderColor?i=a.getValueAtIndexOrDefault(n.pointBorderColor,e,i):n.borderColor&&(i=n.borderColor),i},getPointBorderWidth:function(t,e){var i=this.chart.options.elements.point.borderWidth,n=this.getDataset(),o=t.custom||{};return o.borderWidth?i=o.borderWidth:n.pointBorderWidth?i=a.getValueAtIndexOrDefault(n.pointBorderWidth,e,i):n.borderWidth&&(i=n.borderWidth),i},updateElement:function(t,e,i){var n,o,r=this,l=r.getMeta(),s=t.custom||{},d=r.getDataset(),u=r.index,c=d.data[e],h=r.getScaleForId(l.yAxisID),f=r.getScaleForId(l.xAxisID),g=r.chart.options.elements.point,p=r.chart.data.labels||[],m=1===p.length||1===d.data.length||r.chart.isCombo;void 0!==d.radius&&void 0===d.pointRadius&&(d.pointRadius=d.radius),void 0!==d.hitRadius&&void 0===d.pointHitRadius&&(d.pointHitRadius=d.hitRadius),n=f.getPixelForValue("object"==typeof c?c:NaN,e,u,m),o=i?h.getBasePixel():r.calculatePointY(c,e,u),t._xScale=f,t._yScale=h,t._datasetIndex=u,t._index=e,t._model={x:n,y:o,skip:s.skip||isNaN(n)||isNaN(o),radius:s.radius||a.getValueAtIndexOrDefault(d.pointRadius,e,g.radius),pointStyle:s.pointStyle||a.getValueAtIndexOrDefault(d.pointStyle,e,g.pointStyle),backgroundColor:r.getPointBackgroundColor(t,e),borderColor:r.getPointBorderColor(t,e),borderWidth:r.getPointBorderWidth(t,e),tension:l.dataset._model?l.dataset._model.tension:0,steppedLine:l.dataset._model?l.dataset._model.steppedLine:!1,hitRadius:s.hitRadius||a.getValueAtIndexOrDefault(d.pointHitRadius,e,g.hitRadius)}},calculatePointY:function(t,e,a){var i,n,o,r=this,l=r.chart,s=r.getMeta(),d=r.getScaleForId(s.yAxisID),u=0,c=0;if(d.options.stacked){for(i=0;a>i;i++)if(n=l.data.datasets[i],o=l.getDatasetMeta(i),"line"===o.type&&o.yAxisID===d.id&&l.isDatasetVisible(i)){var h=Number(d.getRightValue(n.data[e]));0>h?c+=h||0:u+=h||0}var f=Number(d.getRightValue(t));return 0>f?d.getPixelForValue(c+f):d.getPixelForValue(u+f)}return d.getPixelForValue(t)},updateBezierControlPoints:function(){function t(t,e,a){return Math.max(Math.min(t,a),e)}var e,i,n,o,r,l=this,s=l.getMeta(),d=l.chart.chartArea,u=s.data||[];if(s.dataset._model.spanGaps&&(u=u.filter(function(t){return!t._model.skip})),"monotone"===s.dataset._model.cubicInterpolationMode)a.splineCurveMonotone(u);else for(e=0,i=u.length;i>e;++e)n=u[e],o=n._model,r=a.splineCurve(a.previousItem(u,e)._model,o,a.nextItem(u,e)._model,s.dataset._model.tension),o.controlPointPreviousX=r.previous.x,o.controlPointPreviousY=r.previous.y,o.controlPointNextX=r.next.x,o.controlPointNextY=r.next.y;if(l.chart.options.elements.line.capBezierPoints)for(e=0,i=u.length;i>e;++e)o=u[e]._model,o.controlPointPreviousX=t(o.controlPointPreviousX,d.left,d.right),o.controlPointPreviousY=t(o.controlPointPreviousY,d.top,d.bottom),o.controlPointNextX=t(o.controlPointNextX,d.left,d.right),o.controlPointNextY=t(o.controlPointNextY,d.top,d.bottom)},draw:function(t){var a,i,n=this,o=n.getMeta(),r=o.data||[],l=t||1;for(a=0,i=r.length;i>a;++a)r[a].transition(l);for(e(n.getDataset(),n.chart.options)&&o.dataset.transition(l).draw(),a=0,i=r.length;i>a;++a)r[a].draw()},setHoverStyle:function(t){var e=this.chart.data.datasets[t._datasetIndex],i=t._index,n=t.custom||{},o=t._model;o.radius=n.hoverRadius||a.getValueAtIndexOrDefault(e.pointHoverRadius,i,this.chart.options.elements.point.hoverRadius),o.backgroundColor=n.hoverBackgroundColor||a.getValueAtIndexOrDefault(e.pointHoverBackgroundColor,i,a.getHoverColor(o.backgroundColor)),o.borderColor=n.hoverBorderColor||a.getValueAtIndexOrDefault(e.pointHoverBorderColor,i,a.getHoverColor(o.borderColor)),o.borderWidth=n.hoverBorderWidth||a.getValueAtIndexOrDefault(e.pointHoverBorderWidth,i,o.borderWidth)},removeHoverStyle:function(t){var e=this,i=e.chart.data.datasets[t._datasetIndex],n=t._index,o=t.custom||{},r=t._model;void 0!==i.radius&&void 0===i.pointRadius&&(i.pointRadius=i.radius),r.radius=o.radius||a.getValueAtIndexOrDefault(i.pointRadius,n,e.chart.options.elements.point.radius),r.backgroundColor=e.getPointBackgroundColor(t,n),r.borderColor=e.getPointBorderColor(t,n),r.borderWidth=e.getPointBorderWidth(t,n)}})}},{}],19:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.polarArea={scale:{type:"radialLinear",lineArc:!0,ticks:{beginAtZero:!0}},animation:{animateRotate:!0,animateScale:!0},startAngle:-.5*Math.PI,aspectRatio:1,legendCallback:function(t){var e=[];e.push('<ul class="'+t.id+'-legend">');var a=t.data,i=a.datasets,n=a.labels;if(i.length)for(var o=0;o<i[0].data.length;++o)e.push('<li><span style="background-color:'+i[0].backgroundColor[o]+'">'),n[o]&&e.push(n[o]),e.push("</span></li>");return e.push("</ul>"),e.join("")},legend:{labels:{generateLabels:function(t){var a=t.data;return a.labels.length&&a.datasets.length?a.labels.map(function(i,n){var o=t.getDatasetMeta(0),r=a.datasets[0],l=o.data[n],s=l.custom||{},d=e.getValueAtIndexOrDefault,u=t.options.elements.arc,c=s.backgroundColor?s.backgroundColor:d(r.backgroundColor,n,u.backgroundColor),h=s.borderColor?s.borderColor:d(r.borderColor,n,u.borderColor),f=s.borderWidth?s.borderWidth:d(r.borderWidth,n,u.borderWidth);return{text:i,fillStyle:c,strokeStyle:h,lineWidth:f,hidden:isNaN(r.data[n])||o.data[n].hidden,index:n}}):[]}},onClick:function(t,e){var a,i,n,o=e.index,r=this.chart;for(a=0,i=(r.data.datasets||[]).length;i>a;++a)n=r.getDatasetMeta(a),n.data[o].hidden=!n.data[o].hidden;r.update()}},tooltips:{callbacks:{title:function(){return""},label:function(t,e){return e.labels[t.index]+": "+t.yLabel}}}},t.controllers.polarArea=t.DatasetController.extend({dataElementType:t.elements.Arc,linkScales:e.noop,update:function(t){var a=this,i=a.chart,n=i.chartArea,o=a.getMeta(),r=i.options,l=r.elements.arc,s=Math.min(n.right-n.left,n.bottom-n.top);i.outerRadius=Math.max((s-l.borderWidth/2)/2,0),i.innerRadius=Math.max(r.cutoutPercentage?i.outerRadius/100*r.cutoutPercentage:1,0),i.radiusLength=(i.outerRadius-i.innerRadius)/i.getVisibleDatasetCount(),a.outerRadius=i.outerRadius-i.radiusLength*a.index,a.innerRadius=a.outerRadius-i.radiusLength,o.count=a.countVisibleElements(),e.each(o.data,function(e,i){a.updateElement(e,i,t)})},updateElement:function(t,a,i){for(var n=this,o=n.chart,r=n.getDataset(),l=o.options,s=l.animation,d=o.scale,u=e.getValueAtIndexOrDefault,c=o.data.labels,h=n.calculateCircumference(r.data[a]),f=d.xCenter,g=d.yCenter,p=0,m=n.getMeta(),b=0;a>b;++b)isNaN(r.data[b])||m.data[b].hidden||++p;var v=l.startAngle,x=t.hidden?0:d.getDistanceFromCenterForValue(r.data[a]),y=v+h*p,k=y+(t.hidden?0:h),S=s.animateScale?0:d.getDistanceFromCenterForValue(r.data[a]);e.extend(t,{_datasetIndex:n.index,_index:a,_scale:d,_model:{x:f,y:g,innerRadius:0,outerRadius:i?S:x,startAngle:i&&s.animateRotate?v:y,endAngle:i&&s.animateRotate?v:k,label:u(c,a,c[a])}}),n.removeHoverStyle(t),t.pivot()},removeHoverStyle:function(e){t.DatasetController.prototype.removeHoverStyle.call(this,e,this.chart.options.elements.arc)},countVisibleElements:function(){var t=this.getDataset(),a=this.getMeta(),i=0;return e.each(a.data,function(e,a){isNaN(t.data[a])||e.hidden||i++}),i},calculateCircumference:function(t){var e=this.getMeta().count;return e>0&&!isNaN(t)?2*Math.PI/e:0}})}},{}],20:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.radar={scale:{type:"radialLinear"},elements:{line:{tension:0}}},t.controllers.radar=t.DatasetController.extend({datasetElementType:t.elements.Line,dataElementType:t.elements.Point,linkScales:e.noop,addElementAndReset:function(e){t.DatasetController.prototype.addElementAndReset.call(this,e),this.updateBezierControlPoints()},update:function(t){var a=this,i=a.getMeta(),n=i.dataset,o=i.data,r=n.custom||{},l=a.getDataset(),s=a.chart.options.elements.line,d=a.chart.scale;void 0!==l.tension&&void 0===l.lineTension&&(l.lineTension=l.tension),e.extend(i.dataset,{_datasetIndex:a.index,_children:o,_loop:!0,_model:{tension:r.tension?r.tension:e.getValueOrDefault(l.lineTension,s.tension),backgroundColor:r.backgroundColor?r.backgroundColor:l.backgroundColor||s.backgroundColor,borderWidth:r.borderWidth?r.borderWidth:l.borderWidth||s.borderWidth,borderColor:r.borderColor?r.borderColor:l.borderColor||s.borderColor,fill:r.fill?r.fill:void 0!==l.fill?l.fill:s.fill,borderCapStyle:r.borderCapStyle?r.borderCapStyle:l.borderCapStyle||s.borderCapStyle,borderDash:r.borderDash?r.borderDash:l.borderDash||s.borderDash,borderDashOffset:r.borderDashOffset?r.borderDashOffset:l.borderDashOffset||s.borderDashOffset,borderJoinStyle:r.borderJoinStyle?r.borderJoinStyle:l.borderJoinStyle||s.borderJoinStyle,scaleTop:d.top,scaleBottom:d.bottom,scaleZero:d.getBasePosition()}}),i.dataset.pivot(),e.each(o,function(e,i){a.updateElement(e,i,t)},a),a.updateBezierControlPoints()},updateElement:function(t,a,i){var n=this,o=t.custom||{},r=n.getDataset(),l=n.chart.scale,s=n.chart.options.elements.point,d=l.getPointPositionForValue(a,r.data[a]);e.extend(t,{_datasetIndex:n.index,_index:a,_scale:l,_model:{x:i?l.xCenter:d.x,y:i?l.yCenter:d.y,tension:o.tension?o.tension:e.getValueOrDefault(r.tension,n.chart.options.elements.line.tension),radius:o.radius?o.radius:e.getValueAtIndexOrDefault(r.pointRadius,a,s.radius),backgroundColor:o.backgroundColor?o.backgroundColor:e.getValueAtIndexOrDefault(r.pointBackgroundColor,a,s.backgroundColor),borderColor:o.borderColor?o.borderColor:e.getValueAtIndexOrDefault(r.pointBorderColor,a,s.borderColor),borderWidth:o.borderWidth?o.borderWidth:e.getValueAtIndexOrDefault(r.pointBorderWidth,a,s.borderWidth),pointStyle:o.pointStyle?o.pointStyle:e.getValueAtIndexOrDefault(r.pointStyle,a,s.pointStyle),hitRadius:o.hitRadius?o.hitRadius:e.getValueAtIndexOrDefault(r.hitRadius,a,s.hitRadius)}}),t._model.skip=o.skip?o.skip:isNaN(t._model.x)||isNaN(t._model.y)},updateBezierControlPoints:function(){var t=this.chart.chartArea,a=this.getMeta();e.each(a.data,function(i,n){var o=i._model,r=e.splineCurve(e.previousItem(a.data,n,!0)._model,o,e.nextItem(a.data,n,!0)._model,o.tension);o.controlPointPreviousX=Math.max(Math.min(r.previous.x,t.right),t.left),o.controlPointPreviousY=Math.max(Math.min(r.previous.y,t.bottom),t.top),o.controlPointNextX=Math.max(Math.min(r.next.x,t.right),t.left),o.controlPointNextY=Math.max(Math.min(r.next.y,t.bottom),t.top),i.pivot()})},draw:function(t){var a=this.getMeta(),i=t||1;e.each(a.data,function(t){t.transition(i)}),a.dataset.transition(i).draw(),e.each(a.data,function(t){t.draw()})},setHoverStyle:function(t){var a=this.chart.data.datasets[t._datasetIndex],i=t.custom||{},n=t._index,o=t._model;o.radius=i.hoverRadius?i.hoverRadius:e.getValueAtIndexOrDefault(a.pointHoverRadius,n,this.chart.options.elements.point.hoverRadius),o.backgroundColor=i.hoverBackgroundColor?i.hoverBackgroundColor:e.getValueAtIndexOrDefault(a.pointHoverBackgroundColor,n,e.getHoverColor(o.backgroundColor)),o.borderColor=i.hoverBorderColor?i.hoverBorderColor:e.getValueAtIndexOrDefault(a.pointHoverBorderColor,n,e.getHoverColor(o.borderColor)),o.borderWidth=i.hoverBorderWidth?i.hoverBorderWidth:e.getValueAtIndexOrDefault(a.pointHoverBorderWidth,n,o.borderWidth)},removeHoverStyle:function(t){var a=this.chart.data.datasets[t._datasetIndex],i=t.custom||{},n=t._index,o=t._model,r=this.chart.options.elements.point;o.radius=i.radius?i.radius:e.getValueAtIndexOrDefault(a.radius,n,r.radius),o.backgroundColor=i.backgroundColor?i.backgroundColor:e.getValueAtIndexOrDefault(a.pointBackgroundColor,n,r.backgroundColor),o.borderColor=i.borderColor?i.borderColor:e.getValueAtIndexOrDefault(a.pointBorderColor,n,r.borderColor),o.borderWidth=i.borderWidth?i.borderWidth:e.getValueAtIndexOrDefault(a.pointBorderWidth,n,r.borderWidth)}})}},{}],21:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.global.animation={duration:1e3,easing:"easeOutQuart",onProgress:e.noop,onComplete:e.noop},t.Animation=t.Element.extend({currentStep:null,numSteps:60,easing:"",render:null,onAnimationProgress:null,onAnimationComplete:null}),t.animationService={frameDuration:17,animations:[],dropFrames:0,request:null,addAnimation:function(t,e,a,i){var n=this;i||(t.animating=!0);for(var o=0;o<n.animations.length;++o)if(n.animations[o].chartInstance===t)return void(n.animations[o].animationObject=e);n.animations.push({chartInstance:t,animationObject:e}),1===n.animations.length&&n.requestAnimationFrame()},cancelAnimation:function(t){var a=e.findIndex(this.animations,function(e){return e.chartInstance===t});-1!==a&&(this.animations.splice(a,1),t.animating=!1)},requestAnimationFrame:function(){var t=this;null===t.request&&(t.request=e.requestAnimFrame.call(window,function(){t.request=null,t.startDigest()}))},startDigest:function(){var t=this,e=Date.now(),a=0;t.dropFrames>1&&(a=Math.floor(t.dropFrames),t.dropFrames=t.dropFrames%1);for(var i=0;i<t.animations.length;)null===t.animations[i].animationObject.currentStep&&(t.animations[i].animationObject.currentStep=0),t.animations[i].animationObject.currentStep+=1+a,t.animations[i].animationObject.currentStep>t.animations[i].animationObject.numSteps&&(t.animations[i].animationObject.currentStep=t.animations[i].animationObject.numSteps),t.animations[i].animationObject.render(t.animations[i].chartInstance,t.animations[i].animationObject),t.animations[i].animationObject.onAnimationProgress&&t.animations[i].animationObject.onAnimationProgress.call&&t.animations[i].animationObject.onAnimationProgress.call(t.animations[i].chartInstance,t.animations[i]),t.animations[i].animationObject.currentStep===t.animations[i].animationObject.numSteps?(t.animations[i].animationObject.onAnimationComplete&&t.animations[i].animationObject.onAnimationComplete.call&&t.animations[i].animationObject.onAnimationComplete.call(t.animations[i].chartInstance,t.animations[i]),t.animations[i].chartInstance.animating=!1,t.animations.splice(i,1)):++i;var n=Date.now(),o=(n-e)/t.frameDuration;t.dropFrames+=o,t.animations.length>0&&t.requestAnimationFrame()}}}},{}],22:[function(t,e,a){"use strict";e.exports=function(t){var e=t.canvasHelpers={};e.drawPoint=function(t,e,a,i,n){var o,r,l,s,d,u;if("object"==typeof e&&(o=e.toString(),"[object HTMLImageElement]"===o||"[object HTMLCanvasElement]"===o))return void t.drawImage(e,i-e.width/2,n-e.height/2);if(!(isNaN(a)||0>=a)){switch(e){default:t.beginPath(),t.arc(i,n,a,0,2*Math.PI),t.closePath(),t.fill();break;case"triangle":t.beginPath(),r=3*a/Math.sqrt(3),d=r*Math.sqrt(3)/2,t.moveTo(i-r/2,n+d/3),t.lineTo(i+r/2,n+d/3),t.lineTo(i,n-2*d/3),t.closePath(),t.fill();break;case"rect":u=1/Math.SQRT2*a,t.beginPath(),t.fillRect(i-u,n-u,2*u,2*u),t.strokeRect(i-u,n-u,2*u,2*u);break;case"rectRot":u=1/Math.SQRT2*a,t.beginPath(),t.moveTo(i-u,n),t.lineTo(i,n+u),t.lineTo(i+u,n),t.lineTo(i,n-u),t.closePath(),t.fill();break;case"cross":t.beginPath(),t.moveTo(i,n+a),t.lineTo(i,n-a),t.moveTo(i-a,n),t.lineTo(i+a,n),t.closePath();break;case"crossRot":t.beginPath(),l=Math.cos(Math.PI/4)*a,s=Math.sin(Math.PI/4)*a,t.moveTo(i-l,n-s),t.lineTo(i+l,n+s),t.moveTo(i-l,n+s),t.lineTo(i+l,n-s),t.closePath();break;case"star":t.beginPath(),t.moveTo(i,n+a),t.lineTo(i,n-a),t.moveTo(i-a,n),t.lineTo(i+a,n),l=Math.cos(Math.PI/4)*a,s=Math.sin(Math.PI/4)*a,t.moveTo(i-l,n-s),t.lineTo(i+l,n+s),t.moveTo(i-l,n+s),t.lineTo(i+l,n-s),t.closePath();break;case"line":t.beginPath(),t.moveTo(i-a,n),t.lineTo(i+a,n),t.closePath();break;case"dash":t.beginPath(),t.moveTo(i,n),t.lineTo(i+a,n),t.closePath()}t.stroke()}}}},{}],23:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.types={},t.instances={},t.controllers={},t.Controller=function(a){return this.chart=a,this.config=a.config,this.options=this.config.options=e.configMerge(t.defaults.global,t.defaults[this.config.type],this.config.options||{}),this.id=e.uid(),Object.defineProperty(this,"data",{get:function(){return this.config.data}}),t.instances[this.id]=this,this.options.responsive&&this.resize(!0),this.initialize(),this},e.extend(t.Controller.prototype,{initialize:function(){var e=this;return t.plugins.notify("beforeInit",[e]),e.bindEvents(),e.ensureScalesHaveIDs(),e.buildOrUpdateControllers(),e.buildScales(),e.updateLayout(),e.resetElements(),e.initToolTip(),e.update(),t.plugins.notify("afterInit",[e]),e},clear:function(){return e.clear(this.chart),this},stop:function(){return t.animationService.cancelAnimation(this),this},resize:function(a){var i=this,n=i.chart,o=n.canvas,r=e.getMaximumWidth(o),l=n.aspectRatio,s=i.options.maintainAspectRatio&&isNaN(l)===!1&&isFinite(l)&&0!==l?r/l:e.getMaximumHeight(o),d=n.width!==r||n.height!==s;if(!d)return i;o.width=n.width=r,o.height=n.height=s,e.retinaScale(n);var u={width:r,height:s};return t.plugins.notify("resize",[i,u]),i.options.onResize&&i.options.onResize(i,u),a||(i.stop(),i.update(i.options.responsiveAnimationDuration)),i},ensureScalesHaveIDs:function(){var t=this.options,a=t.scales||{},i=t.scale;e.each(a.xAxes,function(t,e){t.id=t.id||"x-axis-"+e}),e.each(a.yAxes,function(t,e){t.id=t.id||"y-axis-"+e}),i&&(i.id=i.id||"scale")},buildScales:function(){var a=this,i=a.options,n=a.scales={},o=[];i.scales&&(o=o.concat((i.scales.xAxes||[]).map(function(t){return{options:t,dtype:"category"}}),(i.scales.yAxes||[]).map(function(t){return{options:t,dtype:"linear"}}))),i.scale&&o.push({options:i.scale,dtype:"radialLinear",isDefault:!0}),e.each(o,function(i){var o=i.options,r=e.getValueOrDefault(o.type,i.dtype),l=t.scaleService.getScaleConstructor(r);if(l){var s=new l({id:o.id,options:o,ctx:a.chart.ctx,chart:a});n[s.id]=s,i.isDefault&&(a.scale=s)}}),t.scaleService.addScalesToLayout(this)},updateLayout:function(){t.layoutService.update(this,this.chart.width,this.chart.height)},buildOrUpdateControllers:function(){var a=this,i=[],n=[];if(e.each(a.data.datasets,function(e,o){var r=a.getDatasetMeta(o);r.type||(r.type=e.type||a.config.type),i.push(r.type),r.controller?r.controller.updateIndex(o):(r.controller=new t.controllers[r.type](a,o),n.push(r.controller))},a),i.length>1)for(var o=1;o<i.length;o++)if(i[o]!==i[o-1]){a.isCombo=!0;break}return n},resetElements:function(){var t=this;e.each(t.data.datasets,function(e,a){t.getDatasetMeta(a).controller.reset()},t)},update:function(a,i){var n=this;t.plugins.notify("beforeUpdate",[n]),n.tooltip._data=n.data;var o=n.buildOrUpdateControllers();e.each(n.data.datasets,function(t,e){n.getDatasetMeta(e).controller.buildOrUpdateElements()},n),t.layoutService.update(n,n.chart.width,n.chart.height),t.plugins.notify("afterScaleUpdate",[n]),e.each(o,function(t){t.reset()}),n.updateDatasets(),t.plugins.notify("afterUpdate",[n]),n.render(a,i)},updateDatasets:function(){var e,a,i=this;if(t.plugins.notify("beforeDatasetsUpdate",[i])){for(e=0,a=i.data.datasets.length;a>e;++e)i.getDatasetMeta(e).controller.update();t.plugins.notify("afterDatasetsUpdate",[i])}},render:function(a,i){var n=this;t.plugins.notify("beforeRender",[n]);var o=n.options.animation;if(o&&("undefined"!=typeof a&&0!==a||"undefined"==typeof a&&0!==o.duration)){var r=new t.Animation;r.numSteps=(a||o.duration)/16.66,r.easing=o.easing,r.render=function(t,a){var i=e.easingEffects[a.easing],n=a.currentStep/a.numSteps,o=i(n);t.draw(o,n,a.currentStep)},r.onAnimationProgress=o.onProgress,r.onAnimationComplete=o.onComplete,t.animationService.addAnimation(n,r,a,i)}else n.draw(),o&&o.onComplete&&o.onComplete.call&&o.onComplete.call(n);return n},draw:function(a){var i=this,n=a||1;i.clear(),t.plugins.notify("beforeDraw",[i,n]),e.each(i.boxes,function(t){t.draw(i.chartArea)},i),i.scale&&i.scale.draw(),t.plugins.notify("beforeDatasetsDraw",[i,n]),e.each(i.data.datasets,function(t,e){i.isDatasetVisible(e)&&i.getDatasetMeta(e).controller.draw(a)},i,!0),t.plugins.notify("afterDatasetsDraw",[i,n]),i.tooltip.transition(n).draw(),t.plugins.notify("afterDraw",[i,n])},getElementAtEvent:function(t){var a=this,i=e.getRelativePosition(t,a.chart),n=[];return e.each(a.data.datasets,function(t,o){if(a.isDatasetVisible(o)){var r=a.getDatasetMeta(o);e.each(r.data,function(t){return t.inRange(i.x,i.y)?(n.push(t),n):void 0})}}),n.slice(0,1)},getElementsAtEvent:function(t){var a=this,i=e.getRelativePosition(t,a.chart),n=[],o=function(){if(a.data.datasets)for(var t=0;t<a.data.datasets.length;t++){var e=a.getDatasetMeta(t);if(a.isDatasetVisible(t))for(var n=0;n<e.data.length;n++)if(e.data[n].inRange(i.x,i.y))return e.data[n]}}.call(a);return o?(e.each(a.data.datasets,function(t,e){if(a.isDatasetVisible(e)){var i=a.getDatasetMeta(e),r=i.data[o._index];r&&!r._view.skip&&n.push(r)}},a),n):n},getElementsAtXAxis:function(t){var a=this,i=e.getRelativePosition(t,a.chart),n=[],o=function(){if(a.data.datasets)for(var t=0;t<a.data.datasets.length;t++){var e=a.getDatasetMeta(t);if(a.isDatasetVisible(t))for(var n=0;n<e.data.length;n++)if(e.data[n].inLabelRange(i.x,i.y))return e.data[n]}}.call(a);return o?(e.each(a.data.datasets,function(t,i){if(a.isDatasetVisible(i)){var r=a.getDatasetMeta(i),l=e.findIndex(r.data,function(t){return o._model.x===t._model.x});-1===l||r.data[l]._view.skip||n.push(r.data[l])}},a),n):n},getElementsAtEventForMode:function(t,e){var a=this;switch(e){case"single":return a.getElementAtEvent(t);case"label":return a.getElementsAtEvent(t);case"dataset":return a.getDatasetAtEvent(t);case"x-axis":return a.getElementsAtXAxis(t);default:return t}},getDatasetAtEvent:function(t){var e=this.getElementAtEvent(t);
    return e.length>0&&(e=this.getDatasetMeta(e[0]._datasetIndex).data),e},getDatasetMeta:function(t){var e=this,a=e.data.datasets[t];a._meta||(a._meta={});var i=a._meta[e.id];return i||(i=a._meta[e.id]={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null}),i},getVisibleDatasetCount:function(){for(var t=0,e=0,a=this.data.datasets.length;a>e;++e)this.isDatasetVisible(e)&&t++;return t},isDatasetVisible:function(t){var e=this.getDatasetMeta(t);return"boolean"==typeof e.hidden?!e.hidden:!this.data.datasets[t].hidden},generateLegend:function(){return this.options.legendCallback(this)},destroy:function(){var a=this;a.stop(),a.clear(),e.unbindEvents(a,a.events),e.removeResizeListener(a.chart.canvas.parentNode);var i=a.chart.canvas;i.width=a.chart.width,i.height=a.chart.height,void 0!==a.chart.originalDevicePixelRatio&&a.chart.ctx.scale(1/a.chart.originalDevicePixelRatio,1/a.chart.originalDevicePixelRatio),i.style.width=a.chart.originalCanvasStyleWidth,i.style.height=a.chart.originalCanvasStyleHeight,t.plugins.notify("destroy",[a]),delete t.instances[a.id]},toBase64Image:function(){return this.chart.canvas.toDataURL.apply(this.chart.canvas,arguments)},initToolTip:function(){var e=this;e.tooltip=new t.Tooltip({_chart:e.chart,_chartInstance:e,_data:e.data,_options:e.options.tooltips},e)},bindEvents:function(){var t=this;e.bindEvents(t,t.options.events,function(e){t.eventHandler(e)})},updateHoverStyle:function(t,e,a){var i,n,o,r=a?"setHoverStyle":"removeHoverStyle";switch(e){case"single":t=[t[0]];break;case"label":case"dataset":case"x-axis":break;default:return}for(n=0,o=t.length;o>n;++n)i=t[n],i&&this.getDatasetMeta(i._datasetIndex).controller[r](i)},eventHandler:function(t){var a=this,i=a.tooltip,n=a.options||{},o=n.hover,r=n.tooltips;return a.lastActive=a.lastActive||[],a.lastTooltipActive=a.lastTooltipActive||[],"mouseout"===t.type?(a.active=[],a.tooltipActive=[]):(a.active=a.getElementsAtEventForMode(t,o.mode),a.tooltipActive=a.getElementsAtEventForMode(t,r.mode)),o.onHover&&o.onHover.call(a,a.active),a.legend&&a.legend.handleEvent&&a.legend.handleEvent(t),("mouseup"===t.type||"click"===t.type)&&n.onClick&&n.onClick.call(a,t,a.active),a.lastActive.length&&a.updateHoverStyle(a.lastActive,o.mode,!1),a.active.length&&o.mode&&a.updateHoverStyle(a.active,o.mode,!0),(r.enabled||r.custom)&&(i.initialize(),i._active=a.tooltipActive,i.update(!0)),i.pivot(),a.animating||e.arrayEquals(a.active,a.lastActive)&&e.arrayEquals(a.tooltipActive,a.lastTooltipActive)||(a.stop(),(r.enabled||r.custom)&&i.update(!0),a.render(o.animationDuration,!0)),a.lastActive=a.active,a.lastTooltipActive=a.tooltipActive,a}})}},{}],24:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=e.noop;t.DatasetController=function(t,e){this.initialize(t,e)},e.extend(t.DatasetController.prototype,{datasetElementType:null,dataElementType:null,initialize:function(t,e){var a=this;a.chart=t,a.index=e,a.linkScales(),a.addElements()},updateIndex:function(t){this.index=t},linkScales:function(){var t=this,e=t.getMeta(),a=t.getDataset();null===e.xAxisID&&(e.xAxisID=a.xAxisID||t.chart.options.scales.xAxes[0].id),null===e.yAxisID&&(e.yAxisID=a.yAxisID||t.chart.options.scales.yAxes[0].id)},getDataset:function(){return this.chart.data.datasets[this.index]},getMeta:function(){return this.chart.getDatasetMeta(this.index)},getScaleForId:function(t){return this.chart.scales[t]},reset:function(){this.update(!0)},createMetaDataset:function(){var t=this,e=t.datasetElementType;return e&&new e({_chart:t.chart.chart,_datasetIndex:t.index})},createMetaData:function(t){var e=this,a=e.dataElementType;return a&&new a({_chart:e.chart.chart,_datasetIndex:e.index,_index:t})},addElements:function(){var t,e,a=this,i=a.getMeta(),n=a.getDataset().data||[],o=i.data;for(t=0,e=n.length;e>t;++t)o[t]=o[t]||a.createMetaData(i,t);i.dataset=i.dataset||a.createMetaDataset()},addElementAndReset:function(t){var e=this,a=e.createMetaData(t);e.getMeta().data.splice(t,0,a),e.updateElement(a,t,!0)},buildOrUpdateElements:function(){var t=this.getMeta(),e=t.data,a=this.getDataset().data.length,i=e.length;if(i>a)e.splice(a,i-a);else if(a>i)for(var n=i;a>n;++n)this.addElementAndReset(n)},update:a,draw:function(t){var a=t||1;e.each(this.getMeta().data,function(t){t.transition(a).draw()})},removeHoverStyle:function(t,a){var i=this.chart.data.datasets[t._datasetIndex],n=t._index,o=t.custom||{},r=e.getValueAtIndexOrDefault,l=t._model;l.backgroundColor=o.backgroundColor?o.backgroundColor:r(i.backgroundColor,n,a.backgroundColor),l.borderColor=o.borderColor?o.borderColor:r(i.borderColor,n,a.borderColor),l.borderWidth=o.borderWidth?o.borderWidth:r(i.borderWidth,n,a.borderWidth)},setHoverStyle:function(t){var a=this.chart.data.datasets[t._datasetIndex],i=t._index,n=t.custom||{},o=e.getValueAtIndexOrDefault,r=e.getHoverColor,l=t._model;l.backgroundColor=n.hoverBackgroundColor?n.hoverBackgroundColor:o(a.hoverBackgroundColor,i,r(l.backgroundColor)),l.borderColor=n.hoverBorderColor?n.hoverBorderColor:o(a.hoverBorderColor,i,r(l.borderColor)),l.borderWidth=n.hoverBorderWidth?n.hoverBorderWidth:o(a.hoverBorderWidth,i,l.borderWidth)}}),t.DatasetController.extend=e.inherits}},{}],25:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.elements={},t.Element=function(t){e.extend(this,t),this.initialize.apply(this,arguments)},e.extend(t.Element.prototype,{initialize:function(){this.hidden=!1},pivot:function(){var t=this;return t._view||(t._view=e.clone(t._model)),t._start=e.clone(t._view),t},transition:function(t){var a=this;return a._view||(a._view=e.clone(a._model)),1===t?(a._view=a._model,a._start=null,a):(a._start||a.pivot(),e.each(a._model,function(i,n){if("_"===n[0]);else if(a._view.hasOwnProperty(n))if(i===a._view[n]);else if("string"==typeof i)try{var o=e.color(a._model[n]).mix(e.color(a._start[n]),t);a._view[n]=o.rgbString()}catch(r){a._view[n]=i}else if("number"==typeof i){var l=void 0!==a._start[n]&&isNaN(a._start[n])===!1?a._start[n]:0;a._view[n]=(a._model[n]-l)*t+l}else a._view[n]=i;else"number"!=typeof i||isNaN(a._view[n])?a._view[n]=i:a._view[n]=i*t},a),a)},tooltipPosition:function(){return{x:this._model.x,y:this._model.y}},hasValue:function(){return e.isNumber(this._model.x)&&e.isNumber(this._model.y)}}),t.Element.extend=e.inherits}},{}],26:[function(t,e,a){"use strict";var i=t(3);e.exports=function(t){function e(t,e,a){var i;return"string"==typeof t?(i=parseInt(t,10),-1!==t.indexOf("%")&&(i=i/100*e.parentNode[a])):i=t,i}function a(t){return void 0!==t&&null!==t&&"none"!==t}function n(t,i,n){var o=document.defaultView,r=t.parentNode,l=o.getComputedStyle(t)[i],s=o.getComputedStyle(r)[i],d=a(l),u=a(s),c=Number.POSITIVE_INFINITY;return d||u?Math.min(d?e(l,t,n):c,u?e(s,r,n):c):"none"}var o=t.helpers={};o.each=function(t,e,a,i){var n,r;if(o.isArray(t))if(r=t.length,i)for(n=r-1;n>=0;n--)e.call(a,t[n],n);else for(n=0;r>n;n++)e.call(a,t[n],n);else if("object"==typeof t){var l=Object.keys(t);for(r=l.length,n=0;r>n;n++)e.call(a,t[l[n]],l[n])}},o.clone=function(t){var e={};return o.each(t,function(t,a){o.isArray(t)?e[a]=t.slice(0):"object"==typeof t&&null!==t?e[a]=o.clone(t):e[a]=t}),e},o.extend=function(t){for(var e=function(e,a){t[a]=e},a=1,i=arguments.length;i>a;a++)o.each(arguments[a],e);return t},o.configMerge=function(e){var a=o.clone(e);return o.each(Array.prototype.slice.call(arguments,1),function(e){o.each(e,function(e,i){if("scales"===i)a[i]=o.scaleMerge(a.hasOwnProperty(i)?a[i]:{},e);else if("scale"===i)a[i]=o.configMerge(a.hasOwnProperty(i)?a[i]:{},t.scaleService.getScaleDefaults(e.type),e);else if(a.hasOwnProperty(i)&&o.isArray(a[i])&&o.isArray(e)){var n=a[i];o.each(e,function(t,e){e<n.length?"object"==typeof n[e]&&null!==n[e]&&"object"==typeof t&&null!==t?n[e]=o.configMerge(n[e],t):n[e]=t:n.push(t)})}else a.hasOwnProperty(i)&&"object"==typeof a[i]&&null!==a[i]&&"object"==typeof e?a[i]=o.configMerge(a[i],e):a[i]=e})}),a},o.scaleMerge=function(e,a){var i=o.clone(e);return o.each(a,function(e,a){"xAxes"===a||"yAxes"===a?i.hasOwnProperty(a)?o.each(e,function(e,n){var r=o.getValueOrDefault(e.type,"xAxes"===a?"category":"linear"),l=t.scaleService.getScaleDefaults(r);n>=i[a].length||!i[a][n].type?i[a].push(o.configMerge(l,e)):e.type&&e.type!==i[a][n].type?i[a][n]=o.configMerge(i[a][n],l,e):i[a][n]=o.configMerge(i[a][n],e)}):(i[a]=[],o.each(e,function(e){var n=o.getValueOrDefault(e.type,"xAxes"===a?"category":"linear");i[a].push(o.configMerge(t.scaleService.getScaleDefaults(n),e))})):i.hasOwnProperty(a)&&"object"==typeof i[a]&&null!==i[a]&&"object"==typeof e?i[a]=o.configMerge(i[a],e):i[a]=e}),i},o.getValueAtIndexOrDefault=function(t,e,a){return void 0===t||null===t?a:o.isArray(t)?e<t.length?t[e]:a:t},o.getValueOrDefault=function(t,e){return void 0===t?e:t},o.indexOf=Array.prototype.indexOf?function(t,e){return t.indexOf(e)}:function(t,e){for(var a=0,i=t.length;i>a;++a)if(t[a]===e)return a;return-1},o.where=function(t,e){if(o.isArray(t)&&Array.prototype.filter)return t.filter(e);var a=[];return o.each(t,function(t){e(t)&&a.push(t)}),a},o.findIndex=Array.prototype.findIndex?function(t,e,a){return t.findIndex(e,a)}:function(t,e,a){a=void 0===a?t:a;for(var i=0,n=t.length;n>i;++i)if(e.call(a,t[i],i,t))return i;return-1},o.findNextWhere=function(t,e,a){(void 0===a||null===a)&&(a=-1);for(var i=a+1;i<t.length;i++){var n=t[i];if(e(n))return n}},o.findPreviousWhere=function(t,e,a){(void 0===a||null===a)&&(a=t.length);for(var i=a-1;i>=0;i--){var n=t[i];if(e(n))return n}},o.inherits=function(t){var e=this,a=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return e.apply(this,arguments)},i=function(){this.constructor=a};return i.prototype=e.prototype,a.prototype=new i,a.extend=o.inherits,t&&o.extend(a.prototype,t),a.__super__=e.prototype,a},o.noop=function(){},o.uid=function(){var t=0;return function(){return t++}}(),o.isNumber=function(t){return!isNaN(parseFloat(t))&&isFinite(t)},o.almostEquals=function(t,e,a){return Math.abs(t-e)<a},o.max=function(t){return t.reduce(function(t,e){return isNaN(e)?t:Math.max(t,e)},Number.NEGATIVE_INFINITY)},o.min=function(t){return t.reduce(function(t,e){return isNaN(e)?t:Math.min(t,e)},Number.POSITIVE_INFINITY)},o.sign=Math.sign?function(t){return Math.sign(t)}:function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},o.log10=Math.log10?function(t){return Math.log10(t)}:function(t){return Math.log(t)/Math.LN10},o.toRadians=function(t){return t*(Math.PI/180)},o.toDegrees=function(t){return t*(180/Math.PI)},o.getAngleFromPoint=function(t,e){var a=e.x-t.x,i=e.y-t.y,n=Math.sqrt(a*a+i*i),o=Math.atan2(i,a);return o<-.5*Math.PI&&(o+=2*Math.PI),{angle:o,distance:n}},o.aliasPixel=function(t){return t%2===0?0:.5},o.splineCurve=function(t,e,a,i){var n=t.skip?e:t,o=e,r=a.skip?e:a,l=Math.sqrt(Math.pow(o.x-n.x,2)+Math.pow(o.y-n.y,2)),s=Math.sqrt(Math.pow(r.x-o.x,2)+Math.pow(r.y-o.y,2)),d=l/(l+s),u=s/(l+s);d=isNaN(d)?0:d,u=isNaN(u)?0:u;var c=i*d,h=i*u;return{previous:{x:o.x-c*(r.x-n.x),y:o.y-c*(r.y-n.y)},next:{x:o.x+h*(r.x-n.x),y:o.y+h*(r.y-n.y)}}},o.EPSILON=Number.EPSILON||1e-14,o.splineCurveMonotone=function(t){var e,a,i,n,r=(t||[]).map(function(t){return{model:t._model,deltaK:0,mK:0}}),l=r.length;for(e=0;l>e;++e)i=r[e],i.model.skip||(a=e>0?r[e-1]:null,n=l-1>e?r[e+1]:null,n&&!n.model.skip&&(i.deltaK=(n.model.y-i.model.y)/(n.model.x-i.model.x)),!a||a.model.skip?i.mK=i.deltaK:!n||n.model.skip?i.mK=a.deltaK:this.sign(a.deltaK)!==this.sign(i.deltaK)?i.mK=0:i.mK=(a.deltaK+i.deltaK)/2);var s,d,u,c;for(e=0;l-1>e;++e)i=r[e],n=r[e+1],i.model.skip||n.model.skip||(o.almostEquals(i.deltaK,0,this.EPSILON)?i.mK=n.mK=0:(s=i.mK/i.deltaK,d=n.mK/i.deltaK,c=Math.pow(s,2)+Math.pow(d,2),9>=c||(u=3/Math.sqrt(c),i.mK=s*u*i.deltaK,n.mK=d*u*i.deltaK)));var h;for(e=0;l>e;++e)i=r[e],i.model.skip||(a=e>0?r[e-1]:null,n=l-1>e?r[e+1]:null,a&&!a.model.skip&&(h=(i.model.x-a.model.x)/3,i.model.controlPointPreviousX=i.model.x-h,i.model.controlPointPreviousY=i.model.y-h*i.mK),n&&!n.model.skip&&(h=(n.model.x-i.model.x)/3,i.model.controlPointNextX=i.model.x+h,i.model.controlPointNextY=i.model.y+h*i.mK))},o.nextItem=function(t,e,a){return a?e>=t.length-1?t[0]:t[e+1]:e>=t.length-1?t[t.length-1]:t[e+1]},o.previousItem=function(t,e,a){return a?0>=e?t[t.length-1]:t[e-1]:0>=e?t[0]:t[e-1]},o.niceNum=function(t,e){var a,i=Math.floor(o.log10(t)),n=t/Math.pow(10,i);return a=e?1.5>n?1:3>n?2:7>n?5:10:1>=n?1:2>=n?2:5>=n?5:10,a*Math.pow(10,i)};var r=o.easingEffects={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return-1*t*(t-2)},easeInOutQuad:function(t){return(t/=.5)<1?.5*t*t:-0.5*(--t*(t-2)-1)},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return 1*((t=t/1-1)*t*t+1)},easeInOutCubic:function(t){return(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return-1*((t=t/1-1)*t*t*t-1)},easeInOutQuart:function(t){return(t/=.5)<1?.5*t*t*t*t:-0.5*((t-=2)*t*t*t-2)},easeInQuint:function(t){return 1*(t/=1)*t*t*t*t},easeOutQuint:function(t){return 1*((t=t/1-1)*t*t*t*t+1)},easeInOutQuint:function(t){return(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},easeInSine:function(t){return-1*Math.cos(t/1*(Math.PI/2))+1},easeOutSine:function(t){return 1*Math.sin(t/1*(Math.PI/2))},easeInOutSine:function(t){return-0.5*(Math.cos(Math.PI*t/1)-1)},easeInExpo:function(t){return 0===t?1:1*Math.pow(2,10*(t/1-1))},easeOutExpo:function(t){return 1===t?1:1*(-Math.pow(2,-10*t/1)+1)},easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(-Math.pow(2,-10*--t)+2)},easeInCirc:function(t){return t>=1?t:-1*(Math.sqrt(1-(t/=1)*t)-1)},easeOutCirc:function(t){return 1*Math.sqrt(1-(t=t/1-1)*t)},easeInOutCirc:function(t){return(t/=.5)<1?-0.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},easeInElastic:function(t){var e=1.70158,a=0,i=1;return 0===t?0:1===(t/=1)?1:(a||(a=.3),i<Math.abs(1)?(i=1,e=a/4):e=a/(2*Math.PI)*Math.asin(1/i),-(i*Math.pow(2,10*(t-=1))*Math.sin((1*t-e)*(2*Math.PI)/a)))},easeOutElastic:function(t){var e=1.70158,a=0,i=1;return 0===t?0:1===(t/=1)?1:(a||(a=.3),i<Math.abs(1)?(i=1,e=a/4):e=a/(2*Math.PI)*Math.asin(1/i),i*Math.pow(2,-10*t)*Math.sin((1*t-e)*(2*Math.PI)/a)+1)},easeInOutElastic:function(t){var e=1.70158,a=0,i=1;return 0===t?0:2===(t/=.5)?1:(a||(a=1*(.3*1.5)),i<Math.abs(1)?(i=1,e=a/4):e=a/(2*Math.PI)*Math.asin(1/i),1>t?-.5*(i*Math.pow(2,10*(t-=1))*Math.sin((1*t-e)*(2*Math.PI)/a)):i*Math.pow(2,-10*(t-=1))*Math.sin((1*t-e)*(2*Math.PI)/a)*.5+1)},easeInBack:function(t){var e=1.70158;return 1*(t/=1)*t*((e+1)*t-e)},easeOutBack:function(t){var e=1.70158;return 1*((t=t/1-1)*t*((e+1)*t+e)+1)},easeInOutBack:function(t){var e=1.70158;return(t/=.5)<1?.5*(t*t*(((e*=1.525)+1)*t-e)):.5*((t-=2)*t*(((e*=1.525)+1)*t+e)+2)},easeInBounce:function(t){return 1-r.easeOutBounce(1-t)},easeOutBounce:function(t){return(t/=1)<1/2.75?1*(7.5625*t*t):2/2.75>t?1*(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1*(7.5625*(t-=2.25/2.75)*t+.9375):1*(7.5625*(t-=2.625/2.75)*t+.984375)},easeInOutBounce:function(t){return.5>t?.5*r.easeInBounce(2*t):.5*r.easeOutBounce(2*t-1)+.5}};o.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(t,1e3/60)}}(),o.cancelAnimFrame=function(){return window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){return window.clearTimeout(t,1e3/60)}}(),o.getRelativePosition=function(t,e){var a,i,n=t.originalEvent||t,r=t.currentTarget||t.srcElement,l=r.getBoundingClientRect(),s=n.touches;s&&s.length>0?(a=s[0].clientX,i=s[0].clientY):(a=n.clientX,i=n.clientY);var d=parseFloat(o.getStyle(r,"padding-left")),u=parseFloat(o.getStyle(r,"padding-top")),c=parseFloat(o.getStyle(r,"padding-right")),h=parseFloat(o.getStyle(r,"padding-bottom")),f=l.right-l.left-d-c,g=l.bottom-l.top-u-h;return a=Math.round((a-l.left-d)/f*r.width/e.currentDevicePixelRatio),i=Math.round((i-l.top-u)/g*r.height/e.currentDevicePixelRatio),{x:a,y:i}},o.addEvent=function(t,e,a){t.addEventListener?t.addEventListener(e,a):t.attachEvent?t.attachEvent("on"+e,a):t["on"+e]=a},o.removeEvent=function(t,e,a){t.removeEventListener?t.removeEventListener(e,a,!1):t.detachEvent?t.detachEvent("on"+e,a):t["on"+e]=o.noop},o.bindEvents=function(t,e,a){var i=t.events=t.events||{};o.each(e,function(e){i[e]=function(){a.apply(t,arguments)},o.addEvent(t.chart.canvas,e,i[e])})},o.unbindEvents=function(t,e){var a=t.chart.canvas;o.each(e,function(t,e){o.removeEvent(a,e,t)})},o.getConstraintWidth=function(t){return n(t,"max-width","clientWidth")},o.getConstraintHeight=function(t){return n(t,"max-height","clientHeight")},o.getMaximumWidth=function(t){var e=t.parentNode,a=parseInt(o.getStyle(e,"padding-left"),10),i=parseInt(o.getStyle(e,"padding-right"),10),n=e.clientWidth-a-i,r=o.getConstraintWidth(t);return isNaN(r)?n:Math.min(n,r)},o.getMaximumHeight=function(t){var e=t.parentNode,a=parseInt(o.getStyle(e,"padding-top"),10),i=parseInt(o.getStyle(e,"padding-bottom"),10),n=e.clientHeight-a-i,r=o.getConstraintHeight(t);return isNaN(r)?n:Math.min(n,r)},o.getStyle=function(t,e){return t.currentStyle?t.currentStyle[e]:document.defaultView.getComputedStyle(t,null).getPropertyValue(e)},o.retinaScale=function(t){var e=t.ctx,a=t.canvas,i=a.width,n=a.height,o=t.currentDevicePixelRatio=window.devicePixelRatio||1;1!==o&&(a.height=n*o,a.width=i*o,e.scale(o,o),t.originalDevicePixelRatio=t.originalDevicePixelRatio||o),a.style.width=i+"px",a.style.height=n+"px"},o.clear=function(t){t.ctx.clearRect(0,0,t.width,t.height)},o.fontString=function(t,e,a){return e+" "+t+"px "+a},o.longestText=function(t,e,a,i){i=i||{};var n=i.data=i.data||{},r=i.garbageCollect=i.garbageCollect||[];i.font!==e&&(n=i.data={},r=i.garbageCollect=[],i.font=e),t.font=e;var l=0;o.each(a,function(e){void 0!==e&&null!==e&&o.isArray(e)!==!0?l=o.measureText(t,n,r,l,e):o.isArray(e)&&o.each(e,function(e){void 0===e||null===e||o.isArray(e)||(l=o.measureText(t,n,r,l,e))})});var s=r.length/2;if(s>a.length){for(var d=0;s>d;d++)delete n[r[d]];r.splice(0,s)}return l},o.measureText=function(t,e,a,i,n){var o=e[n];return o||(o=e[n]=t.measureText(n).width,a.push(n)),o>i&&(i=o),i},o.numberOfLabelLines=function(t){var e=1;return o.each(t,function(t){o.isArray(t)&&t.length>e&&(e=t.length)}),e},o.drawRoundedRectangle=function(t,e,a,i,n,o){t.beginPath(),t.moveTo(e+o,a),t.lineTo(e+i-o,a),t.quadraticCurveTo(e+i,a,e+i,a+o),t.lineTo(e+i,a+n-o),t.quadraticCurveTo(e+i,a+n,e+i-o,a+n),t.lineTo(e+o,a+n),t.quadraticCurveTo(e,a+n,e,a+n-o),t.lineTo(e,a+o),t.quadraticCurveTo(e,a,e+o,a),t.closePath()},o.color=function(e){return i?i(e instanceof CanvasGradient?t.defaults.global.defaultColor:e):(console.error("Color.js not found!"),e)},o.addResizeListener=function(t,e){var a=document.createElement("iframe"),i="chartjs-hidden-iframe";a.classlist?a.classlist.add(i):a.setAttribute("class",i),a.tabIndex=-1;var n=a.style;n.width="100%",n.display="block",n.border=0,n.height=0,n.margin=0,n.position="absolute",n.left=0,n.right=0,n.top=0,n.bottom=0,t.insertBefore(a,t.firstChild),(a.contentWindow||a).onresize=function(){return e?e():void 0}},o.removeResizeListener=function(t){var e=t.querySelector(".chartjs-hidden-iframe");e&&e.parentNode.removeChild(e)},o.isArray=Array.isArray?function(t){return Array.isArray(t)}:function(t){return"[object Array]"===Object.prototype.toString.call(t)},o.arrayEquals=function(t,e){var a,i,n,r;if(!t||!e||t.length!==e.length)return!1;for(a=0,i=t.length;i>a;++a)if(n=t[a],r=e[a],n instanceof Array&&r instanceof Array){if(!o.arrayEquals(n,r))return!1}else if(n!==r)return!1;return!0},o.callCallback=function(t,e,a){t&&"function"==typeof t.call&&t.apply(a,e)},o.getHoverColor=function(t){return t instanceof CanvasPattern?t:o.color(t).saturate(.5).darken(.1).rgbString()}}},{3:3}],27:[function(t,e,a){"use strict";e.exports=function(){var t=function(e,a){var i=this,n=t.helpers;return i.config=a||{data:{datasets:[]}},e.length&&e[0].getContext&&(e=e[0]),e.getContext&&(e=e.getContext("2d")),i.ctx=e,i.canvas=e.canvas,e.canvas.style.display=e.canvas.style.display||"block",i.width=e.canvas.width||parseInt(n.getStyle(e.canvas,"width"),10)||n.getMaximumWidth(e.canvas),i.height=e.canvas.height||parseInt(n.getStyle(e.canvas,"height"),10)||n.getMaximumHeight(e.canvas),i.aspectRatio=i.width/i.height,(isNaN(i.aspectRatio)||isFinite(i.aspectRatio)===!1)&&(i.aspectRatio=void 0!==a.aspectRatio?a.aspectRatio:2),i.originalCanvasStyleWidth=e.canvas.style.width,i.originalCanvasStyleHeight=e.canvas.style.height,n.retinaScale(i),i.controller=new t.Controller(i),n.addResizeListener(e.canvas.parentNode,function(){i.controller&&i.controller.config.options.responsive&&i.controller.resize()}),i.controller?i.controller:i};return t.defaults={global:{responsive:!0,responsiveAnimationDuration:0,maintainAspectRatio:!0,events:["mousemove","mouseout","click","touchstart","touchmove"],hover:{onHover:null,mode:"single",animationDuration:400},onClick:null,defaultColor:"rgba(0,0,0,0.1)",defaultFontColor:"#666",defaultFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",defaultFontSize:12,defaultFontStyle:"normal",showLines:!0,elements:{},legendCallback:function(t){var e=[];e.push('<ul class="'+t.id+'-legend">');for(var a=0;a<t.data.datasets.length;a++)e.push('<li><span style="background-color:'+t.data.datasets[a].backgroundColor+'"></span>'),t.data.datasets[a].label&&e.push(t.data.datasets[a].label),e.push("</li>");return e.push("</ul>"),e.join("")}}},t.Chart=t,t}},{}],28:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.layoutService={defaults:{},addBox:function(t,e){t.boxes||(t.boxes=[]),t.boxes.push(e)},removeBox:function(t,e){t.boxes&&t.boxes.splice(t.boxes.indexOf(e),1)},update:function(t,a,i){function n(t){var e,a=t.isHorizontal();a?(e=t.update(t.options.fullWidth?p:k,y),S-=e.height):(e=t.update(x,v),k-=e.width),w.push({horizontal:a,minSize:e,box:t})}function o(t){var a=e.findNextWhere(w,function(e){return e.box===t});if(a)if(t.isHorizontal()){var i={left:C,right:M,top:0,bottom:0};t.update(t.options.fullWidth?p:k,m/2,i)}else t.update(a.minSize.width,S)}function r(t){var a=e.findNextWhere(w,function(e){return e.box===t}),i={left:0,right:0,top:D,bottom:I};a&&t.update(a.minSize.width,S,i)}function l(t){t.isHorizontal()?(t.left=t.options.fullWidth?s:C,t.right=t.options.fullWidth?a-s:C+k,t.top=F,t.bottom=F+t.height,F=t.bottom):(t.left=P,t.right=P+t.width,t.top=D,t.bottom=D+S,P=t.right)}if(t){var s=0,d=0,u=e.where(t.boxes,function(t){return"left"===t.options.position}),c=e.where(t.boxes,function(t){return"right"===t.options.position}),h=e.where(t.boxes,function(t){return"top"===t.options.position}),f=e.where(t.boxes,function(t){return"bottom"===t.options.position}),g=e.where(t.boxes,function(t){return"chartArea"===t.options.position});h.sort(function(t,e){return(e.options.fullWidth?1:0)-(t.options.fullWidth?1:0)}),f.sort(function(t,e){return(t.options.fullWidth?1:0)-(e.options.fullWidth?1:0)});var p=a-2*s,m=i-2*d,b=p/2,v=m/2,x=(a-b)/(u.length+c.length),y=(i-v)/(h.length+f.length),k=p,S=m,w=[];e.each(u.concat(c,h,f),n);var C=s,M=s,D=d,I=d;e.each(u.concat(c),o),e.each(u,function(t){C+=t.width}),e.each(c,function(t){M+=t.width}),e.each(h.concat(f),o),e.each(h,function(t){D+=t.height}),e.each(f,function(t){I+=t.height}),e.each(u.concat(c),r),C=s,M=s,D=d,I=d,e.each(u,function(t){C+=t.width}),e.each(c,function(t){M+=t.width}),e.each(h,function(t){D+=t.height}),e.each(f,function(t){I+=t.height});var A=i-D-I,T=a-C-M;(T!==k||A!==S)&&(e.each(u,function(t){t.height=A}),e.each(c,function(t){t.height=A}),e.each(h,function(t){t.options.fullWidth||(t.width=T)}),e.each(f,function(t){t.options.fullWidth||(t.width=T)}),S=A,k=T);var P=s,F=d;e.each(u.concat(h),l),P+=k,F+=S,e.each(c,l),e.each(f,l),t.chartArea={left:C,top:D,right:C+k,bottom:D+S},e.each(g,function(e){e.left=t.chartArea.left,e.top=t.chartArea.top,e.right=t.chartArea.right,e.bottom=t.chartArea.bottom,e.update(k,S)})}}}}},{}],29:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=e.noop;t.defaults.global.legend={display:!0,position:"top",fullWidth:!0,reverse:!1,onClick:function(t,e){var a=e.datasetIndex,i=this.chart,n=i.getDatasetMeta(a);n.hidden=null===n.hidden?!i.data.datasets[a].hidden:null,i.update()},onHover:null,labels:{boxWidth:40,padding:10,generateLabels:function(t){var a=t.data;return e.isArray(a.datasets)?a.datasets.map(function(a,i){return{text:a.label,fillStyle:e.isArray(a.backgroundColor)?a.backgroundColor[0]:a.backgroundColor,hidden:!t.isDatasetVisible(i),lineCap:a.borderCapStyle,lineDash:a.borderDash,lineDashOffset:a.borderDashOffset,lineJoin:a.borderJoinStyle,lineWidth:a.borderWidth,strokeStyle:a.borderColor,pointStyle:a.pointStyle,datasetIndex:i}},this):[]}}},t.Legend=t.Element.extend({initialize:function(t){e.extend(this,t),this.legendHitBoxes=[],this.doughnutMode=!1},beforeUpdate:a,update:function(t,e,a){var i=this;return i.beforeUpdate(),i.maxWidth=t,i.maxHeight=e,i.margins=a,i.beforeSetDimensions(),i.setDimensions(),i.afterSetDimensions(),i.beforeBuildLabels(),i.buildLabels(),i.afterBuildLabels(),i.beforeFit(),i.fit(),i.afterFit(),i.afterUpdate(),i.minSize},afterUpdate:a,beforeSetDimensions:a,setDimensions:function(){var t=this;t.isHorizontal()?(t.width=t.maxWidth,t.left=0,t.right=t.width):(t.height=t.maxHeight,t.top=0,t.bottom=t.height),t.paddingLeft=0,t.paddingTop=0,t.paddingRight=0,t.paddingBottom=0,t.minSize={width:0,height:0}},afterSetDimensions:a,beforeBuildLabels:a,buildLabels:function(){var t=this;t.legendItems=t.options.labels.generateLabels.call(t,t.chart),t.options.reverse&&t.legendItems.reverse()},afterBuildLabels:a,beforeFit:a,fit:function(){var a=this,i=a.options,n=i.labels,o=i.display,r=a.ctx,l=t.defaults.global,s=e.getValueOrDefault,d=s(n.fontSize,l.defaultFontSize),u=s(n.fontStyle,l.defaultFontStyle),c=s(n.fontFamily,l.defaultFontFamily),h=e.fontString(d,u,c),f=a.legendHitBoxes=[],g=a.minSize,p=a.isHorizontal();if(p?(g.width=a.maxWidth,g.height=o?10:0):(g.width=o?10:0,g.height=a.maxHeight),o)if(r.font=h,p){var m=a.lineWidths=[0],b=a.legendItems.length?d+n.padding:0;r.textAlign="left",r.textBaseline="top",e.each(a.legendItems,function(t,e){var i=n.usePointStyle?d*Math.sqrt(2):n.boxWidth,o=i+d/2+r.measureText(t.text).width;m[m.length-1]+o+n.padding>=a.width&&(b+=d+n.padding,m[m.length]=a.left),f[e]={left:0,top:0,width:o,height:d},m[m.length-1]+=o+n.padding}),g.height+=b}else{var v=n.padding,x=a.columnWidths=[],y=n.padding,k=0,S=0,w=d+v;e.each(a.legendItems,function(t,e){var a=n.usePointStyle?2*n.boxWidth:n.boxWidth,i=a+d/2+r.measureText(t.text).width;S+w>g.height&&(y+=k+n.padding,x.push(k),k=0,S=0),k=Math.max(k,i),S+=w,f[e]={left:0,top:0,width:i,height:d}}),y+=k,x.push(k),g.width+=y}a.width=g.width,a.height=g.height},afterFit:a,isHorizontal:function(){return"top"===this.options.position||"bottom"===this.options.position},draw:function(){var a=this,i=a.options,n=i.labels,o=t.defaults.global,r=o.elements.line,l=a.width,s=a.lineWidths;if(i.display){var d,u=a.ctx,c=e.getValueOrDefault,h=c(n.fontColor,o.defaultFontColor),f=c(n.fontSize,o.defaultFontSize),g=c(n.fontStyle,o.defaultFontStyle),p=c(n.fontFamily,o.defaultFontFamily),m=e.fontString(f,g,p);u.textAlign="left",u.textBaseline="top",u.lineWidth=.5,u.strokeStyle=h,u.fillStyle=h,u.font=m;var b=n.boxWidth,v=a.legendHitBoxes,x=function(e,a,n){if(!(isNaN(b)||0>=b)){u.save(),u.fillStyle=c(n.fillStyle,o.defaultColor),u.lineCap=c(n.lineCap,r.borderCapStyle),u.lineDashOffset=c(n.lineDashOffset,r.borderDashOffset),u.lineJoin=c(n.lineJoin,r.borderJoinStyle),u.lineWidth=c(n.lineWidth,r.borderWidth),u.strokeStyle=c(n.strokeStyle,o.defaultColor);var l=0===c(n.lineWidth,r.borderWidth);if(u.setLineDash&&u.setLineDash(c(n.lineDash,r.borderDash)),i.labels&&i.labels.usePointStyle){var s=f*Math.SQRT2/2,d=s/Math.SQRT2,h=e+d,g=a+d;t.canvasHelpers.drawPoint(u,n.pointStyle,s,h,g)}else l||u.strokeRect(e,a,b,f),u.fillRect(e,a,b,f);u.restore()}},y=function(t,e,a,i){u.fillText(a.text,b+f/2+t,e),a.hidden&&(u.beginPath(),u.lineWidth=2,u.moveTo(b+f/2+t,e+f/2),u.lineTo(b+f/2+t+i,e+f/2),u.stroke())},k=a.isHorizontal();d=k?{x:a.left+(l-s[0])/2,y:a.top+n.padding,line:0}:{x:a.left+n.padding,y:a.top+n.padding,line:0};var S=f+n.padding;e.each(a.legendItems,function(t,e){var i=u.measureText(t.text).width,o=n.usePointStyle?f+f/2+i:b+f/2+i,r=d.x,c=d.y;k?r+o>=l&&(c=d.y+=S,d.line++,r=d.x=a.left+(l-s[d.line])/2):c+S>a.bottom&&(r=d.x=r+a.columnWidths[d.line]+n.padding,c=d.y=a.top,d.line++),x(r,c,t),v[e].left=r,v[e].top=c,y(r,c,t,i),k?d.x+=o+n.padding:d.y+=S})}},handleEvent:function(t){var a=this,i=a.options,n="mouseup"===t.type?"click":t.type;if("mousemove"===n){if(!i.onHover)return}else{if("click"!==n)return;if(!i.onClick)return}var o=e.getRelativePosition(t,a.chart.chart),r=o.x,l=o.y;if(r>=a.left&&r<=a.right&&l>=a.top&&l<=a.bottom)for(var s=a.legendHitBoxes,d=0;d<s.length;++d){var u=s[d];if(r>=u.left&&r<=u.left+u.width&&l>=u.top&&l<=u.top+u.height){if("click"===n){i.onClick.call(a,t,a.legendItems[d]);break}if("mousemove"===n){i.onHover.call(a,t,a.legendItems[d]);break}}}}}),t.plugins.register({beforeInit:function(e){var a=e.options,i=a.legend;i&&(e.legend=new t.Legend({ctx:e.chart.ctx,options:i,chart:e}),t.layoutService.addBox(e,e.legend))}})}},{}],30:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers.noop;t.plugins={_plugins:[],register:function(t){var e=this._plugins;[].concat(t).forEach(function(t){-1===e.indexOf(t)&&e.push(t)})},unregister:function(t){var e=this._plugins;[].concat(t).forEach(function(t){var a=e.indexOf(t);-1!==a&&e.splice(a,1)})},clear:function(){this._plugins=[]},count:function(){return this._plugins.length},getAll:function(){return this._plugins},notify:function(t,e){var a,i,n=this._plugins,o=n.length;for(a=0;o>a;++a)if(i=n[a],"function"==typeof i[t]&&i[t].apply(i,e||[])===!1)return!1;return!0}},t.PluginBase=t.Element.extend({beforeInit:e,afterInit:e,beforeUpdate:e,afterUpdate:e,beforeDraw:e,afterDraw:e,destroy:e}),t.pluginService=t.plugins}},{}],31:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.scale={display:!0,position:"left",gridLines:{display:!0,color:"rgba(0, 0, 0, 0.1)",lineWidth:1,drawBorder:!0,drawOnChartArea:!0,drawTicks:!0,tickMarkLength:10,zeroLineWidth:1,zeroLineColor:"rgba(0,0,0,0.25)",offsetGridLines:!1,borderDash:[],borderDashOffset:0},scaleLabel:{labelString:"",display:!1},ticks:{beginAtZero:!1,minRotation:0,maxRotation:50,mirror:!1,padding:10,reverse:!1,display:!0,autoSkip:!0,autoSkipPadding:0,labelOffset:0,callback:function(t){return e.isArray(t)?t:""+t}}},t.Scale=t.Element.extend({beforeUpdate:function(){e.callCallback(this.options.beforeUpdate,[this])},update:function(t,a,i){var n=this;return n.beforeUpdate(),n.maxWidth=t,n.maxHeight=a,n.margins=e.extend({left:0,right:0,top:0,bottom:0},i),n.beforeSetDimensions(),n.setDimensions(),n.afterSetDimensions(),n.beforeDataLimits(),n.determineDataLimits(),n.afterDataLimits(),n.beforeBuildTicks(),n.buildTicks(),n.afterBuildTicks(),n.beforeTickToLabelConversion(),n.convertTicksToLabels(),n.afterTickToLabelConversion(),n.beforeCalculateTickRotation(),n.calculateTickRotation(),n.afterCalculateTickRotation(),n.beforeFit(),n.fit(),n.afterFit(),n.afterUpdate(),n.minSize},afterUpdate:function(){e.callCallback(this.options.afterUpdate,[this])},beforeSetDimensions:function(){e.callCallback(this.options.beforeSetDimensions,[this])},setDimensions:function(){var t=this;t.isHorizontal()?(t.width=t.maxWidth,t.left=0,t.right=t.width):(t.height=t.maxHeight,t.top=0,t.bottom=t.height),t.paddingLeft=0,t.paddingTop=0,t.paddingRight=0,t.paddingBottom=0},afterSetDimensions:function(){e.callCallback(this.options.afterSetDimensions,[this])},beforeDataLimits:function(){e.callCallback(this.options.beforeDataLimits,[this])},determineDataLimits:e.noop,afterDataLimits:function(){e.callCallback(this.options.afterDataLimits,[this]);
    },beforeBuildTicks:function(){e.callCallback(this.options.beforeBuildTicks,[this])},buildTicks:e.noop,afterBuildTicks:function(){e.callCallback(this.options.afterBuildTicks,[this])},beforeTickToLabelConversion:function(){e.callCallback(this.options.beforeTickToLabelConversion,[this])},convertTicksToLabels:function(){var t=this;t.ticks=t.ticks.map(function(e,a,i){return t.options.ticks.userCallback?t.options.ticks.userCallback(e,a,i):t.options.ticks.callback(e,a,i)},t)},afterTickToLabelConversion:function(){e.callCallback(this.options.afterTickToLabelConversion,[this])},beforeCalculateTickRotation:function(){e.callCallback(this.options.beforeCalculateTickRotation,[this])},calculateTickRotation:function(){var a=this,i=a.ctx,n=t.defaults.global,o=a.options.ticks,r=e.getValueOrDefault(o.fontSize,n.defaultFontSize),l=e.getValueOrDefault(o.fontStyle,n.defaultFontStyle),s=e.getValueOrDefault(o.fontFamily,n.defaultFontFamily),d=e.fontString(r,l,s);i.font=d;var u,c=i.measureText(a.ticks[0]).width,h=i.measureText(a.ticks[a.ticks.length-1]).width;if(a.labelRotation=o.minRotation||0,a.paddingRight=0,a.paddingLeft=0,a.options.display&&a.isHorizontal()){a.paddingRight=h/2+3,a.paddingLeft=c/2+3,a.longestTextCache||(a.longestTextCache={});for(var f,g,p=e.longestText(i,d,a.ticks,a.longestTextCache),m=p,b=a.getPixelForTick(1)-a.getPixelForTick(0)-6;m>b&&a.labelRotation<o.maxRotation;){if(f=Math.cos(e.toRadians(a.labelRotation)),g=Math.sin(e.toRadians(a.labelRotation)),u=f*c,u+r/2>a.yLabelWidth&&(a.paddingLeft=u+r/2),a.paddingRight=r/2,g*p>a.maxHeight){a.labelRotation--;break}a.labelRotation++,m=f*p}}a.margins&&(a.paddingLeft=Math.max(a.paddingLeft-a.margins.left,0),a.paddingRight=Math.max(a.paddingRight-a.margins.right,0))},afterCalculateTickRotation:function(){e.callCallback(this.options.afterCalculateTickRotation,[this])},beforeFit:function(){e.callCallback(this.options.beforeFit,[this])},fit:function(){var a=this,i=a.minSize={width:0,height:0},n=a.options,o=t.defaults.global,r=n.ticks,l=n.scaleLabel,s=n.gridLines,d=n.display,u=a.isHorizontal(),c=e.getValueOrDefault(r.fontSize,o.defaultFontSize),h=e.getValueOrDefault(r.fontStyle,o.defaultFontStyle),f=e.getValueOrDefault(r.fontFamily,o.defaultFontFamily),g=e.fontString(c,h,f),p=e.getValueOrDefault(l.fontSize,o.defaultFontSize),m=n.gridLines.tickMarkLength;if(u?i.width=a.isFullWidth()?a.maxWidth-a.margins.left-a.margins.right:a.maxWidth:i.width=d&&s.drawTicks?m:0,u?i.height=d&&s.drawTicks?m:0:i.height=a.maxHeight,l.display&&d&&(u?i.height+=1.5*p:i.width+=1.5*p),r.display&&d){a.longestTextCache||(a.longestTextCache={});var b=e.longestText(a.ctx,g,a.ticks,a.longestTextCache),v=e.numberOfLabelLines(a.ticks),x=.5*c;if(u){a.longestLabelWidth=b;var y=Math.sin(e.toRadians(a.labelRotation))*a.longestLabelWidth+c*v+x*v;i.height=Math.min(a.maxHeight,i.height+y),a.ctx.font=g;var k=a.ctx.measureText(a.ticks[0]).width,S=a.ctx.measureText(a.ticks[a.ticks.length-1]).width,w=Math.cos(e.toRadians(a.labelRotation)),C=Math.sin(e.toRadians(a.labelRotation));a.paddingLeft=0!==a.labelRotation?w*k+3:k/2+3,a.paddingRight=0!==a.labelRotation?C*(c/2)+3:S/2+3}else{var M=a.maxWidth-i.width,D=r.mirror;D?b=0:b+=a.options.ticks.padding,M>b?i.width+=b:i.width=a.maxWidth,a.paddingTop=c/2,a.paddingBottom=c/2}}a.margins&&(a.paddingLeft=Math.max(a.paddingLeft-a.margins.left,0),a.paddingTop=Math.max(a.paddingTop-a.margins.top,0),a.paddingRight=Math.max(a.paddingRight-a.margins.right,0),a.paddingBottom=Math.max(a.paddingBottom-a.margins.bottom,0)),a.width=i.width,a.height=i.height},afterFit:function(){e.callCallback(this.options.afterFit,[this])},isHorizontal:function(){return"top"===this.options.position||"bottom"===this.options.position},isFullWidth:function(){return this.options.fullWidth},getRightValue:function(t){return null===t||"undefined"==typeof t?NaN:"number"==typeof t&&isNaN(t)?NaN:"object"==typeof t?t instanceof Date||t.isValid?t:this.getRightValue(this.isHorizontal()?t.x:t.y):t},getLabelForIndex:e.noop,getPixelForValue:e.noop,getValueForPixel:e.noop,getPixelForTick:function(t,e){var a=this;if(a.isHorizontal()){var i=a.width-(a.paddingLeft+a.paddingRight),n=i/Math.max(a.ticks.length-(a.options.gridLines.offsetGridLines?0:1),1),o=n*t+a.paddingLeft;e&&(o+=n/2);var r=a.left+Math.round(o);return r+=a.isFullWidth()?a.margins.left:0}var l=a.height-(a.paddingTop+a.paddingBottom);return a.top+t*(l/(a.ticks.length-1))},getPixelForDecimal:function(t){var e=this;if(e.isHorizontal()){var a=e.width-(e.paddingLeft+e.paddingRight),i=a*t+e.paddingLeft,n=e.left+Math.round(i);return n+=e.isFullWidth()?e.margins.left:0}return e.top+t*e.height},getBasePixel:function(){var t=this,e=t.min,a=t.max;return t.getPixelForValue(t.beginAtZero?0:0>e&&0>a?a:e>0&&a>0?e:0)},draw:function(a){var i=this,n=i.options;if(n.display){var o,r,l=i.ctx,s=t.defaults.global,d=n.ticks,u=n.gridLines,c=n.scaleLabel,h=0!==i.labelRotation,f=d.autoSkip,g=i.isHorizontal();d.maxTicksLimit&&(r=d.maxTicksLimit);var p=e.getValueOrDefault(d.fontColor,s.defaultFontColor),m=e.getValueOrDefault(d.fontSize,s.defaultFontSize),b=e.getValueOrDefault(d.fontStyle,s.defaultFontStyle),v=e.getValueOrDefault(d.fontFamily,s.defaultFontFamily),x=e.fontString(m,b,v),y=u.tickMarkLength,k=e.getValueOrDefault(u.borderDash,s.borderDash),S=e.getValueOrDefault(u.borderDashOffset,s.borderDashOffset),w=e.getValueOrDefault(c.fontColor,s.defaultFontColor),C=e.getValueOrDefault(c.fontSize,s.defaultFontSize),M=e.getValueOrDefault(c.fontStyle,s.defaultFontStyle),D=e.getValueOrDefault(c.fontFamily,s.defaultFontFamily),I=e.fontString(C,M,D),A=e.toRadians(i.labelRotation),T=Math.cos(A),P=i.longestLabelWidth*T;l.fillStyle=p;var F=[];if(g){if(o=!1,h&&(P/=2),(P+d.autoSkipPadding)*i.ticks.length>i.width-(i.paddingLeft+i.paddingRight)&&(o=1+Math.floor((P+d.autoSkipPadding)*i.ticks.length/(i.width-(i.paddingLeft+i.paddingRight)))),r&&i.ticks.length>r)for(;!o||i.ticks.length/(o||1)>r;)o||(o=1),o+=1;f||(o=!1)}var R="right"===n.position?i.left:i.right-y,_="right"===n.position?i.left+y:i.right,V="bottom"===n.position?i.top:i.bottom-y,L="bottom"===n.position?i.top+y:i.bottom;if(e.each(i.ticks,function(t,r){if(void 0!==t&&null!==t){var l=i.ticks.length===r+1,s=o>1&&r%o>0||r%o===0&&r+o>=i.ticks.length;if((!s||l)&&void 0!==t&&null!==t){var c,f;r===("undefined"!=typeof i.zeroLineIndex?i.zeroLineIndex:0)?(c=u.zeroLineWidth,f=u.zeroLineColor):(c=e.getValueAtIndexOrDefault(u.lineWidth,r),f=e.getValueAtIndexOrDefault(u.color,r));var p,m,b,v,x,w,C,M,D,I,T="middle",P="middle";if(g){h||(P="top"===n.position?"bottom":"top"),T=h?"right":"center";var O=i.getPixelForTick(r)+e.aliasPixel(c);D=i.getPixelForTick(r,u.offsetGridLines)+d.labelOffset,I=h?i.top+12:"top"===n.position?i.bottom-y:i.top+y,p=b=x=C=O,m=V,v=L,w=a.top,M=a.bottom}else{"left"===n.position?d.mirror?(D=i.right+d.padding,T="left"):(D=i.right-d.padding,T="right"):d.mirror?(D=i.left-d.padding,T="right"):(D=i.left+d.padding,T="left");var B=i.getPixelForTick(r);B+=e.aliasPixel(c),I=i.getPixelForTick(r,u.offsetGridLines),p=R,b=_,x=a.left,C=a.right,m=v=w=M=B}F.push({tx1:p,ty1:m,tx2:b,ty2:v,x1:x,y1:w,x2:C,y2:M,labelX:D,labelY:I,glWidth:c,glColor:f,glBorderDash:k,glBorderDashOffset:S,rotation:-1*A,label:t,textBaseline:P,textAlign:T})}}}),e.each(F,function(t){if(u.display&&(l.save(),l.lineWidth=t.glWidth,l.strokeStyle=t.glColor,l.setLineDash&&(l.setLineDash(t.glBorderDash),l.lineDashOffset=t.glBorderDashOffset),l.beginPath(),u.drawTicks&&(l.moveTo(t.tx1,t.ty1),l.lineTo(t.tx2,t.ty2)),u.drawOnChartArea&&(l.moveTo(t.x1,t.y1),l.lineTo(t.x2,t.y2)),l.stroke(),l.restore()),d.display){l.save(),l.translate(t.labelX,t.labelY),l.rotate(t.rotation),l.font=x,l.textBaseline=t.textBaseline,l.textAlign=t.textAlign;var a=t.label;if(e.isArray(a))for(var i=0,n=-(a.length-1)*m*.75;i<a.length;++i)l.fillText(""+a[i],0,n),n+=1.5*m;else l.fillText(a,0,0);l.restore()}}),c.display){var O,B,W=0;if(g)O=i.left+(i.right-i.left)/2,B="bottom"===n.position?i.bottom-C/2:i.top+C/2;else{var z="left"===n.position;O=z?i.left+C/2:i.right-C/2,B=i.top+(i.bottom-i.top)/2,W=z?-.5*Math.PI:.5*Math.PI}l.save(),l.translate(O,B),l.rotate(W),l.textAlign="center",l.textBaseline="middle",l.fillStyle=w,l.font=I,l.fillText(c.labelString,0,0),l.restore()}if(u.drawBorder){l.lineWidth=e.getValueAtIndexOrDefault(u.lineWidth,0),l.strokeStyle=e.getValueAtIndexOrDefault(u.color,0);var N=i.left,H=i.right,E=i.top,U=i.bottom,q=e.aliasPixel(l.lineWidth);g?(E=U="top"===n.position?i.bottom:i.top,E+=q,U+=q):(N=H="left"===n.position?i.right:i.left,N+=q,H+=q),l.beginPath(),l.moveTo(N,E),l.lineTo(H,U),l.stroke()}}}})}},{}],32:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.scaleService={constructors:{},defaults:{},registerScaleType:function(t,a,i){this.constructors[t]=a,this.defaults[t]=e.clone(i)},getScaleConstructor:function(t){return this.constructors.hasOwnProperty(t)?this.constructors[t]:void 0},getScaleDefaults:function(a){return this.defaults.hasOwnProperty(a)?e.scaleMerge(t.defaults.scale,this.defaults[a]):{}},updateScaleDefaults:function(t,a){var i=this.defaults;i.hasOwnProperty(t)&&(i[t]=e.extend(i[t],a))},addScalesToLayout:function(a){e.each(a.scales,function(e){t.layoutService.addBox(a,e)})}}}},{}],33:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.global.title={display:!1,position:"top",fullWidth:!0,fontStyle:"bold",padding:10,text:""};var a=e.noop;t.Title=t.Element.extend({initialize:function(a){var i=this;e.extend(i,a),i.options=e.configMerge(t.defaults.global.title,a.options),i.legendHitBoxes=[]},beforeUpdate:function(){var a=this.chart.options;a&&a.title&&(this.options=e.configMerge(t.defaults.global.title,a.title))},update:function(t,e,a){var i=this;return i.beforeUpdate(),i.maxWidth=t,i.maxHeight=e,i.margins=a,i.beforeSetDimensions(),i.setDimensions(),i.afterSetDimensions(),i.beforeBuildLabels(),i.buildLabels(),i.afterBuildLabels(),i.beforeFit(),i.fit(),i.afterFit(),i.afterUpdate(),i.minSize},afterUpdate:a,beforeSetDimensions:a,setDimensions:function(){var t=this;t.isHorizontal()?(t.width=t.maxWidth,t.left=0,t.right=t.width):(t.height=t.maxHeight,t.top=0,t.bottom=t.height),t.paddingLeft=0,t.paddingTop=0,t.paddingRight=0,t.paddingBottom=0,t.minSize={width:0,height:0}},afterSetDimensions:a,beforeBuildLabels:a,buildLabels:a,afterBuildLabels:a,beforeFit:a,fit:function(){var a=this,i=e.getValueOrDefault,n=a.options,o=t.defaults.global,r=n.display,l=i(n.fontSize,o.defaultFontSize),s=a.minSize;a.isHorizontal()?(s.width=a.maxWidth,s.height=r?l+2*n.padding:0):(s.width=r?l+2*n.padding:0,s.height=a.maxHeight),a.width=s.width,a.height=s.height},afterFit:a,isHorizontal:function(){var t=this.options.position;return"top"===t||"bottom"===t},draw:function(){var a=this,i=a.ctx,n=e.getValueOrDefault,o=a.options,r=t.defaults.global;if(o.display){var l,s,d=n(o.fontSize,r.defaultFontSize),u=n(o.fontStyle,r.defaultFontStyle),c=n(o.fontFamily,r.defaultFontFamily),h=e.fontString(d,u,c),f=0,g=a.top,p=a.left,m=a.bottom,b=a.right;i.fillStyle=n(o.fontColor,r.defaultFontColor),i.font=h,a.isHorizontal()?(l=p+(b-p)/2,s=g+(m-g)/2):(l="left"===o.position?p+d/2:b-d/2,s=g+(m-g)/2,f=Math.PI*("left"===o.position?-.5:.5)),i.save(),i.translate(l,s),i.rotate(f),i.textAlign="center",i.textBaseline="middle",i.fillText(o.text,0,0),i.restore()}}}),t.plugins.register({beforeInit:function(e){var a=e.options,i=a.title;i&&(e.titleBlock=new t.Title({ctx:e.chart.ctx,options:i,chart:e}),t.layoutService.addBox(e,e.titleBlock))}})}},{}],34:[function(t,e,a){"use strict";e.exports=function(t){function e(t,e){return e&&(n.isArray(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function a(t){if(!t.length)return!1;var e,a,i=[],n=[];for(e=0,a=t.length;a>e;++e){var o=t[e];if(o&&o.hasValue()){var r=o.tooltipPosition();i.push(r.x),n.push(r.y)}}var l=0,s=0;for(e=0;e<i.length;++e)i[e]&&(l+=i[e],s+=n[e]);return{x:Math.round(l/i.length),y:Math.round(s/i.length)}}function i(t){var e=t._xScale,a=t._yScale||t._scale,i=t._index,n=t._datasetIndex;return{xLabel:e?e.getLabelForIndex(i,n):"",yLabel:a?a.getLabelForIndex(i,n):"",index:i,datasetIndex:n}}var n=t.helpers;t.defaults.global.tooltips={enabled:!0,custom:null,mode:"single",backgroundColor:"rgba(0,0,0,0.8)",titleFontStyle:"bold",titleSpacing:2,titleMarginBottom:6,titleFontColor:"#fff",titleAlign:"left",bodySpacing:2,bodyFontColor:"#fff",bodyAlign:"left",footerFontStyle:"bold",footerSpacing:2,footerMarginTop:6,footerFontColor:"#fff",footerAlign:"left",yPadding:6,xPadding:6,yAlign:"center",xAlign:"center",caretSize:5,cornerRadius:6,multiKeyBackground:"#fff",callbacks:{beforeTitle:n.noop,title:function(t,e){var a="",i=e.labels,n=i?i.length:0;if(t.length>0){var o=t[0];o.xLabel?a=o.xLabel:n>0&&o.index<n&&(a=i[o.index])}return a},afterTitle:n.noop,beforeBody:n.noop,beforeLabel:n.noop,label:function(t,e){var a=e.datasets[t.datasetIndex].label||"";return a+": "+t.yLabel},labelColor:function(t,e){var a=e.getDatasetMeta(t.datasetIndex),i=a.data[t.index],n=i._view;return{borderColor:n.borderColor,backgroundColor:n.backgroundColor}},afterLabel:n.noop,afterBody:n.noop,beforeFooter:n.noop,footer:n.noop,afterFooter:n.noop}},t.Tooltip=t.Element.extend({initialize:function(){var e=this,a=t.defaults.global,i=e._options,o=n.getValueOrDefault;n.extend(e,{_model:{xPadding:i.xPadding,yPadding:i.yPadding,xAlign:i.xAlign,yAlign:i.yAlign,bodyFontColor:i.bodyFontColor,_bodyFontFamily:o(i.bodyFontFamily,a.defaultFontFamily),_bodyFontStyle:o(i.bodyFontStyle,a.defaultFontStyle),_bodyAlign:i.bodyAlign,bodyFontSize:o(i.bodyFontSize,a.defaultFontSize),bodySpacing:i.bodySpacing,titleFontColor:i.titleFontColor,_titleFontFamily:o(i.titleFontFamily,a.defaultFontFamily),_titleFontStyle:o(i.titleFontStyle,a.defaultFontStyle),titleFontSize:o(i.titleFontSize,a.defaultFontSize),_titleAlign:i.titleAlign,titleSpacing:i.titleSpacing,titleMarginBottom:i.titleMarginBottom,footerFontColor:i.footerFontColor,_footerFontFamily:o(i.footerFontFamily,a.defaultFontFamily),_footerFontStyle:o(i.footerFontStyle,a.defaultFontStyle),footerFontSize:o(i.footerFontSize,a.defaultFontSize),_footerAlign:i.footerAlign,footerSpacing:i.footerSpacing,footerMarginTop:i.footerMarginTop,caretSize:i.caretSize,cornerRadius:i.cornerRadius,backgroundColor:i.backgroundColor,opacity:0,legendColorBackground:i.multiKeyBackground}})},getTitle:function(){var t=this,a=t._options,i=a.callbacks,n=i.beforeTitle.apply(t,arguments),o=i.title.apply(t,arguments),r=i.afterTitle.apply(t,arguments),l=[];return l=e(l,n),l=e(l,o),l=e(l,r)},getBeforeBody:function(){var t=this._options.callbacks.beforeBody.apply(this,arguments);return n.isArray(t)?t:void 0!==t?[t]:[]},getBody:function(t,a){var i=this,o=i._options.callbacks,r=[];return n.each(t,function(t){var n={before:[],lines:[],after:[]};e(n.before,o.beforeLabel.call(i,t,a)),e(n.lines,o.label.call(i,t,a)),e(n.after,o.afterLabel.call(i,t,a)),r.push(n)}),r},getAfterBody:function(){var t=this._options.callbacks.afterBody.apply(this,arguments);return n.isArray(t)?t:void 0!==t?[t]:[]},getFooter:function(){var t=this,a=t._options.callbacks,i=a.beforeFooter.apply(t,arguments),n=a.footer.apply(t,arguments),o=a.afterFooter.apply(t,arguments),r=[];return r=e(r,i),r=e(r,n),r=e(r,o)},update:function(t){var e,o,r=this,l=r._options,s=r._model,d=r._active,u=r._data,c=r._chartInstance;if(d.length){s.opacity=1;var h=[],f=a(d),g=[];for(e=0,o=d.length;o>e;++e)g.push(i(d[e]));l.itemSort&&(g=g.sort(function(t,e){return l.itemSort(t,e,u)})),d.length>1&&n.each(g,function(t){h.push(l.callbacks.labelColor.call(r,t,c))}),n.extend(s,{title:r.getTitle(g,u),beforeBody:r.getBeforeBody(g,u),body:r.getBody(g,u),afterBody:r.getAfterBody(g,u),footer:r.getFooter(g,u),x:Math.round(f.x),y:Math.round(f.y),caretPadding:n.getValueOrDefault(f.padding,2),labelColors:h});var p=r.getTooltipSize(s);r.determineAlignment(p),n.extend(s,r.getBackgroundPoint(s,p))}else r._model.opacity=0;return t&&l.custom&&l.custom.call(r,s),r},getTooltipSize:function(t){var e=this._chart.ctx,a={height:2*t.yPadding,width:0},i=t.body,o=i.reduce(function(t,e){return t+e.before.length+e.lines.length+e.after.length},0);o+=t.beforeBody.length+t.afterBody.length;var r=t.title.length,l=t.footer.length,s=t.titleFontSize,d=t.bodyFontSize,u=t.footerFontSize;a.height+=r*s,a.height+=(r-1)*t.titleSpacing,a.height+=r?t.titleMarginBottom:0,a.height+=o*d,a.height+=o?(o-1)*t.bodySpacing:0,a.height+=l?t.footerMarginTop:0,a.height+=l*u,a.height+=l?(l-1)*t.footerSpacing:0;var c=0,h=function(t){a.width=Math.max(a.width,e.measureText(t).width+c)};return e.font=n.fontString(s,t._titleFontStyle,t._titleFontFamily),n.each(t.title,h),e.font=n.fontString(d,t._bodyFontStyle,t._bodyFontFamily),n.each(t.beforeBody.concat(t.afterBody),h),c=i.length>1?d+2:0,n.each(i,function(t){n.each(t.before,h),n.each(t.lines,h),n.each(t.after,h)}),c=0,e.font=n.fontString(u,t._footerFontStyle,t._footerFontFamily),n.each(t.footer,h),a.width+=2*t.xPadding,a},determineAlignment:function(t){var e=this,a=e._model,i=e._chart,n=e._chartInstance.chartArea;a.y<t.height?a.yAlign="top":a.y>i.height-t.height&&(a.yAlign="bottom");var o,r,l,s,d,u=(n.left+n.right)/2,c=(n.top+n.bottom)/2;"center"===a.yAlign?(o=function(t){return u>=t},r=function(t){return t>u}):(o=function(e){return e<=t.width/2},r=function(e){return e>=i.width-t.width/2}),l=function(e){return e+t.width>i.width},s=function(e){return e-t.width<0},d=function(t){return c>=t?"top":"bottom"},o(a.x)?(a.xAlign="left",l(a.x)&&(a.xAlign="center",a.yAlign=d(a.y))):r(a.x)&&(a.xAlign="right",s(a.x)&&(a.xAlign="center",a.yAlign=d(a.y)))},getBackgroundPoint:function(t,e){var a={x:t.x,y:t.y},i=t.caretSize,n=t.caretPadding,o=t.cornerRadius,r=t.xAlign,l=t.yAlign,s=i+n,d=o+n;return"right"===r?a.x-=e.width:"center"===r&&(a.x-=e.width/2),"top"===l?a.y+=s:"bottom"===l?a.y-=e.height+s:a.y-=e.height/2,"center"===l?"left"===r?a.x+=s:"right"===r&&(a.x-=s):"left"===r?a.x-=d:"right"===r&&(a.x+=d),a},drawCaret:function(t,e,a){var i,o,r,l,s,d,u=this._view,c=this._chart.ctx,h=u.caretSize,f=u.cornerRadius,g=u.xAlign,p=u.yAlign,m=t.x,b=t.y,v=e.width,x=e.height;"center"===p?("left"===g?(i=m,o=i-h,r=i):(i=m+v,o=i+h,r=i),s=b+x/2,l=s-h,d=s+h):("left"===g?(i=m+f,o=i+h,r=o+h):"right"===g?(i=m+v-f,o=i-h,r=o-h):(o=m+v/2,i=o-h,r=o+h),"top"===p?(l=b,s=l-h,d=l):(l=b+x,s=l+h,d=l));var y=n.color(u.backgroundColor);c.fillStyle=y.alpha(a*y.alpha()).rgbString(),c.beginPath(),c.moveTo(i,l),c.lineTo(o,s),c.lineTo(r,d),c.closePath(),c.fill()},drawTitle:function(t,e,a,i){var o=e.title;if(o.length){a.textAlign=e._titleAlign,a.textBaseline="top";var r=e.titleFontSize,l=e.titleSpacing,s=n.color(e.titleFontColor);a.fillStyle=s.alpha(i*s.alpha()).rgbString(),a.font=n.fontString(r,e._titleFontStyle,e._titleFontFamily);var d,u;for(d=0,u=o.length;u>d;++d)a.fillText(o[d],t.x,t.y),t.y+=r+l,d+1===o.length&&(t.y+=e.titleMarginBottom-l)}},drawBody:function(t,e,a,i){var o=e.bodyFontSize,r=e.bodySpacing,l=e.body;a.textAlign=e._bodyAlign,a.textBaseline="top";var s=n.color(e.bodyFontColor),d=s.alpha(i*s.alpha()).rgbString();a.fillStyle=d,a.font=n.fontString(o,e._bodyFontStyle,e._bodyFontFamily);var u=0,c=function(e){a.fillText(e,t.x+u,t.y),t.y+=o+r};n.each(e.beforeBody,c);var h=l.length>1;u=h?o+2:0,n.each(l,function(r,l){n.each(r.before,c),n.each(r.lines,function(r){h&&(a.fillStyle=n.color(e.legendColorBackground).alpha(i).rgbaString(),a.fillRect(t.x,t.y,o,o),a.strokeStyle=n.color(e.labelColors[l].borderColor).alpha(i).rgbaString(),a.strokeRect(t.x,t.y,o,o),a.fillStyle=n.color(e.labelColors[l].backgroundColor).alpha(i).rgbaString(),a.fillRect(t.x+1,t.y+1,o-2,o-2),a.fillStyle=d),c(r)}),n.each(r.after,c)}),u=0,n.each(e.afterBody,c),t.y-=r},drawFooter:function(t,e,a,i){var o=e.footer;if(o.length){t.y+=e.footerMarginTop,a.textAlign=e._footerAlign,a.textBaseline="top";var r=n.color(e.footerFontColor);a.fillStyle=r.alpha(i*r.alpha()).rgbString(),a.font=n.fontString(e.footerFontSize,e._footerFontStyle,e._footerFontFamily),n.each(o,function(i){a.fillText(i,t.x,t.y),t.y+=e.footerFontSize+e.footerSpacing})}},draw:function(){var t=this._chart.ctx,e=this._view;if(0!==e.opacity){var a=this.getTooltipSize(e),i={x:e.x,y:e.y},o=Math.abs(e.opacity<.001)?0:e.opacity;if(this._options.enabled){var r=n.color(e.backgroundColor);t.fillStyle=r.alpha(o*r.alpha()).rgbString(),n.drawRoundedRectangle(t,i.x,i.y,a.width,a.height,e.cornerRadius),t.fill(),this.drawCaret(i,a,o),i.x+=e.xPadding,i.y+=e.yPadding,this.drawTitle(i,e,t,o),this.drawBody(i,e,t,o),this.drawFooter(i,e,t,o)}}}})}},{}],35:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=t.defaults.global;a.elements.arc={backgroundColor:a.defaultColor,borderColor:"#fff",borderWidth:2},t.elements.Arc=t.Element.extend({inLabelRange:function(t){var e=this._view;return e?Math.pow(t-e.x,2)<Math.pow(e.radius+e.hoverRadius,2):!1},inRange:function(t,a){var i=this._view;if(i){for(var n=e.getAngleFromPoint(i,{x:t,y:a}),o=n.angle,r=n.distance,l=i.startAngle,s=i.endAngle;l>s;)s+=2*Math.PI;for(;o>s;)o-=2*Math.PI;for(;l>o;)o+=2*Math.PI;var d=o>=l&&s>=o,u=r>=i.innerRadius&&r<=i.outerRadius;return d&&u}return!1},tooltipPosition:function(){var t=this._view,e=t.startAngle+(t.endAngle-t.startAngle)/2,a=(t.outerRadius-t.innerRadius)/2+t.innerRadius;return{x:t.x+Math.cos(e)*a,y:t.y+Math.sin(e)*a}},draw:function(){var t=this._chart.ctx,e=this._view,a=e.startAngle,i=e.endAngle;t.beginPath(),t.arc(e.x,e.y,e.outerRadius,a,i),t.arc(e.x,e.y,e.innerRadius,i,a,!0),t.closePath(),t.strokeStyle=e.borderColor,t.lineWidth=e.borderWidth,t.fillStyle=e.backgroundColor,t.fill(),t.lineJoin="bevel",e.borderWidth&&t.stroke()}})}},{}],36:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=t.defaults.global;t.defaults.global.elements.line={tension:.4,backgroundColor:a.defaultColor,borderWidth:3,borderColor:a.defaultColor,borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",capBezierPoints:!0,fill:!0},t.elements.Line=t.Element.extend({draw:function(){function t(t,e){var a=e._view;e._view.steppedLine===!0?(s.lineTo(a.x,t._view.y),s.lineTo(a.x,a.y)):0===e._view.tension?s.lineTo(a.x,a.y):s.bezierCurveTo(t._view.controlPointNextX,t._view.controlPointNextY,a.controlPointPreviousX,a.controlPointPreviousY,a.x,a.y)}var i=this,n=i._view,o=n.spanGaps,r=n.scaleZero,l=i._loop,s=i._chart.ctx;s.save();var d=i._children.slice(),u=-1;l&&d.length&&d.push(d[0]);var c,h,f,g;if(d.length&&n.fill){for(s.beginPath(),c=0;c<d.length;++c)h=d[c],f=e.previousItem(d,c),g=h._view,0===c?(l?s.moveTo(r.x,r.y):s.moveTo(g.x,r),g.skip||(u=c,s.lineTo(g.x,g.y))):(f=-1===u?f:d[u],g.skip?o||u!==c-1||(l?s.lineTo(r.x,r.y):s.lineTo(f._view.x,r)):(u!==c-1?o&&-1!==u?t(f,h):l?s.lineTo(g.x,g.y):(s.lineTo(g.x,r),s.lineTo(g.x,g.y)):t(f,h),u=c));l||-1===u||s.lineTo(d[u]._view.x,r),s.fillStyle=n.backgroundColor||a.defaultColor,s.closePath(),s.fill()}var p=a.elements.line;for(s.lineCap=n.borderCapStyle||p.borderCapStyle,s.setLineDash&&s.setLineDash(n.borderDash||p.borderDash),s.lineDashOffset=n.borderDashOffset||p.borderDashOffset,s.lineJoin=n.borderJoinStyle||p.borderJoinStyle,s.lineWidth=n.borderWidth||p.borderWidth,s.strokeStyle=n.borderColor||a.defaultColor,s.beginPath(),u=-1,c=0;c<d.length;++c)h=d[c],f=e.previousItem(d,c),g=h._view,0===c?g.skip||(s.moveTo(g.x,g.y),u=c):(f=-1===u?f:d[u],g.skip||(u!==c-1&&!o||-1===u?s.moveTo(g.x,g.y):t(f,h),u=c));s.stroke(),s.restore()}})}},{}],37:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=t.defaults.global,i=a.defaultColor;a.elements.point={radius:3,pointStyle:"circle",backgroundColor:i,borderWidth:1,borderColor:i,hitRadius:1,hoverRadius:4,hoverBorderWidth:1},t.elements.Point=t.Element.extend({inRange:function(t,e){var a=this._view;return a?Math.pow(t-a.x,2)+Math.pow(e-a.y,2)<Math.pow(a.hitRadius+a.radius,2):!1},inLabelRange:function(t){var e=this._view;return e?Math.pow(t-e.x,2)<Math.pow(e.radius+e.hitRadius,2):!1},tooltipPosition:function(){var t=this._view;return{x:t.x,y:t.y,padding:t.radius+t.borderWidth}},draw:function(){var n=this._view,o=this._chart.ctx,r=n.pointStyle,l=n.radius,s=n.x,d=n.y;n.skip||(o.strokeStyle=n.borderColor||i,o.lineWidth=e.getValueOrDefault(n.borderWidth,a.elements.point.borderWidth),o.fillStyle=n.backgroundColor||i,t.canvasHelpers.drawPoint(o,r,l,s,d))}})}},{}],38:[function(t,e,a){"use strict";e.exports=function(t){var e=t.defaults.global;e.elements.rectangle={backgroundColor:e.defaultColor,borderWidth:0,borderColor:e.defaultColor,borderSkipped:"bottom"},t.elements.Rectangle=t.Element.extend({draw:function(){function t(t){return s[(u+t)%4]}var e=this._chart.ctx,a=this._view,i=a.width/2,n=a.x-i,o=a.x+i,r=a.base-(a.base-a.y),l=a.borderWidth/2;a.borderWidth&&(n+=l,o-=l,r+=l),e.beginPath(),e.fillStyle=a.backgroundColor,e.strokeStyle=a.borderColor,e.lineWidth=a.borderWidth;var s=[[n,a.base],[n,r],[o,r],[o,a.base]],d=["bottom","left","top","right"],u=d.indexOf(a.borderSkipped,0);-1===u&&(u=0),e.moveTo.apply(e,t(0));for(var c=1;4>c;c++)e.lineTo.apply(e,t(c));e.fill(),a.borderWidth&&e.stroke()},height:function(){var t=this._view;return t.base-t.y},inRange:function(t,e){var a=this._view;return a?a.y<a.base?t>=a.x-a.width/2&&t<=a.x+a.width/2&&e>=a.y&&e<=a.base:t>=a.x-a.width/2&&t<=a.x+a.width/2&&e>=a.base&&e<=a.y:!1},inLabelRange:function(t){var e=this._view;return e?t>=e.x-e.width/2&&t<=e.x+e.width/2:!1},tooltipPosition:function(){var t=this._view;return{x:t.x,y:t.y}}})}},{}],39:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a={position:"bottom"},i=t.Scale.extend({getLabels:function(){var t=this.chart.data;return(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels},determineDataLimits:function(){var t=this,a=t.getLabels();t.minIndex=0,t.maxIndex=a.length-1;var i;void 0!==t.options.ticks.min&&(i=e.indexOf(a,t.options.ticks.min),t.minIndex=-1!==i?i:t.minIndex),void 0!==t.options.ticks.max&&(i=e.indexOf(a,t.options.ticks.max),t.maxIndex=-1!==i?i:t.maxIndex),t.min=a[t.minIndex],t.max=a[t.maxIndex]},buildTicks:function(){var t=this,e=t.getLabels();t.ticks=0===t.minIndex&&t.maxIndex===e.length-1?e:e.slice(t.minIndex,t.maxIndex+1)},getLabelForIndex:function(t,e){var a=this,i=a.chart.data,n=a.isHorizontal();return i.xLabels&&n||i.yLabels&&!n?a.getRightValue(i.datasets[e].data[t]):a.ticks[t]},getPixelForValue:function(t,e,a,i){var n=this,o=Math.max(n.maxIndex+1-n.minIndex-(n.options.gridLines.offsetGridLines?0:1),1);if(void 0!==t&&isNaN(e)){var r=n.getLabels(),l=r.indexOf(t);e=-1!==l?l:e}if(n.isHorizontal()){var s=n.width-(n.paddingLeft+n.paddingRight),d=s/o,u=d*(e-n.minIndex)+n.paddingLeft;return(n.options.gridLines.offsetGridLines&&i||n.maxIndex===n.minIndex&&i)&&(u+=d/2),n.left+Math.round(u)}var c=n.height-(n.paddingTop+n.paddingBottom),h=c/o,f=h*(e-n.minIndex)+n.paddingTop;return n.options.gridLines.offsetGridLines&&i&&(f+=h/2),n.top+Math.round(f)},getPixelForTick:function(t,e){return this.getPixelForValue(this.ticks[t],t+this.minIndex,null,e)},getValueForPixel:function(t){var e,a=this,i=Math.max(a.ticks.length-(a.options.gridLines.offsetGridLines?0:1),1),n=a.isHorizontal(),o=n?a.width-(a.paddingLeft+a.paddingRight):a.height-(a.paddingTop+a.paddingBottom),r=o/i;return t-=n?a.left:a.top,a.options.gridLines.offsetGridLines&&(t-=r/2),t-=n?a.paddingLeft:a.paddingTop,e=0>=t?0:Math.round(t/r)},getBasePixel:function(){return this.bottom}});t.scaleService.registerScaleType("category",i,a)}},{}],40:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a={position:"left",ticks:{callback:function(t,a,i){var n=i.length>3?i[2]-i[1]:i[1]-i[0];Math.abs(n)>1&&t!==Math.floor(t)&&(n=t-Math.floor(t));var o=e.log10(Math.abs(n)),r="";if(0!==t){var l=-1*Math.floor(o);l=Math.max(Math.min(l,20),0),r=t.toFixed(l)}else r="0";return r}}},i=t.LinearScaleBase.extend({determineDataLimits:function(){function t(t){return l?t.xAxisID===a.id:t.yAxisID===a.id}var a=this,i=a.options,n=a.chart,o=n.data,r=o.datasets,l=a.isHorizontal();if(a.min=null,a.max=null,i.stacked){var s={};e.each(r,function(o,r){var l=n.getDatasetMeta(r);void 0===s[l.type]&&(s[l.type]={positiveValues:[],negativeValues:[]});var d=s[l.type].positiveValues,u=s[l.type].negativeValues;n.isDatasetVisible(r)&&t(l)&&e.each(o.data,function(t,e){var n=+a.getRightValue(t);isNaN(n)||l.data[e].hidden||(d[e]=d[e]||0,u[e]=u[e]||0,i.relativePoints?d[e]=100:0>n?u[e]+=n:d[e]+=n)})}),e.each(s,function(t){var i=t.positiveValues.concat(t.negativeValues),n=e.min(i),o=e.max(i);a.min=null===a.min?n:Math.min(a.min,n),a.max=null===a.max?o:Math.max(a.max,o)})}else e.each(r,function(i,o){var r=n.getDatasetMeta(o);n.isDatasetVisible(o)&&t(r)&&e.each(i.data,function(t,e){var i=+a.getRightValue(t);isNaN(i)||r.data[e].hidden||(null===a.min?a.min=i:i<a.min&&(a.min=i),null===a.max?a.max=i:i>a.max&&(a.max=i))})});this.handleTickRangeOptions()},getTickLimit:function(){var a,i=this,n=i.options.ticks;if(i.isHorizontal())a=Math.min(n.maxTicksLimit?n.maxTicksLimit:11,Math.ceil(i.width/50));else{var o=e.getValueOrDefault(n.fontSize,t.defaults.global.defaultFontSize);a=Math.min(n.maxTicksLimit?n.maxTicksLimit:11,Math.ceil(i.height/(2*o)))}return a},handleDirectionalChanges:function(){this.isHorizontal()||this.ticks.reverse()},getLabelForIndex:function(t,e){return+this.getRightValue(this.chart.data.datasets[e].data[t])},getPixelForValue:function(t){var e,a,i=this,n=i.paddingLeft,o=i.paddingBottom,r=i.start,l=+i.getRightValue(t),s=i.end-r;return i.isHorizontal()?(a=i.width-(n+i.paddingRight),e=i.left+a/s*(l-r),Math.round(e+n)):(a=i.height-(i.paddingTop+o),e=i.bottom-o-a/s*(l-r),Math.round(e))},getValueForPixel:function(t){var e=this,a=e.isHorizontal(),i=e.paddingLeft,n=e.paddingBottom,o=a?e.width-(i+e.paddingRight):e.height-(e.paddingTop+n),r=(a?t-e.left-i:e.bottom-n-t)/o;return e.start+(e.end-e.start)*r},getPixelForTick:function(t){return this.getPixelForValue(this.ticksAsNumbers[t])}});t.scaleService.registerScaleType("linear",i,a)}},{}],41:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=e.noop;t.LinearScaleBase=t.Scale.extend({handleTickRangeOptions:function(){var t=this,a=t.options,i=a.ticks;if(i.beginAtZero){var n=e.sign(t.min),o=e.sign(t.max);0>n&&0>o?t.max=0:n>0&&o>0&&(t.min=0)}void 0!==i.min?t.min=i.min:void 0!==i.suggestedMin&&(t.min=Math.min(t.min,i.suggestedMin)),void 0!==i.max?t.max=i.max:void 0!==i.suggestedMax&&(t.max=Math.max(t.max,i.suggestedMax)),t.min===t.max&&(t.max++,i.beginAtZero||t.min--)},getTickLimit:a,handleDirectionalChanges:a,buildTicks:function(){var t=this,a=t.options,i=t.ticks=[],n=a.ticks,o=e.getValueOrDefault,r=t.getTickLimit();r=Math.max(2,r);var l,s=n.fixedStepSize&&n.fixedStepSize>0||n.stepSize&&n.stepSize>0;if(s)l=o(n.fixedStepSize,n.stepSize);else{var d=e.niceNum(t.max-t.min,!1);l=e.niceNum(d/(r-1),!0)}var u=Math.floor(t.min/l)*l,c=Math.ceil(t.max/l)*l,h=(c-u)/l;h=e.almostEquals(h,Math.round(h),l/1e3)?Math.round(h):Math.ceil(h),i.push(void 0!==n.min?n.min:u);for(var f=1;h>f;++f)i.push(u+f*l);i.push(void 0!==n.max?n.max:c),t.handleDirectionalChanges(),t.max=e.max(i),t.min=e.min(i),n.reverse?(i.reverse(),t.start=t.max,t.end=t.min):(t.start=t.min,t.end=t.max)},convertTicksToLabels:function(){var e=this;e.ticksAsNumbers=e.ticks.slice(),e.zeroLineIndex=e.ticks.indexOf(0),t.Scale.prototype.convertTicksToLabels.call(e)}})}},{}],42:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a={position:"left",ticks:{callback:function(t,a,i){var n=t/Math.pow(10,Math.floor(e.log10(t)));return 0===t?"0":1===n||2===n||5===n||0===a||a===i.length-1?t.toExponential():""}}},i=t.Scale.extend({determineDataLimits:function(){function t(t){return d?t.xAxisID===a.id:t.yAxisID===a.id}var a=this,i=a.options,n=i.ticks,o=a.chart,r=o.data,l=r.datasets,s=e.getValueOrDefault,d=a.isHorizontal();if(a.min=null,a.max=null,a.minNotZero=null,i.stacked){var u={};e.each(l,function(n,r){var l=o.getDatasetMeta(r);o.isDatasetVisible(r)&&t(l)&&(void 0===u[l.type]&&(u[l.type]=[]),e.each(n.data,function(t,e){var n=u[l.type],o=+a.getRightValue(t);isNaN(o)||l.data[e].hidden||(n[e]=n[e]||0,i.relativePoints?n[e]=100:n[e]+=o)}))}),e.each(u,function(t){var i=e.min(t),n=e.max(t);a.min=null===a.min?i:Math.min(a.min,i),
    a.max=null===a.max?n:Math.max(a.max,n)})}else e.each(l,function(i,n){var r=o.getDatasetMeta(n);o.isDatasetVisible(n)&&t(r)&&e.each(i.data,function(t,e){var i=+a.getRightValue(t);isNaN(i)||r.data[e].hidden||(null===a.min?a.min=i:i<a.min&&(a.min=i),null===a.max?a.max=i:i>a.max&&(a.max=i),0!==i&&(null===a.minNotZero||i<a.minNotZero)&&(a.minNotZero=i))})});a.min=s(n.min,a.min),a.max=s(n.max,a.max),a.min===a.max&&(0!==a.min&&null!==a.min?(a.min=Math.pow(10,Math.floor(e.log10(a.min))-1),a.max=Math.pow(10,Math.floor(e.log10(a.max))+1)):(a.min=1,a.max=10))},buildTicks:function(){for(var t=this,a=t.options,i=a.ticks,n=e.getValueOrDefault,o=t.ticks=[],r=n(i.min,Math.pow(10,Math.floor(e.log10(t.min))));r<t.max;){o.push(r);var l,s;0===r?(l=Math.floor(e.log10(t.minNotZero)),s=Math.round(t.minNotZero/Math.pow(10,l))):(l=Math.floor(e.log10(r)),s=Math.floor(r/Math.pow(10,l))+1),10===s&&(s=1,++l),r=s*Math.pow(10,l)}var d=n(i.max,r);o.push(d),t.isHorizontal()||o.reverse(),t.max=e.max(o),t.min=e.min(o),i.reverse?(o.reverse(),t.start=t.max,t.end=t.min):(t.start=t.min,t.end=t.max)},convertTicksToLabels:function(){this.tickValues=this.ticks.slice(),t.Scale.prototype.convertTicksToLabels.call(this)},getLabelForIndex:function(t,e){return+this.getRightValue(this.chart.data.datasets[e].data[t])},getPixelForTick:function(t){return this.getPixelForValue(this.tickValues[t])},getPixelForValue:function(t){var a,i,n,o=this,r=o.start,l=+o.getRightValue(t),s=o.paddingTop,d=o.paddingBottom,u=o.paddingLeft,c=o.options,h=c.ticks;return o.isHorizontal()?(n=e.log10(o.end)-e.log10(r),0===l?i=o.left+u:(a=o.width-(u+o.paddingRight),i=o.left+a/n*(e.log10(l)-e.log10(r)),i+=u)):(a=o.height-(s+d),0!==r||h.reverse?0===o.end&&h.reverse?(n=e.log10(o.start)-e.log10(o.minNotZero),i=l===o.end?o.top+s:l===o.minNotZero?o.top+s+.02*a:o.top+s+.02*a+.98*a/n*(e.log10(l)-e.log10(o.minNotZero))):(n=e.log10(o.end)-e.log10(r),a=o.height-(s+d),i=o.bottom-d-a/n*(e.log10(l)-e.log10(r))):(n=e.log10(o.end)-e.log10(o.minNotZero),i=l===r?o.bottom-d:l===o.minNotZero?o.bottom-d-.02*a:o.bottom-d-.02*a-.98*a/n*(e.log10(l)-e.log10(o.minNotZero)))),i},getValueForPixel:function(t){var a,i,n=this,o=e.log10(n.end)-e.log10(n.start);return n.isHorizontal()?(i=n.width-(n.paddingLeft+n.paddingRight),a=n.start*Math.pow(10,(t-n.left-n.paddingLeft)*o/i)):(i=n.height-(n.paddingTop+n.paddingBottom),a=Math.pow(10,(n.bottom-n.paddingBottom-t)*o/i)/n.start),a}});t.scaleService.registerScaleType("logarithmic",i,a)}},{}],43:[function(t,e,a){"use strict";e.exports=function(t){var e=t.helpers,a=t.defaults.global,i={display:!0,animate:!0,lineArc:!1,position:"chartArea",angleLines:{display:!0,color:"rgba(0, 0, 0, 0.1)",lineWidth:1},ticks:{showLabelBackdrop:!0,backdropColor:"rgba(255,255,255,0.75)",backdropPaddingY:2,backdropPaddingX:2},pointLabels:{fontSize:10,callback:function(t){return t}}},n=t.LinearScaleBase.extend({getValueCount:function(){return this.chart.data.labels.length},setDimensions:function(){var t=this,i=t.options,n=i.ticks;t.width=t.maxWidth,t.height=t.maxHeight,t.xCenter=Math.round(t.width/2),t.yCenter=Math.round(t.height/2);var o=e.min([t.height,t.width]),r=e.getValueOrDefault(n.fontSize,a.defaultFontSize);t.drawingArea=i.display?o/2-(r/2+n.backdropPaddingY):o/2},determineDataLimits:function(){var t=this,a=t.chart;t.min=null,t.max=null,e.each(a.data.datasets,function(i,n){if(a.isDatasetVisible(n)){var o=a.getDatasetMeta(n);e.each(i.data,function(e,a){var i=+t.getRightValue(e);isNaN(i)||o.data[a].hidden||(null===t.min?t.min=i:i<t.min&&(t.min=i),null===t.max?t.max=i:i>t.max&&(t.max=i))})}}),t.handleTickRangeOptions()},getTickLimit:function(){var t=this.options.ticks,i=e.getValueOrDefault(t.fontSize,a.defaultFontSize);return Math.min(t.maxTicksLimit?t.maxTicksLimit:11,Math.ceil(this.drawingArea/(1.5*i)))},convertTicksToLabels:function(){var e=this;t.LinearScaleBase.prototype.convertTicksToLabels.call(e),e.pointLabels=e.chart.data.labels.map(e.options.pointLabels.callback,e)},getLabelForIndex:function(t,e){return+this.getRightValue(this.chart.data.datasets[e].data[t])},fit:function(){var t,i,n,o,r,l,s,d,u,c,h,f,g=this.options.pointLabels,p=e.getValueOrDefault(g.fontSize,a.defaultFontSize),m=e.getValueOrDefault(g.fontStyle,a.defaultFontStyle),b=e.getValueOrDefault(g.fontFamily,a.defaultFontFamily),v=e.fontString(p,m,b),x=e.min([this.height/2-p-5,this.width/2]),y=this.width,k=0;for(this.ctx.font=v,i=0;i<this.getValueCount();i++){t=this.getPointPosition(i,x),n=this.ctx.measureText(this.pointLabels[i]?this.pointLabels[i]:"").width+5;var S=this.getIndexAngle(i)+Math.PI/2,w=360*S/(2*Math.PI)%360;0===w||180===w?(o=n/2,t.x+o>y&&(y=t.x+o,r=i),t.x-o<k&&(k=t.x-o,s=i)):180>w?t.x+n>y&&(y=t.x+n,r=i):t.x-n<k&&(k=t.x-n,s=i)}u=k,c=Math.ceil(y-this.width),l=this.getIndexAngle(r),d=this.getIndexAngle(s),h=c/Math.sin(l+Math.PI/2),f=u/Math.sin(d+Math.PI/2),h=e.isNumber(h)?h:0,f=e.isNumber(f)?f:0,this.drawingArea=Math.round(x-(f+h)/2),this.setCenterPoint(f,h)},setCenterPoint:function(t,e){var a=this,i=a.width-e-a.drawingArea,n=t+a.drawingArea;a.xCenter=Math.round((n+i)/2+a.left),a.yCenter=Math.round(a.height/2+a.top)},getIndexAngle:function(t){var e=2*Math.PI/this.getValueCount(),a=this.chart.options&&this.chart.options.startAngle?this.chart.options.startAngle:0,i=a*Math.PI*2/360;return t*e-Math.PI/2+i},getDistanceFromCenterForValue:function(t){var e=this;if(null===t)return 0;var a=e.drawingArea/(e.max-e.min);return e.options.reverse?(e.max-t)*a:(t-e.min)*a},getPointPosition:function(t,e){var a=this,i=a.getIndexAngle(t);return{x:Math.round(Math.cos(i)*e)+a.xCenter,y:Math.round(Math.sin(i)*e)+a.yCenter}},getPointPositionForValue:function(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))},getBasePosition:function(){var t=this,e=t.min,a=t.max;return t.getPointPositionForValue(0,t.beginAtZero?0:0>e&&0>a?a:e>0&&a>0?e:0)},draw:function(){var t=this,i=t.options,n=i.gridLines,o=i.ticks,r=i.angleLines,l=i.pointLabels,s=e.getValueOrDefault;if(i.display){var d=t.ctx,u=s(o.fontSize,a.defaultFontSize),c=s(o.fontStyle,a.defaultFontStyle),h=s(o.fontFamily,a.defaultFontFamily),f=e.fontString(u,c,h);if(e.each(t.ticks,function(r,l){if(l>0||i.reverse){var c=t.getDistanceFromCenterForValue(t.ticksAsNumbers[l]),h=t.yCenter-c;if(n.display&&0!==l)if(d.strokeStyle=e.getValueAtIndexOrDefault(n.color,l-1),d.lineWidth=e.getValueAtIndexOrDefault(n.lineWidth,l-1),i.lineArc)d.beginPath(),d.arc(t.xCenter,t.yCenter,c,0,2*Math.PI),d.closePath(),d.stroke();else{d.beginPath();for(var g=0;g<t.getValueCount();g++){var p=t.getPointPosition(g,c);0===g?d.moveTo(p.x,p.y):d.lineTo(p.x,p.y)}d.closePath(),d.stroke()}if(o.display){var m=s(o.fontColor,a.defaultFontColor);if(d.font=f,o.showLabelBackdrop){var b=d.measureText(r).width;d.fillStyle=o.backdropColor,d.fillRect(t.xCenter-b/2-o.backdropPaddingX,h-u/2-o.backdropPaddingY,b+2*o.backdropPaddingX,u+2*o.backdropPaddingY)}d.textAlign="center",d.textBaseline="middle",d.fillStyle=m,d.fillText(r,t.xCenter,h)}}}),!i.lineArc){d.lineWidth=r.lineWidth,d.strokeStyle=r.color;for(var g=t.getDistanceFromCenterForValue(i.reverse?t.min:t.max),p=s(l.fontSize,a.defaultFontSize),m=s(l.fontStyle,a.defaultFontStyle),b=s(l.fontFamily,a.defaultFontFamily),v=e.fontString(p,m,b),x=t.getValueCount()-1;x>=0;x--){if(r.display){var y=t.getPointPosition(x,g);d.beginPath(),d.moveTo(t.xCenter,t.yCenter),d.lineTo(y.x,y.y),d.stroke(),d.closePath()}var k=t.getPointPosition(x,g+5),S=s(l.fontColor,a.defaultFontColor);d.font=v,d.fillStyle=S;var w=t.pointLabels,C=this.getIndexAngle(x)+Math.PI/2,M=360*C/(2*Math.PI)%360;0===M||180===M?d.textAlign="center":180>M?d.textAlign="left":d.textAlign="right",90===M||270===M?d.textBaseline="middle":M>270||90>M?d.textBaseline="bottom":d.textBaseline="top",d.fillText(w[x]?w[x]:"",k.x,k.y)}}}}});t.scaleService.registerScaleType("radialLinear",n,i)}},{}],44:[function(t,e,a){"use strict";var i=t(1);i="function"==typeof i?i:window.moment,e.exports=function(t){var e=t.helpers,a={units:[{name:"millisecond",steps:[1,2,5,10,20,50,100,250,500]},{name:"second",steps:[1,2,5,10,30]},{name:"minute",steps:[1,2,5,10,30]},{name:"hour",steps:[1,2,3,6,12]},{name:"day",steps:[1,2,5]},{name:"week",maxStep:4},{name:"month",maxStep:3},{name:"quarter",maxStep:4},{name:"year",maxStep:!1}]},n={position:"bottom",time:{parser:!1,format:!1,unit:!1,round:!1,displayFormat:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{millisecond:"h:mm:ss.SSS a",second:"h:mm:ss a",minute:"h:mm:ss a",hour:"MMM D, hA",day:"ll",week:"ll",month:"MMM YYYY",quarter:"[Q]Q - YYYY",year:"YYYY"}},ticks:{autoSkip:!1}},o=t.Scale.extend({initialize:function(){if(!i)throw new Error("Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com");t.Scale.prototype.initialize.call(this)},getLabelMoment:function(t,e){return null===t||null===e?null:"undefined"!=typeof this.labelMoments[t]?this.labelMoments[t][e]:null},getLabelDiff:function(t,e){var a=this;return null===t||null===e?null:(void 0===a.labelDiffs&&a.buildLabelDiffs(),"undefined"!=typeof a.labelDiffs[t]?a.labelDiffs[t][e]:null)},getMomentStartOf:function(t){var e=this;return"week"===e.options.time.unit&&e.options.time.isoWeekday!==!1?t.clone().startOf("isoWeek").isoWeekday(e.options.time.isoWeekday):t.clone().startOf(e.tickUnit)},determineDataLimits:function(){var t=this;t.labelMoments=[];var a=[];t.chart.data.labels&&t.chart.data.labels.length>0?(e.each(t.chart.data.labels,function(e){var i=t.parseTime(e);i.isValid()&&(t.options.time.round&&i.startOf(t.options.time.round),a.push(i))},t),t.firstTick=i.min.call(t,a),t.lastTick=i.max.call(t,a)):(t.firstTick=null,t.lastTick=null),e.each(t.chart.data.datasets,function(n,o){var r=[],l=t.chart.isDatasetVisible(o);"object"==typeof n.data[0]&&null!==n.data[0]?e.each(n.data,function(e){var a=t.parseTime(t.getRightValue(e));a.isValid()&&(t.options.time.round&&a.startOf(t.options.time.round),r.push(a),l&&(t.firstTick=null!==t.firstTick?i.min(t.firstTick,a):a,t.lastTick=null!==t.lastTick?i.max(t.lastTick,a):a))},t):r=a,t.labelMoments.push(r)},t),t.options.time.min&&(t.firstTick=t.parseTime(t.options.time.min)),t.options.time.max&&(t.lastTick=t.parseTime(t.options.time.max)),t.firstTick=(t.firstTick||i()).clone(),t.lastTick=(t.lastTick||i()).clone()},buildLabelDiffs:function(){var t=this;t.labelDiffs=[];var a=[];t.chart.data.labels&&t.chart.data.labels.length>0&&e.each(t.chart.data.labels,function(e){var i=t.parseTime(e);i.isValid()&&(t.options.time.round&&i.startOf(t.options.time.round),a.push(i.diff(t.firstTick,t.tickUnit,!0)))},t),e.each(t.chart.data.datasets,function(i){var n=[];"object"==typeof i.data[0]&&null!==i.data[0]?e.each(i.data,function(e){var a=t.parseTime(t.getRightValue(e));a.isValid()&&(t.options.time.round&&a.startOf(t.options.time.round),n.push(a.diff(t.firstTick,t.tickUnit,!0)))},t):n=a,t.labelDiffs.push(n)},t)},buildTicks:function(){var i=this;i.ctx.save();var n=e.getValueOrDefault(i.options.ticks.fontSize,t.defaults.global.defaultFontSize),o=e.getValueOrDefault(i.options.ticks.fontStyle,t.defaults.global.defaultFontStyle),r=e.getValueOrDefault(i.options.ticks.fontFamily,t.defaults.global.defaultFontFamily),l=e.fontString(n,o,r);if(i.ctx.font=l,i.ticks=[],i.unitScale=1,i.scaleSizeInUnits=0,i.options.time.unit)i.tickUnit=i.options.time.unit||"day",i.displayFormat=i.options.time.displayFormats[i.tickUnit],i.scaleSizeInUnits=i.lastTick.diff(i.firstTick,i.tickUnit,!0),i.unitScale=e.getValueOrDefault(i.options.time.unitStepSize,1);else{var s=i.isHorizontal()?i.width-(i.paddingLeft+i.paddingRight):i.height-(i.paddingTop+i.paddingBottom),d=i.tickFormatFunction(i.firstTick,0,[]),u=i.ctx.measureText(d).width,c=Math.cos(e.toRadians(i.options.ticks.maxRotation)),h=Math.sin(e.toRadians(i.options.ticks.maxRotation));u=u*c+n*h;var f=s/u;i.tickUnit=i.options.time.minUnit,i.scaleSizeInUnits=i.lastTick.diff(i.firstTick,i.tickUnit,!0),i.displayFormat=i.options.time.displayFormats[i.tickUnit];for(var g=0,p=a.units[g];g<a.units.length;){if(i.unitScale=1,e.isArray(p.steps)&&Math.ceil(i.scaleSizeInUnits/f)<e.max(p.steps)){for(var m=0;m<p.steps.length;++m)if(p.steps[m]>=Math.ceil(i.scaleSizeInUnits/f)){i.unitScale=e.getValueOrDefault(i.options.time.unitStepSize,p.steps[m]);break}break}if(p.maxStep===!1||Math.ceil(i.scaleSizeInUnits/f)<p.maxStep){i.unitScale=e.getValueOrDefault(i.options.time.unitStepSize,Math.ceil(i.scaleSizeInUnits/f));break}++g,p=a.units[g],i.tickUnit=p.name;var b=i.firstTick.diff(i.getMomentStartOf(i.firstTick),i.tickUnit,!0),v=i.getMomentStartOf(i.lastTick.clone().add(1,i.tickUnit)).diff(i.lastTick,i.tickUnit,!0);i.scaleSizeInUnits=i.lastTick.diff(i.firstTick,i.tickUnit,!0)+b+v,i.displayFormat=i.options.time.displayFormats[p.name]}}var x;if(i.options.time.min?x=i.getMomentStartOf(i.firstTick):(i.firstTick=i.getMomentStartOf(i.firstTick),x=i.firstTick),!i.options.time.max){var y=i.getMomentStartOf(i.lastTick),k=y.diff(i.lastTick,i.tickUnit,!0);0>k?i.lastTick=i.getMomentStartOf(i.lastTick.add(1,i.tickUnit)):k>=0&&(i.lastTick=y),i.scaleSizeInUnits=i.lastTick.diff(i.firstTick,i.tickUnit,!0)}i.options.time.displayFormat&&(i.displayFormat=i.options.time.displayFormat),i.ticks.push(i.firstTick.clone());for(var S=1;S<=i.scaleSizeInUnits;++S){var w=x.clone().add(S,i.tickUnit);if(i.options.time.max&&w.diff(i.lastTick,i.tickUnit,!0)>=0)break;S%i.unitScale===0&&i.ticks.push(w)}var C=i.ticks[i.ticks.length-1].diff(i.lastTick,i.tickUnit);(0!==C||0===i.scaleSizeInUnits)&&(i.options.time.max?(i.ticks.push(i.lastTick.clone()),i.scaleSizeInUnits=i.lastTick.diff(i.ticks[0],i.tickUnit,!0)):(i.ticks.push(i.lastTick.clone()),i.scaleSizeInUnits=i.lastTick.diff(i.firstTick,i.tickUnit,!0))),i.ctx.restore(),i.labelDiffs=void 0},getLabelForIndex:function(t,e){var a=this,i=a.chart.data.labels&&t<a.chart.data.labels.length?a.chart.data.labels[t]:"";return"object"==typeof a.chart.data.datasets[e].data[0]&&(i=a.getRightValue(a.chart.data.datasets[e].data[t])),a.options.time.tooltipFormat&&(i=a.parseTime(i).format(a.options.time.tooltipFormat)),i},tickFormatFunction:function(t,a,i){var n=t.format(this.displayFormat),o=this.options.ticks,r=e.getValueOrDefault(o.callback,o.userCallback);return r?r(n,a,i):n},convertTicksToLabels:function(){var t=this;t.tickMoments=t.ticks,t.ticks=t.ticks.map(t.tickFormatFunction,t)},getPixelForValue:function(t,e,a){var i=this,n=null;if(void 0!==e&&void 0!==a&&(n=i.getLabelDiff(a,e)),null===n&&(t&&t.isValid||(t=i.parseTime(i.getRightValue(t))),t&&t.isValid&&t.isValid()&&(n=t.diff(i.firstTick,i.tickUnit,!0))),null!==n){var o=0!==n?n/i.scaleSizeInUnits:n;if(i.isHorizontal()){var r=i.width-(i.paddingLeft+i.paddingRight),l=r*o+i.paddingLeft;return i.left+Math.round(l)}var s=i.height-(i.paddingTop+i.paddingBottom),d=s*o+i.paddingTop;return i.top+Math.round(d)}},getPixelForTick:function(t){return this.getPixelForValue(this.tickMoments[t],null,null)},getValueForPixel:function(t){var e=this,a=e.isHorizontal()?e.width-(e.paddingLeft+e.paddingRight):e.height-(e.paddingTop+e.paddingBottom),n=(t-(e.isHorizontal()?e.left+e.paddingLeft:e.top+e.paddingTop))/a;return n*=e.scaleSizeInUnits,e.firstTick.clone().add(i.duration(n,e.tickUnit).asSeconds(),"seconds")},parseTime:function(t){var e=this;return"string"==typeof e.options.time.parser?i(t,e.options.time.parser):"function"==typeof e.options.time.parser?e.options.time.parser(t):"function"==typeof t.getMonth||"number"==typeof t?i(t):t.isValid&&t.isValid()?t:"string"!=typeof e.options.time.format&&e.options.time.format.call?(console.warn("options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale"),e.options.time.format(t)):i(t,e.options.time.format)}});t.scaleService.registerScaleType("time",o,n)}},{1:1}]},{},[7])(7)});
    // Peity jQuery plugin version 3.2.1
    // (c) 2016 Ben Pickles
    //
    // http://benpickles.github.io/peity
    //
    // Released under MIT license.
    (function(k,w,h,v){var d=k.fn.peity=function(a,b){y&&this.each(function(){var e=k(this),c=e.data("_peity");c?(a&&(c.type=a),k.extend(c.opts,b)):(c=new x(e,a,k.extend({},d.defaults[a],e.data("peity"),b)),e.change(function(){c.draw()}).data("_peity",c));c.draw()});return this},x=function(a,b,e){this.$el=a;this.type=b;this.opts=e},o=x.prototype,q=o.svgElement=function(a,b){return k(w.createElementNS("http://www.w3.org/2000/svg",a)).attr(b)},y="createElementNS"in w&&q("svg",{})[0].createSVGRect;o.draw=
    function(){var a=this.opts;d.graphers[this.type].call(this,a);a.after&&a.after.call(this,a)};o.fill=function(){var a=this.opts.fill;return k.isFunction(a)?a:function(b,e){return a[e%a.length]}};o.prepare=function(a,b){this.$svg||this.$el.hide().after(this.$svg=q("svg",{"class":"peity"}));return this.$svg.empty().data("peity",this).attr({height:b,width:a})};o.values=function(){return k.map(this.$el.text().split(this.opts.delimiter),function(a){return parseFloat(a)})};d.defaults={};d.graphers={};d.register=
    function(a,b,e){this.defaults[a]=b;this.graphers[a]=e};d.register("pie",{fill:["#ff9900","#fff4dd","#ffc66e"],radius:8},function(a){if(!a.delimiter){var b=this.$el.text().match(/[^0-9\.]/);a.delimiter=b?b[0]:","}b=k.map(this.values(),function(a){return 0<a?a:0});if("/"==a.delimiter)var e=b[0],b=[e,h.max(0,b[1]-e)];for(var c=0,e=b.length,t=0;c<e;c++)t+=b[c];t||(e=2,t=1,b=[0,1]);var l=2*a.radius,l=this.prepare(a.width||l,a.height||l),c=l.width(),f=l.height(),j=c/2,d=f/2,f=h.min(j,d),a=a.innerRadius;
    "donut"==this.type&&!a&&(a=0.5*f);for(var r=h.PI,s=this.fill(),g=this.scale=function(a,b){var c=a/t*r*2-r/2;return[b*h.cos(c)+j,b*h.sin(c)+d]},m=0,c=0;c<e;c++){var u=b[c],i=u/t;if(0!=i){if(1==i)if(a)var i=j-0.01,p=d-f,n=d-a,i=q("path",{d:["M",j,p,"A",f,f,0,1,1,i,p,"L",i,n,"A",a,a,0,1,0,j,n].join(" ")});else i=q("circle",{cx:j,cy:d,r:f});else p=m+u,n=["M"].concat(g(m,f),"A",f,f,0,0.5<i?1:0,1,g(p,f),"L"),a?n=n.concat(g(p,a),"A",a,a,0,0.5<i?1:0,0,g(m,a)):n.push(j,d),m+=u,i=q("path",{d:n.join(" ")});
    i.attr("fill",s.call(this,u,c,b));l.append(i)}}});d.register("donut",k.extend(!0,{},d.defaults.pie),function(a){d.graphers.pie.call(this,a)});d.register("line",{delimiter:",",fill:"#c6d9fd",height:16,min:0,stroke:"#4d89f9",strokeWidth:1,width:32},function(a){var b=this.values();1==b.length&&b.push(b[0]);for(var e=h.max.apply(h,a.max==v?b:b.concat(a.max)),c=h.min.apply(h,a.min==v?b:b.concat(a.min)),d=this.prepare(a.width,a.height),l=a.strokeWidth,f=d.width(),j=d.height()-l,k=e-c,e=this.x=function(a){return a*
    (f/(b.length-1))},r=this.y=function(a){var b=j;k&&(b-=(a-c)/k*j);return b+l/2},s=r(h.max(c,0)),g=[0,s],m=0;m<b.length;m++)g.push(e(m),r(b[m]));g.push(f,s);a.fill&&d.append(q("polygon",{fill:a.fill,points:g.join(" ")}));l&&d.append(q("polyline",{fill:"none",points:g.slice(2,g.length-2).join(" "),stroke:a.stroke,"stroke-width":l,"stroke-linecap":"square"}))});d.register("bar",{delimiter:",",fill:["#4D89F9"],height:16,min:0,padding:0.1,width:32},function(a){for(var b=this.values(),e=h.max.apply(h,a.max==
    v?b:b.concat(a.max)),c=h.min.apply(h,a.min==v?b:b.concat(a.min)),d=this.prepare(a.width,a.height),l=d.width(),f=d.height(),j=e-c,a=a.padding,k=this.fill(),r=this.x=function(a){return a*l/b.length},s=this.y=function(a){return f-(j?(a-c)/j*f:1)},g=0;g<b.length;g++){var m=r(g+a),u=r(g+1-a)-m,i=b[g],p=s(i),n=p,o;j?0>i?n=s(h.min(e,0)):p=s(h.max(c,0)):o=1;o=p-n;0==o&&(o=1,0<e&&j&&n--);d.append(q("rect",{fill:k.call(this,i,g,b),x:m,y:n,width:u,height:o}))}})})(jQuery,document,Math);
    
    !function(e,t,n){"use strict";!function o(e,t,n){function a(s,l){if(!t[s]){if(!e[s]){var i="function"==typeof require&&require;if(!l&&i)return i(s,!0);if(r)return r(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var c=t[s]={exports:{}};e[s][0].call(c.exports,function(t){var n=e[s][1][t];return a(n?n:t)},c,c.exports,o,e,t,n)}return t[s].exports}for(var r="function"==typeof require&&require,s=0;s<n.length;s++)a(n[s]);return a}({1:[function(o,a,r){var s=function(e){return e&&e.__esModule?e:{"default":e}};Object.defineProperty(r,"__esModule",{value:!0});var l,i,u,c,d=o("./modules/handle-dom"),f=o("./modules/utils"),p=o("./modules/handle-swal-dom"),m=o("./modules/handle-click"),v=o("./modules/handle-key"),y=s(v),h=o("./modules/default-params"),b=s(h),g=o("./modules/set-params"),w=s(g);r["default"]=u=c=function(){function o(e){var t=a;return t[e]===n?b["default"][e]:t[e]}var a=arguments[0];if(d.addClass(t.body,"stop-scrolling"),p.resetInput(),a===n)return f.logStr("SweetAlert expects at least 1 attribute!"),!1;var r=f.extend({},b["default"]);switch(typeof a){case"string":r.title=a,r.text=arguments[1]||"",r.type=arguments[2]||"";break;case"object":if(a.title===n)return f.logStr('Missing "title" argument!'),!1;r.title=a.title;for(var s in b["default"])r[s]=o(s);r.confirmButtonText=r.showCancelButton?"Confirm":b["default"].confirmButtonText,r.confirmButtonText=o("confirmButtonText"),r.doneFunction=arguments[1]||null;break;default:return f.logStr('Unexpected type of argument! Expected "string" or "object", got '+typeof a),!1}w["default"](r),p.fixVerticalPosition(),p.openModal(arguments[1]);for(var u=p.getModal(),v=u.querySelectorAll("button"),h=["onclick","onmouseover","onmouseout","onmousedown","onmouseup","onfocus"],g=function(e){return m.handleButton(e,r,u)},C=0;C<v.length;C++)for(var S=0;S<h.length;S++){var x=h[S];v[C][x]=g}p.getOverlay().onclick=g,l=e.onkeydown;var k=function(e){return y["default"](e,r,u)};e.onkeydown=k,e.onfocus=function(){setTimeout(function(){i!==n&&(i.focus(),i=n)},0)},c.enableButtons()},u.setDefaults=c.setDefaults=function(e){if(!e)throw new Error("userParams is required");if("object"!=typeof e)throw new Error("userParams has to be a object");f.extend(b["default"],e)},u.close=c.close=function(){var o=p.getModal();d.fadeOut(p.getOverlay(),5),d.fadeOut(o,5),d.removeClass(o,"showSweetAlert"),d.addClass(o,"hideSweetAlert"),d.removeClass(o,"visible");var a=o.querySelector(".sa-icon.sa-success");d.removeClass(a,"animate"),d.removeClass(a.querySelector(".sa-tip"),"animateSuccessTip"),d.removeClass(a.querySelector(".sa-long"),"animateSuccessLong");var r=o.querySelector(".sa-icon.sa-error");d.removeClass(r,"animateErrorIcon"),d.removeClass(r.querySelector(".sa-x-mark"),"animateXMark");var s=o.querySelector(".sa-icon.sa-warning");return d.removeClass(s,"pulseWarning"),d.removeClass(s.querySelector(".sa-body"),"pulseWarningIns"),d.removeClass(s.querySelector(".sa-dot"),"pulseWarningIns"),setTimeout(function(){var e=o.getAttribute("data-custom-class");d.removeClass(o,e)},300),d.removeClass(t.body,"stop-scrolling"),e.onkeydown=l,e.previousActiveElement&&e.previousActiveElement.focus(),i=n,clearTimeout(o.timeout),!0},u.showInputError=c.showInputError=function(e){var t=p.getModal(),n=t.querySelector(".sa-input-error");d.addClass(n,"show");var o=t.querySelector(".sa-error-container");d.addClass(o,"show"),o.querySelector("p").innerHTML=e,setTimeout(function(){u.enableButtons()},1),t.querySelector("input").focus()},u.resetInputError=c.resetInputError=function(e){if(e&&13===e.keyCode)return!1;var t=p.getModal(),n=t.querySelector(".sa-input-error");d.removeClass(n,"show");var o=t.querySelector(".sa-error-container");d.removeClass(o,"show")},u.disableButtons=c.disableButtons=function(){var e=p.getModal(),t=e.querySelector("button.confirm"),n=e.querySelector("button.cancel");t.disabled=!0,n.disabled=!0},u.enableButtons=c.enableButtons=function(){var e=p.getModal(),t=e.querySelector("button.confirm"),n=e.querySelector("button.cancel");t.disabled=!1,n.disabled=!1},"undefined"!=typeof e?e.sweetAlert=e.swal=u:f.logStr("SweetAlert is a frontend module!"),a.exports=r["default"]},{"./modules/default-params":2,"./modules/handle-click":3,"./modules/handle-dom":4,"./modules/handle-key":5,"./modules/handle-swal-dom":6,"./modules/set-params":8,"./modules/utils":9}],2:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var o={title:"",text:"",type:null,allowOutsideClick:!1,showConfirmButton:!0,showCancelButton:!1,closeOnConfirm:!0,closeOnCancel:!0,confirmButtonText:"OK",confirmButtonColor:"#8CD4F5",cancelButtonText:"Cancel",imageUrl:null,imageSize:null,timer:null,customClass:"",html:!1,animation:!0,allowEscapeKey:!0,inputType:"text",inputPlaceholder:"",inputValue:"",showLoaderOnConfirm:!1};n["default"]=o,t.exports=n["default"]},{}],3:[function(t,n,o){Object.defineProperty(o,"__esModule",{value:!0});var a=t("./utils"),r=(t("./handle-swal-dom"),t("./handle-dom")),s=function(t,n,o){function s(e){m&&n.confirmButtonColor&&(p.style.backgroundColor=e)}var u,c,d,f=t||e.event,p=f.target||f.srcElement,m=-1!==p.className.indexOf("confirm"),v=-1!==p.className.indexOf("sweet-overlay"),y=r.hasClass(o,"visible"),h=n.doneFunction&&"true"===o.getAttribute("data-has-done-function");switch(m&&n.confirmButtonColor&&(u=n.confirmButtonColor,c=a.colorLuminance(u,-.04),d=a.colorLuminance(u,-.14)),f.type){case"mouseover":s(c);break;case"mouseout":s(u);break;case"mousedown":s(d);break;case"mouseup":s(c);break;case"focus":var b=o.querySelector("button.confirm"),g=o.querySelector("button.cancel");m?g.style.boxShadow="none":b.style.boxShadow="none";break;case"click":var w=o===p,C=r.isDescendant(o,p);if(!w&&!C&&y&&!n.allowOutsideClick)break;m&&h&&y?l(o,n):h&&y||v?i(o,n):r.isDescendant(o,p)&&"BUTTON"===p.tagName&&sweetAlert.close()}},l=function(e,t){var n=!0;r.hasClass(e,"show-input")&&(n=e.querySelector("input").value,n||(n="")),t.doneFunction(n),t.closeOnConfirm&&sweetAlert.close(),t.showLoaderOnConfirm&&sweetAlert.disableButtons()},i=function(e,t){var n=String(t.doneFunction).replace(/\s/g,""),o="function("===n.substring(0,9)&&")"!==n.substring(9,10);o&&t.doneFunction(!1),t.closeOnCancel&&sweetAlert.close()};o["default"]={handleButton:s,handleConfirm:l,handleCancel:i},n.exports=o["default"]},{"./handle-dom":4,"./handle-swal-dom":6,"./utils":9}],4:[function(n,o,a){Object.defineProperty(a,"__esModule",{value:!0});var r=function(e,t){return new RegExp(" "+t+" ").test(" "+e.className+" ")},s=function(e,t){r(e,t)||(e.className+=" "+t)},l=function(e,t){var n=" "+e.className.replace(/[\t\r\n]/g," ")+" ";if(r(e,t)){for(;n.indexOf(" "+t+" ")>=0;)n=n.replace(" "+t+" "," ");e.className=n.replace(/^\s+|\s+$/g,"")}},i=function(e){var n=t.createElement("div");return n.appendChild(t.createTextNode(e)),n.innerHTML},u=function(e){e.style.opacity="",e.style.display="block"},c=function(e){if(e&&!e.length)return u(e);for(var t=0;t<e.length;++t)u(e[t])},d=function(e){e.style.opacity="",e.style.display="none"},f=function(e){if(e&&!e.length)return d(e);for(var t=0;t<e.length;++t)d(e[t])},p=function(e,t){for(var n=t.parentNode;null!==n;){if(n===e)return!0;n=n.parentNode}return!1},m=function(e){e.style.left="-9999px",e.style.display="block";var t,n=e.clientHeight;return t="undefined"!=typeof getComputedStyle?parseInt(getComputedStyle(e).getPropertyValue("padding-top"),10):parseInt(e.currentStyle.padding),e.style.left="",e.style.display="none","-"+parseInt((n+t)/2)+"px"},v=function(e,t){if(+e.style.opacity<1){t=t||16,e.style.opacity=0,e.style.display="block";var n=+new Date,o=function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){e.style.opacity=+e.style.opacity+(new Date-n)/100,n=+new Date,+e.style.opacity<1&&setTimeout(o,t)});o()}e.style.display="block"},y=function(e,t){t=t||16,e.style.opacity=1;var n=+new Date,o=function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){e.style.opacity=+e.style.opacity-(new Date-n)/100,n=+new Date,+e.style.opacity>0?setTimeout(o,t):e.style.display="none"});o()},h=function(n){if("function"==typeof MouseEvent){var o=new MouseEvent("click",{view:e,bubbles:!1,cancelable:!0});n.dispatchEvent(o)}else if(t.createEvent){var a=t.createEvent("MouseEvents");a.initEvent("click",!1,!1),n.dispatchEvent(a)}else t.createEventObject?n.fireEvent("onclick"):"function"==typeof n.onclick&&n.onclick()},b=function(t){"function"==typeof t.stopPropagation?(t.stopPropagation(),t.preventDefault()):e.event&&e.event.hasOwnProperty("cancelBubble")&&(e.event.cancelBubble=!0)};a.hasClass=r,a.addClass=s,a.removeClass=l,a.escapeHtml=i,a._show=u,a.show=c,a._hide=d,a.hide=f,a.isDescendant=p,a.getTopMargin=m,a.fadeIn=v,a.fadeOut=y,a.fireClick=h,a.stopEventPropagation=b},{}],5:[function(t,o,a){Object.defineProperty(a,"__esModule",{value:!0});var r=t("./handle-dom"),s=t("./handle-swal-dom"),l=function(t,o,a){var l=t||e.event,i=l.keyCode||l.which,u=a.querySelector("button.confirm"),c=a.querySelector("button.cancel"),d=a.querySelectorAll("button[tabindex]");if(-1!==[9,13,32,27].indexOf(i)){for(var f=l.target||l.srcElement,p=-1,m=0;m<d.length;m++)if(f===d[m]){p=m;break}9===i?(f=-1===p?u:p===d.length-1?d[0]:d[p+1],r.stopEventPropagation(l),f.focus(),o.confirmButtonColor&&s.setFocusStyle(f,o.confirmButtonColor)):13===i?("INPUT"===f.tagName&&(f=u,u.focus()),f=-1===p?u:n):27===i&&o.allowEscapeKey===!0?(f=c,r.fireClick(f,l)):f=n}};a["default"]=l,o.exports=a["default"]},{"./handle-dom":4,"./handle-swal-dom":6}],6:[function(n,o,a){var r=function(e){return e&&e.__esModule?e:{"default":e}};Object.defineProperty(a,"__esModule",{value:!0});var s=n("./utils"),l=n("./handle-dom"),i=n("./default-params"),u=r(i),c=n("./injected-html"),d=r(c),f=".sweet-alert",p=".sweet-overlay",m=function(){var e=t.createElement("div");for(e.innerHTML=d["default"];e.firstChild;)t.body.appendChild(e.firstChild)},v=function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){var e=t.querySelector(f);return e||(m(),e=v()),e}),y=function(){var e=v();return e?e.querySelector("input"):void 0},h=function(){return t.querySelector(p)},b=function(e,t){var n=s.hexToRgb(t);e.style.boxShadow="0 0 2px rgba("+n+", 0.8), inset 0 0 0 1px rgba(0, 0, 0, 0.05)"},g=function(n){var o=v();l.fadeIn(h(),10),l.show(o),l.addClass(o,"showSweetAlert"),l.removeClass(o,"hideSweetAlert"),e.previousActiveElement=t.activeElement;var a=o.querySelector("button.confirm");a.focus(),setTimeout(function(){l.addClass(o,"visible")},500);var r=o.getAttribute("data-timer");if("null"!==r&&""!==r){var s=n;o.timeout=setTimeout(function(){var e=(s||null)&&"true"===o.getAttribute("data-has-done-function");e?s(null):sweetAlert.close()},r)}},w=function(){var e=v(),t=y();l.removeClass(e,"show-input"),t.value=u["default"].inputValue,t.setAttribute("type",u["default"].inputType),t.setAttribute("placeholder",u["default"].inputPlaceholder),C()},C=function(e){if(e&&13===e.keyCode)return!1;var t=v(),n=t.querySelector(".sa-input-error");l.removeClass(n,"show");var o=t.querySelector(".sa-error-container");l.removeClass(o,"show")},S=function(){var e=v();e.style.marginTop=l.getTopMargin(v())};a.sweetAlertInitialize=m,a.getModal=v,a.getOverlay=h,a.getInput=y,a.setFocusStyle=b,a.openModal=g,a.resetInput=w,a.resetInputError=C,a.fixVerticalPosition=S},{"./default-params":2,"./handle-dom":4,"./injected-html":7,"./utils":9}],7:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var o='<div class="sweet-overlay" tabIndex="-1"></div><div class="sweet-alert"><div class="sa-icon sa-error">\n      <span class="sa-x-mark">\n        <span class="sa-line sa-left"></span>\n        <span class="sa-line sa-right"></span>\n      </span>\n    </div><div class="sa-icon sa-warning">\n      <span class="sa-body"></span>\n      <span class="sa-dot"></span>\n    </div><div class="sa-icon sa-info"></div><div class="sa-icon sa-success">\n      <span class="sa-line sa-tip"></span>\n      <span class="sa-line sa-long"></span>\n\n      <div class="sa-placeholder"></div>\n      <div class="sa-fix"></div>\n    </div><div class="sa-icon sa-custom"></div><h2>Title</h2>\n    <p>Text</p>\n    <fieldset>\n      <input type="text" tabIndex="3" />\n      <div class="sa-input-error"></div>\n    </fieldset><div class="sa-error-container">\n      <div class="icon">!</div>\n      <p>Not valid!</p>\n    </div><div class="sa-button-container">\n      <button class="cancel" tabIndex="2">Cancel</button>\n      <div class="sa-confirm-button-container">\n        <button class="confirm" tabIndex="1">OK</button><div class="la-ball-fall">\n          <div></div>\n          <div></div>\n          <div></div>\n        </div>\n      </div>\n    </div></div>';n["default"]=o,t.exports=n["default"]},{}],8:[function(e,t,o){Object.defineProperty(o,"__esModule",{value:!0});var a=e("./utils"),r=e("./handle-swal-dom"),s=e("./handle-dom"),l=["error","warning","info","success","input","prompt"],i=function(e){var t=r.getModal(),o=t.querySelector("h2"),i=t.querySelector("p"),u=t.querySelector("button.cancel"),c=t.querySelector("button.confirm");if(o.innerHTML=e.html?e.title:s.escapeHtml(e.title).split("\n").join("<br>"),i.innerHTML=e.html?e.text:s.escapeHtml(e.text||"").split("\n").join("<br>"),e.text&&s.show(i),e.customClass)s.addClass(t,e.customClass),t.setAttribute("data-custom-class",e.customClass);else{var d=t.getAttribute("data-custom-class");s.removeClass(t,d),t.setAttribute("data-custom-class","")}if(s.hide(t.querySelectorAll(".sa-icon")),e.type&&!a.isIE8()){var f=function(){for(var o=!1,a=0;a<l.length;a++)if(e.type===l[a]){o=!0;break}if(!o)return logStr("Unknown alert type: "+e.type),{v:!1};var i=["success","error","warning","info"],u=n;-1!==i.indexOf(e.type)&&(u=t.querySelector(".sa-icon.sa-"+e.type),s.show(u));var c=r.getInput();switch(e.type){case"success":s.addClass(u,"animate"),s.addClass(u.querySelector(".sa-tip"),"animateSuccessTip"),s.addClass(u.querySelector(".sa-long"),"animateSuccessLong");break;case"error":s.addClass(u,"animateErrorIcon"),s.addClass(u.querySelector(".sa-x-mark"),"animateXMark");break;case"warning":s.addClass(u,"pulseWarning"),s.addClass(u.querySelector(".sa-body"),"pulseWarningIns"),s.addClass(u.querySelector(".sa-dot"),"pulseWarningIns");break;case"input":case"prompt":c.setAttribute("type",e.inputType),c.value=e.inputValue,c.setAttribute("placeholder",e.inputPlaceholder),s.addClass(t,"show-input"),setTimeout(function(){c.focus(),c.addEventListener("keyup",swal.resetInputError)},400)}}();if("object"==typeof f)return f.v}if(e.imageUrl){var p=t.querySelector(".sa-icon.sa-custom");p.style.backgroundImage="url("+e.imageUrl+")",s.show(p);var m=80,v=80;if(e.imageSize){var y=e.imageSize.toString().split("x"),h=y[0],b=y[1];h&&b?(m=h,v=b):logStr("Parameter imageSize expects value with format WIDTHxHEIGHT, got "+e.imageSize)}p.setAttribute("style",p.getAttribute("style")+"width:"+m+"px; height:"+v+"px")}t.setAttribute("data-has-cancel-button",e.showCancelButton),e.showCancelButton?u.style.display="inline-block":s.hide(u),t.setAttribute("data-has-confirm-button",e.showConfirmButton),e.showConfirmButton?c.style.display="inline-block":s.hide(c),e.cancelButtonText&&(u.innerHTML=s.escapeHtml(e.cancelButtonText)),e.confirmButtonText&&(c.innerHTML=s.escapeHtml(e.confirmButtonText)),e.confirmButtonColor&&(c.style.backgroundColor=e.confirmButtonColor,c.style.borderLeftColor=e.confirmLoadingButtonColor,c.style.borderRightColor=e.confirmLoadingButtonColor,r.setFocusStyle(c,e.confirmButtonColor)),t.setAttribute("data-allow-outside-click",e.allowOutsideClick);var g=e.doneFunction?!0:!1;t.setAttribute("data-has-done-function",g),e.animation?"string"==typeof e.animation?t.setAttribute("data-animation",e.animation):t.setAttribute("data-animation","pop"):t.setAttribute("data-animation","none"),t.setAttribute("data-timer",e.timer)};o["default"]=i,t.exports=o["default"]},{"./handle-dom":4,"./handle-swal-dom":6,"./utils":9}],9:[function(t,n,o){Object.defineProperty(o,"__esModule",{value:!0});var a=function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e},r=function(e){var t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?parseInt(t[1],16)+", "+parseInt(t[2],16)+", "+parseInt(t[3],16):null},s=function(){return e.attachEvent&&!e.addEventListener},l=function(t){e.console&&e.console.log("SweetAlert: "+t)},i=function(e,t){e=String(e).replace(/[^0-9a-f]/gi,""),e.length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),t=t||0;var n,o,a="#";for(o=0;3>o;o++)n=parseInt(e.substr(2*o,2),16),n=Math.round(Math.min(Math.max(0,n+n*t),255)).toString(16),a+=("00"+n).substr(n.length);return a};o.extend=a,o.hexToRgb=r,o.isIE8=s,o.logStr=l,o.colorLuminance=i},{}]},{},[1]),"function"==typeof define&&define.amd?define(function(){return sweetAlert}):"undefined"!=typeof module&&module.exports&&(module.exports=sweetAlert)}(window,document);
    /* ========================================================================
     * bootstrap-tour - v0.10.3
     * http://bootstraptour.com
     * ========================================================================
     * Copyright 2012-2015 Ulrich Sossou
     *
     * ========================================================================
     * Licensed under the MIT License (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     https://opensource.org/licenses/MIT
     *
     * 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.
     * ========================================================================
     */
    
    (function(window, factory) {
      if (typeof define === 'function' && define.amd) {
        return define(['jquery'], function(jQuery) {
          return window.Tour = factory(jQuery);
        });
      } else if (typeof exports === 'object') {
        return module.exports = factory(require('jQuery'));
      } else {
        return window.Tour = factory(window.jQuery);
      }
    })(window, function($) {
      var Tour, document;
      document = window.document;
      Tour = (function() {
        function Tour(options) {
          var storage;
          try {
            storage = window.localStorage;
          } catch (_error) {
            storage = false;
          }
          this._options = $.extend({
            name: 'tour',
            steps: [],
            container: 'body',
            autoscroll: true,
            keyboard: true,
            storage: storage,
            debug: false,
            backdrop: false,
            backdropContainer: 'body',
            backdropPadding: 0,
            redirect: true,
            orphan: false,
            duration: false,
            delay: false,
            basePath: '',
            template: '<div class="popover" role="tooltip"> <div class="arrow"></div> <h3 class="popover-title"></h3> <div class="popover-content"></div> <div class="popover-navigation"> <div class="btn-group"> <button class="btn btn-sm btn-default" data-role="prev">&laquo; Prev</button> <button class="btn btn-sm btn-default" data-role="next">Next &raquo;</button> <button class="btn btn-sm btn-default" data-role="pause-resume" data-pause-text="Pause" data-resume-text="Resume">Pause</button> </div> <button class="btn btn-sm btn-default" data-role="end">End tour</button> </div> </div>',
            afterSetState: function(key, value) {},
            afterGetState: function(key, value) {},
            afterRemoveState: function(key) {},
            onStart: function(tour) {},
            onEnd: function(tour) {},
            onShow: function(tour) {},
            onShown: function(tour) {},
            onHide: function(tour) {},
            onHidden: function(tour) {},
            onNext: function(tour) {},
            onPrev: function(tour) {},
            onPause: function(tour, duration) {},
            onResume: function(tour, duration) {},
            onRedirectError: function(tour) {}
          }, options);
          this._force = false;
          this._inited = false;
          this._current = null;
          this.backdrop = {
            overlay: null,
            $element: null,
            $background: null,
            backgroundShown: false,
            overlayElementShown: false
          };
          this;
        }
    
        Tour.prototype.addSteps = function(steps) {
          var step, _i, _len;
          for (_i = 0, _len = steps.length; _i < _len; _i++) {
            step = steps[_i];
            this.addStep(step);
          }
          return this;
        };
    
        Tour.prototype.addStep = function(step) {
          this._options.steps.push(step);
          return this;
        };
    
        Tour.prototype.getStep = function(i) {
          if (this._options.steps[i] != null) {
            return $.extend({
              id: "step-" + i,
              path: '',
              host: '',
              placement: 'right',
              title: '',
              content: '<p></p>',
              next: i === this._options.steps.length - 1 ? -1 : i + 1,
              prev: i - 1,
              animation: true,
              container: this._options.container,
              autoscroll: this._options.autoscroll,
              backdrop: this._options.backdrop,
              backdropContainer: this._options.backdropContainer,
              backdropPadding: this._options.backdropPadding,
              redirect: this._options.redirect,
              reflexElement: this._options.steps[i].element,
              backdropElement: this._options.steps[i].element,
              orphan: this._options.orphan,
              duration: this._options.duration,
              delay: this._options.delay,
              template: this._options.template,
              onShow: this._options.onShow,
              onShown: this._options.onShown,
              onHide: this._options.onHide,
              onHidden: this._options.onHidden,
              onNext: this._options.onNext,
              onPrev: this._options.onPrev,
              onPause: this._options.onPause,
              onResume: this._options.onResume,
              onRedirectError: this._options.onRedirectError
            }, this._options.steps[i]);
          }
        };
    
        Tour.prototype.init = function(force) {
          this._force = force;
          if (this.ended()) {
            this._debug('Tour ended, init prevented.');
            return this;
          }
          this.setCurrentStep();
          this._initMouseNavigation();
          this._initKeyboardNavigation();
          this._onResize((function(_this) {
            return function() {
              return _this.showStep(_this._current);
            };
          })(this));
          if (this._current !== null) {
            this.showStep(this._current);
          }
          this._inited = true;
          return this;
        };
    
        Tour.prototype.start = function(force) {
          var promise;
          if (force == null) {
            force = false;
          }
          if (!this._inited) {
            this.init(force);
          }
          if (this._current === null) {
            promise = this._makePromise(this._options.onStart != null ? this._options.onStart(this) : void 0);
            this._callOnPromiseDone(promise, this.showStep, 0);
          }
          return this;
        };
    
        Tour.prototype.next = function() {
          var promise;
          promise = this.hideStep(this._current, this._current + 1);
          return this._callOnPromiseDone(promise, this._showNextStep);
        };
    
        Tour.prototype.prev = function() {
          var promise;
          promise = this.hideStep(this._current, this._current - 1);
          return this._callOnPromiseDone(promise, this._showPrevStep);
        };
    
        Tour.prototype.goTo = function(i) {
          var promise;
          promise = this.hideStep(this._current, i);
          return this._callOnPromiseDone(promise, this.showStep, i);
        };
    
        Tour.prototype.end = function() {
          var endHelper, promise;
          endHelper = (function(_this) {
            return function(e) {
              $(document).off("click.tour-" + _this._options.name);
              $(document).off("keyup.tour-" + _this._options.name);
              $(window).off("resize.tour-" + _this._options.name);
              _this._setState('end', 'yes');
              _this._inited = false;
              _this._force = false;
              _this._clearTimer();
              if (_this._options.onEnd != null) {
                return _this._options.onEnd(_this);
              }
            };
          })(this);
          promise = this.hideStep(this._current);
          return this._callOnPromiseDone(promise, endHelper);
        };
    
        Tour.prototype.ended = function() {
          return !this._force && !!this._getState('end');
        };
    
        Tour.prototype.restart = function() {
          this._removeState('current_step');
          this._removeState('end');
          this._removeState('redirect_to');
          return this.start();
        };
    
        Tour.prototype.pause = function() {
          var step;
          step = this.getStep(this._current);
          if (!(step && step.duration)) {
            return this;
          }
          this._paused = true;
          this._duration -= new Date().getTime() - this._start;
          window.clearTimeout(this._timer);
          this._debug("Paused/Stopped step " + (this._current + 1) + " timer (" + this._duration + " remaining).");
          if (step.onPause != null) {
            return step.onPause(this, this._duration);
          }
        };
    
        Tour.prototype.resume = function() {
          var step;
          step = this.getStep(this._current);
          if (!(step && step.duration)) {
            return this;
          }
          this._paused = false;
          this._start = new Date().getTime();
          this._duration = this._duration || step.duration;
          this._timer = window.setTimeout((function(_this) {
            return function() {
              if (_this._isLast()) {
                return _this.next();
              } else {
                return _this.end();
              }
            };
          })(this), this._duration);
          this._debug("Started step " + (this._current + 1) + " timer with duration " + this._duration);
          if ((step.onResume != null) && this._duration !== step.duration) {
            return step.onResume(this, this._duration);
          }
        };
    
        Tour.prototype.hideStep = function(i, iNext) {
          var hideDelay, hideStepHelper, promise, step;
          step = this.getStep(i);
          if (!step) {
            return;
          }
          this._clearTimer();
          promise = this._makePromise(step.onHide != null ? step.onHide(this, i) : void 0);
          hideStepHelper = (function(_this) {
            return function(e) {
              var $element, next_step;
              $element = $(step.element);
              if (!($element.data('bs.popover') || $element.data('popover'))) {
                $element = $('body');
              }
              $element.popover('destroy').removeClass("tour-" + _this._options.name + "-element tour-" + _this._options.name + "-" + i + "-element").removeData('bs.popover').focus();
              if (step.reflex) {
                $(step.reflexElement).removeClass('tour-step-element-reflex').off("" + (_this._reflexEvent(step.reflex)) + ".tour-" + _this._options.name);
              }
              if (step.backdrop) {
                next_step = (iNext != null) && _this.getStep(iNext);
                if (!next_step || !next_step.backdrop || next_step.backdropElement !== step.backdropElement) {
                  _this._hideBackdrop();
                }
              }
              if (step.onHidden != null) {
                return step.onHidden(_this);
              }
            };
          })(this);
          hideDelay = step.delay.hide || step.delay;
          if ({}.toString.call(hideDelay) === '[object Number]' && hideDelay > 0) {
            this._debug("Wait " + hideDelay + " milliseconds to hide the step " + (this._current + 1));
            window.setTimeout((function(_this) {
              return function() {
                return _this._callOnPromiseDone(promise, hideStepHelper);
              };
            })(this), hideDelay);
          } else {
            this._callOnPromiseDone(promise, hideStepHelper);
          }
          return promise;
        };
    
        Tour.prototype.showStep = function(i) {
          var path, promise, showDelay, showStepHelper, skipToPrevious, step;
          if (this.ended()) {
            this._debug('Tour ended, showStep prevented.');
            return this;
          }
          step = this.getStep(i);
          if (!step) {
            return;
          }
          skipToPrevious = i < this._current;
          promise = this._makePromise(step.onShow != null ? step.onShow(this, i) : void 0);
          this.setCurrentStep(i);
          path = (function() {
            switch ({}.toString.call(step.path)) {
              case '[object Function]':
                return step.path();
              case '[object String]':
                return this._options.basePath + step.path;
              default:
                return step.path;
            }
          }).call(this);
          if (step.redirect && this._isRedirect(step.host, path, document.location)) {
            this._redirect(step, i, path);
            if (!this._isJustPathHashDifferent(step.host, path, document.location)) {
              return;
            }
          }
          showStepHelper = (function(_this) {
            return function(e) {
              var showPopoverAndOverlay;
              if (_this._isOrphan(step)) {
                if (step.orphan === false) {
                  _this._debug("Skip the orphan step " + (_this._current + 1) + ".\nOrphan option is false and the element does not exist or is hidden.");
                  if (skipToPrevious) {
                    _this._showPrevStep();
                  } else {
                    _this._showNextStep();
                  }
                  return;
                }
                _this._debug("Show the orphan step " + (_this._current + 1) + ". Orphans option is true.");
              }
              if (step.backdrop) {
                _this._showBackdrop(step);
              }
              showPopoverAndOverlay = function() {
                if (_this.getCurrentStep() !== i || _this.ended()) {
                  return;
                }
                if ((step.element != null) && step.backdrop) {
                  _this._showOverlayElement(step, true);
                }
                _this._showPopover(step, i);
                if (step.onShown != null) {
                  step.onShown(_this);
                }
                return _this._debug("Step " + (_this._current + 1) + " of " + _this._options.steps.length);
              };
              if (step.autoscroll) {
                _this._scrollIntoView(step, showPopoverAndOverlay);
              } else {
                showPopoverAndOverlay();
              }
              if (step.duration) {
                return _this.resume();
              }
            };
          })(this);
          showDelay = step.delay.show || step.delay;
          if ({}.toString.call(showDelay) === '[object Number]' && showDelay > 0) {
            this._debug("Wait " + showDelay + " milliseconds to show the step " + (this._current + 1));
            window.setTimeout((function(_this) {
              return function() {
                return _this._callOnPromiseDone(promise, showStepHelper);
              };
            })(this), showDelay);
          } else {
            this._callOnPromiseDone(promise, showStepHelper);
          }
          return promise;
        };
    
        Tour.prototype.getCurrentStep = function() {
          return this._current;
        };
    
        Tour.prototype.setCurrentStep = function(value) {
          if (value != null) {
            this._current = value;
            this._setState('current_step', value);
          } else {
            this._current = this._getState('current_step');
            this._current = this._current === null ? null : parseInt(this._current, 10);
          }
          return this;
        };
    
        Tour.prototype.redraw = function() {
          return this._showOverlayElement(this.getStep(this.getCurrentStep()).element, true);
        };
    
        Tour.prototype._setState = function(key, value) {
          var e, keyName;
          if (this._options.storage) {
            keyName = "" + this._options.name + "_" + key;
            try {
              this._options.storage.setItem(keyName, value);
            } catch (_error) {
              e = _error;
              if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
                this._debug('LocalStorage quota exceeded. State storage failed.');
              }
            }
            return this._options.afterSetState(keyName, value);
          } else {
            if (this._state == null) {
              this._state = {};
            }
            return this._state[key] = value;
          }
        };
    
        Tour.prototype._removeState = function(key) {
          var keyName;
          if (this._options.storage) {
            keyName = "" + this._options.name + "_" + key;
            this._options.storage.removeItem(keyName);
            return this._options.afterRemoveState(keyName);
          } else {
            if (this._state != null) {
              return delete this._state[key];
            }
          }
        };
    
        Tour.prototype._getState = function(key) {
          var keyName, value;
          if (this._options.storage) {
            keyName = "" + this._options.name + "_" + key;
            value = this._options.storage.getItem(keyName);
          } else {
            if (this._state != null) {
              value = this._state[key];
            }
          }
          if (value === void 0 || value === 'null') {
            value = null;
          }
          this._options.afterGetState(key, value);
          return value;
        };
    
        Tour.prototype._showNextStep = function() {
          var promise, showNextStepHelper, step;
          step = this.getStep(this._current);
          showNextStepHelper = (function(_this) {
            return function(e) {
              return _this.showStep(step.next);
            };
          })(this);
          promise = this._makePromise(step.onNext != null ? step.onNext(this) : void 0);
          return this._callOnPromiseDone(promise, showNextStepHelper);
        };
    
        Tour.prototype._showPrevStep = function() {
          var promise, showPrevStepHelper, step;
          step = this.getStep(this._current);
          showPrevStepHelper = (function(_this) {
            return function(e) {
              return _this.showStep(step.prev);
            };
          })(this);
          promise = this._makePromise(step.onPrev != null ? step.onPrev(this) : void 0);
          return this._callOnPromiseDone(promise, showPrevStepHelper);
        };
    
        Tour.prototype._debug = function(text) {
          if (this._options.debug) {
            return window.console.log("Bootstrap Tour '" + this._options.name + "' | " + text);
          }
        };
    
        Tour.prototype._isRedirect = function(host, path, location) {
          var currentPath;
          if ((host != null) && host !== '' && (({}.toString.call(host) === '[object RegExp]' && !host.test(location.origin)) || ({}.toString.call(host) === '[object String]' && this._isHostDifferent(host, location)))) {
            return true;
          }
          currentPath = [location.pathname, location.search, location.hash].join('');
          return (path != null) && path !== '' && (({}.toString.call(path) === '[object RegExp]' && !path.test(currentPath)) || ({}.toString.call(path) === '[object String]' && this._isPathDifferent(path, currentPath)));
        };
    
        Tour.prototype._isHostDifferent = function(host, location) {
          switch ({}.toString.call(host)) {
            case '[object RegExp]':
              return !host.test(location.origin);
            case '[object String]':
              return this._getProtocol(host) !== this._getProtocol(location.href) || this._getHost(host) !== this._getHost(location.href);
            default:
              return true;
          }
        };
    
        Tour.prototype._isPathDifferent = function(path, currentPath) {
          return this._getPath(path) !== this._getPath(currentPath) || !this._equal(this._getQuery(path), this._getQuery(currentPath)) || !this._equal(this._getHash(path), this._getHash(currentPath));
        };
    
        Tour.prototype._isJustPathHashDifferent = function(host, path, location) {
          var currentPath;
          if ((host != null) && host !== '') {
            if (this._isHostDifferent(host, location)) {
              return false;
            }
          }
          currentPath = [location.pathname, location.search, location.hash].join('');
          if ({}.toString.call(path) === '[object String]') {
            return this._getPath(path) === this._getPath(currentPath) && this._equal(this._getQuery(path), this._getQuery(currentPath)) && !this._equal(this._getHash(path), this._getHash(currentPath));
          }
          return false;
        };
    
        Tour.prototype._redirect = function(step, i, path) {
          var href;
          if ($.isFunction(step.redirect)) {
            return step.redirect.call(this, path);
          } else {
            href = {}.toString.call(step.host) === '[object String]' ? "" + step.host + path : path;
            this._debug("Redirect to " + href);
            if (this._getState('redirect_to') === ("" + i)) {
              this._debug("Error redirection loop to " + path);
              this._removeState('redirect_to');
              if (step.onRedirectError != null) {
                return step.onRedirectError(this);
              }
            } else {
              this._setState('redirect_to', "" + i);
              return document.location.href = href;
            }
          }
        };
    
        Tour.prototype._isOrphan = function(step) {
          return (step.element == null) || !$(step.element).length || $(step.element).is(':hidden') && ($(step.element)[0].namespaceURI !== 'http://www.w3.org/2000/svg');
        };
    
        Tour.prototype._isLast = function() {
          return this._current < this._options.steps.length - 1;
        };
    
        Tour.prototype._showPopover = function(step, i) {
          var $element, $tip, isOrphan, options, shouldAddSmart;
          $(".tour-" + this._options.name).remove();
          options = $.extend({}, this._options);
          isOrphan = this._isOrphan(step);
          step.template = this._template(step, i);
          if (isOrphan) {
            step.element = 'body';
            step.placement = 'top';
          }
          $element = $(step.element);
          $element.addClass("tour-" + this._options.name + "-element tour-" + this._options.name + "-" + i + "-element");
          if (step.options) {
            $.extend(options, step.options);
          }
          if (step.reflex && !isOrphan) {
            $(step.reflexElement).addClass('tour-step-element-reflex').off("" + (this._reflexEvent(step.reflex)) + ".tour-" + this._options.name).on("" + (this._reflexEvent(step.reflex)) + ".tour-" + this._options.name, (function(_this) {
              return function() {
                if (_this._isLast()) {
                  return _this.next();
                } else {
                  return _this.end();
                }
              };
            })(this));
          }
          shouldAddSmart = step.smartPlacement === true && step.placement.search(/auto/i) === -1;
          $element.popover({
            placement: shouldAddSmart ? "auto " + step.placement : step.placement,
            trigger: 'manual',
            title: step.title,
            content: step.content,
            html: true,
            animation: step.animation,
            container: step.container,
            template: step.template,
            selector: step.element
          }).popover('show');
          $tip = $element.data('bs.popover') ? $element.data('bs.popover').tip() : $element.data('popover').tip();
          $tip.attr('id', step.id);
          this._focus($tip, $element, step.next < 0);
          this._reposition($tip, step);
          if (isOrphan) {
            return this._center($tip);
          }
        };
    
        Tour.prototype._template = function(step, i) {
          var $navigation, $next, $prev, $resume, $template, template;
          template = step.template;
          if (this._isOrphan(step) && {}.toString.call(step.orphan) !== '[object Boolean]') {
            template = step.orphan;
          }
          $template = $.isFunction(template) ? $(template(i, step)) : $(template);
          $navigation = $template.find('.popover-navigation');
          $prev = $navigation.find('[data-role="prev"]');
          $next = $navigation.find('[data-role="next"]');
          $resume = $navigation.find('[data-role="pause-resume"]');
          if (this._isOrphan(step)) {
            $template.addClass('orphan');
          }
          $template.addClass("tour-" + this._options.name + " tour-" + this._options.name + "-" + i);
          if (step.reflex) {
            $template.addClass("tour-" + this._options.name + "-reflex");
          }
          if (step.prev < 0) {
            $prev.addClass('disabled').prop('disabled', true).prop('tabindex', -1);
          }
          if (step.next < 0) {
            $next.addClass('disabled').prop('disabled', true).prop('tabindex', -1);
          }
          if (!step.duration) {
            $resume.remove();
          }
          return $template.clone().wrap('<div>').parent().html();
        };
    
        Tour.prototype._reflexEvent = function(reflex) {
          if ({}.toString.call(reflex) === '[object Boolean]') {
            return 'click';
          } else {
            return reflex;
          }
        };
    
        Tour.prototype._focus = function($tip, $element, end) {
          var $next, role;
          role = end ? 'end' : 'next';
          $next = $tip.find("[data-role='" + role + "']");
          return $element.on('shown.bs.popover', function() {
            return $next.focus();
          });
        };
    
        Tour.prototype._reposition = function($tip, step) {
          var offsetBottom, offsetHeight, offsetRight, offsetWidth, originalLeft, originalTop, tipOffset;
          offsetWidth = $tip[0].offsetWidth;
          offsetHeight = $tip[0].offsetHeight;
          tipOffset = $tip.offset();
          originalLeft = tipOffset.left;
          originalTop = tipOffset.top;
          offsetBottom = $(document).outerHeight() - tipOffset.top - $tip.outerHeight();
          if (offsetBottom < 0) {
            tipOffset.top = tipOffset.top + offsetBottom;
          }
          offsetRight = $('html').outerWidth() - tipOffset.left - $tip.outerWidth();
          if (offsetRight < 0) {
            tipOffset.left = tipOffset.left + offsetRight;
          }
          if (tipOffset.top < 0) {
            tipOffset.top = 0;
          }
          if (tipOffset.left < 0) {
            tipOffset.left = 0;
          }
          $tip.offset(tipOffset);
          if (step.placement === 'bottom' || step.placement === 'top') {
            if (originalLeft !== tipOffset.left) {
              return this._replaceArrow($tip, (tipOffset.left - originalLeft) * 2, offsetWidth, 'left');
            }
          } else {
            if (originalTop !== tipOffset.top) {
              return this._replaceArrow($tip, (tipOffset.top - originalTop) * 2, offsetHeight, 'top');
            }
          }
        };
    
        Tour.prototype._center = function($tip) {
          return $tip.css('top', $(window).outerHeight() / 2 - $tip.outerHeight() / 2);
        };
    
        Tour.prototype._replaceArrow = function($tip, delta, dimension, position) {
          return $tip.find('.arrow').css(position, delta ? 50 * (1 - delta / dimension) + '%' : '');
        };
    
        Tour.prototype._scrollIntoView = function(step, callback) {
          var $element, $window, counter, height, offsetTop, scrollTop, windowHeight;
          $element = $(step.element);
          if (!$element.length) {
            return callback();
          }
          $window = $(window);
          offsetTop = $element.offset().top;
          height = $element.outerHeight();
          windowHeight = $window.height();
          scrollTop = 0;
          switch (step.placement) {
            case 'top':
              scrollTop = Math.max(0, offsetTop - (windowHeight / 2));
              break;
            case 'left':
            case 'right':
              scrollTop = Math.max(0, (offsetTop + height / 2) - (windowHeight / 2));
              break;
            case 'bottom':
              scrollTop = Math.max(0, (offsetTop + height) - (windowHeight / 2));
          }
          this._debug("Scroll into view. ScrollTop: " + scrollTop + ". Element offset: " + offsetTop + ". Window height: " + windowHeight + ".");
          counter = 0;
          return $('body, html').stop(true, true).animate({
            scrollTop: Math.ceil(scrollTop)
          }, (function(_this) {
            return function() {
              if (++counter === 2) {
                callback();
                return _this._debug("Scroll into view.\nAnimation end element offset: " + ($element.offset().top) + ".\nWindow height: " + ($window.height()) + ".");
              }
            };
          })(this));
        };
    
        Tour.prototype._onResize = function(callback, timeout) {
          return $(window).on("resize.tour-" + this._options.name, function() {
            clearTimeout(timeout);
            return timeout = setTimeout(callback, 100);
          });
        };
    
        Tour.prototype._initMouseNavigation = function() {
          var _this;
          _this = this;
          return $(document).off("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='prev']").off("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='next']").off("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='end']").off("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='pause-resume']").on("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='next']", (function(_this) {
            return function(e) {
              e.preventDefault();
              return _this.next();
            };
          })(this)).on("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='prev']", (function(_this) {
            return function(e) {
              e.preventDefault();
              if (_this._current > 0) {
                return _this.prev();
              }
            };
          })(this)).on("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='end']", (function(_this) {
            return function(e) {
              e.preventDefault();
              return _this.end();
            };
          })(this)).on("click.tour-" + this._options.name, ".popover.tour-" + this._options.name + " *[data-role='pause-resume']", function(e) {
            var $this;
            e.preventDefault();
            $this = $(this);
            $this.text(_this._paused ? $this.data('pause-text') : $this.data('resume-text'));
            if (_this._paused) {
              return _this.resume();
            } else {
              return _this.pause();
            }
          });
        };
    
        Tour.prototype._initKeyboardNavigation = function() {
          if (!this._options.keyboard) {
            return;
          }
          return $(document).on("keyup.tour-" + this._options.name, (function(_this) {
            return function(e) {
              if (!e.which) {
                return;
              }
              switch (e.which) {
                case 39:
                  e.preventDefault();
                  if (_this._isLast()) {
                    return _this.next();
                  } else {
                    return _this.end();
                  }
                  break;
                case 37:
                  e.preventDefault();
                  if (_this._current > 0) {
                    return _this.prev();
                  }
              }
            };
          })(this));
        };
    
        Tour.prototype._makePromise = function(result) {
          if (result && $.isFunction(result.then)) {
            return result;
          } else {
            return null;
          }
        };
    
        Tour.prototype._callOnPromiseDone = function(promise, cb, arg) {
          if (promise) {
            return promise.then((function(_this) {
              return function(e) {
                return cb.call(_this, arg);
              };
            })(this));
          } else {
            return cb.call(this, arg);
          }
        };
    
        Tour.prototype._showBackdrop = function(step) {
          if (this.backdrop.backgroundShown) {
            return;
          }
          this.backdrop = $('<div>', {
            "class": 'tour-backdrop'
          });
          this.backdrop.backgroundShown = true;
          return $(step.backdropContainer).append(this.backdrop);
        };
    
        Tour.prototype._hideBackdrop = function() {
          this._hideOverlayElement();
          return this._hideBackground();
        };
    
        Tour.prototype._hideBackground = function() {
          if (this.backdrop && this.backdrop.remove) {
            this.backdrop.remove();
            this.backdrop.overlay = null;
            return this.backdrop.backgroundShown = false;
          }
        };
    
        Tour.prototype._showOverlayElement = function(step, force) {
          var $backdropElement, $element, elementData;
          $element = $(step.element);
          $backdropElement = $(step.backdropElement);
          if (!$element || $element.length === 0 || this.backdrop.overlayElementShown && !force) {
            return;
          }
          if (!this.backdrop.overlayElementShown) {
            this.backdrop.$element = $backdropElement.addClass('tour-step-backdrop');
            this.backdrop.$background = $('<div>', {
              "class": 'tour-step-background'
            });
            this.backdrop.$background.appendTo(step.backdropContainer);
            this.backdrop.overlayElementShown = true;
          }
          elementData = {
            width: $backdropElement.innerWidth(),
            height: $backdropElement.innerHeight(),
            offset: $backdropElement.offset()
          };
          if (step.backdropPadding) {
            elementData = this._applyBackdropPadding(step.backdropPadding, elementData);
          }
          return this.backdrop.$background.width(elementData.width).height(elementData.height).offset(elementData.offset);
        };
    
        Tour.prototype._hideOverlayElement = function() {
          if (!this.backdrop.overlayElementShown) {
            return;
          }
          this.backdrop.$element.removeClass('tour-step-backdrop');
          this.backdrop.$background.remove();
          this.backdrop.$element = null;
          this.backdrop.$background = null;
          return this.backdrop.overlayElementShown = false;
        };
    
        Tour.prototype._applyBackdropPadding = function(padding, data) {
          if (typeof padding === 'object') {
            if (padding.top == null) {
              padding.top = 0;
            }
            if (padding.right == null) {
              padding.right = 0;
            }
            if (padding.bottom == null) {
              padding.bottom = 0;
            }
            if (padding.left == null) {
              padding.left = 0;
            }
            data.offset.top = data.offset.top - padding.top;
            data.offset.left = data.offset.left - padding.left;
            data.width = data.width + padding.left + padding.right;
            data.height = data.height + padding.top + padding.bottom;
          } else {
            data.offset.top = data.offset.top - padding;
            data.offset.left = data.offset.left - padding;
            data.width = data.width + (padding * 2);
            data.height = data.height + (padding * 2);
          }
          return data;
        };
    
        Tour.prototype._clearTimer = function() {
          window.clearTimeout(this._timer);
          this._timer = null;
          return this._duration = null;
        };
    
        Tour.prototype._getProtocol = function(url) {
          url = url.split('://');
          if (url.length > 1) {
            return url[0];
          } else {
            return 'http';
          }
        };
    
        Tour.prototype._getHost = function(url) {
          url = url.split('//');
          url = url.length > 1 ? url[1] : url[0];
          return url.split('/')[0];
        };
    
        Tour.prototype._getPath = function(path) {
          return path.replace(/\/?$/, '').split('?')[0].split('#')[0];
        };
    
        Tour.prototype._getQuery = function(path) {
          return this._getParams(path, '?');
        };
    
        Tour.prototype._getHash = function(path) {
          return this._getParams(path, '#');
        };
    
        Tour.prototype._getParams = function(path, start) {
          var param, params, paramsObject, _i, _len;
          params = path.split(start);
          if (params.length === 1) {
            return {};
          }
          params = params[1].split('&');
          paramsObject = {};
          for (_i = 0, _len = params.length; _i < _len; _i++) {
            param = params[_i];
            param = param.split('=');
            paramsObject[param[0]] = param[1] || '';
          }
          return paramsObject;
        };
    
        Tour.prototype._equal = function(obj1, obj2) {
          var k, obj1Keys, obj2Keys, v, _i, _len;
          if ({}.toString.call(obj1) === '[object Object]' && {}.toString.call(obj2) === '[object Object]') {
            obj1Keys = Object.keys(obj1);
            obj2Keys = Object.keys(obj2);
            if (obj1Keys.length !== obj2Keys.length) {
              return false;
            }
            for (k in obj1) {
              v = obj1[k];
              if (!this._equal(obj2[k], v)) {
                return false;
              }
            }
            return true;
          } else if ({}.toString.call(obj1) === '[object Array]' && {}.toString.call(obj2) === '[object Array]') {
            if (obj1.length !== obj2.length) {
              return false;
            }
            for (k = _i = 0, _len = obj1.length; _i < _len; k = ++_i) {
              v = obj1[k];
              if (!this._equal(v, obj2[k])) {
                return false;
              }
            }
            return true;
          } else {
            return obj1 === obj2;
          }
        };
    
        return Tour;
    
      })();
      return Tour;
    });
    
    /*! X-editable - v1.5.1 
    * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery
    * http://github.com/vitalets/x-editable
    * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */
    /**
    Form with single input element, two buttons and two states: normal/loading.
    Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown.
    Editableform is linked with one of input types, e.g. 'text', 'select' etc.
    
    @class editableform
    @uses text
    @uses textarea
    **/
    (function ($) {
        "use strict";
        
        var EditableForm = function (div, options) {
            this.options = $.extend({}, $.fn.editableform.defaults, options);
            this.$div = $(div); //div, containing form. Not form tag. Not editable-element.
            if(!this.options.scope) {
                this.options.scope = this;
            }
            //nothing shown after init
        };
    
        EditableForm.prototype = {
            constructor: EditableForm,
            initInput: function() {  //called once
                //take input from options (as it is created in editable-element)
                this.input = this.options.input;
                
                //set initial value
                //todo: may be add check: typeof str === 'string' ? 
                this.value = this.input.str2value(this.options.value); 
                
                //prerender: get input.$input
                this.input.prerender();
            },
            initTemplate: function() {
                this.$form = $($.fn.editableform.template); 
            },
            initButtons: function() {
                var $btn = this.$form.find('.editable-buttons');
                $btn.append($.fn.editableform.buttons);
                if(this.options.showbuttons === 'bottom') {
                    $btn.addClass('editable-buttons-bottom');
                }
            },
            /**
            Renders editableform
    
            @method render
            **/        
            render: function() {
                //init loader
                this.$loading = $($.fn.editableform.loading);        
                this.$div.empty().append(this.$loading);
                
                //init form template and buttons
                this.initTemplate();
                if(this.options.showbuttons) {
                    this.initButtons();
                } else {
                    this.$form.find('.editable-buttons').remove();
                }
    
                //show loading state
                this.showLoading();            
                
                //flag showing is form now saving value to server. 
                //It is needed to wait when closing form.
                this.isSaving = false;
                
                /**        
                Fired when rendering starts
                @event rendering 
                @param {Object} event event object
                **/            
                this.$div.triggerHandler('rendering');
                
                //init input
                this.initInput();
                
                //append input to form
                this.$form.find('div.editable-input').append(this.input.$tpl);            
                
                //append form to container
                this.$div.append(this.$form);
                
                //render input
                $.when(this.input.render())
                .then($.proxy(function () {
                    //setup input to submit automatically when no buttons shown
                    if(!this.options.showbuttons) {
                        this.input.autosubmit(); 
                    }
                     
                    //attach 'cancel' handler
                    this.$form.find('.editable-cancel').click($.proxy(this.cancel, this));
                    
                    if(this.input.error) {
                        this.error(this.input.error);
                        this.$form.find('.editable-submit').attr('disabled', true);
                        this.input.$input.attr('disabled', true);
                        //prevent form from submitting
                        this.$form.submit(function(e){ e.preventDefault(); });
                    } else {
                        this.error(false);
                        this.input.$input.removeAttr('disabled');
                        this.$form.find('.editable-submit').removeAttr('disabled');
                        var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value;
                        this.input.value2input(value);
                        //attach submit handler
                        this.$form.submit($.proxy(this.submit, this));
                    }
    
                    /**        
                    Fired when form is rendered
                    @event rendered
                    @param {Object} event event object
                    **/            
                    this.$div.triggerHandler('rendered');                
    
                    this.showForm();
                    
                    //call postrender method to perform actions required visibility of form
                    if(this.input.postrender) {
                        this.input.postrender();
                    }                
                }, this));
            },
            cancel: function() {   
                /**        
                Fired when form was cancelled by user
                @event cancel 
                @param {Object} event event object
                **/              
                this.$div.triggerHandler('cancel');
            },
            showLoading: function() {
                var w, h;
                if(this.$form) {
                    //set loading size equal to form
                    w = this.$form.outerWidth();
                    h = this.$form.outerHeight(); 
                    if(w) {
                        this.$loading.width(w);
                    }
                    if(h) {
                        this.$loading.height(h);
                    }
                    this.$form.hide();
                } else {
                    //stretch loading to fill container width
                    w = this.$loading.parent().width();
                    if(w) {
                        this.$loading.width(w);
                    }
                }
                this.$loading.show(); 
            },
    
            showForm: function(activate) {
                this.$loading.hide();
                this.$form.show();
                if(activate !== false) {
                    this.input.activate(); 
                }
                /**        
                Fired when form is shown
                @event show 
                @param {Object} event event object
                **/                    
                this.$div.triggerHandler('show');
            },
    
            error: function(msg) {
                var $group = this.$form.find('.control-group'),
                    $block = this.$form.find('.editable-error-block'),
                    lines;
    
                if(msg === false) {
                    $group.removeClass($.fn.editableform.errorGroupClass);
                    $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); 
                } else {
                    //convert newline to <br> for more pretty error display
                    if(msg) {
                        lines = (''+msg).split('\n');
                        for (var i = 0; i < lines.length; i++) {
                            lines[i] = $('<div>').text(lines[i]).html();
                        }
                        msg = lines.join('<br>');
                    }
                    $group.addClass($.fn.editableform.errorGroupClass);
                    $block.addClass($.fn.editableform.errorBlockClass).html(msg).show();
                }
            },
    
            submit: function(e) {
                e.stopPropagation();
                e.preventDefault();
                
                //get new value from input
                var newValue = this.input.input2value(); 
    
                //validation: if validate returns string or truthy value - means error
                //if returns object like {newValue: '...'} => submitted value is reassigned to it
                var error = this.validate(newValue);
                if ($.type(error) === 'object' && error.newValue !== undefined) {
                    newValue = error.newValue;
                    this.input.value2input(newValue);
                    if(typeof error.msg === 'string') {
                        this.error(error.msg);
                        this.showForm();
                        return;
                    }
                } else if (error) {
                    this.error(error);
                    this.showForm();
                    return;
                } 
                
                //if value not changed --> trigger 'nochange' event and return
                /*jslint eqeq: true*/
                if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) {
                /*jslint eqeq: false*/                
                    /**        
                    Fired when value not changed but form is submitted. Requires savenochange = false.
                    @event nochange 
                    @param {Object} event event object
                    **/                    
                    this.$div.triggerHandler('nochange');            
                    return;
                } 
    
                //convert value for submitting to server
                var submitValue = this.input.value2submit(newValue);
                
                this.isSaving = true;
                
                //sending data to server
                $.when(this.save(submitValue))
                .done($.proxy(function(response) {
                    this.isSaving = false;
    
                    //run success callback
                    var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null;
    
                    //if success callback returns false --> keep form open and do not activate input
                    if(res === false) {
                        this.error(false);
                        this.showForm(false);
                        return;
                    }
    
                    //if success callback returns string -->  keep form open, show error and activate input               
                    if(typeof res === 'string') {
                        this.error(res);
                        this.showForm();
                        return;
                    }
    
                    //if success callback returns object like {newValue: <something>} --> use that value instead of submitted
                    //it is usefull if you want to chnage value in url-function
                    if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) {
                        newValue = res.newValue;
                    }
    
                    //clear error message
                    this.error(false);   
                    this.value = newValue;
                    /**        
                    Fired when form is submitted
                    @event save 
                    @param {Object} event event object
                    @param {Object} params additional params
                    @param {mixed} params.newValue raw new value
                    @param {mixed} params.submitValue submitted value as string
                    @param {Object} params.response ajax response
    
                    @example
                    $('#form-div').on('save'), function(e, params){
                        if(params.newValue === 'username') {...}
                    });
                    **/
                    this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response});
                }, this))
                .fail($.proxy(function(xhr) {
                    this.isSaving = false;
    
                    var msg;
                    if(typeof this.options.error === 'function') {
                        msg = this.options.error.call(this.options.scope, xhr, newValue);
                    } else {
                        msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!';
                    }
    
                    this.error(msg);
                    this.showForm();
                }, this));
            },
    
            save: function(submitValue) {
                //try parse composite pk defined as json string in data-pk 
                this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); 
                
                var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk,
                /*
                  send on server in following cases:
                  1. url is function
                  2. url is string AND (pk defined OR send option = always) 
                */
                send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))),
                params;
    
                if (send) { //send to server
                    this.showLoading();
    
                    //standard params
                    params = {
                        name: this.options.name || '',
                        value: submitValue,
                        pk: pk 
                    };
    
                    //additional params
                    if(typeof this.options.params === 'function') {
                        params = this.options.params.call(this.options.scope, params);  
                    } else {
                        //try parse json in single quotes (from data-params attribute)
                        this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true);   
                        $.extend(params, this.options.params);
                    }
    
                    if(typeof this.options.url === 'function') { //user's function
                        return this.options.url.call(this.options.scope, params);
                    } else {  
                        //send ajax to server and return deferred object
                        return $.ajax($.extend({
                            url     : this.options.url,
                            data    : params,
                            type    : 'POST'
                        }, this.options.ajaxOptions));
                    }
                }
            }, 
    
            validate: function (value) {
                if (value === undefined) {
                    value = this.value;
                }
                if (typeof this.options.validate === 'function') {
                    return this.options.validate.call(this.options.scope, value);
                }
            },
    
            option: function(key, value) {
                if(key in this.options) {
                    this.options[key] = value;
                }
                
                if(key === 'value') {
                    this.setValue(value);
                }
                
                //do not pass option to input as it is passed in editable-element
            },
    
            setValue: function(value, convertStr) {
                if(convertStr) {
                    this.value = this.input.str2value(value);
                } else {
                    this.value = value;
                }
                
                //if form is visible, update input
                if(this.$form && this.$form.is(':visible')) {
                    this.input.value2input(this.value);
                }            
            }               
        };
    
        /*
        Initialize editableform. Applied to jQuery object.
    
        @method $().editableform(options)
        @params {Object} options
        @example
        var $form = $('&lt;div&gt;').editableform({
            type: 'text',
            name: 'username',
            url: '/post',
            value: 'vitaliy'
        });
    
        //to display form you should call 'render' method
        $form.editableform('render');     
        */
        $.fn.editableform = function (option) {
            var args = arguments;
            return this.each(function () {
                var $this = $(this), 
                data = $this.data('editableform'), 
                options = typeof option === 'object' && option; 
                if (!data) {
                    $this.data('editableform', (data = new EditableForm(this, options)));
                }
    
                if (typeof option === 'string') { //call method 
                    data[option].apply(data, Array.prototype.slice.call(args, 1));
                } 
            });
        };
    
        //keep link to constructor to allow inheritance
        $.fn.editableform.Constructor = EditableForm;    
    
        //defaults
        $.fn.editableform.defaults = {
            /* see also defaults for input */
    
            /**
            Type of input. Can be <code>text|textarea|select|date|checklist</code>
    
            @property type 
            @type string
            @default 'text'
            **/
            type: 'text',
            /**
            Url for submit, e.g. <code>'/post'</code>  
            If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks.
    
            @property url 
            @type string|function
            @default null
            @example
            url: function(params) {
                var d = new $.Deferred;
                if(params.value === 'abc') {
                    return d.reject('error message'); //returning error via deferred object
                } else {
                    //async saving data in js model
                    someModel.asyncSaveMethod({
                       ..., 
                       success: function(){
                          d.resolve();
                       }
                    }); 
                    return d.promise();
                }
            } 
            **/        
            url:null,
            /**
            Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value).  
            If defined as <code>function</code> - returned object **overwrites** original ajax data.
            @example
            params: function(params) {
                //originally params contain pk, name and value
                params.a = 1;
                return params;
            }
    
            @property params 
            @type object|function
            @default null
            **/          
            params:null,
            /**
            Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute
    
            @property name 
            @type string
            @default null
            **/         
            name: null,
            /**
            Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>.
            Can be calculated dynamically via function.
    
            @property pk 
            @type string|object|function
            @default null
            **/         
            pk: null,
            /**
            Initial value. If not defined - will be taken from element's content.
            For __select__ type should be defined (as it is ID of shown text).
    
            @property value 
            @type string|object
            @default null
            **/        
            value: null,
            /**
            Value that will be displayed in input if original field value is empty (`null|undefined|''`).
    
            @property defaultValue 
            @type string|object
            @default null
            @since 1.4.6
            **/        
            defaultValue: null,
            /**
            Strategy for sending data on server. Can be `auto|always|never`.
            When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally.
    
            @property send 
            @type string
            @default 'auto'
            **/          
            send: 'auto', 
            /**
            Function for client-side validation. If returns string - means validation not passed and string showed as error.
            Since 1.5.1 you can modify submitted value by returning object from `validate`: 
            `{newValue: '...'}` or `{newValue: '...', msg: '...'}`
    
            @property validate 
            @type function
            @default null
            @example
            validate: function(value) {
                if($.trim(value) == '') {
                    return 'This field is required';
                }
            }
            **/         
            validate: null,
            /**
            Success callback. Called when value successfully sent on server and **response status = 200**.  
            Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code>
            or <code>{success: false, msg: "server error"}</code> you can check it inside this callback.  
            If it returns **string** - means error occured and string is shown as error message.  
            If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user.  
            Otherwise newValue simply rendered into element.
            
            @property success 
            @type function
            @default null
            @example
            success: function(response, newValue) {
                if(!response.success) return response.msg;
            }
            **/          
            success: null,
            /**
            Error callback. Called when request failed (response status != 200).  
            Usefull when you want to parse error response and display a custom message.
            Must return **string** - the message to be displayed in the error block.
                    
            @property error 
            @type function
            @default null
            @since 1.4.4
            @example
            error: function(response, newValue) {
                if(response.status === 500) {
                    return 'Service unavailable. Please try later.';
                } else {
                    return response.responseText;
                }
            }
            **/          
            error: null,
            /**
            Additional options for submit ajax request.
            List of values: http://api.jquery.com/jQuery.ajax
            
            @property ajaxOptions 
            @type object
            @default null
            @since 1.1.1        
            @example 
            ajaxOptions: {
                type: 'put',
                dataType: 'json'
            }        
            **/        
            ajaxOptions: null,
            /**
            Where to show buttons: left(true)|bottom|false  
            Form without buttons is auto-submitted.
    
            @property showbuttons 
            @type boolean|string
            @default true
            @since 1.1.1
            **/         
            showbuttons: true,
            /**
            Scope for callback methods (success, validate).  
            If <code>null</code> means editableform instance itself. 
    
            @property scope 
            @type DOMElement|object
            @default null
            @since 1.2.0
            @private
            **/            
            scope: null,
            /**
            Whether to save or cancel value when it was not changed but form was submitted
    
            @property savenochange 
            @type boolean
            @default false
            @since 1.2.0
            **/
            savenochange: false
        };   
    
        /*
        Note: following params could redefined in engine: bootstrap or jqueryui:
        Classes 'control-group' and 'editable-error-block' must always present!
        */      
        $.fn.editableform.template = '<form class="form-inline editableform">'+
        '<div class="control-group">' + 
        '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+
        '<div class="editable-error-block"></div>' + 
        '</div>' + 
        '</form>';
    
        //loading div
        $.fn.editableform.loading = '<div class="editableform-loading"></div>';
    
        //buttons
        $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+
        '<button type="button" class="editable-cancel">cancel</button>';      
    
        //error class attached to control-group
        $.fn.editableform.errorGroupClass = null;  
    
        //error class attached to editable-error-block
        $.fn.editableform.errorBlockClass = 'editable-error';
        
        //engine
        $.fn.editableform.engine = 'jquery';
    }(window.jQuery));
    
    /**
    * EditableForm utilites
    */
    (function ($) {
        "use strict";
        
        //utils
        $.fn.editableutils = {
            /**
            * classic JS inheritance function
            */  
            inherit: function (Child, Parent) {
                var F = function() { };
                F.prototype = Parent.prototype;
                Child.prototype = new F();
                Child.prototype.constructor = Child;
                Child.superclass = Parent.prototype;
            },
    
            /**
            * set caret position in input
            * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
            */        
            setCursorPosition: function(elem, pos) {
                if (elem.setSelectionRange) {
                    elem.setSelectionRange(pos, pos);
                } else if (elem.createTextRange) {
                    var range = elem.createTextRange();
                    range.collapse(true);
                    range.moveEnd('character', pos);
                    range.moveStart('character', pos);
                    range.select();
                }
            },
    
            /**
            * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes)
            * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}">
            * safe = true --> means no exception will be thrown
            * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery
            */
            tryParseJson: function(s, safe) {
                if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) {
                    if (safe) {
                        try {
                            /*jslint evil: true*/
                            s = (new Function('return ' + s))();
                            /*jslint evil: false*/
                        } catch (e) {} finally {
                            return s;
                        }
                    } else {
                        /*jslint evil: true*/
                        s = (new Function('return ' + s))();
                        /*jslint evil: false*/
                    }
                }
                return s;
            },
    
            /**
            * slice object by specified keys
            */
            sliceObj: function(obj, keys, caseSensitive /* default: false */) {
                var key, keyLower, newObj = {};
    
                if (!$.isArray(keys) || !keys.length) {
                    return newObj;
                }
    
                for (var i = 0; i < keys.length; i++) {
                    key = keys[i];
                    if (obj.hasOwnProperty(key)) {
                        newObj[key] = obj[key];
                    }
    
                    if(caseSensitive === true) {
                        continue;
                    }
    
                    //when getting data-* attributes via $.data() it's converted to lowercase.
                    //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery
                    //workaround is code below.
                    keyLower = key.toLowerCase();
                    if (obj.hasOwnProperty(keyLower)) {
                        newObj[key] = obj[keyLower];
                    }
                }
    
                return newObj;
            },
    
            /*
            exclude complex objects from $.data() before pass to config
            */
            getConfigData: function($element) {
                var data = {};
                $.each($element.data(), function(k, v) {
                    if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) {
                        data[k] = v;
                    }
                });
                return data;
            },
    
            /*
             returns keys of object
            */
            objectKeys: function(o) {
                if (Object.keys) {
                    return Object.keys(o);  
                } else {
                    if (o !== Object(o)) {
                        throw new TypeError('Object.keys called on a non-object');
                    }
                    var k=[], p;
                    for (p in o) {
                        if (Object.prototype.hasOwnProperty.call(o,p)) {
                            k.push(p);
                        }
                    }
                    return k;
                }
    
            },
            
           /**
            method to escape html.
           **/
           escape: function(str) {
               return $('<div>').text(str).html();
           },
           
           /*
            returns array items from sourceData having value property equal or inArray of 'value'
           */
           itemsByValue: function(value, sourceData, valueProp) {
               if(!sourceData || value === null) {
                   return [];
               }
               
               if (typeof(valueProp) !== "function") {
                   var idKey = valueProp || 'value';
                   valueProp = function (e) { return e[idKey]; };
               }
                          
               var isValArray = $.isArray(value),
               result = [], 
               that = this;
    
               $.each(sourceData, function(i, o) {
                   if(o.children) {
                       result = result.concat(that.itemsByValue(value, o.children, valueProp));
                   } else {
                       /*jslint eqeq: true*/
                       if(isValArray) {
                           if($.grep(value, function(v){  return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) {
                               result.push(o); 
                           }
                       } else {
                           var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o;
                           if(value == itemValue) {
                               result.push(o); 
                           }
                       }
                       /*jslint eqeq: false*/
                   }
               });
               
               return result;
           },
           
           /*
           Returns input by options: type, mode. 
           */
           createInput: function(options) {
               var TypeConstructor, typeOptions, input,
               type = options.type;
    
               //`date` is some kind of virtual type that is transformed to one of exact types
               //depending on mode and core lib
               if(type === 'date') {
                   //inline
                   if(options.mode === 'inline') {
                       if($.fn.editabletypes.datefield) {
                           type = 'datefield';
                       } else if($.fn.editabletypes.dateuifield) {
                           type = 'dateuifield';
                       }
                   //popup
                   } else {
                       if($.fn.editabletypes.date) {
                           type = 'date';
                       } else if($.fn.editabletypes.dateui) {
                           type = 'dateui';
                       }
                   }
                   
                   //if type still `date` and not exist in types, replace with `combodate` that is base input
                   if(type === 'date' && !$.fn.editabletypes.date) {
                       type = 'combodate';
                   } 
               }
               
               //`datetime` should be datetimefield in 'inline' mode
               if(type === 'datetime' && options.mode === 'inline') {
                 type = 'datetimefield';  
               }           
    
               //change wysihtml5 to textarea for jquery UI and plain versions
               if(type === 'wysihtml5' && !$.fn.editabletypes[type]) {
                   type = 'textarea';
               }
    
               //create input of specified type. Input will be used for converting value, not in form
               if(typeof $.fn.editabletypes[type] === 'function') {
                   TypeConstructor = $.fn.editabletypes[type];
                   typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults));
                   input = new TypeConstructor(typeOptions);
                   return input;
               } else {
                   $.error('Unknown type: '+ type);
                   return false; 
               }  
           },
           
           //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
           supportsTransitions: function () {
               var b = document.body || document.documentElement,
                   s = b.style,
                   p = 'transition',
                   v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'];
                   
               if(typeof s[p] === 'string') {
                   return true; 
               }
    
               // Tests for vendor specific prop
               p = p.charAt(0).toUpperCase() + p.substr(1);
               for(var i=0; i<v.length; i++) {
                   if(typeof s[v[i] + p] === 'string') { 
                       return true; 
                   }
               }
               return false;
           }            
           
        };      
    }(window.jQuery));
    
    /**
    Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br>
    This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br>
    Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br>
    Applied as jQuery method.
    
    @class editableContainer
    @uses editableform
    **/
    (function ($) {
        "use strict";
    
        var Popup = function (element, options) {
            this.init(element, options);
        };
        
        var Inline = function (element, options) {
            this.init(element, options);
        };    
    
        //methods
        Popup.prototype = {
            containerName: null, //method to call container on element
            containerDataName: null, //object name in element's .data()
            innerCss: null, //tbd in child class
            containerClass: 'editable-container editable-popup', //css class applied to container element
            defaults: {}, //container itself defaults
            
            init: function(element, options) {
                this.$element = $(element);
                //since 1.4.1 container do not use data-* directly as they already merged into options.
                this.options = $.extend({}, $.fn.editableContainer.defaults, options);         
                this.splitOptions();
                
                //set scope of form callbacks to element
                this.formOptions.scope = this.$element[0]; 
                
                this.initContainer();
                
                //flag to hide container, when saving value will finish
                this.delayedHide = false;
    
                //bind 'destroyed' listener to destroy container when element is removed from dom
                this.$element.on('destroyed', $.proxy(function(){
                    this.destroy();
                }, this)); 
                
                //attach document handler to close containers on click / escape
                if(!$(document).data('editable-handlers-attached')) {
                    //close all on escape
                    $(document).on('keyup.editable', function (e) {
                        if (e.which === 27) {
                            $('.editable-open').editableContainer('hide');
                            //todo: return focus on element 
                        }
                    });
    
                    //close containers when click outside 
                    //(mousedown could be better than click, it closes everything also on drag drop)
                    $(document).on('click.editable', function(e) {
                        var $target = $(e.target), i,
                            exclude_classes = ['.editable-container', 
                                               '.ui-datepicker-header', 
                                               '.datepicker', //in inline mode datepicker is rendered into body
                                               '.modal-backdrop', 
                                               '.bootstrap-wysihtml5-insert-image-modal', 
                                               '.bootstrap-wysihtml5-insert-link-modal'
                                               ];
                        
                        //check if element is detached. It occurs when clicking in bootstrap datepicker
                        if (!$.contains(document.documentElement, e.target)) {
                          return;
                        }
    
                        //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document
                        //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199
                        //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec
                        if($target.is(document)) {
                           return; 
                        }
                        
                        //if click inside one of exclude classes --> no nothing
                        for(i=0; i<exclude_classes.length; i++) {
                             if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) {
                                 return;
                             }
                        }
                          
                        //close all open containers (except one - target)
                        Popup.prototype.closeOthers(e.target);
                    });
                    
                    $(document).data('editable-handlers-attached', true);
                }                        
            },
    
            //split options on containerOptions and formOptions
            splitOptions: function() {
                this.containerOptions = {};
                this.formOptions = {};
                
                if(!$.fn[this.containerName]) {
                    throw new Error(this.containerName + ' not found. Have you included corresponding js file?');   
                }
                
                //keys defined in container defaults go to container, others go to form
                for(var k in this.options) {
                  if(k in this.defaults) {
                     this.containerOptions[k] = this.options[k];
                  } else {
                     this.formOptions[k] = this.options[k];
                  } 
                }
            },
            
            /*
            Returns jquery object of container
            @method tip()
            */         
            tip: function() {
                return this.container() ? this.container().$tip : null;
            },
    
            /* returns container object */
            container: function() {
                var container;
                //first, try get it by `containerDataName`
                if(this.containerDataName) {
                    if(container = this.$element.data(this.containerDataName)) {
                        return container;
                    }
                }
                //second, try `containerName`
                container = this.$element.data(this.containerName);
                return container;
            },
    
            /* call native method of underlying container, e.g. this.$element.popover('method') */ 
            call: function() {
                this.$element[this.containerName].apply(this.$element, arguments); 
            },        
            
            initContainer: function(){
                this.call(this.containerOptions);
            },
    
            renderForm: function() {
                this.$form
                .editableform(this.formOptions)
                .on({
                    save: $.proxy(this.save, this), //click on submit button (value changed)
                    nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed)                
                    cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button
                    show: $.proxy(function() {
                        if(this.delayedHide) {
                            this.hide(this.delayedHide.reason);
                            this.delayedHide = false;
                        } else {
                            this.setPosition();
                        }
                    }, this), //re-position container every time form is shown (occurs each time after loading state)
                    rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown
                    resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed 
                    rendered: $.proxy(function(){
                        /**        
                        Fired when container is shown and form is rendered (for select will wait for loading dropdown options).  
                        **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one.
                        The workaround is to check `arguments.length` that is always `2` for x-editable.                     
                        
                        @event shown 
                        @param {Object} event event object
                        @example
                        $('#username').on('shown', function(e, editable) {
                            editable.input.$input.val('overwriting value of input..');
                        });                     
                        **/                      
                        /*
                         TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events.  
                        */
                        this.$element.triggerHandler('shown', $(this.options.scope).data('editable')); 
                    }, this) 
                })
                .editableform('render');
            },        
    
            /**
            Shows container with form
            @method show()
            @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
            **/
            /* Note: poshytip owerwrites this method totally! */          
            show: function (closeAll) {
                this.$element.addClass('editable-open');
                if(closeAll !== false) {
                    //close all open containers (except this)
                    this.closeOthers(this.$element[0]);  
                }
                
                //show container itself
                this.innerShow();
                this.tip().addClass(this.containerClass);
    
                /*
                Currently, form is re-rendered on every show. 
                The main reason is that we dont know, what will container do with content when closed:
                remove(), detach() or just hide() - it depends on container.
                
                Detaching form itself before hide and re-insert before show is good solution, 
                but visually it looks ugly --> container changes size before hide.  
                */             
                
                //if form already exist - delete previous data 
                if(this.$form) {
                    //todo: destroy prev data!
                    //this.$form.destroy();
                }
    
                this.$form = $('<div>');
                
                //insert form into container body
                if(this.tip().is(this.innerCss)) {
                    //for inline container
                    this.tip().append(this.$form); 
                } else {
                    this.tip().find(this.innerCss).append(this.$form);
                } 
                
                //render form
                this.renderForm();
            },
    
            /**
            Hides container with form
            @method hide()
            @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code>
            **/         
            hide: function(reason) {  
                if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) {
                    return;
                }
                
                //if form is saving value, schedule hide
                if(this.$form.data('editableform').isSaving) {
                    this.delayedHide = {reason: reason};
                    return;    
                } else {
                    this.delayedHide = false;
                }
    
                this.$element.removeClass('editable-open');   
                this.innerHide();
    
                /**
                Fired when container was hidden. It occurs on both save or cancel.  
                **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one.
                The workaround is to check `arguments.length` that is always `2` for x-editable. 
    
                @event hidden 
                @param {object} event event object
                @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code>
                @example
                $('#username').on('hidden', function(e, reason) {
                    if(reason === 'save' || reason === 'cancel') {
                        //auto-open next editable
                        $(this).closest('tr').next().find('.editable').editable('show');
                    } 
                });
                **/
                this.$element.triggerHandler('hidden', reason || 'manual');   
            },
    
            /* internal show method. To be overwritten in child classes */
            innerShow: function () {
                 
            },        
    
            /* internal hide method. To be overwritten in child classes */
            innerHide: function () {
    
            },
            
            /**
            Toggles container visibility (show / hide)
            @method toggle()
            @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
            **/          
            toggle: function(closeAll) {
                if(this.container() && this.tip() && this.tip().is(':visible')) {
                    this.hide();
                } else {
                    this.show(closeAll);
                } 
            },
    
            /*
            Updates the position of container when content changed.
            @method setPosition()
            */       
            setPosition: function() {
                //tbd in child class
            },
    
            save: function(e, params) {
                /**        
                Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance
                
                @event save 
                @param {Object} event event object
                @param {Object} params additional params
                @param {mixed} params.newValue submitted value
                @param {Object} params.response ajax response
                @example
                $('#username').on('save', function(e, params) {
                    //assuming server response: '{success: true}'
                    var pk = $(this).data('editableContainer').options.pk;
                    if(params.response && params.response.success) {
                        alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!');
                    } else {
                        alert('error!'); 
                    } 
                });
                **/             
                this.$element.triggerHandler('save', params);
                
                //hide must be after trigger, as saving value may require methods of plugin, applied to input
                this.hide('save');
            },
    
            /**
            Sets new option
            
            @method option(key, value)
            @param {string} key 
            @param {mixed} value 
            **/         
            option: function(key, value) {
                this.options[key] = value;
                if(key in this.containerOptions) {
                    this.containerOptions[key] = value;
                    this.setContainerOption(key, value); 
                } else {
                    this.formOptions[key] = value;
                    if(this.$form) {
                        this.$form.editableform('option', key, value);  
                    }
                }
            },
            
            setContainerOption: function(key, value) {
                this.call('option', key, value);
            },
    
            /**
            Destroys the container instance
            @method destroy()
            **/        
            destroy: function() {
                this.hide();
                this.innerDestroy();
                this.$element.off('destroyed');
                this.$element.removeData('editableContainer');
            },
            
            /* to be overwritten in child classes */
            innerDestroy: function() {
                
            }, 
            
            /*
            Closes other containers except one related to passed element. 
            Other containers can be cancelled or submitted (depends on onblur option)
            */
            closeOthers: function(element) {
                $('.editable-open').each(function(i, el){
                    //do nothing with passed element and it's children
                    if(el === element || $(el).find(element).length) {
                        return;
                    }
    
                    //otherwise cancel or submit all open containers 
                    var $el = $(el),
                    ec = $el.data('editableContainer');
    
                    if(!ec) {
                        return;  
                    }
                    
                    if(ec.options.onblur === 'cancel') {
                        $el.data('editableContainer').hide('onblur');
                    } else if(ec.options.onblur === 'submit') {
                        $el.data('editableContainer').tip().find('form').submit();
                    }
                });
    
            },
            
            /**
            Activates input of visible container (e.g. set focus)
            @method activate()
            **/         
            activate: function() {
                if(this.tip && this.tip().is(':visible') && this.$form) {
                   this.$form.data('editableform').input.activate(); 
                }
            } 
    
        };
    
        /**
        jQuery method to initialize editableContainer.
        
        @method $().editableContainer(options)
        @params {Object} options
        @example
        $('#edit').editableContainer({
            type: 'text',
            url: '/post',
            pk: 1,
            value: 'hello'
        });
        **/  
        $.fn.editableContainer = function (option) {
            var args = arguments;
            return this.each(function () {
                var $this = $(this),
                dataKey = 'editableContainer', 
                data = $this.data(dataKey),
                options = typeof option === 'object' && option,
                Constructor = (options.mode === 'inline') ? Inline : Popup;             
    
                if (!data) {
                    $this.data(dataKey, (data = new Constructor(this, options)));
                }
    
                if (typeof option === 'string') { //call method 
                    data[option].apply(data, Array.prototype.slice.call(args, 1));
                }            
            });
        };     
    
        //store constructors
        $.fn.editableContainer.Popup = Popup;
        $.fn.editableContainer.Inline = Inline;
    
        //defaults
        $.fn.editableContainer.defaults = {
            /**
            Initial value of form input
    
            @property value 
            @type mixed
            @default null
            @private
            **/        
            value: null,
            /**
            Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container.
    
            @property placement 
            @type string
            @default 'top'
            **/        
            placement: 'top',
            /**
            Whether to hide container on save/cancel.
    
            @property autohide 
            @type boolean
            @default true
            @private 
            **/        
            autohide: true,
            /**
            Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>.  
            Setting <code>ignore</code> allows to have several containers open. 
    
            @property onblur 
            @type string
            @default 'cancel'
            @since 1.1.1
            **/        
            onblur: 'cancel',
            
            /**
            Animation speed (inline mode only)
            @property anim 
            @type string
            @default false
            **/        
            anim: false,
            
            /**
            Mode of editable, can be `popup` or `inline` 
            
            @property mode 
            @type string         
            @default 'popup'
            @since 1.4.0        
            **/        
            mode: 'popup'        
        };
    
        /* 
        * workaround to have 'destroyed' event to destroy popover when element is destroyed
        * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom
        */
        jQuery.event.special.destroyed = {
            remove: function(o) {
                if (o.handler) {
                    o.handler();
                }
            }
        };    
    
    }(window.jQuery));
    
    /**
    * Editable Inline 
    * ---------------------
    */
    (function ($) {
        "use strict";
        
        //copy prototype from EditableContainer
        //extend methods
        $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, {
            containerName: 'editableform',
            innerCss: '.editable-inline',
            containerClass: 'editable-container editable-inline', //css class applied to container element
                     
            initContainer: function(){
                //container is <span> element
                this.$tip = $('<span></span>');
                
                //convert anim to miliseconds (int)
                if(!this.options.anim) {
                    this.options.anim = 0;
                }         
            },
            
            splitOptions: function() {
                //all options are passed to form
                this.containerOptions = {};
                this.formOptions = this.options;
            },
            
            tip: function() {
               return this.$tip; 
            },
            
            innerShow: function () {
                this.$element.hide();
                this.tip().insertAfter(this.$element).show();
            }, 
            
            innerHide: function () {
                this.$tip.hide(this.options.anim, $.proxy(function() {
                    this.$element.show();
                    this.innerDestroy();
                }, this)); 
            },
            
            innerDestroy: function() {
                if(this.tip()) {
                    this.tip().empty().remove();
                }
            } 
        });
    
    }(window.jQuery));
    /**
    Makes editable any HTML element on the page. Applied as jQuery method.
    
    @class editable
    @uses editableContainer
    **/
    (function ($) {
        "use strict";
    
        var Editable = function (element, options) {
            this.$element = $(element);
            //data-* has more priority over js options: because dynamically created elements may change data-* 
            this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element));  
            if(this.options.selector) {
                this.initLive();
            } else {
                this.init();
            }
            
            //check for transition support
            if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) {
                this.options.highlight = false;
            }
        };
    
        Editable.prototype = {
            constructor: Editable, 
            init: function () {
                var isValueByText = false, 
                    doAutotext, finalize;
    
                //name
                this.options.name = this.options.name || this.$element.attr('id');
                 
                //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select)
                //also we set scope option to have access to element inside input specific callbacks (e. g. source as function)
                this.options.scope = this.$element[0]; 
                this.input = $.fn.editableutils.createInput(this.options);
                if(!this.input) {
                    return; 
                }            
    
                //set value from settings or by element's text
                if (this.options.value === undefined || this.options.value === null) {
                    this.value = this.input.html2value($.trim(this.$element.html()));
                    isValueByText = true;
                } else {
                    /*
                      value can be string when received from 'data-value' attribute
                      for complext objects value can be set as json string in data-value attribute, 
                      e.g. data-value="{city: 'Moscow', street: 'Lenina'}"
                    */
                    this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); 
                    if(typeof this.options.value === 'string') {
                        this.value = this.input.str2value(this.options.value);
                    } else {
                        this.value = this.options.value;
                    }
                }
                
                //add 'editable' class to every editable element
                this.$element.addClass('editable');
                
                //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks
                if(this.input.type === 'textarea') {
                    this.$element.addClass('editable-pre-wrapped');
                }
                
                //attach handler activating editable. In disabled mode it just prevent default action (useful for links)
                if(this.options.toggle !== 'manual') {
                    this.$element.addClass('editable-click');
                    this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){
                        //prevent following link if editable enabled
                        if(!this.options.disabled) {
                            e.preventDefault();
                        }
                        
                        //stop propagation not required because in document click handler it checks event target
                        //e.stopPropagation();
                        
                        if(this.options.toggle === 'mouseenter') {
                            //for hover only show container
                            this.show();
                        } else {
                            //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener
                            var closeAll = (this.options.toggle !== 'click');
                            this.toggle(closeAll);
                        }
                    }, this));
                } else {
                    this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually
                }
                
                //if display is function it's far more convinient to have autotext = always to render correctly on init
                //see https://github.com/vitalets/x-editable-yii/issues/34
                if(typeof this.options.display === 'function') {
                    this.options.autotext = 'always';
                }
                
                //check conditions for autotext:
                switch(this.options.autotext) {
                  case 'always':
                   doAutotext = true;
                  break;
                  case 'auto':
                    //if element text is empty and value is defined and value not generated by text --> run autotext
                    doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText;
                  break;
                  default:
                   doAutotext = false;
                }
    
                //depending on autotext run render() or just finilize init
                $.when(doAutotext ? this.render() : true).then($.proxy(function() {
                    if(this.options.disabled) {
                        this.disable();
                    } else {
                        this.enable(); 
                    }
                   /**        
                   Fired when element was initialized by `$().editable()` method. 
                   Please note that you should setup `init` handler **before** applying `editable`. 
                                  
                   @event init 
                   @param {Object} event event object
                   @param {Object} editable editable instance (as here it cannot accessed via data('editable'))
                   @since 1.2.0
                   @example
                   $('#username').on('init', function(e, editable) {
                       alert('initialized ' + editable.options.name);
                   });
                   $('#username').editable();
                   **/                  
                    this.$element.triggerHandler('init', this);
                }, this));
            },
    
            /*
             Initializes parent element for live editables 
            */
            initLive: function() {
               //store selector 
               var selector = this.options.selector;
               //modify options for child elements
               this.options.selector = false; 
               this.options.autotext = 'never';
               //listen toggle events
               this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){
                   var $target = $(e.target);
                   if(!$target.data('editable')) {
                       //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user)
                       //see https://github.com/vitalets/x-editable/issues/137 
                       if($target.hasClass(this.options.emptyclass)) {
                          $target.empty();
                       }
                       $target.editable(this.options).trigger(e);
                   }
               }, this)); 
            },
            
            /*
            Renders value into element's text.
            Can call custom display method from options.
            Can return deferred object.
            @method render()
            @param {mixed} response server response (if exist) to pass into display function
            */          
            render: function(response) {
                //do not display anything
                if(this.options.display === false) {
                    return;
                }
                
                //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded
                if(this.input.value2htmlFinal) {
                    return this.input.value2html(this.value, this.$element[0], this.options.display, response); 
                //if display method defined --> use it    
                } else if(typeof this.options.display === 'function') {
                    return this.options.display.call(this.$element[0], this.value, response);
                //else use input's original value2html() method    
                } else {
                    return this.input.value2html(this.value, this.$element[0]); 
                }
            },
            
            /**
            Enables editable
            @method enable()
            **/          
            enable: function() {
                this.options.disabled = false;
                this.$element.removeClass('editable-disabled');
                this.handleEmpty(this.isEmpty);
                if(this.options.toggle !== 'manual') {
                    if(this.$element.attr('tabindex') === '-1') {    
                        this.$element.removeAttr('tabindex');                                
                    }
                }
            },
            
            /**
            Disables editable
            @method disable()
            **/         
            disable: function() {
                this.options.disabled = true; 
                this.hide();           
                this.$element.addClass('editable-disabled');
                this.handleEmpty(this.isEmpty);
                //do not stop focus on this element
                this.$element.attr('tabindex', -1);                
            },
            
            /**
            Toggles enabled / disabled state of editable element
            @method toggleDisabled()
            **/         
            toggleDisabled: function() {
                if(this.options.disabled) {
                    this.enable();
                } else { 
                    this.disable(); 
                }
            },  
            
            /**
            Sets new option
            
            @method option(key, value)
            @param {string|object} key option name or object with several options
            @param {mixed} value option new value
            @example
            $('.editable').editable('option', 'pk', 2);
            **/          
            option: function(key, value) {
                //set option(s) by object
                if(key && typeof key === 'object') {
                   $.each(key, $.proxy(function(k, v){
                      this.option($.trim(k), v); 
                   }, this)); 
                   return;
                }
    
                //set option by string             
                this.options[key] = value;                          
                
                //disabled
                if(key === 'disabled') {
                   return value ? this.disable() : this.enable();
                } 
                
                //value
                if(key === 'value') {
                    this.setValue(value);
                }
                
                //transfer new option to container! 
                if(this.container) {
                    this.container.option(key, value);  
                }
                 
                //pass option to input directly (as it points to the same in form)
                if(this.input.option) {
                    this.input.option(key, value);
                }
                
            },              
            
            /*
            * set emptytext if element is empty
            */
            handleEmpty: function (isEmpty) {
                //do not handle empty if we do not display anything
                if(this.options.display === false) {
                    return;
                }
    
                /* 
                isEmpty may be set directly as param of method.
                It is required when we enable/disable field and can't rely on content 
                as node content is text: "Empty" that is not empty %)
                */
                if(isEmpty !== undefined) { 
                    this.isEmpty = isEmpty;
                } else {
                    //detect empty
                    //for some inputs we need more smart check
                    //e.g. wysihtml5 may have <br>, <p></p>, <img>
                    if(typeof(this.input.isEmpty) === 'function') {
                        this.isEmpty = this.input.isEmpty(this.$element);                    
                    } else {
                        this.isEmpty = $.trim(this.$element.html()) === '';
                    }
                }           
                
                //emptytext shown only for enabled
                if(!this.options.disabled) {
                    if (this.isEmpty) {
                        this.$element.html(this.options.emptytext);
                        if(this.options.emptyclass) {
                            this.$element.addClass(this.options.emptyclass);
                        }
                    } else if(this.options.emptyclass) {
                        this.$element.removeClass(this.options.emptyclass);
                    }
                } else {
                    //below required if element disable property was changed
                    if(this.isEmpty) {
                        this.$element.empty();
                        if(this.options.emptyclass) {
                            this.$element.removeClass(this.options.emptyclass);
                        }
                    }
                }
            },        
            
            /**
            Shows container with form
            @method show()
            @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
            **/  
            show: function (closeAll) {
                if(this.options.disabled) {
                    return;
                }
                
                //init editableContainer: popover, tooltip, inline, etc..
                if(!this.container) {
                    var containerOptions = $.extend({}, this.options, {
                        value: this.value,
                        input: this.input //pass input to form (as it is already created)
                    });
                    this.$element.editableContainer(containerOptions);
                    //listen `save` event 
                    this.$element.on("save.internal", $.proxy(this.save, this));
                    this.container = this.$element.data('editableContainer'); 
                } else if(this.container.tip().is(':visible')) {
                    return;
                }      
                
                //show container
                this.container.show(closeAll);
            },
            
            /**
            Hides container with form
            @method hide()
            **/       
            hide: function () {   
                if(this.container) {  
                    this.container.hide();
                }
            },
            
            /**
            Toggles container visibility (show / hide)
            @method toggle()
            @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
            **/  
            toggle: function(closeAll) {
                if(this.container && this.container.tip().is(':visible')) {
                    this.hide();
                } else {
                    this.show(closeAll);
                }
            },
            
            /*
            * called when form was submitted
            */          
            save: function(e, params) {
                //mark element with unsaved class if needed
                if(this.options.unsavedclass) {
                    /*
                     Add unsaved css to element if:
                      - url is not user's function 
                      - value was not sent to server
                      - params.response === undefined, that means data was not sent
                      - value changed 
                    */
                    var sent = false;
                    sent = sent || typeof this.options.url === 'function';
                    sent = sent || this.options.display === false; 
                    sent = sent || params.response !== undefined; 
                    sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); 
                    
                    if(sent) {
                        this.$element.removeClass(this.options.unsavedclass); 
                    } else {
                        this.$element.addClass(this.options.unsavedclass);                    
                    }
                }
                
                //highlight when saving
                if(this.options.highlight) {
                    var $e = this.$element,
                        bgColor = $e.css('background-color');
                        
                    $e.css('background-color', this.options.highlight);
                    setTimeout(function(){
                        if(bgColor === 'transparent') {
                            bgColor = ''; 
                        }
                        $e.css('background-color', bgColor);
                        $e.addClass('editable-bg-transition');
                        setTimeout(function(){
                           $e.removeClass('editable-bg-transition');  
                        }, 1700);
                    }, 10);
                }
                
                //set new value
                this.setValue(params.newValue, false, params.response);
                
                /**        
                Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance
                
                @event save 
                @param {Object} event event object
                @param {Object} params additional params
                @param {mixed} params.newValue submitted value
                @param {Object} params.response ajax response
                @example
                $('#username').on('save', function(e, params) {
                    alert('Saved value: ' + params.newValue);
                });
                **/
                //event itself is triggered by editableContainer. Description here is only for documentation              
            },
    
            validate: function () {
                if (typeof this.options.validate === 'function') {
                    return this.options.validate.call(this, this.value);
                }
            },
            
            /**
            Sets new value of editable
            @method setValue(value, convertStr)
            @param {mixed} value new value 
            @param {boolean} convertStr whether to convert value from string to internal format
            **/         
            setValue: function(value, convertStr, response) {
                if(convertStr) {
                    this.value = this.input.str2value(value);
                } else {
                    this.value = value;
                }
                if(this.container) {
                    this.container.option('value', this.value);
                }
                $.when(this.render(response))
                .then($.proxy(function() {
                    this.handleEmpty();
                }, this));
            },
            
            /**
            Activates input of visible container (e.g. set focus)
            @method activate()
            **/         
            activate: function() {
                if(this.container) {
                   this.container.activate(); 
                }
            },
            
            /**
            Removes editable feature from element
            @method destroy()
            **/        
            destroy: function() {
                this.disable();
                
                if(this.container) {
                   this.container.destroy(); 
                }
                
                this.input.destroy();
    
                if(this.options.toggle !== 'manual') {
                    this.$element.removeClass('editable-click');
                    this.$element.off(this.options.toggle + '.editable');
                } 
                
                this.$element.off("save.internal");
                
                this.$element.removeClass('editable editable-open editable-disabled');
                this.$element.removeData('editable');
            }        
        };
    
        /* EDITABLE PLUGIN DEFINITION
        * ======================= */
    
        /**
        jQuery method to initialize editable element.
        
        @method $().editable(options)
        @params {Object} options
        @example
        $('#username').editable({
            type: 'text',
            url: '/post',
            pk: 1
        });
        **/
        $.fn.editable = function (option) {
            //special API methods returning non-jquery object
            var result = {}, args = arguments, datakey = 'editable';
            switch (option) {
                /**
                Runs client-side validation for all matched editables
                
                @method validate()
                @returns {Object} validation errors map
                @example
                $('#username, #fullname').editable('validate');
                // possible result:
                {
                  username: "username is required",
                  fullname: "fullname should be minimum 3 letters length"
                }
                **/
                case 'validate':
                    this.each(function () {
                        var $this = $(this), data = $this.data(datakey), error;
                        if (data && (error = data.validate())) {
                            result[data.options.name] = error;
                        }
                    });
                return result;
    
                /**
                Returns current values of editable elements.   
                Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements.    
                If value of some editable is `null` or `undefined` it is excluded from result object.
                When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object.   
                 
                @method getValue()
                @param {bool} isSingle whether to return just value of single element
                @returns {Object} object of element names and values
                @example
                $('#username, #fullname').editable('getValue');
                //result:
                {
                username: "superuser",
                fullname: "John"
                }
                //isSingle = true
                $('#username').editable('getValue', true);
                //result "superuser" 
                **/
                case 'getValue':
                    if(arguments.length === 2 && arguments[1] === true) { //isSingle = true
                        result = this.eq(0).data(datakey).value;
                    } else {
                        this.each(function () {
                            var $this = $(this), data = $this.data(datakey);
                            if (data && data.value !== undefined && data.value !== null) {
                                result[data.options.name] = data.input.value2submit(data.value);
                            }
                        });
                    }
                return result;
    
                /**
                This method collects values from several editable elements and submit them all to server.   
                Internally it runs client-side validation for all fields and submits only in case of success.  
                See <a href="#newrecord">creating new records</a> for details.  
                Since 1.5.1 `submit` can be applied to single element to send data programmatically. In that case
                `url`, `success` and `error` is taken from initial options and you can just call `$('#username').editable('submit')`. 
                
                @method submit(options)
                @param {object} options 
                @param {object} options.url url to submit data 
                @param {object} options.data additional data to submit
                @param {object} options.ajaxOptions additional ajax options
                @param {function} options.error(obj) error handler 
                @param {function} options.success(obj,config) success handler
                @returns {Object} jQuery object
                **/
                case 'submit':  //collects value, validate and submit to server for creating new record
                    var config = arguments[1] || {},
                    $elems = this,
                    errors = this.editable('validate');
    
                    // validation ok
                    if($.isEmptyObject(errors)) {
                        var ajaxOptions = {};
                                                          
                        // for single element use url, success etc from options
                        if($elems.length === 1) {
                            var editable = $elems.data('editable');
                            //standard params
                            var params = {
                                name: editable.options.name || '',
                                value: editable.input.value2submit(editable.value),
                                pk: (typeof editable.options.pk === 'function') ? 
                                    editable.options.pk.call(editable.options.scope) : 
                                    editable.options.pk 
                            };
    
                            //additional params
                            if(typeof editable.options.params === 'function') {
                                params = editable.options.params.call(editable.options.scope, params);  
                            } else {
                                //try parse json in single quotes (from data-params attribute)
                                editable.options.params = $.fn.editableutils.tryParseJson(editable.options.params, true);   
                                $.extend(params, editable.options.params);
                            }
    
                            ajaxOptions = {
                                url: editable.options.url,
                                data: params,
                                type: 'POST'  
                            };
                            
                            // use success / error from options 
                            config.success = config.success || editable.options.success;
                            config.error = config.error || editable.options.error;
                            
                        // multiple elements
                        } else {
                            var values = this.editable('getValue'); 
                            
                            ajaxOptions = {
                                url: config.url,
                                data: values, 
                                type: 'POST'
                            };                        
                        }                    
    
                        // ajax success callabck (response 200 OK)
                        ajaxOptions.success = typeof config.success === 'function' ? function(response) {
                                config.success.call($elems, response, config);
                            } : $.noop;
                                      
                        // ajax error callabck
                        ajaxOptions.error = typeof config.error === 'function' ? function() {
                                 config.error.apply($elems, arguments);
                            } : $.noop;
                           
                        // extend ajaxOptions    
                        if(config.ajaxOptions) { 
                            $.extend(ajaxOptions, config.ajaxOptions);
                        }
                        
                        // extra data 
                        if(config.data) {
                            $.extend(ajaxOptions.data, config.data);
                        }                     
                        
                        // perform ajax request
                        $.ajax(ajaxOptions);
                    } else { //client-side validation error
                        if(typeof config.error === 'function') {
                            config.error.call($elems, errors);
                        }
                    }
                return this;
            }
    
            //return jquery object
            return this.each(function () {
                var $this = $(this), 
                    data = $this.data(datakey), 
                    options = typeof option === 'object' && option;
    
                //for delegated targets do not store `editable` object for element
                //it's allows several different selectors.
                //see: https://github.com/vitalets/x-editable/issues/312    
                if(options && options.selector) {
                    data = new Editable(this, options);
                    return; 
                }    
                
                if (!data) {
                    $this.data(datakey, (data = new Editable(this, options)));
                }
    
                if (typeof option === 'string') { //call method 
                    data[option].apply(data, Array.prototype.slice.call(args, 1));
                } 
            });
        };    
                
    
        $.fn.editable.defaults = {
            /**
            Type of input. Can be <code>text|textarea|select|date|checklist</code> and more
    
            @property type 
            @type string
            @default 'text'
            **/
            type: 'text',        
            /**
            Sets disabled state of editable
    
            @property disabled 
            @type boolean
            @default false
            **/         
            disabled: false,
            /**
            How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>.   
            When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable.    
            **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, 
            you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document.
            
            @example
            $('#edit-button').click(function(e) {
                e.stopPropagation();
                $('#username').editable('toggle');
            });
    
            @property toggle 
            @type string
            @default 'click'
            **/          
            toggle: 'click',
            /**
            Text shown when element is empty.
    
            @property emptytext 
            @type string
            @default 'Empty'
            **/         
            emptytext: 'Empty',
            /**
            Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date.
            For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>.  
            <code>auto</code> - text will be automatically set only if element is empty.  
            <code>always|never</code> - always(never) try to set element's text.
    
            @property autotext 
            @type string
            @default 'auto'
            **/          
            autotext: 'auto', 
            /**
            Initial value of input. If not set, taken from element's text.  
            Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option).  
            For example, to display currency sign:
            @example
            <a id="price" data-type="text" data-value="100"></a>
            <script>
            $('#price').editable({
                ...
                display: function(value) {
                  $(this).text(value + '$');
                } 
            }) 
            </script>
                    
            @property value 
            @type mixed
            @default element's text
            **/
            value: null,
            /**
            Callback to perform custom displaying of value in element's text.  
            If `null`, default input's display used.  
            If `false`, no displaying methods will be called, element's text will never change.  
            Runs under element's scope.  
            _**Parameters:**_  
            
            * `value` current value to be displayed
            * `response` server response (if display called after ajax submit), since 1.4.0
             
            For _inputs with source_ (select, checklist) parameters are different:  
              
            * `value` current value to be displayed
            * `sourceData` array of items for current input (e.g. dropdown items) 
            * `response` server response (if display called after ajax submit), since 1.4.0
                      
            To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`.
            
            @property display 
            @type function|boolean
            @default null
            @since 1.2.0
            @example
            display: function(value, sourceData) {
               //display checklist as comma-separated values
               var html = [],
                   checked = $.fn.editableutils.itemsByValue(value, sourceData);
                   
               if(checked.length) {
                   $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
                   $(this).html(html.join(', '));
               } else {
                   $(this).empty(); 
               }
            }
            **/          
            display: null,
            /**
            Css class applied when editable text is empty.
    
            @property emptyclass 
            @type string
            @since 1.4.1        
            @default editable-empty
            **/        
            emptyclass: 'editable-empty',
            /**
            Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`).  
            You may set it to `null` if you work with editables locally and submit them together.  
    
            @property unsavedclass 
            @type string
            @since 1.4.1        
            @default editable-unsaved
            **/        
            unsavedclass: 'editable-unsaved',
            /**
            If selector is provided, editable will be delegated to the specified targets.  
            Usefull for dynamically generated DOM elements.  
            **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, 
            as they actually become editable only after first click.  
            You should manually set class `editable-click` to these elements.  
            Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element:
    
            @property selector 
            @type string
            @since 1.4.1        
            @default null
            @example
            <div id="user">
              <!-- empty -->
              <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a>
              <!-- non-empty -->
              <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a>
            </div>     
            
            <script>
            $('#user').editable({
                selector: 'a',
                url: '/post',
                pk: 1
            });
            </script>
            **/         
            selector: null,
            /**
            Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers.
            
            @property highlight 
            @type string|boolean
            @since 1.4.5        
            @default #FFFF80 
            **/
            highlight: '#FFFF80'
        };
        
    }(window.jQuery));
    
    /**
    AbstractInput - base class for all editable inputs.
    It defines interface to be implemented by any input type.
    To create your own input you can inherit from this class.
    
    @class abstractinput
    **/
    (function ($) {
        "use strict";
    
        //types
        $.fn.editabletypes = {};
    
        var AbstractInput = function () { };
    
        AbstractInput.prototype = {
           /**
            Initializes input
    
            @method init() 
            **/
           init: function(type, options, defaults) {
               this.type = type;
               this.options = $.extend({}, defaults, options);
           },
    
           /*
           this method called before render to init $tpl that is inserted in DOM
           */
           prerender: function() {
               this.$tpl = $(this.options.tpl); //whole tpl as jquery object    
               this.$input = this.$tpl;         //control itself, can be changed in render method
               this.$clear = null;              //clear button
               this.error = null;               //error message, if input cannot be rendered           
           },
           
           /**
            Renders input from tpl. Can return jQuery deferred object.
            Can be overwritten in child objects
    
            @method render()
           **/
           render: function() {
    
           }, 
    
           /**
            Sets element's html by value. 
    
            @method value2html(value, element)
            @param {mixed} value
            @param {DOMElement} element
           **/
           value2html: function(value, element) {
               $(element)[this.options.escape ? 'text' : 'html']($.trim(value));
           },
    
           /**
            Converts element's html to value
    
            @method html2value(html)
            @param {string} html
            @returns {mixed}
           **/
           html2value: function(html) {
               return $('<div>').html(html).text();
           },
    
           /**
            Converts value to string (for internal compare). For submitting to server used value2submit().
    
            @method value2str(value) 
            @param {mixed} value
            @returns {string}
           **/
           value2str: function(value) {
               return value;
           }, 
    
           /**
            Converts string received from server into value. Usually from `data-value` attribute.
    
            @method str2value(str)
            @param {string} str
            @returns {mixed}
           **/
           str2value: function(str) {
               return str;
           }, 
           
           /**
            Converts value for submitting to server. Result can be string or object.
    
            @method value2submit(value) 
            @param {mixed} value
            @returns {mixed}
           **/
           value2submit: function(value) {
               return value;
           },
    
           /**
            Sets value of input.
    
            @method value2input(value) 
            @param {mixed} value
           **/
           value2input: function(value) {
               this.$input.val(value);
           },
    
           /**
            Returns value of input. Value can be object (e.g. datepicker)
    
            @method input2value() 
           **/
           input2value: function() { 
               return this.$input.val();
           }, 
    
           /**
            Activates input. For text it sets focus.
    
            @method activate() 
           **/
           activate: function() {
               if(this.$input.is(':visible')) {
                   this.$input.focus();
               }
           },
    
           /**
            Creates input.
    
            @method clear() 
           **/        
           clear: function() {
               this.$input.val(null);
           },
    
           /**
            method to escape html.
           **/
           escape: function(str) {
               return $('<div>').text(str).html();
           },
           
           /**
            attach handler to automatically submit form when value changed (useful when buttons not shown)
           **/
           autosubmit: function() {
            
           },
           
           /**
           Additional actions when destroying element 
           **/
           destroy: function() {
           },
    
           // -------- helper functions --------
           setClass: function() {          
               if(this.options.inputclass) {
                   this.$input.addClass(this.options.inputclass); 
               } 
           },
    
           setAttr: function(attr) {
               if (this.options[attr] !== undefined && this.options[attr] !== null) {
                   this.$input.attr(attr, this.options[attr]);
               } 
           },
           
           option: function(key, value) {
                this.options[key] = value;
           }
           
        };
            
        AbstractInput.defaults = {  
            /**
            HTML template of input. Normally you should not change it.
    
            @property tpl 
            @type string
            @default ''
            **/   
            tpl: '',
            /**
            CSS class automatically applied to input
            
            @property inputclass 
            @type string
            @default null
            **/         
            inputclass: null,
            
            /**
            If `true` - html will be escaped in content of element via $.text() method.  
            If `false` - html will not be escaped, $.html() used.  
            When you use own `display` function, this option obviosly has no effect.
            
            @property escape 
            @type boolean
            @since 1.5.0
            @default true
            **/         
            escape: true,
                    
            //scope for external methods (e.g. source defined as function)
            //for internal use only
            scope: null,
            
            //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults)
            showbuttons: true 
        };
        
        $.extend($.fn.editabletypes, {abstractinput: AbstractInput});
            
    }(window.jQuery));
    
    /**
    List - abstract class for inputs that have source option loaded from js array or via ajax
    
    @class list
    @extends abstractinput
    **/
    (function ($) {
        "use strict";
        
        var List = function (options) {
           
        };
    
        $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput);
    
        $.extend(List.prototype, {
            render: function () {
                var deferred = $.Deferred();
    
                this.error = null;
                this.onSourceReady(function () {
                    this.renderList();
                    deferred.resolve();
                }, function () {
                    this.error = this.options.sourceError;
                    deferred.resolve();
                });
    
                return deferred.promise();
            },
    
            html2value: function (html) {
                return null; //can't set value by text
            },
            
            value2html: function (value, element, display, response) {
                var deferred = $.Deferred(),
                    success = function () {
                        if(typeof display === 'function') {
                            //custom display method
                            display.call(element, value, this.sourceData, response); 
                        } else {
                            this.value2htmlFinal(value, element);
                        }
                        deferred.resolve();
                   };
                
                //for null value just call success without loading source
                if(value === null) {
                   success.call(this);   
                } else {
                   this.onSourceReady(success, function () { deferred.resolve(); });
                }
    
                return deferred.promise();
            },  
    
            // ------------- additional functions ------------
    
            onSourceReady: function (success, error) {
                //run source if it function
                var source;
                if ($.isFunction(this.options.source)) {
                    source = this.options.source.call(this.options.scope);
                    this.sourceData = null;
                    //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed
                } else {
                    source = this.options.source;
                }            
                
                //if allready loaded just call success
                if(this.options.sourceCache && $.isArray(this.sourceData)) {
                    success.call(this);
                    return; 
                }
    
                //try parse json in single quotes (for double quotes jquery does automatically)
                try {
                    source = $.fn.editableutils.tryParseJson(source, false);
                } catch (e) {
                    error.call(this);
                    return;
                }
    
                //loading from url
                if (typeof source === 'string') {
                    //try to get sourceData from cache
                    if(this.options.sourceCache) {
                        var cacheID = source,
                        cache;
    
                        if (!$(document).data(cacheID)) {
                            $(document).data(cacheID, {});
                        }
                        cache = $(document).data(cacheID);
    
                        //check for cached data
                        if (cache.loading === false && cache.sourceData) { //take source from cache
                            this.sourceData = cache.sourceData;
                            this.doPrepend();
                            success.call(this);
                            return;
                        } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later
                            cache.callbacks.push($.proxy(function () {
                                this.sourceData = cache.sourceData;
                                this.doPrepend();
                                success.call(this);
                            }, this));
    
                            //also collecting error callbacks
                            cache.err_callbacks.push($.proxy(error, this));
                            return;
                        } else { //no cache yet, activate it
                            cache.loading = true;
                            cache.callbacks = [];
                            cache.err_callbacks = [];
                        }
                    }
                    
                    //ajaxOptions for source. Can be overwritten bt options.sourceOptions
                    var ajaxOptions = $.extend({
                        url: source,
                        type: 'get',
                        cache: false,
                        dataType: 'json',
                        success: $.proxy(function (data) {
                            if(cache) {
                                cache.loading = false;
                            }
                            this.sourceData = this.makeArray(data);
                            if($.isArray(this.sourceData)) {
                                if(cache) {
                                    //store result in cache
                                    cache.sourceData = this.sourceData;
                                    //run success callbacks for other fields waiting for this source
                                    $.each(cache.callbacks, function () { this.call(); }); 
                                }
                                this.doPrepend();
                                success.call(this);
                            } else {
                                error.call(this);
                                if(cache) {
                                    //run error callbacks for other fields waiting for this source
                                    $.each(cache.err_callbacks, function () { this.call(); }); 
                                }
                            }
                        }, this),
                        error: $.proxy(function () {
                            error.call(this);
                            if(cache) {
                                 cache.loading = false;
                                 //run error callbacks for other fields
                                 $.each(cache.err_callbacks, function () { this.call(); }); 
                            }
                        }, this)
                    }, this.options.sourceOptions);
                    
                    //loading sourceData from server
                    $.ajax(ajaxOptions);
                    
                } else { //options as json/array
                    this.sourceData = this.makeArray(source);
                        
                    if($.isArray(this.sourceData)) {
                        this.doPrepend();
                        success.call(this);   
                    } else {
                        error.call(this);
                    }
                }
            },
    
            doPrepend: function () {
                if(this.options.prepend === null || this.options.prepend === undefined) {
                    return;  
                }
                
                if(!$.isArray(this.prependData)) {
                    //run prepend if it is function (once)
                    if ($.isFunction(this.options.prepend)) {
                        this.options.prepend = this.options.prepend.call(this.options.scope);
                    }
                  
                    //try parse json in single quotes
                    this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true);
                    
                    //convert prepend from string to object
                    if (typeof this.options.prepend === 'string') {
                        this.options.prepend = {'': this.options.prepend};
                    }
                    
                    this.prependData = this.makeArray(this.options.prepend);
                }
    
                if($.isArray(this.prependData) && $.isArray(this.sourceData)) {
                    this.sourceData = this.prependData.concat(this.sourceData);
                }
            },
    
            /*
             renders input list
            */
            renderList: function() {
                // this method should be overwritten in child class
            },
           
             /*
             set element's html by value
            */
            value2htmlFinal: function(value, element) {
                // this method should be overwritten in child class
            },        
    
            /**
            * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}]
            */
            makeArray: function(data) {
                var count, obj, result = [], item, iterateItem;
                if(!data || typeof data === 'string') {
                    return null; 
                }
    
                if($.isArray(data)) { //array
                    /* 
                       function to iterate inside item of array if item is object.
                       Caclulates count of keys in item and store in obj. 
                    */
                    iterateItem = function (k, v) {
                        obj = {value: k, text: v};
                        if(count++ >= 2) {
                            return false;// exit from `each` if item has more than one key.
                        }
                    };
                
                    for(var i = 0; i < data.length; i++) {
                        item = data[i]; 
                        if(typeof item === 'object') {
                            count = 0; //count of keys inside item
                            $.each(item, iterateItem);
                            //case: [{val1: 'text1'}, {val2: 'text2} ...]
                            if(count === 1) { 
                                result.push(obj); 
                                //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...]
                            } else if(count > 1) {
                                //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text')
                                if(item.children) {
                                    item.children = this.makeArray(item.children);   
                                }
                                result.push(item);
                            }
                        } else {
                            //case: ['text1', 'text2' ...]
                            result.push({value: item, text: item}); 
                        }
                    }
                } else {  //case: {val1: 'text1', val2: 'text2, ...}
                    $.each(data, function (k, v) {
                        result.push({value: k, text: v});
                    });  
                }
                return result;
            },
            
            option: function(key, value) {
                this.options[key] = value;
                if(key === 'source') {
                    this.sourceData = null;
                }
                if(key === 'prepend') {
                    this.prependData = null;
                }            
            }        
    
        });      
    
        List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            /**
            Source data for list.  
            If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]`  
            For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order.
            
            If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option.
              
            If **function**, it should return data in format above (since 1.4.0).
            
            Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only).  
            `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` 
    
            
            @property source 
            @type string | array | object | function
            @default null
            **/         
            source: null, 
            /**
            Data automatically prepended to the beginning of dropdown list.
            
            @property prepend 
            @type string | array | object | function
            @default false
            **/         
            prepend: false,
            /**
            Error message when list cannot be loaded (e.g. ajax error)
            
            @property sourceError 
            @type string
            @default Error when loading list
            **/          
            sourceError: 'Error when loading list',
            /**
            if <code>true</code> and source is **string url** - results will be cached for fields with the same source.    
            Usefull for editable column in grid to prevent extra requests.
            
            @property sourceCache 
            @type boolean
            @default true
            @since 1.2.0
            **/        
            sourceCache: true,
            /**
            Additional ajax options to be used in $.ajax() when loading list from server.
            Useful to send extra parameters (`data` key) or change request method (`type` key).
            
            @property sourceOptions 
            @type object|function
            @default null
            @since 1.5.0
            **/        
            sourceOptions: null
        });
    
        $.fn.editabletypes.list = List;      
    
    }(window.jQuery));
    
    /**
    Text input
    
    @class text
    @extends abstractinput
    @final
    @example
    <a href="#" id="username" data-type="text" data-pk="1">awesome</a>
    <script>
    $(function(){
        $('#username').editable({
            url: '/post',
            title: 'Enter username'
        });
    });
    </script>
    **/
    (function ($) {
        "use strict";
        
        var Text = function (options) {
            this.init('text', options, Text.defaults);
        };
    
        $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput);
    
        $.extend(Text.prototype, {
            render: function() {
               this.renderClear();
               this.setClass();
               this.setAttr('placeholder');
            },
            
            activate: function() {
                if(this.$input.is(':visible')) {
                    this.$input.focus();
                    $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length);
                    if(this.toggleClear) {
                        this.toggleClear();
                    }
                }
            },
            
            //render clear button
            renderClear:  function() {
               if (this.options.clear) {
                   this.$clear = $('<span class="editable-clear-x"></span>');
                   this.$input.after(this.$clear)
                              .css('padding-right', 24)
                              .keyup($.proxy(function(e) {
                                  //arrows, enter, tab, etc
                                  if(~$.inArray(e.keyCode, [40,38,9,13,27])) {
                                    return;
                                  }                            
    
                                  clearTimeout(this.t);
                                  var that = this;
                                  this.t = setTimeout(function() {
                                    that.toggleClear(e);
                                  }, 100);
                                  
                              }, this))
                              .parent().css('position', 'relative');
                              
                   this.$clear.click($.proxy(this.clear, this));                       
               }            
            },
            
            postrender: function() {
                /*
                //now `clear` is positioned via css
                if(this.$clear) {
                    //can position clear button only here, when form is shown and height can be calculated
    //                var h = this.$input.outerHeight(true) || 20,
                    var h = this.$clear.parent().height(),
                        delta = (h - this.$clear.height()) / 2;
                        
                    //this.$clear.css({bottom: delta, right: delta});
                }
                */ 
            },
            
            //show / hide clear button
            toggleClear: function(e) {
                if(!this.$clear) {
                    return;
                }
                
                var len = this.$input.val().length,
                    visible = this.$clear.is(':visible');
                     
                if(len && !visible) {
                    this.$clear.show();
                } 
                
                if(!len && visible) {
                    this.$clear.hide();
                } 
            },
            
            clear: function() {
               this.$clear.hide();
               this.$input.val('').focus();
            }          
        });
    
        Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            /**
            @property tpl 
            @default <input type="text">
            **/         
            tpl: '<input type="text">',
            /**
            Placeholder attribute of input. Shown when input is empty.
    
            @property placeholder 
            @type string
            @default null
            **/             
            placeholder: null,
            
            /**
            Whether to show `clear` button 
            
            @property clear 
            @type boolean
            @default true        
            **/
            clear: true
        });
    
        $.fn.editabletypes.text = Text;
    
    }(window.jQuery));
    
    /**
    Textarea input
    
    @class textarea
    @extends abstractinput
    @final
    @example
    <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a>
    <script>
    $(function(){
        $('#comments').editable({
            url: '/post',
            title: 'Enter comments',
            rows: 10
        });
    });
    </script>
    **/
    (function ($) {
        "use strict";
        
        var Textarea = function (options) {
            this.init('textarea', options, Textarea.defaults);
        };
    
        $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput);
    
        $.extend(Textarea.prototype, {
            render: function () {
                this.setClass();
                this.setAttr('placeholder');
                this.setAttr('rows');                        
                
                //ctrl + enter
                this.$input.keydown(function (e) {
                    if (e.ctrlKey && e.which === 13) {
                        $(this).closest('form').submit();
                    }
                });
            },
            
           //using `white-space: pre-wrap` solves \n  <--> BR conversion very elegant!
           /* 
           value2html: function(value, element) {
                var html = '', lines;
                if(value) {
                    lines = value.split("\n");
                    for (var i = 0; i < lines.length; i++) {
                        lines[i] = $('<div>').text(lines[i]).html();
                    }
                    html = lines.join('<br>');
                }
                $(element).html(html);
            },
           
            html2value: function(html) {
                if(!html) {
                    return '';
                }
    
                var regex = new RegExp(String.fromCharCode(10), 'g');
                var lines = html.split(/<br\s*\/?>/i);
                for (var i = 0; i < lines.length; i++) {
                    var text = $('<div>').html(lines[i]).text();
    
                    // Remove newline characters (\n) to avoid them being converted by value2html() method
                    // thus adding extra <br> tags
                    text = text.replace(regex, '');
    
                    lines[i] = text;
                }
                return lines.join("\n");
            },
             */
            activate: function() {
                $.fn.editabletypes.text.prototype.activate.call(this);
            }
        });
    
        Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            /**
            @property tpl
            @default <textarea></textarea>
            **/
            tpl:'<textarea></textarea>',
            /**
            @property inputclass
            @default input-large
            **/
            inputclass: 'input-large',
            /**
            Placeholder attribute of input. Shown when input is empty.
    
            @property placeholder
            @type string
            @default null
            **/
            placeholder: null,
            /**
            Number of rows in textarea
    
            @property rows
            @type integer
            @default 7
            **/        
            rows: 7        
        });
    
        $.fn.editabletypes.textarea = Textarea;
    
    }(window.jQuery));
    
    /**
    Select (dropdown)
    
    @class select
    @extends list
    @final
    @example
    <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a>
    <script>
    $(function(){
        $('#status').editable({
            value: 2,    
            source: [
                  {value: 1, text: 'Active'},
                  {value: 2, text: 'Blocked'},
                  {value: 3, text: 'Deleted'}
               ]
        });
    });
    </script>
    **/
    (function ($) {
        "use strict";
        
        var Select = function (options) {
            this.init('select', options, Select.defaults);
        };
    
        $.fn.editableutils.inherit(Select, $.fn.editabletypes.list);
    
        $.extend(Select.prototype, {
            renderList: function() {
                this.$input.empty();
    
                var fillItems = function($el, data) {
                    var attr;
                    if($.isArray(data)) {
                        for(var i=0; i<data.length; i++) {
                            attr = {};
                            if(data[i].children) {
                                attr.label = data[i].text;
                                $el.append(fillItems($('<optgroup>', attr), data[i].children)); 
                            } else {
                                attr.value = data[i].value;
                                if(data[i].disabled) {
                                    attr.disabled = true;
                                }
                                $el.append($('<option>', attr).text(data[i].text)); 
                            }
                        }
                    }
                    return $el;
                };        
    
                fillItems(this.$input, this.sourceData);
                
                this.setClass();
                
                //enter submit
                this.$input.on('keydown.editable', function (e) {
                    if (e.which === 13) {
                        $(this).closest('form').submit();
                    }
                });            
            },
           
            value2htmlFinal: function(value, element) {
                var text = '', 
                    items = $.fn.editableutils.itemsByValue(value, this.sourceData);
                    
                if(items.length) {
                    text = items[0].text;
                }
                
                //$(element).text(text);
                $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element);
            },
            
            autosubmit: function() {
                this.$input.off('keydown.editable').on('change.editable', function(){
                    $(this).closest('form').submit();
                });
            }
        });      
    
        Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
            /**
            @property tpl 
            @default <select></select>
            **/         
            tpl:'<select></select>'
        });
    
        $.fn.editabletypes.select = Select;      
    
    }(window.jQuery));
    
    /**
    List of checkboxes. 
    Internally value stored as javascript array of values.
    
    @class checklist
    @extends list
    @final
    @example
    <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a>
    <script>
    $(function(){
        $('#options').editable({
            value: [2, 3],    
            source: [
                  {value: 1, text: 'option1'},
                  {value: 2, text: 'option2'},
                  {value: 3, text: 'option3'}
               ]
        });
    });
    </script>
    **/
    (function ($) {
        "use strict";
        
        var Checklist = function (options) {
            this.init('checklist', options, Checklist.defaults);
        };
    
        $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list);
    
        $.extend(Checklist.prototype, {
            renderList: function() {
                var $label, $div;
                
                this.$tpl.empty();
                
                if(!$.isArray(this.sourceData)) {
                    return;
                }
    
                for(var i=0; i<this.sourceData.length; i++) {
                    $label = $('<label>').append($('<input>', {
                                               type: 'checkbox',
                                               value: this.sourceData[i].value 
                                         }))
                                         .append($('<span>').text(' '+this.sourceData[i].text));
                    
                    $('<div>').append($label).appendTo(this.$tpl);
                }
                
                this.$input = this.$tpl.find('input[type="checkbox"]');
                this.setClass();
            },
           
           value2str: function(value) {
               return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : '';
           },  
           
           //parse separated string
            str2value: function(str) {
               var reg, value = null;
               if(typeof str === 'string' && str.length) {
                   reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*');
                   value = str.split(reg);
               } else if($.isArray(str)) {
                   value = str; 
               } else {
                   value = [str];
               }
               return value;
            },       
           
           //set checked on required checkboxes
           value2input: function(value) {
                this.$input.prop('checked', false);
                if($.isArray(value) && value.length) {
                   this.$input.each(function(i, el) {
                       var $el = $(el);
                       // cannot use $.inArray as it performs strict comparison
                       $.each(value, function(j, val){
                           /*jslint eqeq: true*/
                           if($el.val() == val) {
                           /*jslint eqeq: false*/                           
                               $el.prop('checked', true);
                           }
                       });
                   }); 
                }  
            },  
            
           input2value: function() { 
               var checked = [];
               this.$input.filter(':checked').each(function(i, el) {
                   checked.push($(el).val());
               });
               return checked;
           },            
              
           //collect text of checked boxes
            value2htmlFinal: function(value, element) {
               var html = [],
                   checked = $.fn.editableutils.itemsByValue(value, this.sourceData),
                   escape = this.options.escape;
                   
               if(checked.length) {
                   $.each(checked, function(i, v) {
                       var text = escape ? $.fn.editableutils.escape(v.text) : v.text; 
                       html.push(text); 
                   });
                   $(element).html(html.join('<br>'));
               } else {
                   $(element).empty(); 
               }
            },
            
           activate: function() {
               this.$input.first().focus();
           },
           
           autosubmit: function() {
               this.$input.on('keydown', function(e){
                   if (e.which === 13) {
                       $(this).closest('form').submit();
                   }
               });
           }
        });      
    
        Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
            /**
            @property tpl 
            @default <div></div>
            **/         
            tpl:'<div class="editable-checklist"></div>',
            
            /**
            @property inputclass 
            @type string
            @default null
            **/         
            inputclass: null,        
            
            /**
            Separator of values when reading from `data-value` attribute
    
            @property separator 
            @type string
            @default ','
            **/         
            separator: ','
        });
    
        $.fn.editabletypes.checklist = Checklist;      
    
    }(window.jQuery));
    
    /**
    HTML5 input types.
    Following types are supported:
    
    * password
    * email
    * url
    * tel
    * number
    * range
    * time
    
    Learn more about html5 inputs:  
    http://www.w3.org/wiki/HTML5_form_additions  
    To check browser compatibility please see:  
    https://developer.mozilla.org/en-US/docs/HTML/Element/Input
                
    @class html5types 
    @extends text
    @final
    @since 1.3.0
    @example
    <a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a>
    <script>
    $(function(){
        $('#email').editable({
            url: '/post',
            title: 'Enter email'
        });
    });
    </script>
    **/
    
    /**
    @property tpl 
    @default depends on type
    **/ 
    
    /*
    Password
    */
    (function ($) {
        "use strict";
        
        var Password = function (options) {
            this.init('password', options, Password.defaults);
        };
        $.fn.editableutils.inherit(Password, $.fn.editabletypes.text);
        $.extend(Password.prototype, {
           //do not display password, show '[hidden]' instead
           value2html: function(value, element) {
               if(value) {
                   $(element).text('[hidden]');
               } else {
                   $(element).empty(); 
               }
           },
           //as password not displayed, should not set value by html
           html2value: function(html) {
               return null;
           }       
        });    
        Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
            tpl: '<input type="password">'
        });
        $.fn.editabletypes.password = Password;
    }(window.jQuery));
    
    
    /*
    Email
    */
    (function ($) {
        "use strict";
        
        var Email = function (options) {
            this.init('email', options, Email.defaults);
        };
        $.fn.editableutils.inherit(Email, $.fn.editabletypes.text);
        Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
            tpl: '<input type="email">'
        });
        $.fn.editabletypes.email = Email;
    }(window.jQuery));
    
    
    /*
    Url
    */
    (function ($) {
        "use strict";
        
        var Url = function (options) {
            this.init('url', options, Url.defaults);
        };
        $.fn.editableutils.inherit(Url, $.fn.editabletypes.text);
        Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
            tpl: '<input type="url">'
        });
        $.fn.editabletypes.url = Url;
    }(window.jQuery));
    
    
    /*
    Tel
    */
    (function ($) {
        "use strict";
        
        var Tel = function (options) {
            this.init('tel', options, Tel.defaults);
        };
        $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text);
        Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
            tpl: '<input type="tel">'
        });
        $.fn.editabletypes.tel = Tel;
    }(window.jQuery));
    
    
    /*
    Number
    */
    (function ($) {
        "use strict";
        
        var NumberInput = function (options) {
            this.init('number', options, NumberInput.defaults);
        };
        $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text);
        $.extend(NumberInput.prototype, {
             render: function () {
                NumberInput.superclass.render.call(this);
                this.setAttr('min');
                this.setAttr('max');
                this.setAttr('step');
            },
            postrender: function() {
                if(this.$clear) {
                    //increase right ffset  for up/down arrows
                    this.$clear.css({right: 24});
                    /*
                    //can position clear button only here, when form is shown and height can be calculated
                    var h = this.$input.outerHeight(true) || 20,
                        delta = (h - this.$clear.height()) / 2;
                    
                    //add 12px to offset right for up/down arrows    
                    this.$clear.css({top: delta, right: delta + 16});
                    */
                } 
            }        
        });     
        NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
            tpl: '<input type="number">',
            inputclass: 'input-mini',
            min: null,
            max: null,
            step: null
        });
        $.fn.editabletypes.number = NumberInput;
    }(window.jQuery));
    
    
    /*
    Range (inherit from number)
    */
    (function ($) {
        "use strict";
        
        var Range = function (options) {
            this.init('range', options, Range.defaults);
        };
        $.fn.editableutils.inherit(Range, $.fn.editabletypes.number);
        $.extend(Range.prototype, {
            render: function () {
                this.$input = this.$tpl.filter('input');
                
                this.setClass();
                this.setAttr('min');
                this.setAttr('max');
                this.setAttr('step');           
                
                this.$input.on('input', function(){
                    $(this).siblings('output').text($(this).val()); 
                });  
            },
            activate: function() {
                this.$input.focus();
            }         
        });
        Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, {
            tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>',
            inputclass: 'input-medium'
        });
        $.fn.editabletypes.range = Range;
    }(window.jQuery));
    
    /*
    Time
    */
    (function ($) {
        "use strict";
    
        var Time = function (options) {
            this.init('time', options, Time.defaults);
        };
        //inherit from abstract, as inheritance from text gives selection error.
        $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput);
        $.extend(Time.prototype, {
            render: function() {
               this.setClass();
            }        
        });
        Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            tpl: '<input type="time">'
        });
        $.fn.editabletypes.time = Time;
    }(window.jQuery));
    
    /**
    Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2.  
    Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options.  
     
    You should manually download and include select2 distributive:  
    
        <link href="select2/select2.css" rel="stylesheet" type="text/css"></link>  
        <script src="select2/select2.js"></script>  
        
    To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): 
    
        <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link>    
        
    **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source.    
    You need initially put both `data-value` and element's text youself:    
    
        <a href="#" data-type="select2" data-value="1">Text1</a>
        
        
    @class select2
    @extends abstractinput
    @since 1.4.1
    @final
    @example
    <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a>
    <script>
    $(function(){
        //local source
        $('#country').editable({
            source: [
                  {id: 'gb', text: 'Great Britain'},
                  {id: 'us', text: 'United States'},
                  {id: 'ru', text: 'Russia'}
               ],
            select2: {
               multiple: true
            }
        });
        //remote source (simple)
        $('#country').editable({
            source: '/getCountries',
            select2: {
                placeholder: 'Select Country',
                minimumInputLength: 1
            }
        });
        //remote source (advanced)
        $('#country').editable({
            select2: {
                placeholder: 'Select Country',
                allowClear: true,
                minimumInputLength: 3,
                id: function (item) {
                    return item.CountryId;
                },
                ajax: {
                    url: '/getCountries',
                    dataType: 'json',
                    data: function (term, page) {
                        return { query: term };
                    },
                    results: function (data, page) {
                        return { results: data };
                    }
                },
                formatResult: function (item) {
                    return item.CountryName;
                },
                formatSelection: function (item) {
                    return item.CountryName;
                },
                initSelection: function (element, callback) {
                    return $.get('/getCountryById', { query: element.val() }, function (data) {
                        callback(data);
                    });
                } 
            }  
        });
    });
    </script>
    **/
    (function ($) {
        "use strict";
        
        var Constructor = function (options) {
            this.init('select2', options, Constructor.defaults);
    
            options.select2 = options.select2 || {};
    
            this.sourceData = null;
            
            //placeholder
            if(options.placeholder) {
                options.select2.placeholder = options.placeholder;
            }
           
            //if not `tags` mode, use source
            if(!options.select2.tags && options.source) {
                var source = options.source;
                //if source is function, call it (once!)
                if ($.isFunction(options.source)) {
                    source = options.source.call(options.scope);
                }               
    
                if (typeof source === 'string') {
                    options.select2.ajax = options.select2.ajax || {};
                    //some default ajax params
                    if(!options.select2.ajax.data) {
                        options.select2.ajax.data = function(term) {return { query:term };};
                    }
                    if(!options.select2.ajax.results) {
                        options.select2.ajax.results = function(data) { return {results:data };};
                    }
                    options.select2.ajax.url = source;
                } else {
                    //check format and convert x-editable format to select2 format (if needed)
                    this.sourceData = this.convertSource(source);
                    options.select2.data = this.sourceData;
                }
            } 
    
            //overriding objects in config (as by default jQuery extend() is not recursive)
            this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2);
    
            //detect whether it is multi-valued
            this.isMultiple = this.options.select2.tags || this.options.select2.multiple;
            this.isRemote = ('ajax' in this.options.select2);
    
            //store function returning ID of item
            //should be here as used inautotext for local source
            this.idFunc = this.options.select2.id;
            if (typeof(this.idFunc) !== "function") {
                var idKey = this.idFunc || 'id';
                this.idFunc = function (e) { return e[idKey]; };
            }
    
            //store function that renders text in select2
            this.formatSelection = this.options.select2.formatSelection;
            if (typeof(this.formatSelection) !== "function") {
                this.formatSelection = function (e) { return e.text; };
            }
        };
    
        $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);
    
        $.extend(Constructor.prototype, {
            render: function() {
                this.setClass();
    
                //can not apply select2 here as it calls initSelection 
                //over input that does not have correct value yet.
                //apply select2 only in value2input
                //this.$input.select2(this.options.select2);
    
                //when data is loaded via ajax, we need to know when it's done to populate listData
                if(this.isRemote) {
                    //listen to loaded event to populate data
                    this.$input.on('select2-loaded', $.proxy(function(e) {
                        this.sourceData = e.items.results;
                    }, this));
                }
    
                //trigger resize of editableform to re-position container in multi-valued mode
                if(this.isMultiple) {
                   this.$input.on('change', function() {
                       $(this).closest('form').parent().triggerHandler('resize');
                   });
                }
           },
    
           value2html: function(value, element) {
               var text = '', data,
                   that = this;
    
               if(this.options.select2.tags) { //in tags mode just assign value
                  data = value; 
                  //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc);
               } else if(this.sourceData) {
                  data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); 
               } else {
                  //can not get list of possible values 
                  //(e.g. autotext for select2 with ajax source)
               }
    
               //data may be array (when multiple values allowed)
               if($.isArray(data)) {
                   //collect selected data and show with separator
                   text = [];
                   $.each(data, function(k, v){
                       text.push(v && typeof v === 'object' ? that.formatSelection(v) : v);
                   });
               } else if(data) {
                   text = that.formatSelection(data);
               }
    
               text = $.isArray(text) ? text.join(this.options.viewseparator) : text;
    
               //$(element).text(text);
               Constructor.superclass.value2html.call(this, text, element); 
           },
    
           html2value: function(html) {
               return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null;
           },
    
           value2input: function(value) {
               // if value array => join it anyway
               if($.isArray(value)) {
                  value = value.join(this.getSeparator());
               }
    
               //for remote source just set value, text is updated by initSelection
               if(!this.$input.data('select2')) {
                   this.$input.val(value);
                   this.$input.select2(this.options.select2);
               } else {
                   //second argument needed to separate initial change from user's click (for autosubmit)   
                   this.$input.val(value).trigger('change', true); 
    
                   //Uncaught Error: cannot call val() if initSelection() is not defined
                   //this.$input.select2('val', value);
               }
    
               // if defined remote source AND no multiple mode AND no user's initSelection provided --> 
               // we should somehow get text for provided id.
               // The solution is to use element's text as text for that id (exclude empty)
               if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) {
                   // customId and customText are methods to extract `id` and `text` from data object
                   // we can use this workaround only if user did not define these methods
                   // otherwise we cant construct data object
                   var customId = this.options.select2.id,
                       customText = this.options.select2.formatSelection;
    
                   if(!customId && !customText) {
                       var $el = $(this.options.scope);
                       if (!$el.data('editable').isEmpty) {
                           var data = {id: value, text: $el.text()};
                           this.$input.select2('data', data); 
                       }
                   }
               }
           },
           
           input2value: function() { 
               return this.$input.select2('val');
           },
    
           str2value: function(str, separator) {
                if(typeof str !== 'string' || !this.isMultiple) {
                    return str;
                }
    
                separator = separator || this.getSeparator();
    
                var val, i, l;
    
                if (str === null || str.length < 1) {
                    return null;
                }
                val = str.split(separator);
                for (i = 0, l = val.length; i < l; i = i + 1) {
                    val[i] = $.trim(val[i]);
                }
    
                return val;
           },
    
            autosubmit: function() {
                this.$input.on('change', function(e, isInitial){
                    if(!isInitial) {
                      $(this).closest('form').submit();
                    }
                });
            },
    
            getSeparator: function() {
                return this.options.select2.separator || $.fn.select2.defaults.separator;
            },
    
            /*
            Converts source from x-editable format: {value: 1, text: "1"} to
            select2 format: {id: 1, text: "1"}
            */
            convertSource: function(source) {
                if($.isArray(source) && source.length && source[0].value !== undefined) {
                    for(var i = 0; i<source.length; i++) {
                        if(source[i].value !== undefined) {
                            source[i].id = source[i].value;
                            delete source[i].value;
                        }
                    }
                }
                return source;
            },
            
            destroy: function() {
                if(this.$input.data('select2')) {
                    this.$input.select2('destroy');
                }
            }
            
        });
    
        Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            /**
            @property tpl 
            @default <input type="hidden">
            **/
            tpl:'<input type="hidden">',
            /**
            Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2).
    
            @property select2 
            @type object
            @default null
            **/
            select2: null,
            /**
            Placeholder attribute of select
    
            @property placeholder 
            @type string
            @default null
            **/
            placeholder: null,
            /**
            Source data for select. It will be assigned to select2 `data` property and kept here just for convenience.
            Please note, that format is different from simple `select` input: use 'id' instead of 'value'.
            E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`.
    
            @property source 
            @type array|string|function
            @default null        
            **/
            source: null,
            /**
            Separator used to display tags.
    
            @property viewseparator 
            @type string
            @default ', '        
            **/
            viewseparator: ', '
        });
    
        $.fn.editabletypes.select2 = Constructor;
    
    }(window.jQuery));
    
    /**
    * Combodate - 1.0.5
    * Dropdown date and time picker.
    * Converts text input into dropdowns to pick day, month, year, hour, minute and second.
    * Uses momentjs as datetime library http://momentjs.com.
    * For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang 
    *
    * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight
    * In combodate: 
    * 12:00 pm --> 12:00 (24-h format, midday)
    * 12:00 am --> 00:00 (24-h format, midnight, start of day)
    * 
    * Differs from momentjs parse rules:
    * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change)
    * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change)
    * 
    * 
    * Author: Vitaliy Potapov
    * Project page: http://github.com/vitalets/combodate
    * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License.
    **/
    (function ($) {
    
        var Combodate = function (element, options) {
            this.$element = $(element);
            if(!this.$element.is('input')) {
                $.error('Combodate should be applied to INPUT element');
                return;
            }
            this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data());
            this.init();  
         };
    
        Combodate.prototype = {
            constructor: Combodate, 
            init: function () {
                this.map = {
                    //key   regexp    moment.method
                    day:    ['D',    'date'], 
                    month:  ['M',    'month'], 
                    year:   ['Y',    'year'], 
                    hour:   ['[Hh]', 'hours'],
                    minute: ['m',    'minutes'], 
                    second: ['s',    'seconds'],
                    ampm:   ['[Aa]', ''] 
                };
                
                this.$widget = $('<span class="combodate"></span>').html(this.getTemplate());
                          
                this.initCombos();
                
                //update original input on change 
                this.$widget.on('change', 'select', $.proxy(function(e) {
                    this.$element.val(this.getValue()).change();
                    // update days count if month or year changes
                    if (this.options.smartDays) {
                        if ($(e.target).is('.month') || $(e.target).is('.year')) {
                            this.fillCombo('day');
                        }
                    }
                }, this));
                
                this.$widget.find('select').css('width', 'auto');
                                           
                // hide original input and insert widget                                       
                this.$element.hide().after(this.$widget);
                
                // set initial value
                this.setValue(this.$element.val() || this.options.value);
            },
            
            /*
             Replace tokens in template with <select> elements 
            */         
            getTemplate: function() {
                var tpl = this.options.template;
    
                //first pass
                $.each(this.map, function(k, v) {
                    v = v[0]; 
                    var r = new RegExp(v+'+'),
                        token = v.length > 1 ? v.substring(1, 2) : v;
                        
                    tpl = tpl.replace(r, '{'+token+'}');
                });
    
                //replace spaces with &nbsp;
                tpl = tpl.replace(/ /g, '&nbsp;');
    
                //second pass
                $.each(this.map, function(k, v) {
                    v = v[0];
                    var token = v.length > 1 ? v.substring(1, 2) : v;
                        
                    tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>');
                });   
    
                return tpl;
            },
            
            /*
             Initialize combos that presents in template 
            */        
            initCombos: function() {
                for (var k in this.map) {
                    var $c = this.$widget.find('.'+k);
                    // set properties like this.$day, this.$month etc.
                    this['$'+k] = $c.length ? $c : null;
                    // fill with items
                    this.fillCombo(k);
                }
            },
    
            /*
             Fill combo with items 
            */        
            fillCombo: function(k) {
                var $combo = this['$'+k];
                if (!$combo) {
                    return;
                }
    
                // define method name to fill items, e.g `fillDays`
                var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); 
                var items = this[f]();
                var value = $combo.val();
    
                $combo.empty();
                for(var i=0; i<items.length; i++) {
                    $combo.append('<option value="'+items[i][0]+'">'+items[i][1]+'</option>');
                }
    
                $combo.val(value);
            },
    
            /*
             Initialize items of combos. Handles `firstItem` option 
            */
            fillCommon: function(key) {
                var values = [],
                    relTime;
                    
                if(this.options.firstItem === 'name') {
                    //need both to support moment ver < 2 and  >= 2
                    relTime = moment.relativeTime || moment.langData()._relativeTime; 
                    var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key];
                    //take last entry (see momentjs lang files structure) 
                    header = header.split(' ').reverse()[0];                
                    values.push(['', header]);
                } else if(this.options.firstItem === 'empty') {
                    values.push(['', '']);
                }
                return values;
            },  
    
    
            /*
            fill day
            */
            fillDay: function() {
                var items = this.fillCommon('d'), name, i,
                    twoDigit = this.options.template.indexOf('DD') !== -1,
                    daysCount = 31;
    
                // detect days count (depends on month and year)
                // originally https://github.com/vitalets/combodate/pull/7
                if (this.options.smartDays && this.$month && this.$year) {
                    var month = parseInt(this.$month.val(), 10);
                    var year = parseInt(this.$year.val(), 10);
    
                    if (!isNaN(month) && !isNaN(year)) {
                        daysCount = moment([year, month]).daysInMonth();
                    }
                }
    
                for (i = 1; i <= daysCount; i++) {
                    name = twoDigit ? this.leadZero(i) : i;
                    items.push([i, name]);
                }
                return items;        
            },
            
            /*
            fill month
            */
            fillMonth: function() {
                var items = this.fillCommon('M'), name, i, 
                    longNames = this.options.template.indexOf('MMMM') !== -1,
                    shortNames = this.options.template.indexOf('MMM') !== -1,
                    twoDigit = this.options.template.indexOf('MM') !== -1;
                    
                for(i=0; i<=11; i++) {
                    if(longNames) {
                        //see https://github.com/timrwood/momentjs.com/pull/36
                        name = moment().date(1).month(i).format('MMMM');
                    } else if(shortNames) {
                        name = moment().date(1).month(i).format('MMM');
                    } else if(twoDigit) {
                        name = this.leadZero(i+1);
                    } else {
                        name = i+1;
                    }
                    items.push([i, name]);
                } 
                return items;
            },  
            
            /*
            fill year
            */
            fillYear: function() {
                var items = [], name, i, 
                    longNames = this.options.template.indexOf('YYYY') !== -1;
               
                for(i=this.options.maxYear; i>=this.options.minYear; i--) {
                    name = longNames ? i : (i+'').substring(2);
                    items[this.options.yearDescending ? 'push' : 'unshift']([i, name]);
                }
                
                items = this.fillCommon('y').concat(items);
                
                return items;              
            },    
            
            /*
            fill hour
            */
            fillHour: function() {
                var items = this.fillCommon('h'), name, i,
                    h12 = this.options.template.indexOf('h') !== -1,
                    h24 = this.options.template.indexOf('H') !== -1,
                    twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1,
                    min = h12 ? 1 : 0, 
                    max = h12 ? 12 : 23;
                    
                for(i=min; i<=max; i++) {
                    name = twoDigit ? this.leadZero(i) : i;
                    items.push([i, name]);
                } 
                return items;                 
            },    
            
            /*
            fill minute
            */
            fillMinute: function() {
                var items = this.fillCommon('m'), name, i,
                    twoDigit = this.options.template.indexOf('mm') !== -1;
    
                for(i=0; i<=59; i+= this.options.minuteStep) {
                    name = twoDigit ? this.leadZero(i) : i;
                    items.push([i, name]);
                }    
                return items;              
            },  
            
            /*
            fill second
            */
            fillSecond: function() {
                var items = this.fillCommon('s'), name, i,
                    twoDigit = this.options.template.indexOf('ss') !== -1;
    
                for(i=0; i<=59; i+= this.options.secondStep) {
                    name = twoDigit ? this.leadZero(i) : i;
                    items.push([i, name]);
                }    
                return items;              
            },  
            
            /*
            fill ampm
            */
            fillAmpm: function() {
                var ampmL = this.options.template.indexOf('a') !== -1,
                    ampmU = this.options.template.indexOf('A') !== -1,            
                    items = [
                        ['am', ampmL ? 'am' : 'AM'],
                        ['pm', ampmL ? 'pm' : 'PM']
                    ];
                return items;                              
            },                                       
    
            /*
             Returns current date value from combos. 
             If format not specified - `options.format` used.
             If format = `null` - Moment object returned.
            */
            getValue: function(format) {
                var dt, values = {}, 
                    that = this,
                    notSelected = false;
                    
                //getting selected values    
                $.each(this.map, function(k, v) {
                    if(k === 'ampm') {
                        return;
                    }
                    var def = k === 'day' ? 1 : 0;
                      
                    values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; 
                    
                    if(isNaN(values[k])) {
                       notSelected = true;
                       return false; 
                    }
                });
                
                //if at least one visible combo not selected - return empty string
                if(notSelected) {
                   return '';
                }
                
                //convert hours 12h --> 24h 
                if(this.$ampm) {
                    //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
                    if(values.hour === 12) {
                        values.hour = this.$ampm.val() === 'am' ? 0 : 12;                    
                    } else {
                        values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12;
                    }
                }    
                
                dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]);
                
                //highlight invalid date
                this.highlight(dt);
                                  
                format = format === undefined ? this.options.format : format;
                if(format === null) {
                   return dt.isValid() ? dt : null; 
                } else {
                   return dt.isValid() ? dt.format(format) : ''; 
                }           
            },
            
            setValue: function(value) {
                if(!value) {
                    return;
                }
                
                var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value),
                    that = this,
                    values = {};
                
                //function to find nearest value in select options
                function getNearest($select, value) {
                    var delta = {};
                    $select.children('option').each(function(i, opt){
                        var optValue = $(opt).attr('value'),
                        distance;
    
                        if(optValue === '') return;
                        distance = Math.abs(optValue - value); 
                        if(typeof delta.distance === 'undefined' || distance < delta.distance) {
                            delta = {value: optValue, distance: distance};
                        } 
                    }); 
                    return delta.value;
                }             
                
                if(dt.isValid()) {
                    //read values from date object
                    $.each(this.map, function(k, v) {
                        if(k === 'ampm') {
                           return; 
                        }
                        values[k] = dt[v[1]]();
                    });
                   
                    if(this.$ampm) {
                        //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
                        if(values.hour >= 12) {
                            values.ampm = 'pm';
                            if(values.hour > 12) {
                                values.hour -= 12;
                            }
                        } else {
                            values.ampm = 'am';
                            if(values.hour === 0) {
                                values.hour = 12;
                            }
                        } 
                    }
                   
                    $.each(values, function(k, v) {
                        //call val() for each existing combo, e.g. this.$hour.val()
                        if(that['$'+k]) {
                           
                            if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) {
                               v = getNearest(that['$'+k], v);
                            }
                           
                            if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) {
                               v = getNearest(that['$'+k], v);
                            }                       
                           
                            that['$'+k].val(v);
                        }
                    });
    
                    // update days count
                    if (this.options.smartDays) {
                        this.fillCombo('day');
                    }
                   
                   this.$element.val(dt.format(this.options.format)).change();
                }
            },
            
            /*
             highlight combos if date is invalid
            */
            highlight: function(dt) {
                if(!dt.isValid()) {
                    if(this.options.errorClass) {
                        this.$widget.addClass(this.options.errorClass);
                    } else {
                        //store original border color
                        if(!this.borderColor) {
                            this.borderColor = this.$widget.find('select').css('border-color'); 
                        }
                        this.$widget.find('select').css('border-color', 'red');
                    } 
                } else {
                    if(this.options.errorClass) {
                        this.$widget.removeClass(this.options.errorClass);
                    } else {
                        this.$widget.find('select').css('border-color', this.borderColor);
                    }  
                }
            },
            
            leadZero: function(v) {
                return v <= 9 ? '0' + v : v; 
            },
            
            destroy: function() {
                this.$widget.remove();
                this.$element.removeData('combodate').show();
            }
            
            //todo: clear method        
        };
    
        $.fn.combodate = function ( option ) {
            var d, args = Array.apply(null, arguments);
            args.shift();
    
            //getValue returns date as string / object (not jQuery object)
            if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) {
              return d.getValue.apply(d, args);
            }        
            
            return this.each(function () {
                var $this = $(this),
                data = $this.data('combodate'),
                options = typeof option == 'object' && option;
                if (!data) {
                    $this.data('combodate', (data = new Combodate(this, options)));
                }
                if (typeof option == 'string' && typeof data[option] == 'function') {
                    data[option].apply(data, args);
                }
            });
        };  
        
        $.fn.combodate.defaults = {
             //in this format value stored in original input
            format: 'DD-MM-YYYY HH:mm',      
            //in this format items in dropdowns are displayed
            template: 'D / MMM / YYYY   H : mm',
            //initial value, can be `new Date()`    
            value: null,                       
            minYear: 1970,
            maxYear: 2015,
            yearDescending: true,
            minuteStep: 5,
            secondStep: 1,
            firstItem: 'empty', //'name', 'empty', 'none'
            errorClass: null,
            roundTime: true, // whether to round minutes and seconds if step > 1
            smartDays: false // whether days in combo depend on selected month: 31, 30, 28
        };
    
    }(window.jQuery));
    /**
    Combodate input - dropdown date and time picker.    
    Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com).
    
        <script src="js/moment.min.js"></script>
       
    Allows to input:
    
    * only date
    * only time 
    * both date and time  
    
    Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker.  
    Internally value stored as `momentjs` object. 
    
    @class combodate
    @extends abstractinput
    @final
    @since 1.4.0
    @example
    <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a>
    <script>
    $(function(){
        $('#dob').editable({
            format: 'YYYY-MM-DD',    
            viewformat: 'DD.MM.YYYY',    
            template: 'D / MMMM / YYYY',    
            combodate: {
                    minYear: 2000,
                    maxYear: 2015,
                    minuteStep: 1
               }
            }
        });
    });
    </script>
    **/
    
    /*global moment*/
    
    (function ($) {
        "use strict";
        
        var Constructor = function (options) {
            this.init('combodate', options, Constructor.defaults);
            
            //by default viewformat equals to format
            if(!this.options.viewformat) {
                this.options.viewformat = this.options.format;
            }        
            
            //try parse combodate config defined as json string in data-combodate
            options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true);
    
            //overriding combodate config (as by default jQuery extend() is not recursive)
            this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, {
                format: this.options.format,
                template: this.options.template
            });
        };
    
        $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);    
        
        $.extend(Constructor.prototype, {
            render: function () {
                this.$input.combodate(this.options.combodate);
                        
                if($.fn.editableform.engine === 'bs3') {
                    this.$input.siblings().find('select').addClass('form-control');
                }
                
                if(this.options.inputclass) {
                    this.$input.siblings().find('select').addClass(this.options.inputclass);
                }            
                //"clear" link
                /*
                if(this.options.clear) {
                    this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
                        e.preventDefault();
                        e.stopPropagation();
                        this.clear();
                    }, this));
                    
                    this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));  
                } 
                */               
            },
            
            value2html: function(value, element) {
                var text = value ? value.format(this.options.viewformat) : '';
                //$(element).text(text);
                Constructor.superclass.value2html.call(this, text, element);  
            },
    
            html2value: function(html) {
                return html ? moment(html, this.options.viewformat) : null;
            },   
            
            value2str: function(value) {
                return value ? value.format(this.options.format) : '';
           }, 
           
           str2value: function(str) {
               return str ? moment(str, this.options.format) : null;
           }, 
           
           value2submit: function(value) {
               return this.value2str(value);
           },                    
    
           value2input: function(value) {
               this.$input.combodate('setValue', value);
           },
            
           input2value: function() { 
               return this.$input.combodate('getValue', null);
           },       
           
           activate: function() {
               this.$input.siblings('.combodate').find('select').eq(0).focus();
           },
           
           /*
           clear:  function() {
              this.$input.data('datepicker').date = null;
              this.$input.find('.active').removeClass('active');
           },
           */
           
           autosubmit: function() {
               
           }
    
        });
        
        Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            /**
            @property tpl 
            @default <input type="text">
            **/         
            tpl:'<input type="text">',
            /**
            @property inputclass 
            @default null
            **/         
            inputclass: null,
            /**
            Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
            See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format)  
            
            @property format 
            @type string
            @default YYYY-MM-DD
            **/         
            format:'YYYY-MM-DD',
            /**
            Format used for displaying date. Also applied when converting date from element's text on init.   
            If not specified equals to `format`.
            
            @property viewformat 
            @type string
            @default null
            **/          
            viewformat: null,        
            /**
            Template used for displaying dropdowns.
            
            @property template 
            @type string
            @default D / MMM / YYYY
            **/          
            template: 'D / MMM / YYYY',  
            /**
            Configuration of combodate.
            Full list of options: http://vitalets.github.com/combodate/#docs
            
            @property combodate 
            @type object
            @default null
            **/
            combodate: null
            
            /*
            (not implemented yet)
            Text shown as clear date button. 
            If <code>false</code> clear button will not be rendered.
            
            @property clear 
            @type boolean|string
            @default 'x clear'         
            */
            //clear: '&times; clear'
        });   
    
        $.fn.editabletypes.combodate = Constructor;
    
    }(window.jQuery));
    
    /*
    Editableform based on Twitter Bootstrap 3
    */
    (function ($) {
        "use strict";
        
        //store parent methods
        var pInitInput = $.fn.editableform.Constructor.prototype.initInput;
        
        $.extend($.fn.editableform.Constructor.prototype, {
            initTemplate: function() {
                this.$form = $($.fn.editableform.template); 
                this.$form.find('.control-group').addClass('form-group');
                this.$form.find('.editable-error-block').addClass('help-block');
            },
            initInput: function() {  
                pInitInput.apply(this);
    
                //for bs3 set default class `input-sm` to standard inputs
                var emptyInputClass = this.input.options.inputclass === null || this.input.options.inputclass === false;
                var defaultClass = 'input-sm';
                
                //bs3 add `form-control` class to standard inputs
                var stdtypes = 'text,select,textarea,password,email,url,tel,number,range,time,typeaheadjs'.split(','); 
                if(~$.inArray(this.input.type, stdtypes)) {
                    this.input.$input.addClass('form-control');
                    if(emptyInputClass) {
                        this.input.options.inputclass = defaultClass;
                        this.input.$input.addClass(defaultClass);
                    }
                }             
            
                //apply bs3 size class also to buttons (to fit size of control)
                var $btn = this.$form.find('.editable-buttons');
                var classes = emptyInputClass ? [defaultClass] : this.input.options.inputclass.split(' ');
                for(var i=0; i<classes.length; i++) {
                    // `btn-sm` is default now
                    /*
                    if(classes[i].toLowerCase() === 'input-sm') { 
                        $btn.find('button').addClass('btn-sm');  
                    }
                    */
                    if(classes[i].toLowerCase() === 'input-lg') {
                        $btn.find('button').removeClass('btn-sm').addClass('btn-lg'); 
                    }
                }
            }
        });    
        
        //buttons
        $.fn.editableform.buttons = 
          '<button type="submit" class="btn btn-primary btn-sm editable-submit">'+
            '<i class="glyphicon glyphicon-ok"></i>'+
          '</button>'+
          '<button type="button" class="btn btn-default btn-sm editable-cancel">'+
            '<i class="glyphicon glyphicon-remove"></i>'+
          '</button>';         
        
        //error classes
        $.fn.editableform.errorGroupClass = 'has-error';
        $.fn.editableform.errorBlockClass = null;  
        //engine
        $.fn.editableform.engine = 'bs3';  
    }(window.jQuery));
    /**
    * Editable Popover3 (for Bootstrap 3) 
    * ---------------------
    * requires bootstrap-popover.js
    */
    (function ($) {
        "use strict";
    
        //extend methods
        $.extend($.fn.editableContainer.Popup.prototype, {
            containerName: 'popover',
            containerDataName: 'bs.popover',
            innerCss: '.popover-content',
            defaults: $.fn.popover.Constructor.DEFAULTS,
    
            initContainer: function(){
                $.extend(this.containerOptions, {
                    trigger: 'manual',
                    selector: false,
                    content: ' ',
                    template: this.defaults.template
                });
                
                //as template property is used in inputs, hide it from popover
                var t;
                if(this.$element.data('template')) {
                   t = this.$element.data('template');
                   this.$element.removeData('template');  
                } 
                
                this.call(this.containerOptions);
                
                if(t) {
                   //restore data('template')
                   this.$element.data('template', t); 
                }
            }, 
            
            /* show */
            innerShow: function () {
                this.call('show');                
            },  
            
            /* hide */
            innerHide: function () {
                this.call('hide');       
            }, 
            
            /* destroy */
            innerDestroy: function() {
                this.call('destroy');
            },                               
            
            setContainerOption: function(key, value) {
                this.container().options[key] = value; 
            },               
    
            /**
            * move popover to new position. This function mainly copied from bootstrap-popover.
            */
            /*jshint laxcomma: true, eqeqeq: false*/
            setPosition: function () { 
    
                (function() {
                /*    
                    var $tip = this.tip()
                    , inside
                    , pos
                    , actualWidth
                    , actualHeight
                    , placement
                    , tp
                    , tpt
                    , tpb
                    , tpl
                    , tpr;
    
                    placement = typeof this.options.placement === 'function' ?
                    this.options.placement.call(this, $tip[0], this.$element[0]) :
                    this.options.placement;
    
                    inside = /in/.test(placement);
                   
                    $tip
                  //  .detach()
                  //vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover
                    .removeClass('top right bottom left')
                    .css({ top: 0, left: 0, display: 'block' });
                  //  .insertAfter(this.$element);
                   
                    pos = this.getPosition(inside);
    
                    actualWidth = $tip[0].offsetWidth;
                    actualHeight = $tip[0].offsetHeight;
    
                    placement = inside ? placement.split(' ')[1] : placement;
    
                    tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
                    tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
                    tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
                    tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
    
                    switch (placement) {
                        case 'bottom':
                            if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) {
                                if (tpt.top > $(window).scrollTop()) {
                                    placement = 'top';
                                } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
                                    placement = 'right';
                                } else if (tpl.left > $(window).scrollLeft()) {
                                    placement = 'left';
                                } else {
                                    placement = 'right';
                                }
                            }
                            break;
                        case 'top':
                            if (tpt.top < $(window).scrollTop()) {
                                if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) {
                                    placement = 'bottom';
                                } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
                                    placement = 'right';
                                } else if (tpl.left > $(window).scrollLeft()) {
                                    placement = 'left';
                                } else {
                                    placement = 'right';
                                }
                            }
                            break;
                        case 'left':
                            if (tpl.left < $(window).scrollLeft()) {
                                if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
                                    placement = 'right';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'top';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'bottom';
                                } else {
                                    placement = 'right';
                                }
                            }
                            break;
                        case 'right':
                            if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) {
                                if (tpl.left > $(window).scrollLeft()) {
                                    placement = 'left';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'top';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'bottom';
                                }
                            }
                            break;
                    }
    
                    switch (placement) {
                        case 'bottom':
                            tp = tpb;
                            break;
                        case 'top':
                            tp = tpt;
                            break;
                        case 'left':
                            tp = tpl;
                            break;
                        case 'right':
                            tp = tpr;
                            break;
                    }
    
                    $tip
                    .offset(tp)
                    .addClass(placement)
                    .addClass('in');
               */
                         
               
                var $tip = this.tip();
                
                var placement = typeof this.options.placement == 'function' ?
                    this.options.placement.call(this, $tip[0], this.$element[0]) :
                    this.options.placement;            
    
                var autoToken = /\s?auto?\s?/i;
                var autoPlace = autoToken.test(placement);
                if (autoPlace) {
                    placement = placement.replace(autoToken, '') || 'top';
                }
                
                
                var pos = this.getPosition();
                var actualWidth = $tip[0].offsetWidth;
                var actualHeight = $tip[0].offsetHeight;
    
                if (autoPlace) {
                    var $parent = this.$element.parent();
    
                    var orgPlacement = placement;
                    var docScroll    = document.documentElement.scrollTop || document.body.scrollTop;
                    var parentWidth  = this.options.container == 'body' ? window.innerWidth  : $parent.outerWidth();
                    var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight();
                    var parentLeft   = this.options.container == 'body' ? 0 : $parent.offset().left;
    
                    placement = placement == 'bottom' && pos.top   + pos.height  + actualHeight - docScroll > parentHeight  ? 'top'    :
                                placement == 'top'    && pos.top   - docScroll   - actualHeight < 0                         ? 'bottom' :
                                placement == 'right'  && pos.right + actualWidth > parentWidth                              ? 'left'   :
                                placement == 'left'   && pos.left  - actualWidth < parentLeft                               ? 'right'  :
                                placement;
    
                    $tip
                      .removeClass(orgPlacement)
                      .addClass(placement);
                }
    
    
                var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight);
    
                this.applyPlacement(calculatedOffset, placement);            
                         
                    
                }).call(this.container());
              /*jshint laxcomma: false, eqeqeq: true*/  
            }            
        });
    
    }(window.jQuery));
    
    /* =========================================================
     * bootstrap-datepicker.js
     * http://www.eyecon.ro/bootstrap-datepicker
     * =========================================================
     * Copyright 2012 Stefan Petre
     * Improvements by Andrew Rowls
     *
     * 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.
     * ========================================================= */
    
    (function( $ ) {
    
        function UTCDate(){
            return new Date(Date.UTC.apply(Date, arguments));
        }
        function UTCToday(){
            var today = new Date();
            return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
        }
    
        // Picker object
    
        var Datepicker = function(element, options) {
            var that = this;
    
            this._process_options(options);
    
            this.element = $(element);
            this.isInline = false;
            this.isInput = this.element.is('input');
            this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false;
            this.hasInput = this.component && this.element.find('input').length;
            if(this.component && this.component.length === 0)
                this.component = false;
    
            this.picker = $(DPGlobal.template);
            this._buildEvents();
            this._attachEvents();
    
            if(this.isInline) {
                this.picker.addClass('datepicker-inline').appendTo(this.element);
            } else {
                this.picker.addClass('datepicker-dropdown dropdown-menu');
            }
    
            if (this.o.rtl){
                this.picker.addClass('datepicker-rtl');
                this.picker.find('.prev i, .next i')
                            .toggleClass('icon-arrow-left icon-arrow-right');
            }
    
    
            this.viewMode = this.o.startView;
    
            if (this.o.calendarWeeks)
                this.picker.find('tfoot th.today')
                            .attr('colspan', function(i, val){
                                return parseInt(val) + 1;
                            });
    
            this._allow_update = false;
    
            this.setStartDate(this.o.startDate);
            this.setEndDate(this.o.endDate);
            this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
    
            this.fillDow();
            this.fillMonths();
    
            this._allow_update = true;
    
            this.update();
            this.showMode();
    
            if(this.isInline) {
                this.show();
            }
        };
    
        Datepicker.prototype = {
            constructor: Datepicker,
    
            _process_options: function(opts){
                // Store raw options for reference
                this._o = $.extend({}, this._o, opts);
                // Processed options
                var o = this.o = $.extend({}, this._o);
    
                // Check if "de-DE" style date is available, if not language should
                // fallback to 2 letter code eg "de"
                var lang = o.language;
                if (!dates[lang]) {
                    lang = lang.split('-')[0];
                    if (!dates[lang])
                        lang = defaults.language;
                }
                o.language = lang;
    
                switch(o.startView){
                    case 2:
                    case 'decade':
                        o.startView = 2;
                        break;
                    case 1:
                    case 'year':
                        o.startView = 1;
                        break;
                    default:
                        o.startView = 0;
                }
    
                switch (o.minViewMode) {
                    case 1:
                    case 'months':
                        o.minViewMode = 1;
                        break;
                    case 2:
                    case 'years':
                        o.minViewMode = 2;
                        break;
                    default:
                        o.minViewMode = 0;
                }
    
                o.startView = Math.max(o.startView, o.minViewMode);
    
                o.weekStart %= 7;
                o.weekEnd = ((o.weekStart + 6) % 7);
    
                var format = DPGlobal.parseFormat(o.format)
                if (o.startDate !== -Infinity) {
                    o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
                }
                if (o.endDate !== Infinity) {
                    o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
                }
    
                o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
                if (!$.isArray(o.daysOfWeekDisabled))
                    o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
                o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) {
                    return parseInt(d, 10);
                });
            },
            _events: [],
            _secondaryEvents: [],
            _applyEvents: function(evs){
                for (var i=0, el, ev; i<evs.length; i++){
                    el = evs[i][0];
                    ev = evs[i][1];
                    el.on(ev);
                }
            },
            _unapplyEvents: function(evs){
                for (var i=0, el, ev; i<evs.length; i++){
                    el = evs[i][0];
                    ev = evs[i][1];
                    el.off(ev);
                }
            },
            _buildEvents: function(){
                if (this.isInput) { // single input
                    this._events = [
                        [this.element, {
                            focus: $.proxy(this.show, this),
                            keyup: $.proxy(this.update, this),
                            keydown: $.proxy(this.keydown, this)
                        }]
                    ];
                }
                else if (this.component && this.hasInput){ // component: input + button
                    this._events = [
                        // For components that are not readonly, allow keyboard nav
                        [this.element.find('input'), {
                            focus: $.proxy(this.show, this),
                            keyup: $.proxy(this.update, this),
                            keydown: $.proxy(this.keydown, this)
                        }],
                        [this.component, {
                            click: $.proxy(this.show, this)
                        }]
                    ];
                }
                else if (this.element.is('div')) {  // inline datepicker
                    this.isInline = true;
                }
                else {
                    this._events = [
                        [this.element, {
                            click: $.proxy(this.show, this)
                        }]
                    ];
                }
    
                this._secondaryEvents = [
                    [this.picker, {
                        click: $.proxy(this.click, this)
                    }],
                    [$(window), {
                        resize: $.proxy(this.place, this)
                    }],
                    [$(document), {
                        mousedown: $.proxy(function (e) {
                            // Clicked outside the datepicker, hide it
                            if (!(
                                this.element.is(e.target) ||
                                this.element.find(e.target).size() ||
                                this.picker.is(e.target) ||
                                this.picker.find(e.target).size()
                            )) {
                                this.hide();
                            }
                        }, this)
                    }]
                ];
            },
            _attachEvents: function(){
                this._detachEvents();
                this._applyEvents(this._events);
            },
            _detachEvents: function(){
                this._unapplyEvents(this._events);
            },
            _attachSecondaryEvents: function(){
                this._detachSecondaryEvents();
                this._applyEvents(this._secondaryEvents);
            },
            _detachSecondaryEvents: function(){
                this._unapplyEvents(this._secondaryEvents);
            },
            _trigger: function(event, altdate){
                var date = altdate || this.date,
                    local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000));
    
                this.element.trigger({
                    type: event,
                    date: local_date,
                    format: $.proxy(function(altformat){
                        var format = altformat || this.o.format;
                        return DPGlobal.formatDate(date, format, this.o.language);
                    }, this)
                });
            },
    
            show: function(e) {
                if (!this.isInline)
                    this.picker.appendTo('body');
                this.picker.show();
                this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
                this.place();
                this._attachSecondaryEvents();
                if (e) {
                    e.preventDefault();
                }
                this._trigger('show');
            },
    
            hide: function(e){
                if(this.isInline) return;
                if (!this.picker.is(':visible')) return;
                this.picker.hide().detach();
                this._detachSecondaryEvents();
                this.viewMode = this.o.startView;
                this.showMode();
    
                if (
                    this.o.forceParse &&
                    (
                        this.isInput && this.element.val() ||
                        this.hasInput && this.element.find('input').val()
                    )
                )
                    this.setValue();
                this._trigger('hide');
            },
    
            remove: function() {
                this.hide();
                this._detachEvents();
                this._detachSecondaryEvents();
                this.picker.remove();
                delete this.element.data().datepicker;
                if (!this.isInput) {
                    delete this.element.data().date;
                }
            },
    
            getDate: function() {
                var d = this.getUTCDate();
                return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
            },
    
            getUTCDate: function() {
                return this.date;
            },
    
            setDate: function(d) {
                this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
            },
    
            setUTCDate: function(d) {
                this.date = d;
                this.setValue();
            },
    
            setValue: function() {
                var formatted = this.getFormattedDate();
                if (!this.isInput) {
                    if (this.component){
                        this.element.find('input').val(formatted);
                    }
                } else {
                    this.element.val(formatted);
                }
            },
    
            getFormattedDate: function(format) {
                if (format === undefined)
                    format = this.o.format;
                return DPGlobal.formatDate(this.date, format, this.o.language);
            },
    
            setStartDate: function(startDate){
                this._process_options({startDate: startDate});
                this.update();
                this.updateNavArrows();
            },
    
            setEndDate: function(endDate){
                this._process_options({endDate: endDate});
                this.update();
                this.updateNavArrows();
            },
    
            setDaysOfWeekDisabled: function(daysOfWeekDisabled){
                this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
                this.update();
                this.updateNavArrows();
            },
    
            place: function(){
                            if(this.isInline) return;
                var zIndex = parseInt(this.element.parents().filter(function() {
                                return $(this).css('z-index') != 'auto';
                            }).first().css('z-index'))+10;
                var offset = this.component ? this.component.parent().offset() : this.element.offset();
                var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true);
                this.picker.css({
                    top: offset.top + height,
                    left: offset.left,
                    zIndex: zIndex
                });
            },
    
            _allow_update: true,
            update: function(){
                if (!this._allow_update) return;
    
                var date, fromArgs = false;
                if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
                    date = arguments[0];
                    fromArgs = true;
                } else {
                    date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
                    delete this.element.data().date;
                }
    
                this.date = DPGlobal.parseDate(date, this.o.format, this.o.language);
    
                if(fromArgs) this.setValue();
    
                if (this.date < this.o.startDate) {
                    this.viewDate = new Date(this.o.startDate);
                } else if (this.date > this.o.endDate) {
                    this.viewDate = new Date(this.o.endDate);
                } else {
                    this.viewDate = new Date(this.date);
                }
                this.fill();
            },
    
            fillDow: function(){
                var dowCnt = this.o.weekStart,
                html = '<tr>';
                if(this.o.calendarWeeks){
                    var cell = '<th class="cw">&nbsp;</th>';
                    html += cell;
                    this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
                }
                while (dowCnt < this.o.weekStart + 7) {
                    html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
                }
                html += '</tr>';
                this.picker.find('.datepicker-days thead').append(html);
            },
    
            fillMonths: function(){
                var html = '',
                i = 0;
                while (i < 12) {
                    html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
                }
                this.picker.find('.datepicker-months td').html(html);
            },
    
            setRange: function(range){
                if (!range || !range.length)
                    delete this.range;
                else
                    this.range = $.map(range, function(d){ return d.valueOf(); });
                this.fill();
            },
    
            getClassNames: function(date){
                var cls = [],
                    year = this.viewDate.getUTCFullYear(),
                    month = this.viewDate.getUTCMonth(),
                    currentDate = this.date.valueOf(),
                    today = new Date();
                if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) {
                    cls.push('old');
                } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) {
                    cls.push('new');
                }
                // Compare internal UTC date with local today, not UTC today
                if (this.o.todayHighlight &&
                    date.getUTCFullYear() == today.getFullYear() &&
                    date.getUTCMonth() == today.getMonth() &&
                    date.getUTCDate() == today.getDate()) {
                    cls.push('today');
                }
                if (currentDate && date.valueOf() == currentDate) {
                    cls.push('active');
                }
                if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
                    $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) {
                    cls.push('disabled');
                }
                if (this.range){
                    if (date > this.range[0] && date < this.range[this.range.length-1]){
                        cls.push('range');
                    }
                    if ($.inArray(date.valueOf(), this.range) != -1){
                        cls.push('selected');
                    }
                }
                return cls;
            },
    
            fill: function() {
                var d = new Date(this.viewDate),
                    year = d.getUTCFullYear(),
                    month = d.getUTCMonth(),
                    startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
                    startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
                    endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
                    endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
                    currentDate = this.date && this.date.valueOf(),
                    tooltip;
                this.picker.find('.datepicker-days thead th.datepicker-switch')
                            .text(dates[this.o.language].months[month]+' '+year);
                this.picker.find('tfoot th.today')
                            .text(dates[this.o.language].today)
                            .toggle(this.o.todayBtn !== false);
                this.picker.find('tfoot th.clear')
                            .text(dates[this.o.language].clear)
                            .toggle(this.o.clearBtn !== false);
                this.updateNavArrows();
                this.fillMonths();
                var prevMonth = UTCDate(year, month-1, 28,0,0,0,0),
                    day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
                prevMonth.setUTCDate(day);
                prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
                var nextMonth = new Date(prevMonth);
                nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
                nextMonth = nextMonth.valueOf();
                var html = [];
                var clsName;
                while(prevMonth.valueOf() < nextMonth) {
                    if (prevMonth.getUTCDay() == this.o.weekStart) {
                        html.push('<tr>');
                        if(this.o.calendarWeeks){
                            // ISO 8601: First week contains first thursday.
                            // ISO also states week starts on Monday, but we can be more abstract here.
                            var
                                // Start of current week: based on weekstart/current date
                                ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
                                // Thursday of this week
                                th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
                                // First Thursday of year, year from thursday
                                yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
                                // Calendar week: ms between thursdays, div ms per day, div 7 days
                                calWeek =  (th - yth) / 864e5 / 7 + 1;
                            html.push('<td class="cw">'+ calWeek +'</td>');
    
                        }
                    }
                    clsName = this.getClassNames(prevMonth);
                    clsName.push('day');
    
                    var before = this.o.beforeShowDay(prevMonth);
                    if (before === undefined)
                        before = {};
                    else if (typeof(before) === 'boolean')
                        before = {enabled: before};
                    else if (typeof(before) === 'string')
                        before = {classes: before};
                    if (before.enabled === false)
                        clsName.push('disabled');
                    if (before.classes)
                        clsName = clsName.concat(before.classes.split(/\s+/));
                    if (before.tooltip)
                        tooltip = before.tooltip;
    
                    clsName = $.unique(clsName);
                    html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
                    if (prevMonth.getUTCDay() == this.o.weekEnd) {
                        html.push('</tr>');
                    }
                    prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
                }
                this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
                var currentYear = this.date && this.date.getUTCFullYear();
    
                var months = this.picker.find('.datepicker-months')
                            .find('th:eq(1)')
                                .text(year)
                                .end()
                            .find('span').removeClass('active');
                if (currentYear && currentYear == year) {
                    months.eq(this.date.getUTCMonth()).addClass('active');
                }
                if (year < startYear || year > endYear) {
                    months.addClass('disabled');
                }
                if (year == startYear) {
                    months.slice(0, startMonth).addClass('disabled');
                }
                if (year == endYear) {
                    months.slice(endMonth+1).addClass('disabled');
                }
    
                html = '';
                year = parseInt(year/10, 10) * 10;
                var yearCont = this.picker.find('.datepicker-years')
                                    .find('th:eq(1)')
                                        .text(year + '-' + (year + 9))
                                        .end()
                                    .find('td');
                year -= 1;
                for (var i = -1; i < 11; i++) {
                    html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>';
                    year += 1;
                }
                yearCont.html(html);
            },
    
            updateNavArrows: function() {
                if (!this._allow_update) return;
    
                var d = new Date(this.viewDate),
                    year = d.getUTCFullYear(),
                    month = d.getUTCMonth();
                switch (this.viewMode) {
                    case 0:
                        if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) {
                            this.picker.find('.prev').css({visibility: 'hidden'});
                        } else {
                            this.picker.find('.prev').css({visibility: 'visible'});
                        }
                        if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) {
                            this.picker.find('.next').css({visibility: 'hidden'});
                        } else {
                            this.picker.find('.next').css({visibility: 'visible'});
                        }
                        break;
                    case 1:
                    case 2:
                        if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) {
                            this.picker.find('.prev').css({visibility: 'hidden'});
                        } else {
                            this.picker.find('.prev').css({visibility: 'visible'});
                        }
                        if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) {
                            this.picker.find('.next').css({visibility: 'hidden'});
                        } else {
                            this.picker.find('.next').css({visibility: 'visible'});
                        }
                        break;
                }
            },
    
            click: function(e) {
                e.preventDefault();
                var target = $(e.target).closest('span, td, th');
                if (target.length == 1) {
                    switch(target[0].nodeName.toLowerCase()) {
                        case 'th':
                            switch(target[0].className) {
                                case 'datepicker-switch':
                                    this.showMode(1);
                                    break;
                                case 'prev':
                                case 'next':
                                    var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
                                    switch(this.viewMode){
                                        case 0:
                                            this.viewDate = this.moveMonth(this.viewDate, dir);
                                            break;
                                        case 1:
                                        case 2:
                                            this.viewDate = this.moveYear(this.viewDate, dir);
                                            break;
                                    }
                                    this.fill();
                                    break;
                                case 'today':
                                    var date = new Date();
                                    date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
    
                                    this.showMode(-2);
                                    var which = this.o.todayBtn == 'linked' ? null : 'view';
                                    this._setDate(date, which);
                                    break;
                                case 'clear':
                                    var element;
                                    if (this.isInput)
                                        element = this.element;
                                    else if (this.component)
                                        element = this.element.find('input');
                                    if (element)
                                        element.val("").change();
                                    this._trigger('changeDate');
                                    this.update();
                                    if (this.o.autoclose)
                                        this.hide();
                                    break;
                            }
                            break;
                        case 'span':
                            if (!target.is('.disabled')) {
                                this.viewDate.setUTCDate(1);
                                if (target.is('.month')) {
                                    var day = 1;
                                    var month = target.parent().find('span').index(target);
                                    var year = this.viewDate.getUTCFullYear();
                                    this.viewDate.setUTCMonth(month);
                                    this._trigger('changeMonth', this.viewDate);
                                    if (this.o.minViewMode === 1) {
                                        this._setDate(UTCDate(year, month, day,0,0,0,0));
                                    }
                                } else {
                                    var year = parseInt(target.text(), 10)||0;
                                    var day = 1;
                                    var month = 0;
                                    this.viewDate.setUTCFullYear(year);
                                    this._trigger('changeYear', this.viewDate);
                                    if (this.o.minViewMode === 2) {
                                        this._setDate(UTCDate(year, month, day,0,0,0,0));
                                    }
                                }
                                this.showMode(-1);
                                this.fill();
                            }
                            break;
                        case 'td':
                            if (target.is('.day') && !target.is('.disabled')){
                                var day = parseInt(target.text(), 10)||1;
                                var year = this.viewDate.getUTCFullYear(),
                                    month = this.viewDate.getUTCMonth();
                                if (target.is('.old')) {
                                    if (month === 0) {
                                        month = 11;
                                        year -= 1;
                                    } else {
                                        month -= 1;
                                    }
                                } else if (target.is('.new')) {
                                    if (month == 11) {
                                        month = 0;
                                        year += 1;
                                    } else {
                                        month += 1;
                                    }
                                }
                                this._setDate(UTCDate(year, month, day,0,0,0,0));
                            }
                            break;
                    }
                }
            },
    
            _setDate: function(date, which){
                if (!which || which == 'date')
                    this.date = new Date(date);
                if (!which || which  == 'view')
                    this.viewDate = new Date(date);
                this.fill();
                this.setValue();
                this._trigger('changeDate');
                var element;
                if (this.isInput) {
                    element = this.element;
                } else if (this.component){
                    element = this.element.find('input');
                }
                if (element) {
                    element.change();
                    if (this.o.autoclose && (!which || which == 'date')) {
                        this.hide();
                    }
                }
            },
    
            moveMonth: function(date, dir){
                if (!dir) return date;
                var new_date = new Date(date.valueOf()),
                    day = new_date.getUTCDate(),
                    month = new_date.getUTCMonth(),
                    mag = Math.abs(dir),
                    new_month, test;
                dir = dir > 0 ? 1 : -1;
                if (mag == 1){
                    test = dir == -1
                        // If going back one month, make sure month is not current month
                        // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
                        ? function(){ return new_date.getUTCMonth() == month; }
                        // If going forward one month, make sure month is as expected
                        // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
                        : function(){ return new_date.getUTCMonth() != new_month; };
                    new_month = month + dir;
                    new_date.setUTCMonth(new_month);
                    // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
                    if (new_month < 0 || new_month > 11)
                        new_month = (new_month + 12) % 12;
                } else {
                    // For magnitudes >1, move one month at a time...
                    for (var i=0; i<mag; i++)
                        // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
                        new_date = this.moveMonth(new_date, dir);
                    // ...then reset the day, keeping it in the new month
                    new_month = new_date.getUTCMonth();
                    new_date.setUTCDate(day);
                    test = function(){ return new_month != new_date.getUTCMonth(); };
                }
                // Common date-resetting loop -- if date is beyond end of month, make it
                // end of month
                while (test()){
                    new_date.setUTCDate(--day);
                    new_date.setUTCMonth(new_month);
                }
                return new_date;
            },
    
            moveYear: function(date, dir){
                return this.moveMonth(date, dir*12);
            },
    
            dateWithinRange: function(date){
                return date >= this.o.startDate && date <= this.o.endDate;
            },
    
            keydown: function(e){
                if (this.picker.is(':not(:visible)')){
                    if (e.keyCode == 27) // allow escape to hide and re-show picker
                        this.show();
                    return;
                }
                var dateChanged = false,
                    dir, day, month,
                    newDate, newViewDate;
                switch(e.keyCode){
                    case 27: // escape
                        this.hide();
                        e.preventDefault();
                        break;
                    case 37: // left
                    case 39: // right
                        if (!this.o.keyboardNavigation) break;
                        dir = e.keyCode == 37 ? -1 : 1;
                        if (e.ctrlKey){
                            newDate = this.moveYear(this.date, dir);
                            newViewDate = this.moveYear(this.viewDate, dir);
                        } else if (e.shiftKey){
                            newDate = this.moveMonth(this.date, dir);
                            newViewDate = this.moveMonth(this.viewDate, dir);
                        } else {
                            newDate = new Date(this.date);
                            newDate.setUTCDate(this.date.getUTCDate() + dir);
                            newViewDate = new Date(this.viewDate);
                            newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
                        }
                        if (this.dateWithinRange(newDate)){
                            this.date = newDate;
                            this.viewDate = newViewDate;
                            this.setValue();
                            this.update();
                            e.preventDefault();
                            dateChanged = true;
                        }
                        break;
                    case 38: // up
                    case 40: // down
                        if (!this.o.keyboardNavigation) break;
                        dir = e.keyCode == 38 ? -1 : 1;
                        if (e.ctrlKey){
                            newDate = this.moveYear(this.date, dir);
                            newViewDate = this.moveYear(this.viewDate, dir);
                        } else if (e.shiftKey){
                            newDate = this.moveMonth(this.date, dir);
                            newViewDate = this.moveMonth(this.viewDate, dir);
                        } else {
                            newDate = new Date(this.date);
                            newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
                            newViewDate = new Date(this.viewDate);
                            newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
                        }
                        if (this.dateWithinRange(newDate)){
                            this.date = newDate;
                            this.viewDate = newViewDate;
                            this.setValue();
                            this.update();
                            e.preventDefault();
                            dateChanged = true;
                        }
                        break;
                    case 13: // enter
                        this.hide();
                        e.preventDefault();
                        break;
                    case 9: // tab
                        this.hide();
                        break;
                }
                if (dateChanged){
                    this._trigger('changeDate');
                    var element;
                    if (this.isInput) {
                        element = this.element;
                    } else if (this.component){
                        element = this.element.find('input');
                    }
                    if (element) {
                        element.change();
                    }
                }
            },
    
            showMode: function(dir) {
                if (dir) {
                    this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
                }
                /*
                    vitalets: fixing bug of very special conditions:
                    jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
                    Method show() does not set display css correctly and datepicker is not shown.
                    Changed to .css('display', 'block') solve the problem.
                    See https://github.com/vitalets/x-editable/issues/37
    
                    In jquery 1.7.2+ everything works fine.
                */
                //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
                this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
                this.updateNavArrows();
            }
        };
    
        var DateRangePicker = function(element, options){
            this.element = $(element);
            this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; });
            delete options.inputs;
    
            $(this.inputs)
                .datepicker(options)
                .bind('changeDate', $.proxy(this.dateUpdated, this));
    
            this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); });
            this.updateDates();
        };
        DateRangePicker.prototype = {
            updateDates: function(){
                this.dates = $.map(this.pickers, function(i){ return i.date; });
                this.updateRanges();
            },
            updateRanges: function(){
                var range = $.map(this.dates, function(d){ return d.valueOf(); });
                $.each(this.pickers, function(i, p){
                    p.setRange(range);
                });
            },
            dateUpdated: function(e){
                var dp = $(e.target).data('datepicker'),
                    new_date = dp.getUTCDate(),
                    i = $.inArray(e.target, this.inputs),
                    l = this.inputs.length;
                if (i == -1) return;
    
                if (new_date < this.dates[i]){
                    // Date being moved earlier/left
                    while (i>=0 && new_date < this.dates[i]){
                        this.pickers[i--].setUTCDate(new_date);
                    }
                }
                else if (new_date > this.dates[i]){
                    // Date being moved later/right
                    while (i<l && new_date > this.dates[i]){
                        this.pickers[i++].setUTCDate(new_date);
                    }
                }
                this.updateDates();
            },
            remove: function(){
                $.map(this.pickers, function(p){ p.remove(); });
                delete this.element.data().datepicker;
            }
        };
    
        function opts_from_el(el, prefix){
            // Derive options from element data-attrs
            var data = $(el).data(),
                out = {}, inkey,
                replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'),
                prefix = new RegExp('^' + prefix.toLowerCase());
            for (var key in data)
                if (prefix.test(key)){
                    inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); });
                    out[inkey] = data[key];
                }
            return out;
        }
    
        function opts_from_locale(lang){
            // Derive options from locale plugins
            var out = {};
            // Check if "de-DE" style date is available, if not language should
            // fallback to 2 letter code eg "de"
            if (!dates[lang]) {
                lang = lang.split('-')[0]
                if (!dates[lang])
                    return;
            }
            var d = dates[lang];
            $.each(locale_opts, function(i,k){
                if (k in d)
                    out[k] = d[k];
            });
            return out;
        }
    
        var old = $.fn.datepicker;
        var datepicker = $.fn.datepicker = function ( option ) {
            var args = Array.apply(null, arguments);
            args.shift();
            var internal_return,
                this_return;
            this.each(function () {
                var $this = $(this),
                    data = $this.data('datepicker'),
                    options = typeof option == 'object' && option;
                if (!data) {
                    var elopts = opts_from_el(this, 'date'),
                        // Preliminary otions
                        xopts = $.extend({}, defaults, elopts, options),
                        locopts = opts_from_locale(xopts.language),
                        // Options priority: js args, data-attrs, locales, defaults
                        opts = $.extend({}, defaults, locopts, elopts, options);
                    if ($this.is('.input-daterange') || opts.inputs){
                        var ropts = {
                            inputs: opts.inputs || $this.find('input').toArray()
                        };
                        $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
                    }
                    else{
                        $this.data('datepicker', (data = new Datepicker(this, opts)));
                    }
                }
                if (typeof option == 'string' && typeof data[option] == 'function') {
                    internal_return = data[option].apply(data, args);
                    if (internal_return !== undefined)
                        return false;
                }
            });
            if (internal_return !== undefined)
                return internal_return;
            else
                return this;
        };
    
        var defaults = $.fn.datepicker.defaults = {
            autoclose: false,
            beforeShowDay: $.noop,
            calendarWeeks: false,
            clearBtn: false,
            daysOfWeekDisabled: [],
            endDate: Infinity,
            forceParse: true,
            format: 'mm/dd/yyyy',
            keyboardNavigation: true,
            language: 'en',
            minViewMode: 0,
            rtl: false,
            startDate: -Infinity,
            startView: 0,
            todayBtn: false,
            todayHighlight: false,
            weekStart: 0
        };
        var locale_opts = $.fn.datepicker.locale_opts = [
            'format',
            'rtl',
            'weekStart'
        ];
        $.fn.datepicker.Constructor = Datepicker;
        var dates = $.fn.datepicker.dates = {
            en: {
                days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
                daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
                daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
                months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                today: "Today",
                clear: "Clear"
            }
        };
    
        var DPGlobal = {
            modes: [
                {
                    clsName: 'days',
                    navFnc: 'Month',
                    navStep: 1
                },
                {
                    clsName: 'months',
                    navFnc: 'FullYear',
                    navStep: 1
                },
                {
                    clsName: 'years',
                    navFnc: 'FullYear',
                    navStep: 10
            }],
            isLeapYear: function (year) {
                return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
            },
            getDaysInMonth: function (year, month) {
                return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
            },
            validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
            nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
            parseFormat: function(format){
                // IE treats \0 as a string end in inputs (truncating the value),
                // so it's a bad format delimiter, anyway
                var separators = format.replace(this.validParts, '\0').split('\0'),
                    parts = format.match(this.validParts);
                if (!separators || !separators.length || !parts || parts.length === 0){
                    throw new Error("Invalid date format.");
                }
                return {separators: separators, parts: parts};
            },
            parseDate: function(date, format, language) {
                if (date instanceof Date) return date;
                if (typeof format === 'string')
                    format = DPGlobal.parseFormat(format);
                if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
                    var part_re = /([\-+]\d+)([dmwy])/,
                        parts = date.match(/([\-+]\d+)([dmwy])/g),
                        part, dir;
                    date = new Date();
                    for (var i=0; i<parts.length; i++) {
                        part = part_re.exec(parts[i]);
                        dir = parseInt(part[1]);
                        switch(part[2]){
                            case 'd':
                                date.setUTCDate(date.getUTCDate() + dir);
                                break;
                            case 'm':
                                date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
                                break;
                            case 'w':
                                date.setUTCDate(date.getUTCDate() + dir * 7);
                                break;
                            case 'y':
                                date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
                                break;
                        }
                    }
                    return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
                }
                var parts = date && date.match(this.nonpunctuation) || [],
                    date = new Date(),
                    parsed = {},
                    setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
                    setters_map = {
                        yyyy: function(d,v){ return d.setUTCFullYear(v); },
                        yy: function(d,v){ return d.setUTCFullYear(2000+v); },
                        m: function(d,v){
                            v -= 1;
                            while (v<0) v += 12;
                            v %= 12;
                            d.setUTCMonth(v);
                            while (d.getUTCMonth() != v)
                                d.setUTCDate(d.getUTCDate()-1);
                            return d;
                        },
                        d: function(d,v){ return d.setUTCDate(v); }
                    },
                    val, filtered, part;
                setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
                setters_map['dd'] = setters_map['d'];
                date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
                var fparts = format.parts.slice();
                // Remove noop parts
                if (parts.length != fparts.length) {
                    fparts = $(fparts).filter(function(i,p){
                        return $.inArray(p, setters_order) !== -1;
                    }).toArray();
                }
                // Process remainder
                if (parts.length == fparts.length) {
                    for (var i=0, cnt = fparts.length; i < cnt; i++) {
                        val = parseInt(parts[i], 10);
                        part = fparts[i];
                        if (isNaN(val)) {
                            switch(part) {
                                case 'MM':
                                    filtered = $(dates[language].months).filter(function(){
                                        var m = this.slice(0, parts[i].length),
                                            p = parts[i].slice(0, m.length);
                                        return m == p;
                                    });
                                    val = $.inArray(filtered[0], dates[language].months) + 1;
                                    break;
                                case 'M':
                                    filtered = $(dates[language].monthsShort).filter(function(){
                                        var m = this.slice(0, parts[i].length),
                                            p = parts[i].slice(0, m.length);
                                        return m == p;
                                    });
                                    val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
                                    break;
                            }
                        }
                        parsed[part] = val;
                    }
                    for (var i=0, s; i<setters_order.length; i++){
                        s = setters_order[i];
                        if (s in parsed && !isNaN(parsed[s]))
                            setters_map[s](date, parsed[s]);
                    }
                }
                return date;
            },
            formatDate: function(date, format, language){
                if (typeof format === 'string')
                    format = DPGlobal.parseFormat(format);
                var val = {
                    d: date.getUTCDate(),
                    D: dates[language].daysShort[date.getUTCDay()],
                    DD: dates[language].days[date.getUTCDay()],
                    m: date.getUTCMonth() + 1,
                    M: dates[language].monthsShort[date.getUTCMonth()],
                    MM: dates[language].months[date.getUTCMonth()],
                    yy: date.getUTCFullYear().toString().substring(2),
                    yyyy: date.getUTCFullYear()
                };
                val.dd = (val.d < 10 ? '0' : '') + val.d;
                val.mm = (val.m < 10 ? '0' : '') + val.m;
                var date = [],
                    seps = $.extend([], format.separators);
                for (var i=0, cnt = format.parts.length; i <= cnt; i++) {
                    if (seps.length)
                        date.push(seps.shift());
                    date.push(val[format.parts[i]]);
                }
                return date.join('');
            },
            headTemplate: '<thead>'+
                                '<tr>'+
                                    '<th class="prev"><i class="icon-arrow-left"/></th>'+
                                    '<th colspan="5" class="datepicker-switch"></th>'+
                                    '<th class="next"><i class="icon-arrow-right"/></th>'+
                                '</tr>'+
                            '</thead>',
            contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
            footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
        };
        DPGlobal.template = '<div class="datepicker">'+
                                '<div class="datepicker-days">'+
                                    '<table class=" table-condensed">'+
                                        DPGlobal.headTemplate+
                                        '<tbody></tbody>'+
                                        DPGlobal.footTemplate+
                                    '</table>'+
                                '</div>'+
                                '<div class="datepicker-months">'+
                                    '<table class="table-condensed">'+
                                        DPGlobal.headTemplate+
                                        DPGlobal.contTemplate+
                                        DPGlobal.footTemplate+
                                    '</table>'+
                                '</div>'+
                                '<div class="datepicker-years">'+
                                    '<table class="table-condensed">'+
                                        DPGlobal.headTemplate+
                                        DPGlobal.contTemplate+
                                        DPGlobal.footTemplate+
                                    '</table>'+
                                '</div>'+
                            '</div>';
    
        $.fn.datepicker.DPGlobal = DPGlobal;
    
    
        /* DATEPICKER NO CONFLICT
        * =================== */
    
        $.fn.datepicker.noConflict = function(){
            $.fn.datepicker = old;
            return this;
        };
    
    
        /* DATEPICKER DATA-API
        * ================== */
    
        $(document).on(
            'focus.datepicker.data-api click.datepicker.data-api',
            '[data-provide="datepicker"]',
            function(e){
                var $this = $(this);
                if ($this.data('datepicker')) return;
                e.preventDefault();
                // component click requires us to explicitly show it
                datepicker.call($this, 'show');
            }
        );
        $(function(){
            //$('[data-provide="datepicker-inline"]').datepicker();
            //vit: changed to support noConflict()
            datepicker.call($('[data-provide="datepicker-inline"]'));
        });
    
    }( window.jQuery ));
    
    /**
    Bootstrap-datepicker.  
    Description and examples: https://github.com/eternicode/bootstrap-datepicker.  
    For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales
    and set `language` option.  
    Since 1.4.0 date has different appearance in **popup** and **inline** modes. 
    
    @class date
    @extends abstractinput
    @final
    @example
    <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a>
    <script>
    $(function(){
        $('#dob').editable({
            format: 'yyyy-mm-dd',    
            viewformat: 'dd/mm/yyyy',    
            datepicker: {
                    weekStart: 1
               }
            }
        });
    });
    </script>
    **/
    (function ($) {
        "use strict";
        
        //store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one
        $.fn.bdatepicker = $.fn.datepicker.noConflict();
        if(!$.fn.datepicker) { //if there were no other datepickers, keep also original name
            $.fn.datepicker = $.fn.bdatepicker;    
        }    
        
        var Date = function (options) {
            this.init('date', options, Date.defaults);
            this.initPicker(options, Date.defaults);
        };
    
        $.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput);    
        
        $.extend(Date.prototype, {
            initPicker: function(options, defaults) {
                //'format' is set directly from settings or data-* attributes
    
                //by default viewformat equals to format
                if(!this.options.viewformat) {
                    this.options.viewformat = this.options.format;
                }
                
                //try parse datepicker config defined as json string in data-datepicker
                options.datepicker = $.fn.editableutils.tryParseJson(options.datepicker, true);
                
                //overriding datepicker config (as by default jQuery extend() is not recursive)
                //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only
                this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, {
                    format: this.options.viewformat
                });
                
                //language
                this.options.datepicker.language = this.options.datepicker.language || 'en'; 
    
                //store DPglobal
                this.dpg = $.fn.bdatepicker.DPGlobal; 
    
                //store parsed formats
                this.parsedFormat = this.dpg.parseFormat(this.options.format);
                this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat);            
            },
            
            render: function () {
                this.$input.bdatepicker(this.options.datepicker);
                
                //"clear" link
                if(this.options.clear) {
                    this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
                        e.preventDefault();
                        e.stopPropagation();
                        this.clear();
                    }, this));
                    
                    this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));  
                }                
            },
            
            value2html: function(value, element) {
               var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : '';
               Date.superclass.value2html.call(this, text, element); 
            },
    
            html2value: function(html) {
                return this.parseDate(html, this.parsedViewFormat);
            },   
    
            value2str: function(value) {
                return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : '';
            }, 
    
            str2value: function(str) {
                return this.parseDate(str, this.parsedFormat);
            }, 
    
            value2submit: function(value) {
                return this.value2str(value);
            },                    
    
            value2input: function(value) {
                this.$input.bdatepicker('update', value);
            },
    
            input2value: function() { 
                return this.$input.data('datepicker').date;
            },       
    
            activate: function() {
            },
    
            clear:  function() {
                this.$input.data('datepicker').date = null;
                this.$input.find('.active').removeClass('active');
                if(!this.options.showbuttons) {
                    this.$input.closest('form').submit(); 
                }
            },
    
            autosubmit: function() {
                this.$input.on('mouseup', '.day', function(e){
                    if($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) {
                        return;
                    }
                    var $form = $(this).closest('form');
                    setTimeout(function() {
                        $form.submit();
                    }, 200);
                });
               //changedate is not suitable as it triggered when showing datepicker. see #149
               /*
               this.$input.on('changeDate', function(e){
                   var $form = $(this).closest('form');
                   setTimeout(function() {
                       $form.submit();
                   }, 200);
               });
               */
           },
           
           /*
            For incorrect date bootstrap-datepicker returns current date that is not suitable
            for datefield.
            This function returns null for incorrect date.  
           */
           parseDate: function(str, format) {
               var date = null, formattedBack;
               if(str) {
                   date = this.dpg.parseDate(str, format, this.options.datepicker.language);
                   if(typeof str === 'string') {
                       formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language);
                       if(str !== formattedBack) {
                           date = null;
                       }
                   }
               }
               return date;
           }
    
        });
    
        Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            /**
            @property tpl 
            @default <div></div>
            **/         
            tpl:'<div class="editable-date well"></div>',
            /**
            @property inputclass 
            @default null
            **/
            inputclass: null,
            /**
            Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
            Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code>  
    
            @property format 
            @type string
            @default yyyy-mm-dd
            **/
            format:'yyyy-mm-dd',
            /**
            Format used for displaying date. Also applied when converting date from element's text on init.   
            If not specified equals to <code>format</code>
    
            @property viewformat 
            @type string
            @default null
            **/
            viewformat: null,
            /**
            Configuration of datepicker.
            Full list of options: http://bootstrap-datepicker.readthedocs.org/en/latest/options.html
    
            @property datepicker 
            @type object
            @default {
                weekStart: 0,
                startView: 0,
                minViewMode: 0,
                autoclose: false
            }
            **/
            datepicker:{
                weekStart: 0,
                startView: 0,
                minViewMode: 0,
                autoclose: false
            },
            /**
            Text shown as clear date button. 
            If <code>false</code> clear button will not be rendered.
    
            @property clear 
            @type boolean|string
            @default 'x clear'
            **/
            clear: '&times; clear'
        });
    
        $.fn.editabletypes.date = Date;
    
    }(window.jQuery));
    
    /**
    Bootstrap datefield input - modification for inline mode.
    Shows normal <input type="text"> and binds popup datepicker.  
    Automatically shown in inline mode.
    
    @class datefield
    @extends date
    
    @since 1.4.0
    **/
    (function ($) {
        "use strict";
        
        var DateField = function (options) {
            this.init('datefield', options, DateField.defaults);
            this.initPicker(options, DateField.defaults);
        };
    
        $.fn.editableutils.inherit(DateField, $.fn.editabletypes.date);    
        
        $.extend(DateField.prototype, {
            render: function () {
                this.$input = this.$tpl.find('input');
                this.setClass();
                this.setAttr('placeholder');
        
                //bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js)        
                this.$tpl.bdatepicker(this.options.datepicker);
                
                //need to disable original event handlers
                this.$input.off('focus keydown');
                
                //update value of datepicker
                this.$input.keyup($.proxy(function(){
                   this.$tpl.removeData('date');
                   this.$tpl.bdatepicker('update');
                }, this));
                
            },   
            
           value2input: function(value) {
               this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : '');
               this.$tpl.bdatepicker('update');
           },
            
           input2value: function() { 
               return this.html2value(this.$input.val());
           },              
            
           activate: function() {
               $.fn.editabletypes.text.prototype.activate.call(this);
           },
           
           autosubmit: function() {
             //reset autosubmit to empty  
           }
        });
        
        DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, {
            /**
            @property tpl 
            **/         
            tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>',
            /**
            @property inputclass 
            @default 'input-small'
            **/         
            inputclass: 'input-small',
            
            /* datepicker config */
            datepicker: {
                weekStart: 0,
                startView: 0,
                minViewMode: 0,
                autoclose: true
            }
        });
        
        $.fn.editabletypes.datefield = DateField;
    
    }(window.jQuery));
    /**
    Bootstrap-datetimepicker.  
    Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker). 
    Before usage you should manually include dependent js and css:
    
        <link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link> 
        <script src="js/bootstrap-datetimepicker.js"></script>
    
    For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales
    and set `language` option.  
    
    @class datetime
    @extends abstractinput
    @final
    @since 1.4.4
    @example
    <a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a>
    <script>
    $(function(){
        $('#last_seen').editable({
            format: 'yyyy-mm-dd hh:ii',    
            viewformat: 'dd/mm/yyyy hh:ii',    
            datetimepicker: {
                    weekStart: 1
               }
            }
        });
    });
    </script>
    **/
    (function ($) {
        "use strict";
    
        var DateTime = function (options) {
            this.init('datetime', options, DateTime.defaults);
            this.initPicker(options, DateTime.defaults);
        };
    
        $.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput);
    
        $.extend(DateTime.prototype, {
            initPicker: function(options, defaults) {
                //'format' is set directly from settings or data-* attributes
    
                //by default viewformat equals to format
                if(!this.options.viewformat) {
                    this.options.viewformat = this.options.format;
                }
                
                //try parse datetimepicker config defined as json string in data-datetimepicker
                options.datetimepicker = $.fn.editableutils.tryParseJson(options.datetimepicker, true);
    
                //overriding datetimepicker config (as by default jQuery extend() is not recursive)
                //since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only
                this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, {
                    format: this.options.viewformat
                });
    
                //language
                this.options.datetimepicker.language = this.options.datetimepicker.language || 'en'; 
    
                //store DPglobal
                this.dpg = $.fn.datetimepicker.DPGlobal; 
    
                //store parsed formats
                this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType);
                this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType);
            },
    
            render: function () {
                this.$input.datetimepicker(this.options.datetimepicker);
    
                //adjust container position when viewMode changes
                //see https://github.com/smalot/bootstrap-datetimepicker/pull/80
                this.$input.on('changeMode', function(e) {
                    var f = $(this).closest('form').parent();
                    //timeout here, otherwise container changes position before form has new size
                    setTimeout(function(){
                        f.triggerHandler('resize');
                    }, 0);
                });
    
                //"clear" link
                if(this.options.clear) {
                    this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
                        e.preventDefault();
                        e.stopPropagation();
                        this.clear();
                    }, this));
    
                    this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));  
                }
            },
    
            value2html: function(value, element) {
                //formatDate works with UTCDate!
                var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : '';
                if(element) {
                    DateTime.superclass.value2html.call(this, text, element);
                } else {
                    return text;
                }
            },
    
            html2value: function(html) {
                //parseDate return utc date!
                var value = this.parseDate(html, this.parsedViewFormat); 
                return value ? this.fromUTC(value) : null;
            },
    
            value2str: function(value) {
                //formatDate works with UTCDate!
                return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : '';
           },
    
           str2value: function(str) {
               //parseDate return utc date!
               var value = this.parseDate(str, this.parsedFormat);
               return value ? this.fromUTC(value) : null;
           },
    
           value2submit: function(value) {
               return this.value2str(value);
           },
    
           value2input: function(value) {
               if(value) {
                 this.$input.data('datetimepicker').setDate(value);
               }
           },
    
           input2value: function() { 
               //date may be cleared, in that case getDate() triggers error
               var dt = this.$input.data('datetimepicker');
               return dt.date ? dt.getDate() : null;
           },
    
           activate: function() {
           },
    
           clear: function() {
              this.$input.data('datetimepicker').date = null;
              this.$input.find('.active').removeClass('active');
              if(!this.options.showbuttons) {
                 this.$input.closest('form').submit(); 
              }          
           },
    
           autosubmit: function() {
               this.$input.on('mouseup', '.minute', function(e){
                   var $form = $(this).closest('form');
                   setTimeout(function() {
                       $form.submit();
                   }, 200);
               });
           },
    
           //convert date from local to utc
           toUTC: function(value) {
             return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value;  
           },
    
           //convert date from utc to local
           fromUTC: function(value) {
             return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value;  
           },
    
           /*
            For incorrect date bootstrap-datetimepicker returns current date that is not suitable
            for datetimefield.
            This function returns null for incorrect date.  
           */
           parseDate: function(str, format) {
               var date = null, formattedBack;
               if(str) {
                   date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType);
                   if(typeof str === 'string') {
                       formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType);
                       if(str !== formattedBack) {
                           date = null;
                       } 
                   }
               }
               return date;
           }
    
        });
    
        DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
            /**
            @property tpl 
            @default <div></div>
            **/         
            tpl:'<div class="editable-date well"></div>',
            /**
            @property inputclass 
            @default null
            **/
            inputclass: null,
            /**
            Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
            Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code>  
            
            @property format 
            @type string
            @default yyyy-mm-dd hh:ii
            **/         
            format:'yyyy-mm-dd hh:ii',
            formatType:'standard',
            /**
            Format used for displaying date. Also applied when converting date from element's text on init.   
            If not specified equals to <code>format</code>
            
            @property viewformat 
            @type string
            @default null
            **/
            viewformat: null,
            /**
            Configuration of datetimepicker.
            Full list of options: https://github.com/smalot/bootstrap-datetimepicker
    
            @property datetimepicker 
            @type object
            @default { }
            **/
            datetimepicker:{
                todayHighlight: false,
                autoclose: false
            },
            /**
            Text shown as clear date button. 
            If <code>false</code> clear button will not be rendered.
    
            @property clear 
            @type boolean|string
            @default 'x clear'
            **/
            clear: '&times; clear'
        });
    
        $.fn.editabletypes.datetime = DateTime;
    
    }(window.jQuery));
    /**
    Bootstrap datetimefield input - datetime input for inline mode.
    Shows normal <input type="text"> and binds popup datetimepicker.  
    Automatically shown in inline mode.
    
    @class datetimefield
    @extends datetime
    
    **/
    (function ($) {
        "use strict";
        
        var DateTimeField = function (options) {
            this.init('datetimefield', options, DateTimeField.defaults);
            this.initPicker(options, DateTimeField.defaults);
        };
    
        $.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime);
        
        $.extend(DateTimeField.prototype, {
            render: function () {
                this.$input = this.$tpl.find('input');
                this.setClass();
                this.setAttr('placeholder');
                
                this.$tpl.datetimepicker(this.options.datetimepicker);
                
                //need to disable original event handlers
                this.$input.off('focus keydown');
                
                //update value of datepicker
                this.$input.keyup($.proxy(function(){
                   this.$tpl.removeData('date');
                   this.$tpl.datetimepicker('update');
                }, this));
                
            },   
          
           value2input: function(value) {
               this.$input.val(this.value2html(value));
               this.$tpl.datetimepicker('update');
           },
            
           input2value: function() { 
               return this.html2value(this.$input.val());
           },              
            
           activate: function() {
               $.fn.editabletypes.text.prototype.activate.call(this);
           },
           
           autosubmit: function() {
             //reset autosubmit to empty  
           }
        });
        
        DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, {
            /**
            @property tpl 
            **/         
            tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>',
            /**
            @property inputclass 
            @default 'input-medium'
            **/         
            inputclass: 'input-medium',
            
            /* datetimepicker config */
            datetimepicker:{
                todayHighlight: false,
                autoclose: true
            }
        });
        
        $.fn.editabletypes.datetimefield = DateTimeField;
    
    }(window.jQuery));
    /*!
     * Select2 4.0.4
     * https://select2.github.io
     *
     * Released under the MIT license
     * https://github.com/select2/select2/blob/master/LICENSE.md
     */
    (function (factory) {
      if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
      } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function (root, jQuery) {
          if (jQuery === undefined) {
            // require('jQuery') returns a factory that requires window to
            // build a jQuery instance, we normalize how we use modules
            // that require this pattern but the window provided is a noop
            // if it's defined (how jquery works)
            if (typeof window !== 'undefined') {
              jQuery = require('jquery');
            }
            else {
              jQuery = require('jquery')(root);
            }
          }
          factory(jQuery);
          return jQuery;
        };
      } else {
        // Browser globals
        factory(jQuery);
      }
    } (function (jQuery) {
      // This is needed so we can catch the AMD loader configuration and use it
      // The inner file should be wrapped (by `banner.start.js`) in a function that
      // returns the AMD loader references.
      var S2 =(function () {
      // Restore the Select2 AMD loader so it can be used
      // Needed mostly in the language files, where the loader is not inserted
      if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd) {
        var S2 = jQuery.fn.select2.amd;
      }
    var S2;(function () { if (!S2 || !S2.requirejs) {
    if (!S2) { S2 = {}; } else { require = S2; }
    /**
     * @license almond 0.3.3 Copyright jQuery Foundation and other contributors.
     * Released under MIT license, http://github.com/requirejs/almond/LICENSE
     */
    //Going sloppy to avoid 'use strict' string cost, but strict practices should
    //be followed.
    /*global setTimeout: false */
    
    var requirejs, require, define;
    (function (undef) {
        var main, req, makeMap, handlers,
            defined = {},
            waiting = {},
            config = {},
            defining = {},
            hasOwn = Object.prototype.hasOwnProperty,
            aps = [].slice,
            jsSuffixRegExp = /\.js$/;
    
        function hasProp(obj, prop) {
            return hasOwn.call(obj, prop);
        }
    
        /**
         * Given a relative module name, like ./something, normalize it to
         * a real name that can be mapped to a path.
         * @param {String} name the relative name
         * @param {String} baseName a real name that the name arg is relative
         * to.
         * @returns {String} normalized name
         */
        function normalize(name, baseName) {
            var nameParts, nameSegment, mapValue, foundMap, lastIndex,
                foundI, foundStarMap, starI, i, j, part, normalizedBaseParts,
                baseParts = baseName && baseName.split("/"),
                map = config.map,
                starMap = (map && map['*']) || {};
    
            //Adjust any relative paths.
            if (name) {
                name = name.split('/');
                lastIndex = name.length - 1;
    
                // If wanting node ID compatibility, strip .js from end
                // of IDs. Have to do this here, and not in nameToUrl
                // because node allows either .js or non .js to map
                // to same file.
                if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
                    name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
                }
    
                // Starts with a '.' so need the baseName
                if (name[0].charAt(0) === '.' && baseParts) {
                    //Convert baseName to array, and lop off the last part,
                    //so that . matches that 'directory' and not name of the baseName's
                    //module. For instance, baseName of 'one/two/three', maps to
                    //'one/two/three.js', but we want the directory, 'one/two' for
                    //this normalization.
                    normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
                    name = normalizedBaseParts.concat(name);
                }
    
                //start trimDots
                for (i = 0; i < name.length; i++) {
                    part = name[i];
                    if (part === '.') {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === '..') {
                        // If at the start, or previous value is still ..,
                        // keep them so that when converted to a path it may
                        // still work when converted to a path, even though
                        // as an ID it is less than ideal. In larger point
                        // releases, may be better to just kick out an error.
                        if (i === 0 || (i === 1 && name[2] === '..') || name[i - 1] === '..') {
                            continue;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots
    
                name = name.join('/');
            }
    
            //Apply map config if available.
            if ((baseParts || starMap) && map) {
                nameParts = name.split('/');
    
                for (i = nameParts.length; i > 0; i -= 1) {
                    nameSegment = nameParts.slice(0, i).join("/");
    
                    if (baseParts) {
                        //Find the longest baseName segment match in the config.
                        //So, do joins on the biggest to smallest lengths of baseParts.
                        for (j = baseParts.length; j > 0; j -= 1) {
                            mapValue = map[baseParts.slice(0, j).join('/')];
    
                            //baseName segment has  config, find if it has one for
                            //this name.
                            if (mapValue) {
                                mapValue = mapValue[nameSegment];
                                if (mapValue) {
                                    //Match, update name to the new value.
                                    foundMap = mapValue;
                                    foundI = i;
                                    break;
                                }
                            }
                        }
                    }
    
                    if (foundMap) {
                        break;
                    }
    
                    //Check for a star map match, but just hold on to it,
                    //if there is a shorter segment match later in a matching
                    //config, then favor over this star map.
                    if (!foundStarMap && starMap && starMap[nameSegment]) {
                        foundStarMap = starMap[nameSegment];
                        starI = i;
                    }
                }
    
                if (!foundMap && foundStarMap) {
                    foundMap = foundStarMap;
                    foundI = starI;
                }
    
                if (foundMap) {
                    nameParts.splice(0, foundI, foundMap);
                    name = nameParts.join('/');
                }
            }
    
            return name;
        }
    
        function makeRequire(relName, forceSync) {
            return function () {
                //A version of a require function that passes a moduleName
                //value for items that may need to
                //look up paths relative to the moduleName
                var args = aps.call(arguments, 0);
    
                //If first arg is not require('string'), and there is only
                //one arg, it is the array form without a callback. Insert
                //a null so that the following concat is correct.
                if (typeof args[0] !== 'string' && args.length === 1) {
                    args.push(null);
                }
                return req.apply(undef, args.concat([relName, forceSync]));
            };
        }
    
        function makeNormalize(relName) {
            return function (name) {
                return normalize(name, relName);
            };
        }
    
        function makeLoad(depName) {
            return function (value) {
                defined[depName] = value;
            };
        }
    
        function callDep(name) {
            if (hasProp(waiting, name)) {
                var args = waiting[name];
                delete waiting[name];
                defining[name] = true;
                main.apply(undef, args);
            }
    
            if (!hasProp(defined, name) && !hasProp(defining, name)) {
                throw new Error('No ' + name);
            }
            return defined[name];
        }
    
        //Turns a plugin!resource to [plugin, resource]
        //with the plugin being undefined if the name
        //did not have a plugin prefix.
        function splitPrefix(name) {
            var prefix,
                index = name ? name.indexOf('!') : -1;
            if (index > -1) {
                prefix = name.substring(0, index);
                name = name.substring(index + 1, name.length);
            }
            return [prefix, name];
        }
    
        //Creates a parts array for a relName where first part is plugin ID,
        //second part is resource ID. Assumes relName has already been normalized.
        function makeRelParts(relName) {
            return relName ? splitPrefix(relName) : [];
        }
    
        /**
         * Makes a name map, normalizing the name, and using a plugin
         * for normalization if necessary. Grabs a ref to plugin
         * too, as an optimization.
         */
        makeMap = function (name, relParts) {
            var plugin,
                parts = splitPrefix(name),
                prefix = parts[0],
                relResourceName = relParts[1];
    
            name = parts[1];
    
            if (prefix) {
                prefix = normalize(prefix, relResourceName);
                plugin = callDep(prefix);
            }
    
            //Normalize according
            if (prefix) {
                if (plugin && plugin.normalize) {
                    name = plugin.normalize(name, makeNormalize(relResourceName));
                } else {
                    name = normalize(name, relResourceName);
                }
            } else {
                name = normalize(name, relResourceName);
                parts = splitPrefix(name);
                prefix = parts[0];
                name = parts[1];
                if (prefix) {
                    plugin = callDep(prefix);
                }
            }
    
            //Using ridiculous property names for space reasons
            return {
                f: prefix ? prefix + '!' + name : name, //fullName
                n: name,
                pr: prefix,
                p: plugin
            };
        };
    
        function makeConfig(name) {
            return function () {
                return (config && config.config && config.config[name]) || {};
            };
        }
    
        handlers = {
            require: function (name) {
                return makeRequire(name);
            },
            exports: function (name) {
                var e = defined[name];
                if (typeof e !== 'undefined') {
                    return e;
                } else {
                    return (defined[name] = {});
                }
            },
            module: function (name) {
                return {
                    id: name,
                    uri: '',
                    exports: defined[name],
                    config: makeConfig(name)
                };
            }
        };
    
        main = function (name, deps, callback, relName) {
            var cjsModule, depName, ret, map, i, relParts,
                args = [],
                callbackType = typeof callback,
                usingExports;
    
            //Use name if no relName
            relName = relName || name;
            relParts = makeRelParts(relName);
    
            //Call the callback to define the module, if necessary.
            if (callbackType === 'undefined' || callbackType === 'function') {
                //Pull out the defined dependencies and pass the ordered
                //values to the callback.
                //Default to [require, exports, module] if no deps
                deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
                for (i = 0; i < deps.length; i += 1) {
                    map = makeMap(deps[i], relParts);
                    depName = map.f;
    
                    //Fast path CommonJS standard dependencies.
                    if (depName === "require") {
                        args[i] = handlers.require(name);
                    } else if (depName === "exports") {
                        //CommonJS module spec 1.1
                        args[i] = handlers.exports(name);
                        usingExports = true;
                    } else if (depName === "module") {
                        //CommonJS module spec 1.1
                        cjsModule = args[i] = handlers.module(name);
                    } else if (hasProp(defined, depName) ||
                               hasProp(waiting, depName) ||
                               hasProp(defining, depName)) {
                        args[i] = callDep(depName);
                    } else if (map.p) {
                        map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                        args[i] = defined[depName];
                    } else {
                        throw new Error(name + ' missing ' + depName);
                    }
                }
    
                ret = callback ? callback.apply(defined[name], args) : undefined;
    
                if (name) {
                    //If setting exports via "module" is in play,
                    //favor that over return value and exports. After that,
                    //favor a non-undefined return value over exports use.
                    if (cjsModule && cjsModule.exports !== undef &&
                            cjsModule.exports !== defined[name]) {
                        defined[name] = cjsModule.exports;
                    } else if (ret !== undef || !usingExports) {
                        //Use the return value from the function.
                        defined[name] = ret;
                    }
                }
            } else if (name) {
                //May just be an object definition for the module. Only
                //worry about defining if have a module name.
                defined[name] = callback;
            }
        };
    
        requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
            if (typeof deps === "string") {
                if (handlers[deps]) {
                    //callback in this case is really relName
                    return handlers[deps](callback);
                }
                //Just return the module wanted. In this scenario, the
                //deps arg is the module name, and second arg (if passed)
                //is just the relName.
                //Normalize module name, if it contains . or ..
                return callDep(makeMap(deps, makeRelParts(callback)).f);
            } else if (!deps.splice) {
                //deps is a config object, not an array.
                config = deps;
                if (config.deps) {
                    req(config.deps, config.callback);
                }
                if (!callback) {
                    return;
                }
    
                if (callback.splice) {
                    //callback is an array, which means it is a dependency list.
                    //Adjust args if there are dependencies
                    deps = callback;
                    callback = relName;
                    relName = null;
                } else {
                    deps = undef;
                }
            }
    
            //Support require(['a'])
            callback = callback || function () {};
    
            //If relName is a function, it is an errback handler,
            //so remove it.
            if (typeof relName === 'function') {
                relName = forceSync;
                forceSync = alt;
            }
    
            //Simulate async callback;
            if (forceSync) {
                main(undef, deps, callback, relName);
            } else {
                //Using a non-zero value because of concern for what old browsers
                //do, and latest browsers "upgrade" to 4 if lower value is used:
                //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
                //If want a value immediately, use require('id') instead -- something
                //that works in almond on the global level, but not guaranteed and
                //unlikely to work in other AMD implementations.
                setTimeout(function () {
                    main(undef, deps, callback, relName);
                }, 4);
            }
    
            return req;
        };
    
        /**
         * Just drops the config on the floor, but returns req in case
         * the config return value is used.
         */
        req.config = function (cfg) {
            return req(cfg);
        };
    
        /**
         * Expose module registry for debugging and tooling
         */
        requirejs._defined = defined;
    
        define = function (name, deps, callback) {
            if (typeof name !== 'string') {
                throw new Error('See almond README: incorrect module build, no module name');
            }
    
            //This module may not have dependencies
            if (!deps.splice) {
                //deps is not an array, so probably means
                //an object literal or factory function for
                //the value. Adjust args.
                callback = deps;
                deps = [];
            }
    
            if (!hasProp(defined, name) && !hasProp(waiting, name)) {
                waiting[name] = [name, deps, callback];
            }
        };
    
        define.amd = {
            jQuery: true
        };
    }());
    
    S2.requirejs = requirejs;S2.require = require;S2.define = define;
    }
    }());
    S2.define("almond", function(){});
    
    /* global jQuery:false, $:false */
    S2.define('jquery',[],function () {
      var _$ = jQuery || $;
    
      if (_$ == null && console && console.error) {
        console.error(
          'Select2: An instance of jQuery or a jQuery-compatible library was not ' +
          'found. Make sure that you are including jQuery before Select2 on your ' +
          'web page.'
        );
      }
    
      return _$;
    });
    
    S2.define('select2/utils',[
      'jquery'
    ], function ($) {
      var Utils = {};
    
      Utils.Extend = function (ChildClass, SuperClass) {
        var __hasProp = {}.hasOwnProperty;
    
        function BaseConstructor () {
          this.constructor = ChildClass;
        }
    
        for (var key in SuperClass) {
          if (__hasProp.call(SuperClass, key)) {
            ChildClass[key] = SuperClass[key];
          }
        }
    
        BaseConstructor.prototype = SuperClass.prototype;
        ChildClass.prototype = new BaseConstructor();
        ChildClass.__super__ = SuperClass.prototype;
    
        return ChildClass;
      };
    
      function getMethods (theClass) {
        var proto = theClass.prototype;
    
        var methods = [];
    
        for (var methodName in proto) {
          var m = proto[methodName];
    
          if (typeof m !== 'function') {
            continue;
          }
    
          if (methodName === 'constructor') {
            continue;
          }
    
          methods.push(methodName);
        }
    
        return methods;
      }
    
      Utils.Decorate = function (SuperClass, DecoratorClass) {
        var decoratedMethods = getMethods(DecoratorClass);
        var superMethods = getMethods(SuperClass);
    
        function DecoratedClass () {
          var unshift = Array.prototype.unshift;
    
          var argCount = DecoratorClass.prototype.constructor.length;
    
          var calledConstructor = SuperClass.prototype.constructor;
    
          if (argCount > 0) {
            unshift.call(arguments, SuperClass.prototype.constructor);
    
            calledConstructor = DecoratorClass.prototype.constructor;
          }
    
          calledConstructor.apply(this, arguments);
        }
    
        DecoratorClass.displayName = SuperClass.displayName;
    
        function ctr () {
          this.constructor = DecoratedClass;
        }
    
        DecoratedClass.prototype = new ctr();
    
        for (var m = 0; m < superMethods.length; m++) {
            var superMethod = superMethods[m];
    
            DecoratedClass.prototype[superMethod] =
              SuperClass.prototype[superMethod];
        }
    
        var calledMethod = function (methodName) {
          // Stub out the original method if it's not decorating an actual method
          var originalMethod = function () {};
    
          if (methodName in DecoratedClass.prototype) {
            originalMethod = DecoratedClass.prototype[methodName];
          }
    
          var decoratedMethod = DecoratorClass.prototype[methodName];
    
          return function () {
            var unshift = Array.prototype.unshift;
    
            unshift.call(arguments, originalMethod);
    
            return decoratedMethod.apply(this, arguments);
          };
        };
    
        for (var d = 0; d < decoratedMethods.length; d++) {
          var decoratedMethod = decoratedMethods[d];
    
          DecoratedClass.prototype[decoratedMethod] = calledMethod(decoratedMethod);
        }
    
        return DecoratedClass;
      };
    
      var Observable = function () {
        this.listeners = {};
      };
    
      Observable.prototype.on = function (event, callback) {
        this.listeners = this.listeners || {};
    
        if (event in this.listeners) {
          this.listeners[event].push(callback);
        } else {
          this.listeners[event] = [callback];
        }
      };
    
      Observable.prototype.trigger = function (event) {
        var slice = Array.prototype.slice;
        var params = slice.call(arguments, 1);
    
        this.listeners = this.listeners || {};
    
        // Params should always come in as an array
        if (params == null) {
          params = [];
        }
    
        // If there are no arguments to the event, use a temporary object
        if (params.length === 0) {
          params.push({});
        }
    
        // Set the `_type` of the first object to the event
        params[0]._type = event;
    
        if (event in this.listeners) {
          this.invoke(this.listeners[event], slice.call(arguments, 1));
        }
    
        if ('*' in this.listeners) {
          this.invoke(this.listeners['*'], arguments);
        }
      };
    
      Observable.prototype.invoke = function (listeners, params) {
        for (var i = 0, len = listeners.length; i < len; i++) {
          listeners[i].apply(this, params);
        }
      };
    
      Utils.Observable = Observable;
    
      Utils.generateChars = function (length) {
        var chars = '';
    
        for (var i = 0; i < length; i++) {
          var randomChar = Math.floor(Math.random() * 36);
          chars += randomChar.toString(36);
        }
    
        return chars;
      };
    
      Utils.bind = function (func, context) {
        return function () {
          func.apply(context, arguments);
        };
      };
    
      Utils._convertData = function (data) {
        for (var originalKey in data) {
          var keys = originalKey.split('-');
    
          var dataLevel = data;
    
          if (keys.length === 1) {
            continue;
          }
    
          for (var k = 0; k < keys.length; k++) {
            var key = keys[k];
    
            // Lowercase the first letter
            // By default, dash-separated becomes camelCase
            key = key.substring(0, 1).toLowerCase() + key.substring(1);
    
            if (!(key in dataLevel)) {
              dataLevel[key] = {};
            }
    
            if (k == keys.length - 1) {
              dataLevel[key] = data[originalKey];
            }
    
            dataLevel = dataLevel[key];
          }
    
          delete data[originalKey];
        }
    
        return data;
      };
    
      Utils.hasScroll = function (index, el) {
        // Adapted from the function created by @ShadowScripter
        // and adapted by @BillBarry on the Stack Exchange Code Review website.
        // The original code can be found at
        // http://codereview.stackexchange.com/q/13338
        // and was designed to be used with the Sizzle selector engine.
    
        var $el = $(el);
        var overflowX = el.style.overflowX;
        var overflowY = el.style.overflowY;
    
        //Check both x and y declarations
        if (overflowX === overflowY &&
            (overflowY === 'hidden' || overflowY === 'visible')) {
          return false;
        }
    
        if (overflowX === 'scroll' || overflowY === 'scroll') {
          return true;
        }
    
        return ($el.innerHeight() < el.scrollHeight ||
          $el.innerWidth() < el.scrollWidth);
      };
    
      Utils.escapeMarkup = function (markup) {
        var replaceMap = {
          '\\': '&#92;',
          '&': '&amp;',
          '<': '&lt;',
          '>': '&gt;',
          '"': '&quot;',
          '\'': '&#39;',
          '/': '&#47;'
        };
    
        // Do not try to escape the markup if it's not a string
        if (typeof markup !== 'string') {
          return markup;
        }
    
        return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
          return replaceMap[match];
        });
      };
    
      // Append an array of jQuery nodes to a given element.
      Utils.appendMany = function ($element, $nodes) {
        // jQuery 1.7.x does not support $.fn.append() with an array
        // Fall back to a jQuery object collection using $.fn.add()
        if ($.fn.jquery.substr(0, 3) === '1.7') {
          var $jqNodes = $();
    
          $.map($nodes, function (node) {
            $jqNodes = $jqNodes.add(node);
          });
    
          $nodes = $jqNodes;
        }
    
        $element.append($nodes);
      };
    
      return Utils;
    });
    
    S2.define('select2/results',[
      'jquery',
      './utils'
    ], function ($, Utils) {
      function Results ($element, options, dataAdapter) {
        this.$element = $element;
        this.data = dataAdapter;
        this.options = options;
    
        Results.__super__.constructor.call(this);
      }
    
      Utils.Extend(Results, Utils.Observable);
    
      Results.prototype.render = function () {
        var $results = $(
          '<ul class="select2-results__options" role="tree"></ul>'
        );
    
        if (this.options.get('multiple')) {
          $results.attr('aria-multiselectable', 'true');
        }
    
        this.$results = $results;
    
        return $results;
      };
    
      Results.prototype.clear = function () {
        this.$results.empty();
      };
    
      Results.prototype.displayMessage = function (params) {
        var escapeMarkup = this.options.get('escapeMarkup');
    
        this.clear();
        this.hideLoading();
    
        var $message = $(
          '<li role="treeitem" aria-live="assertive"' +
          ' class="select2-results__option"></li>'
        );
    
        var message = this.options.get('translations').get(params.message);
    
        $message.append(
          escapeMarkup(
            message(params.args)
          )
        );
    
        $message[0].className += ' select2-results__message';
    
        this.$results.append($message);
      };
    
      Results.prototype.hideMessages = function () {
        this.$results.find('.select2-results__message').remove();
      };
    
      Results.prototype.append = function (data) {
        this.hideLoading();
    
        var $options = [];
    
        if (data.results == null || data.results.length === 0) {
          if (this.$results.children().length === 0) {
            this.trigger('results:message', {
              message: 'noResults'
            });
          }
    
          return;
        }
    
        data.results = this.sort(data.results);
    
        for (var d = 0; d < data.results.length; d++) {
          var item = data.results[d];
    
          var $option = this.option(item);
    
          $options.push($option);
        }
    
        this.$results.append($options);
      };
    
      Results.prototype.position = function ($results, $dropdown) {
        var $resultsContainer = $dropdown.find('.select2-results');
        $resultsContainer.append($results);
      };
    
      Results.prototype.sort = function (data) {
        var sorter = this.options.get('sorter');
    
        return sorter(data);
      };
    
      Results.prototype.highlightFirstItem = function () {
        var $options = this.$results
          .find('.select2-results__option[aria-selected]');
    
        var $selected = $options.filter('[aria-selected=true]');
    
        // Check if there are any selected options
        if ($selected.length > 0) {
          // If there are selected options, highlight the first
          $selected.first().trigger('mouseenter');
        } else {
          // If there are no selected options, highlight the first option
          // in the dropdown
          $options.first().trigger('mouseenter');
        }
    
        this.ensureHighlightVisible();
      };
    
      Results.prototype.setClasses = function () {
        var self = this;
    
        this.data.current(function (selected) {
          var selectedIds = $.map(selected, function (s) {
            return s.id.toString();
          });
    
          var $options = self.$results
            .find('.select2-results__option[aria-selected]');
    
          $options.each(function () {
            var $option = $(this);
    
            var item = $.data(this, 'data');
    
            // id needs to be converted to a string when comparing
            var id = '' + item.id;
    
            if ((item.element != null && item.element.selected) ||
                (item.element == null && $.inArray(id, selectedIds) > -1)) {
              $option.attr('aria-selected', 'true');
            } else {
              $option.attr('aria-selected', 'false');
            }
          });
    
        });
      };
    
      Results.prototype.showLoading = function (params) {
        this.hideLoading();
    
        var loadingMore = this.options.get('translations').get('searching');
    
        var loading = {
          disabled: true,
          loading: true,
          text: loadingMore(params)
        };
        var $loading = this.option(loading);
        $loading.className += ' loading-results';
    
        this.$results.prepend($loading);
      };
    
      Results.prototype.hideLoading = function () {
        this.$results.find('.loading-results').remove();
      };
    
      Results.prototype.option = function (data) {
        var option = document.createElement('li');
        option.className = 'select2-results__option';
    
        var attrs = {
          'role': 'treeitem',
          'aria-selected': 'false'
        };
    
        if (data.disabled) {
          delete attrs['aria-selected'];
          attrs['aria-disabled'] = 'true';
        }
    
        if (data.id == null) {
          delete attrs['aria-selected'];
        }
    
        if (data._resultId != null) {
          option.id = data._resultId;
        }
    
        if (data.title) {
          option.title = data.title;
        }
    
        if (data.children) {
          attrs.role = 'group';
          attrs['aria-label'] = data.text;
          delete attrs['aria-selected'];
        }
    
        for (var attr in attrs) {
          var val = attrs[attr];
    
          option.setAttribute(attr, val);
        }
    
        if (data.children) {
          var $option = $(option);
    
          var label = document.createElement('strong');
          label.className = 'select2-results__group';
    
          var $label = $(label);
          this.template(data, label);
    
          var $children = [];
    
          for (var c = 0; c < data.children.length; c++) {
            var child = data.children[c];
    
            var $child = this.option(child);
    
            $children.push($child);
          }
    
          var $childrenContainer = $('<ul></ul>', {
            'class': 'select2-results__options select2-results__options--nested'
          });
    
          $childrenContainer.append($children);
    
          $option.append(label);
          $option.append($childrenContainer);
        } else {
          this.template(data, option);
        }
    
        $.data(option, 'data', data);
    
        return option;
      };
    
      Results.prototype.bind = function (container, $container) {
        var self = this;
    
        var id = container.id + '-results';
    
        this.$results.attr('id', id);
    
        container.on('results:all', function (params) {
          self.clear();
          self.append(params.data);
    
          if (container.isOpen()) {
            self.setClasses();
            self.highlightFirstItem();
          }
        });
    
        container.on('results:append', function (params) {
          self.append(params.data);
    
          if (container.isOpen()) {
            self.setClasses();
          }
        });
    
        container.on('query', function (params) {
          self.hideMessages();
          self.showLoading(params);
        });
    
        container.on('select', function () {
          if (!container.isOpen()) {
            return;
          }
    
          self.setClasses();
          self.highlightFirstItem();
        });
    
        container.on('unselect', function () {
          if (!container.isOpen()) {
            return;
          }
    
          self.setClasses();
          self.highlightFirstItem();
        });
    
        container.on('open', function () {
          // When the dropdown is open, aria-expended="true"
          self.$results.attr('aria-expanded', 'true');
          self.$results.attr('aria-hidden', 'false');
    
          self.setClasses();
          self.ensureHighlightVisible();
        });
    
        container.on('close', function () {
          // When the dropdown is closed, aria-expended="false"
          self.$results.attr('aria-expanded', 'false');
          self.$results.attr('aria-hidden', 'true');
          self.$results.removeAttr('aria-activedescendant');
        });
    
        container.on('results:toggle', function () {
          var $highlighted = self.getHighlightedResults();
    
          if ($highlighted.length === 0) {
            return;
          }
    
          $highlighted.trigger('mouseup');
        });
    
        container.on('results:select', function () {
          var $highlighted = self.getHighlightedResults();
    
          if ($highlighted.length === 0) {
            return;
          }
    
          var data = $highlighted.data('data');
    
          if ($highlighted.attr('aria-selected') == 'true') {
            self.trigger('close', {});
          } else {
            self.trigger('select', {
              data: data
            });
          }
        });
    
        container.on('results:previous', function () {
          var $highlighted = self.getHighlightedResults();
    
          var $options = self.$results.find('[aria-selected]');
    
          var currentIndex = $options.index($highlighted);
    
          // If we are already at te top, don't move further
          if (currentIndex === 0) {
            return;
          }
    
          var nextIndex = currentIndex - 1;
    
          // If none are highlighted, highlight the first
          if ($highlighted.length === 0) {
            nextIndex = 0;
          }
    
          var $next = $options.eq(nextIndex);
    
          $next.trigger('mouseenter');
    
          var currentOffset = self.$results.offset().top;
          var nextTop = $next.offset().top;
          var nextOffset = self.$results.scrollTop() + (nextTop - currentOffset);
    
          if (nextIndex === 0) {
            self.$results.scrollTop(0);
          } else if (nextTop - currentOffset < 0) {
            self.$results.scrollTop(nextOffset);
          }
        });
    
        container.on('results:next', function () {
          var $highlighted = self.getHighlightedResults();
    
          var $options = self.$results.find('[aria-selected]');
    
          var currentIndex = $options.index($highlighted);
    
          var nextIndex = currentIndex + 1;
    
          // If we are at the last option, stay there
          if (nextIndex >= $options.length) {
            return;
          }
    
          var $next = $options.eq(nextIndex);
    
          $next.trigger('mouseenter');
    
          var currentOffset = self.$results.offset().top +
            self.$results.outerHeight(false);
          var nextBottom = $next.offset().top + $next.outerHeight(false);
          var nextOffset = self.$results.scrollTop() + nextBottom - currentOffset;
    
          if (nextIndex === 0) {
            self.$results.scrollTop(0);
          } else if (nextBottom > currentOffset) {
            self.$results.scrollTop(nextOffset);
          }
        });
    
        container.on('results:focus', function (params) {
          params.element.addClass('select2-results__option--highlighted');
        });
    
        container.on('results:message', function (params) {
          self.displayMessage(params);
        });
    
        if ($.fn.mousewheel) {
          this.$results.on('mousewheel', function (e) {
            var top = self.$results.scrollTop();
    
            var bottom = self.$results.get(0).scrollHeight - top + e.deltaY;
    
            var isAtTop = e.deltaY > 0 && top - e.deltaY <= 0;
            var isAtBottom = e.deltaY < 0 && bottom <= self.$results.height();
    
            if (isAtTop) {
              self.$results.scrollTop(0);
    
              e.preventDefault();
              e.stopPropagation();
            } else if (isAtBottom) {
              self.$results.scrollTop(
                self.$results.get(0).scrollHeight - self.$results.height()
              );
    
              e.preventDefault();
              e.stopPropagation();
            }
          });
        }
    
        this.$results.on('mouseup', '.select2-results__option[aria-selected]',
          function (evt) {
          var $this = $(this);
    
          var data = $this.data('data');
    
          if ($this.attr('aria-selected') === 'true') {
            if (self.options.get('multiple')) {
              self.trigger('unselect', {
                originalEvent: evt,
                data: data
              });
            } else {
              self.trigger('close', {});
            }
    
            return;
          }
    
          self.trigger('select', {
            originalEvent: evt,
            data: data
          });
        });
    
        this.$results.on('mouseenter', '.select2-results__option[aria-selected]',
          function (evt) {
          var data = $(this).data('data');
    
          self.getHighlightedResults()
              .removeClass('select2-results__option--highlighted');
    
          self.trigger('results:focus', {
            data: data,
            element: $(this)
          });
        });
      };
    
      Results.prototype.getHighlightedResults = function () {
        var $highlighted = this.$results
        .find('.select2-results__option--highlighted');
    
        return $highlighted;
      };
    
      Results.prototype.destroy = function () {
        this.$results.remove();
      };
    
      Results.prototype.ensureHighlightVisible = function () {
        var $highlighted = this.getHighlightedResults();
    
        if ($highlighted.length === 0) {
          return;
        }
    
        var $options = this.$results.find('[aria-selected]');
    
        var currentIndex = $options.index($highlighted);
    
        var currentOffset = this.$results.offset().top;
        var nextTop = $highlighted.offset().top;
        var nextOffset = this.$results.scrollTop() + (nextTop - currentOffset);
    
        var offsetDelta = nextTop - currentOffset;
        nextOffset -= $highlighted.outerHeight(false) * 2;
    
        if (currentIndex <= 2) {
          this.$results.scrollTop(0);
        } else if (offsetDelta > this.$results.outerHeight() || offsetDelta < 0) {
          this.$results.scrollTop(nextOffset);
        }
      };
    
      Results.prototype.template = function (result, container) {
        var template = this.options.get('templateResult');
        var escapeMarkup = this.options.get('escapeMarkup');
    
        var content = template(result, container);
    
        if (content == null) {
          container.style.display = 'none';
        } else if (typeof content === 'string') {
          container.innerHTML = escapeMarkup(content);
        } else {
          $(container).append(content);
        }
      };
    
      return Results;
    });
    
    S2.define('select2/keys',[
    
    ], function () {
      var KEYS = {
        BACKSPACE: 8,
        TAB: 9,
        ENTER: 13,
        SHIFT: 16,
        CTRL: 17,
        ALT: 18,
        ESC: 27,
        SPACE: 32,
        PAGE_UP: 33,
        PAGE_DOWN: 34,
        END: 35,
        HOME: 36,
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        DELETE: 46
      };
    
      return KEYS;
    });
    
    S2.define('select2/selection/base',[
      'jquery',
      '../utils',
      '../keys'
    ], function ($, Utils, KEYS) {
      function BaseSelection ($element, options) {
        this.$element = $element;
        this.options = options;
    
        BaseSelection.__super__.constructor.call(this);
      }
    
      Utils.Extend(BaseSelection, Utils.Observable);
    
      BaseSelection.prototype.render = function () {
        var $selection = $(
          '<span class="select2-selection" role="combobox" ' +
          ' aria-haspopup="true" aria-expanded="false">' +
          '</span>'
        );
    
        this._tabindex = 0;
    
        if (this.$element.data('old-tabindex') != null) {
          this._tabindex = this.$element.data('old-tabindex');
        } else if (this.$element.attr('tabindex') != null) {
          this._tabindex = this.$element.attr('tabindex');
        }
    
        $selection.attr('title', this.$element.attr('title'));
        $selection.attr('tabindex', this._tabindex);
    
        this.$selection = $selection;
    
        return $selection;
      };
    
      BaseSelection.prototype.bind = function (container, $container) {
        var self = this;
    
        var id = container.id + '-container';
        var resultsId = container.id + '-results';
    
        this.container = container;
    
        this.$selection.on('focus', function (evt) {
          self.trigger('focus', evt);
        });
    
        this.$selection.on('blur', function (evt) {
          self._handleBlur(evt);
        });
    
        this.$selection.on('keydown', function (evt) {
          self.trigger('keypress', evt);
    
          if (evt.which === KEYS.SPACE) {
            evt.preventDefault();
          }
        });
    
        container.on('results:focus', function (params) {
          self.$selection.attr('aria-activedescendant', params.data._resultId);
        });
    
        container.on('selection:update', function (params) {
          self.update(params.data);
        });
    
        container.on('open', function () {
          // When the dropdown is open, aria-expanded="true"
          self.$selection.attr('aria-expanded', 'true');
          self.$selection.attr('aria-owns', resultsId);
    
          self._attachCloseHandler(container);
        });
    
        container.on('close', function () {
          // When the dropdown is closed, aria-expanded="false"
          self.$selection.attr('aria-expanded', 'false');
          self.$selection.removeAttr('aria-activedescendant');
          self.$selection.removeAttr('aria-owns');
    
          self.$selection.focus();
    
          self._detachCloseHandler(container);
        });
    
        container.on('enable', function () {
          self.$selection.attr('tabindex', self._tabindex);
        });
    
        container.on('disable', function () {
          self.$selection.attr('tabindex', '-1');
        });
      };
    
      BaseSelection.prototype._handleBlur = function (evt) {
        var self = this;
    
        // This needs to be delayed as the active element is the body when the tab
        // key is pressed, possibly along with others.
        window.setTimeout(function () {
          // Don't trigger `blur` if the focus is still in the selection
          if (
            (document.activeElement == self.$selection[0]) ||
            ($.contains(self.$selection[0], document.activeElement))
          ) {
            return;
          }
    
          self.trigger('blur', evt);
        }, 1);
      };
    
      BaseSelection.prototype._attachCloseHandler = function (container) {
        var self = this;
    
        $(document.body).on('mousedown.select2.' + container.id, function (e) {
          var $target = $(e.target);
    
          var $select = $target.closest('.select2');
    
          var $all = $('.select2.select2-container--open');
    
          $all.each(function () {
            var $this = $(this);
    
            if (this == $select[0]) {
              return;
            }
    
            var $element = $this.data('element');
    
            $element.select2('close');
          });
        });
      };
    
      BaseSelection.prototype._detachCloseHandler = function (container) {
        $(document.body).off('mousedown.select2.' + container.id);
      };
    
      BaseSelection.prototype.position = function ($selection, $container) {
        var $selectionContainer = $container.find('.selection');
        $selectionContainer.append($selection);
      };
    
      BaseSelection.prototype.destroy = function () {
        this._detachCloseHandler(this.container);
      };
    
      BaseSelection.prototype.update = function (data) {
        throw new Error('The `update` method must be defined in child classes.');
      };
    
      return BaseSelection;
    });
    
    S2.define('select2/selection/single',[
      'jquery',
      './base',
      '../utils',
      '../keys'
    ], function ($, BaseSelection, Utils, KEYS) {
      function SingleSelection () {
        SingleSelection.__super__.constructor.apply(this, arguments);
      }
    
      Utils.Extend(SingleSelection, BaseSelection);
    
      SingleSelection.prototype.render = function () {
        var $selection = SingleSelection.__super__.render.call(this);
    
        $selection.addClass('select2-selection--single');
    
        $selection.html(
          '<span class="select2-selection__rendered"></span>' +
          '<span class="select2-selection__arrow" role="presentation">' +
            '<b role="presentation"></b>' +
          '</span>'
        );
    
        return $selection;
      };
    
      SingleSelection.prototype.bind = function (container, $container) {
        var self = this;
    
        SingleSelection.__super__.bind.apply(this, arguments);
    
        var id = container.id + '-container';
    
        this.$selection.find('.select2-selection__rendered').attr('id', id);
        this.$selection.attr('aria-labelledby', id);
    
        this.$selection.on('mousedown', function (evt) {
          // Only respond to left clicks
          if (evt.which !== 1) {
            return;
          }
    
          self.trigger('toggle', {
            originalEvent: evt
          });
        });
    
        this.$selection.on('focus', function (evt) {
          // User focuses on the container
        });
    
        this.$selection.on('blur', function (evt) {
          // User exits the container
        });
    
        container.on('focus', function (evt) {
          if (!container.isOpen()) {
            self.$selection.focus();
          }
        });
    
        container.on('selection:update', function (params) {
          self.update(params.data);
        });
      };
    
      SingleSelection.prototype.clear = function () {
        this.$selection.find('.select2-selection__rendered').empty();
      };
    
      SingleSelection.prototype.display = function (data, container) {
        var template = this.options.get('templateSelection');
        var escapeMarkup = this.options.get('escapeMarkup');
    
        return escapeMarkup(template(data, container));
      };
    
      SingleSelection.prototype.selectionContainer = function () {
        return $('<span></span>');
      };
    
      SingleSelection.prototype.update = function (data) {
        if (data.length === 0) {
          this.clear();
          return;
        }
    
        var selection = data[0];
    
        var $rendered = this.$selection.find('.select2-selection__rendered');
        var formatted = this.display(selection, $rendered);
    
        $rendered.empty().append(formatted);
        $rendered.prop('title', selection.title || selection.text);
      };
    
      return SingleSelection;
    });
    
    S2.define('select2/selection/multiple',[
      'jquery',
      './base',
      '../utils'
    ], function ($, BaseSelection, Utils) {
      function MultipleSelection ($element, options) {
        MultipleSelection.__super__.constructor.apply(this, arguments);
      }
    
      Utils.Extend(MultipleSelection, BaseSelection);
    
      MultipleSelection.prototype.render = function () {
        var $selection = MultipleSelection.__super__.render.call(this);
    
        $selection.addClass('select2-selection--multiple');
    
        $selection.html(
          '<ul class="select2-selection__rendered"></ul>'
        );
    
        return $selection;
      };
    
      MultipleSelection.prototype.bind = function (container, $container) {
        var self = this;
    
        MultipleSelection.__super__.bind.apply(this, arguments);
    
        this.$selection.on('click', function (evt) {
          self.trigger('toggle', {
            originalEvent: evt
          });
        });
    
        this.$selection.on(
          'click',
          '.select2-selection__choice__remove',
          function (evt) {
            // Ignore the event if it is disabled
            if (self.options.get('disabled')) {
              return;
            }
    
            var $remove = $(this);
            var $selection = $remove.parent();
    
            var data = $selection.data('data');
    
            self.trigger('unselect', {
              originalEvent: evt,
              data: data
            });
          }
        );
      };
    
      MultipleSelection.prototype.clear = function () {
        this.$selection.find('.select2-selection__rendered').empty();
      };
    
      MultipleSelection.prototype.display = function (data, container) {
        var template = this.options.get('templateSelection');
        var escapeMarkup = this.options.get('escapeMarkup');
    
        return escapeMarkup(template(data, container));
      };
    
      MultipleSelection.prototype.selectionContainer = function () {
        var $container = $(
          '<li class="select2-selection__choice">' +
            '<span class="select2-selection__choice__remove" role="presentation">' +
              '&times;' +
            '</span>' +
          '</li>'
        );
    
        return $container;
      };
    
      MultipleSelection.prototype.update = function (data) {
        this.clear();
    
        if (data.length === 0) {
          return;
        }
    
        var $selections = [];
    
        for (var d = 0; d < data.length; d++) {
          var selection = data[d];
    
          var $selection = this.selectionContainer();
          var formatted = this.display(selection, $selection);
    
          $selection.append(formatted);
          $selection.prop('title', selection.title || selection.text);
    
          $selection.data('data', selection);
    
          $selections.push($selection);
        }
    
        var $rendered = this.$selection.find('.select2-selection__rendered');
    
        Utils.appendMany($rendered, $selections);
      };
    
      return MultipleSelection;
    });
    
    S2.define('select2/selection/placeholder',[
      '../utils'
    ], function (Utils) {
      function Placeholder (decorated, $element, options) {
        this.placeholder = this.normalizePlaceholder(options.get('placeholder'));
    
        decorated.call(this, $element, options);
      }
    
      Placeholder.prototype.normalizePlaceholder = function (_, placeholder) {
        if (typeof placeholder === 'string') {
          placeholder = {
            id: '',
            text: placeholder
          };
        }
    
        return placeholder;
      };
    
      Placeholder.prototype.createPlaceholder = function (decorated, placeholder) {
        var $placeholder = this.selectionContainer();
    
        $placeholder.html(this.display(placeholder));
        $placeholder.addClass('select2-selection__placeholder')
                    .removeClass('select2-selection__choice');
    
        return $placeholder;
      };
    
      Placeholder.prototype.update = function (decorated, data) {
        var singlePlaceholder = (
          data.length == 1 && data[0].id != this.placeholder.id
        );
        var multipleSelections = data.length > 1;
    
        if (multipleSelections || singlePlaceholder) {
          return decorated.call(this, data);
        }
    
        this.clear();
    
        var $placeholder = this.createPlaceholder(this.placeholder);
    
        this.$selection.find('.select2-selection__rendered').append($placeholder);
      };
    
      return Placeholder;
    });
    
    S2.define('select2/selection/allowClear',[
      'jquery',
      '../keys'
    ], function ($, KEYS) {
      function AllowClear () { }
    
      AllowClear.prototype.bind = function (decorated, container, $container) {
        var self = this;
    
        decorated.call(this, container, $container);
    
        if (this.placeholder == null) {
          if (this.options.get('debug') && window.console && console.error) {
            console.error(
              'Select2: The `allowClear` option should be used in combination ' +
              'with the `placeholder` option.'
            );
          }
        }
    
        this.$selection.on('mousedown', '.select2-selection__clear',
          function (evt) {
            self._handleClear(evt);
        });
    
        container.on('keypress', function (evt) {
          self._handleKeyboardClear(evt, container);
        });
      };
    
      AllowClear.prototype._handleClear = function (_, evt) {
        // Ignore the event if it is disabled
        if (this.options.get('disabled')) {
          return;
        }
    
        var $clear = this.$selection.find('.select2-selection__clear');
    
        // Ignore the event if nothing has been selected
        if ($clear.length === 0) {
          return;
        }
    
        evt.stopPropagation();
    
        var data = $clear.data('data');
    
        for (var d = 0; d < data.length; d++) {
          var unselectData = {
            data: data[d]
          };
    
          // Trigger the `unselect` event, so people can prevent it from being
          // cleared.
          this.trigger('unselect', unselectData);
    
          // If the event was prevented, don't clear it out.
          if (unselectData.prevented) {
            return;
          }
        }
    
        this.$element.val(this.placeholder.id).trigger('change');
    
        this.trigger('toggle', {});
      };
    
      AllowClear.prototype._handleKeyboardClear = function (_, evt, container) {
        if (container.isOpen()) {
          return;
        }
    
        if (evt.which == KEYS.DELETE || evt.which == KEYS.BACKSPACE) {
          this._handleClear(evt);
        }
      };
    
      AllowClear.prototype.update = function (decorated, data) {
        decorated.call(this, data);
    
        if (this.$selection.find('.select2-selection__placeholder').length > 0 ||
            data.length === 0) {
          return;
        }
    
        var $remove = $(
          '<span class="select2-selection__clear">' +
            '&times;' +
          '</span>'
        );
        $remove.data('data', data);
    
        this.$selection.find('.select2-selection__rendered').prepend($remove);
      };
    
      return AllowClear;
    });
    
    S2.define('select2/selection/search',[
      'jquery',
      '../utils',
      '../keys'
    ], function ($, Utils, KEYS) {
      function Search (decorated, $element, options) {
        decorated.call(this, $element, options);
      }
    
      Search.prototype.render = function (decorated) {
        var $search = $(
          '<li class="select2-search select2-search--inline">' +
            '<input class="select2-search__field" type="search" tabindex="-1"' +
            ' autocomplete="off" autocorrect="off" autocapitalize="off"' +
            ' spellcheck="false" role="textbox" aria-autocomplete="list" />' +
          '</li>'
        );
    
        this.$searchContainer = $search;
        this.$search = $search.find('input');
    
        var $rendered = decorated.call(this);
    
        this._transferTabIndex();
    
        return $rendered;
      };
    
      Search.prototype.bind = function (decorated, container, $container) {
        var self = this;
    
        decorated.call(this, container, $container);
    
        container.on('open', function () {
          self.$search.trigger('focus');
        });
    
        container.on('close', function () {
          self.$search.val('');
          self.$search.removeAttr('aria-activedescendant');
          self.$search.trigger('focus');
        });
    
        container.on('enable', function () {
          self.$search.prop('disabled', false);
    
          self._transferTabIndex();
        });
    
        container.on('disable', function () {
          self.$search.prop('disabled', true);
        });
    
        container.on('focus', function (evt) {
          self.$search.trigger('focus');
        });
    
        container.on('results:focus', function (params) {
          self.$search.attr('aria-activedescendant', params.id);
        });
    
        this.$selection.on('focusin', '.select2-search--inline', function (evt) {
          self.trigger('focus', evt);
        });
    
        this.$selection.on('focusout', '.select2-search--inline', function (evt) {
          self._handleBlur(evt);
        });
    
        this.$selection.on('keydown', '.select2-search--inline', function (evt) {
          evt.stopPropagation();
    
          self.trigger('keypress', evt);
    
          self._keyUpPrevented = evt.isDefaultPrevented();
    
          var key = evt.which;
    
          if (key === KEYS.BACKSPACE && self.$search.val() === '') {
            var $previousChoice = self.$searchContainer
              .prev('.select2-selection__choice');
    
            if ($previousChoice.length > 0) {
              var item = $previousChoice.data('data');
    
              self.searchRemoveChoice(item);
    
              evt.preventDefault();
            }
          }
        });
    
        // Try to detect the IE version should the `documentMode` property that
        // is stored on the document. This is only implemented in IE and is
        // slightly cleaner than doing a user agent check.
        // This property is not available in Edge, but Edge also doesn't have
        // this bug.
        var msie = document.documentMode;
        var disableInputEvents = msie && msie <= 11;
    
        // Workaround for browsers which do not support the `input` event
        // This will prevent double-triggering of events for browsers which support
        // both the `keyup` and `input` events.
        this.$selection.on(
          'input.searchcheck',
          '.select2-search--inline',
          function (evt) {
            // IE will trigger the `input` event when a placeholder is used on a
            // search box. To get around this issue, we are forced to ignore all
            // `input` events in IE and keep using `keyup`.
            if (disableInputEvents) {
              self.$selection.off('input.search input.searchcheck');
              return;
            }
    
            // Unbind the duplicated `keyup` event
            self.$selection.off('keyup.search');
          }
        );
    
        this.$selection.on(
          'keyup.search input.search',
          '.select2-search--inline',
          function (evt) {
            // IE will trigger the `input` event when a placeholder is used on a
            // search box. To get around this issue, we are forced to ignore all
            // `input` events in IE and keep using `keyup`.
            if (disableInputEvents && evt.type === 'input') {
              self.$selection.off('input.search input.searchcheck');
              return;
            }
    
            var key = evt.which;
    
            // We can freely ignore events from modifier keys
            if (key == KEYS.SHIFT || key == KEYS.CTRL || key == KEYS.ALT) {
              return;
            }
    
            // Tabbing will be handled during the `keydown` phase
            if (key == KEYS.TAB) {
              return;
            }
    
            self.handleSearch(evt);
          }
        );
      };
    
      /**
       * This method will transfer the tabindex attribute from the rendered
       * selection to the search box. This allows for the search box to be used as
       * the primary focus instead of the selection container.
       *
       * @private
       */
      Search.prototype._transferTabIndex = function (decorated) {
        this.$search.attr('tabindex', this.$selection.attr('tabindex'));
        this.$selection.attr('tabindex', '-1');
      };
    
      Search.prototype.createPlaceholder = function (decorated, placeholder) {
        this.$search.attr('placeholder', placeholder.text);
      };
    
      Search.prototype.update = function (decorated, data) {
        var searchHadFocus = this.$search[0] == document.activeElement;
    
        this.$search.attr('placeholder', '');
    
        decorated.call(this, data);
    
        this.$selection.find('.select2-selection__rendered')
                       .append(this.$searchContainer);
    
        this.resizeSearch();
        if (searchHadFocus) {
          this.$search.focus();
        }
      };
    
      Search.prototype.handleSearch = function () {
        this.resizeSearch();
    
        if (!this._keyUpPrevented) {
          var input = this.$search.val();
    
          this.trigger('query', {
            term: input
          });
        }
    
        this._keyUpPrevented = false;
      };
    
      Search.prototype.searchRemoveChoice = function (decorated, item) {
        this.trigger('unselect', {
          data: item
        });
    
        this.$search.val(item.text);
        this.handleSearch();
      };
    
      Search.prototype.resizeSearch = function () {
        this.$search.css('width', '25px');
    
        var width = '';
    
        if (this.$search.attr('placeholder') !== '') {
          width = this.$selection.find('.select2-selection__rendered').innerWidth();
        } else {
          var minimumWidth = this.$search.val().length + 1;
    
          width = (minimumWidth * 0.75) + 'em';
        }
    
        this.$search.css('width', width);
      };
    
      return Search;
    });
    
    S2.define('select2/selection/eventRelay',[
      'jquery'
    ], function ($) {
      function EventRelay () { }
    
      EventRelay.prototype.bind = function (decorated, container, $container) {
        var self = this;
        var relayEvents = [
          'open', 'opening',
          'close', 'closing',
          'select', 'selecting',
          'unselect', 'unselecting'
        ];
    
        var preventableEvents = ['opening', 'closing', 'selecting', 'unselecting'];
    
        decorated.call(this, container, $container);
    
        container.on('*', function (name, params) {
          // Ignore events that should not be relayed
          if ($.inArray(name, relayEvents) === -1) {
            return;
          }
    
          // The parameters should always be an object
          params = params || {};
    
          // Generate the jQuery event for the Select2 event
          var evt = $.Event('select2:' + name, {
            params: params
          });
    
          self.$element.trigger(evt);
    
          // Only handle preventable events if it was one
          if ($.inArray(name, preventableEvents) === -1) {
            return;
          }
    
          params.prevented = evt.isDefaultPrevented();
        });
      };
    
      return EventRelay;
    });
    
    S2.define('select2/translation',[
      'jquery',
      'require'
    ], function ($, require) {
      function Translation (dict) {
        this.dict = dict || {};
      }
    
      Translation.prototype.all = function () {
        return this.dict;
      };
    
      Translation.prototype.get = function (key) {
        return this.dict[key];
      };
    
      Translation.prototype.extend = function (translation) {
        this.dict = $.extend({}, translation.all(), this.dict);
      };
    
      // Static functions
    
      Translation._cache = {};
    
      Translation.loadPath = function (path) {
        if (!(path in Translation._cache)) {
          var translations = require(path);
    
          Translation._cache[path] = translations;
        }
    
        return new Translation(Translation._cache[path]);
      };
    
      return Translation;
    });
    
    S2.define('select2/diacritics',[
    
    ], function () {
      var diacritics = {
        '\u24B6': 'A',
        '\uFF21': 'A',
        '\u00C0': 'A',
        '\u00C1': 'A',
        '\u00C2': 'A',
        '\u1EA6': 'A',
        '\u1EA4': 'A',
        '\u1EAA': 'A',
        '\u1EA8': 'A',
        '\u00C3': 'A',
        '\u0100': 'A',
        '\u0102': 'A',
        '\u1EB0': 'A',
        '\u1EAE': 'A',
        '\u1EB4': 'A',
        '\u1EB2': 'A',
        '\u0226': 'A',
        '\u01E0': 'A',
        '\u00C4': 'A',
        '\u01DE': 'A',
        '\u1EA2': 'A',
        '\u00C5': 'A',
        '\u01FA': 'A',
        '\u01CD': 'A',
        '\u0200': 'A',
        '\u0202': 'A',
        '\u1EA0': 'A',
        '\u1EAC': 'A',
        '\u1EB6': 'A',
        '\u1E00': 'A',
        '\u0104': 'A',
        '\u023A': 'A',
        '\u2C6F': 'A',
        '\uA732': 'AA',
        '\u00C6': 'AE',
        '\u01FC': 'AE',
        '\u01E2': 'AE',
        '\uA734': 'AO',
        '\uA736': 'AU',
        '\uA738': 'AV',
        '\uA73A': 'AV',
        '\uA73C': 'AY',
        '\u24B7': 'B',
        '\uFF22': 'B',
        '\u1E02': 'B',
        '\u1E04': 'B',
        '\u1E06': 'B',
        '\u0243': 'B',
        '\u0182': 'B',
        '\u0181': 'B',
        '\u24B8': 'C',
        '\uFF23': 'C',
        '\u0106': 'C',
        '\u0108': 'C',
        '\u010A': 'C',
        '\u010C': 'C',
        '\u00C7': 'C',
        '\u1E08': 'C',
        '\u0187': 'C',
        '\u023B': 'C',
        '\uA73E': 'C',
        '\u24B9': 'D',
        '\uFF24': 'D',
        '\u1E0A': 'D',
        '\u010E': 'D',
        '\u1E0C': 'D',
        '\u1E10': 'D',
        '\u1E12': 'D',
        '\u1E0E': 'D',
        '\u0110': 'D',
        '\u018B': 'D',
        '\u018A': 'D',
        '\u0189': 'D',
        '\uA779': 'D',
        '\u01F1': 'DZ',
        '\u01C4': 'DZ',
        '\u01F2': 'Dz',
        '\u01C5': 'Dz',
        '\u24BA': 'E',
        '\uFF25': 'E',
        '\u00C8': 'E',
        '\u00C9': 'E',
        '\u00CA': 'E',
        '\u1EC0': 'E',
        '\u1EBE': 'E',
        '\u1EC4': 'E',
        '\u1EC2': 'E',
        '\u1EBC': 'E',
        '\u0112': 'E',
        '\u1E14': 'E',
        '\u1E16': 'E',
        '\u0114': 'E',
        '\u0116': 'E',
        '\u00CB': 'E',
        '\u1EBA': 'E',
        '\u011A': 'E',
        '\u0204': 'E',
        '\u0206': 'E',
        '\u1EB8': 'E',
        '\u1EC6': 'E',
        '\u0228': 'E',
        '\u1E1C': 'E',
        '\u0118': 'E',
        '\u1E18': 'E',
        '\u1E1A': 'E',
        '\u0190': 'E',
        '\u018E': 'E',
        '\u24BB': 'F',
        '\uFF26': 'F',
        '\u1E1E': 'F',
        '\u0191': 'F',
        '\uA77B': 'F',
        '\u24BC': 'G',
        '\uFF27': 'G',
        '\u01F4': 'G',
        '\u011C': 'G',
        '\u1E20': 'G',
        '\u011E': 'G',
        '\u0120': 'G',
        '\u01E6': 'G',
        '\u0122': 'G',
        '\u01E4': 'G',
        '\u0193': 'G',
        '\uA7A0': 'G',
        '\uA77D': 'G',
        '\uA77E': 'G',
        '\u24BD': 'H',
        '\uFF28': 'H',
        '\u0124': 'H',
        '\u1E22': 'H',
        '\u1E26': 'H',
        '\u021E': 'H',
        '\u1E24': 'H',
        '\u1E28': 'H',
        '\u1E2A': 'H',
        '\u0126': 'H',
        '\u2C67': 'H',
        '\u2C75': 'H',
        '\uA78D': 'H',
        '\u24BE': 'I',
        '\uFF29': 'I',
        '\u00CC': 'I',
        '\u00CD': 'I',
        '\u00CE': 'I',
        '\u0128': 'I',
        '\u012A': 'I',
        '\u012C': 'I',
        '\u0130': 'I',
        '\u00CF': 'I',
        '\u1E2E': 'I',
        '\u1EC8': 'I',
        '\u01CF': 'I',
        '\u0208': 'I',
        '\u020A': 'I',
        '\u1ECA': 'I',
        '\u012E': 'I',
        '\u1E2C': 'I',
        '\u0197': 'I',
        '\u24BF': 'J',
        '\uFF2A': 'J',
        '\u0134': 'J',
        '\u0248': 'J',
        '\u24C0': 'K',
        '\uFF2B': 'K',
        '\u1E30': 'K',
        '\u01E8': 'K',
        '\u1E32': 'K',
        '\u0136': 'K',
        '\u1E34': 'K',
        '\u0198': 'K',
        '\u2C69': 'K',
        '\uA740': 'K',
        '\uA742': 'K',
        '\uA744': 'K',
        '\uA7A2': 'K',
        '\u24C1': 'L',
        '\uFF2C': 'L',
        '\u013F': 'L',
        '\u0139': 'L',
        '\u013D': 'L',
        '\u1E36': 'L',
        '\u1E38': 'L',
        '\u013B': 'L',
        '\u1E3C': 'L',
        '\u1E3A': 'L',
        '\u0141': 'L',
        '\u023D': 'L',
        '\u2C62': 'L',
        '\u2C60': 'L',
        '\uA748': 'L',
        '\uA746': 'L',
        '\uA780': 'L',
        '\u01C7': 'LJ',
        '\u01C8': 'Lj',
        '\u24C2': 'M',
        '\uFF2D': 'M',
        '\u1E3E': 'M',
        '\u1E40': 'M',
        '\u1E42': 'M',
        '\u2C6E': 'M',
        '\u019C': 'M',
        '\u24C3': 'N',
        '\uFF2E': 'N',
        '\u01F8': 'N',
        '\u0143': 'N',
        '\u00D1': 'N',
        '\u1E44': 'N',
        '\u0147': 'N',
        '\u1E46': 'N',
        '\u0145': 'N',
        '\u1E4A': 'N',
        '\u1E48': 'N',
        '\u0220': 'N',
        '\u019D': 'N',
        '\uA790': 'N',
        '\uA7A4': 'N',
        '\u01CA': 'NJ',
        '\u01CB': 'Nj',
        '\u24C4': 'O',
        '\uFF2F': 'O',
        '\u00D2': 'O',
        '\u00D3': 'O',
        '\u00D4': 'O',
        '\u1ED2': 'O',
        '\u1ED0': 'O',
        '\u1ED6': 'O',
        '\u1ED4': 'O',
        '\u00D5': 'O',
        '\u1E4C': 'O',
        '\u022C': 'O',
        '\u1E4E': 'O',
        '\u014C': 'O',
        '\u1E50': 'O',
        '\u1E52': 'O',
        '\u014E': 'O',
        '\u022E': 'O',
        '\u0230': 'O',
        '\u00D6': 'O',
        '\u022A': 'O',
        '\u1ECE': 'O',
        '\u0150': 'O',
        '\u01D1': 'O',
        '\u020C': 'O',
        '\u020E': 'O',
        '\u01A0': 'O',
        '\u1EDC': 'O',
        '\u1EDA': 'O',
        '\u1EE0': 'O',
        '\u1EDE': 'O',
        '\u1EE2': 'O',
        '\u1ECC': 'O',
        '\u1ED8': 'O',
        '\u01EA': 'O',
        '\u01EC': 'O',
        '\u00D8': 'O',
        '\u01FE': 'O',
        '\u0186': 'O',
        '\u019F': 'O',
        '\uA74A': 'O',
        '\uA74C': 'O',
        '\u01A2': 'OI',
        '\uA74E': 'OO',
        '\u0222': 'OU',
        '\u24C5': 'P',
        '\uFF30': 'P',
        '\u1E54': 'P',
        '\u1E56': 'P',
        '\u01A4': 'P',
        '\u2C63': 'P',
        '\uA750': 'P',
        '\uA752': 'P',
        '\uA754': 'P',
        '\u24C6': 'Q',
        '\uFF31': 'Q',
        '\uA756': 'Q',
        '\uA758': 'Q',
        '\u024A': 'Q',
        '\u24C7': 'R',
        '\uFF32': 'R',
        '\u0154': 'R',
        '\u1E58': 'R',
        '\u0158': 'R',
        '\u0210': 'R',
        '\u0212': 'R',
        '\u1E5A': 'R',
        '\u1E5C': 'R',
        '\u0156': 'R',
        '\u1E5E': 'R',
        '\u024C': 'R',
        '\u2C64': 'R',
        '\uA75A': 'R',
        '\uA7A6': 'R',
        '\uA782': 'R',
        '\u24C8': 'S',
        '\uFF33': 'S',
        '\u1E9E': 'S',
        '\u015A': 'S',
        '\u1E64': 'S',
        '\u015C': 'S',
        '\u1E60': 'S',
        '\u0160': 'S',
        '\u1E66': 'S',
        '\u1E62': 'S',
        '\u1E68': 'S',
        '\u0218': 'S',
        '\u015E': 'S',
        '\u2C7E': 'S',
        '\uA7A8': 'S',
        '\uA784': 'S',
        '\u24C9': 'T',
        '\uFF34': 'T',
        '\u1E6A': 'T',
        '\u0164': 'T',
        '\u1E6C': 'T',
        '\u021A': 'T',
        '\u0162': 'T',
        '\u1E70': 'T',
        '\u1E6E': 'T',
        '\u0166': 'T',
        '\u01AC': 'T',
        '\u01AE': 'T',
        '\u023E': 'T',
        '\uA786': 'T',
        '\uA728': 'TZ',
        '\u24CA': 'U',
        '\uFF35': 'U',
        '\u00D9': 'U',
        '\u00DA': 'U',
        '\u00DB': 'U',
        '\u0168': 'U',
        '\u1E78': 'U',
        '\u016A': 'U',
        '\u1E7A': 'U',
        '\u016C': 'U',
        '\u00DC': 'U',
        '\u01DB': 'U',
        '\u01D7': 'U',
        '\u01D5': 'U',
        '\u01D9': 'U',
        '\u1EE6': 'U',
        '\u016E': 'U',
        '\u0170': 'U',
        '\u01D3': 'U',
        '\u0214': 'U',
        '\u0216': 'U',
        '\u01AF': 'U',
        '\u1EEA': 'U',
        '\u1EE8': 'U',
        '\u1EEE': 'U',
        '\u1EEC': 'U',
        '\u1EF0': 'U',
        '\u1EE4': 'U',
        '\u1E72': 'U',
        '\u0172': 'U',
        '\u1E76': 'U',
        '\u1E74': 'U',
        '\u0244': 'U',
        '\u24CB': 'V',
        '\uFF36': 'V',
        '\u1E7C': 'V',
        '\u1E7E': 'V',
        '\u01B2': 'V',
        '\uA75E': 'V',
        '\u0245': 'V',
        '\uA760': 'VY',
        '\u24CC': 'W',
        '\uFF37': 'W',
        '\u1E80': 'W',
        '\u1E82': 'W',
        '\u0174': 'W',
        '\u1E86': 'W',
        '\u1E84': 'W',
        '\u1E88': 'W',
        '\u2C72': 'W',
        '\u24CD': 'X',
        '\uFF38': 'X',
        '\u1E8A': 'X',
        '\u1E8C': 'X',
        '\u24CE': 'Y',
        '\uFF39': 'Y',
        '\u1EF2': 'Y',
        '\u00DD': 'Y',
        '\u0176': 'Y',
        '\u1EF8': 'Y',
        '\u0232': 'Y',
        '\u1E8E': 'Y',
        '\u0178': 'Y',
        '\u1EF6': 'Y',
        '\u1EF4': 'Y',
        '\u01B3': 'Y',
        '\u024E': 'Y',
        '\u1EFE': 'Y',
        '\u24CF': 'Z',
        '\uFF3A': 'Z',
        '\u0179': 'Z',
        '\u1E90': 'Z',
        '\u017B': 'Z',
        '\u017D': 'Z',
        '\u1E92': 'Z',
        '\u1E94': 'Z',
        '\u01B5': 'Z',
        '\u0224': 'Z',
        '\u2C7F': 'Z',
        '\u2C6B': 'Z',
        '\uA762': 'Z',
        '\u24D0': 'a',
        '\uFF41': 'a',
        '\u1E9A': 'a',
        '\u00E0': 'a',
        '\u00E1': 'a',
        '\u00E2': 'a',
        '\u1EA7': 'a',
        '\u1EA5': 'a',
        '\u1EAB': 'a',
        '\u1EA9': 'a',
        '\u00E3': 'a',
        '\u0101': 'a',
        '\u0103': 'a',
        '\u1EB1': 'a',
        '\u1EAF': 'a',
        '\u1EB5': 'a',
        '\u1EB3': 'a',
        '\u0227': 'a',
        '\u01E1': 'a',
        '\u00E4': 'a',
        '\u01DF': 'a',
        '\u1EA3': 'a',
        '\u00E5': 'a',
        '\u01FB': 'a',
        '\u01CE': 'a',
        '\u0201': 'a',
        '\u0203': 'a',
        '\u1EA1': 'a',
        '\u1EAD': 'a',
        '\u1EB7': 'a',
        '\u1E01': 'a',
        '\u0105': 'a',
        '\u2C65': 'a',
        '\u0250': 'a',
        '\uA733': 'aa',
        '\u00E6': 'ae',
        '\u01FD': 'ae',
        '\u01E3': 'ae',
        '\uA735': 'ao',
        '\uA737': 'au',
        '\uA739': 'av',
        '\uA73B': 'av',
        '\uA73D': 'ay',
        '\u24D1': 'b',
        '\uFF42': 'b',
        '\u1E03': 'b',
        '\u1E05': 'b',
        '\u1E07': 'b',
        '\u0180': 'b',
        '\u0183': 'b',
        '\u0253': 'b',
        '\u24D2': 'c',
        '\uFF43': 'c',
        '\u0107': 'c',
        '\u0109': 'c',
        '\u010B': 'c',
        '\u010D': 'c',
        '\u00E7': 'c',
        '\u1E09': 'c',
        '\u0188': 'c',
        '\u023C': 'c',
        '\uA73F': 'c',
        '\u2184': 'c',
        '\u24D3': 'd',
        '\uFF44': 'd',
        '\u1E0B': 'd',
        '\u010F': 'd',
        '\u1E0D': 'd',
        '\u1E11': 'd',
        '\u1E13': 'd',
        '\u1E0F': 'd',
        '\u0111': 'd',
        '\u018C': 'd',
        '\u0256': 'd',
        '\u0257': 'd',
        '\uA77A': 'd',
        '\u01F3': 'dz',
        '\u01C6': 'dz',
        '\u24D4': 'e',
        '\uFF45': 'e',
        '\u00E8': 'e',
        '\u00E9': 'e',
        '\u00EA': 'e',
        '\u1EC1': 'e',
        '\u1EBF': 'e',
        '\u1EC5': 'e',
        '\u1EC3': 'e',
        '\u1EBD': 'e',
        '\u0113': 'e',
        '\u1E15': 'e',
        '\u1E17': 'e',
        '\u0115': 'e',
        '\u0117': 'e',
        '\u00EB': 'e',
        '\u1EBB': 'e',
        '\u011B': 'e',
        '\u0205': 'e',
        '\u0207': 'e',
        '\u1EB9': 'e',
        '\u1EC7': 'e',
        '\u0229': 'e',
        '\u1E1D': 'e',
        '\u0119': 'e',
        '\u1E19': 'e',
        '\u1E1B': 'e',
        '\u0247': 'e',
        '\u025B': 'e',
        '\u01DD': 'e',
        '\u24D5': 'f',
        '\uFF46': 'f',
        '\u1E1F': 'f',
        '\u0192': 'f',
        '\uA77C': 'f',
        '\u24D6': 'g',
        '\uFF47': 'g',
        '\u01F5': 'g',
        '\u011D': 'g',
        '\u1E21': 'g',
        '\u011F': 'g',
        '\u0121': 'g',
        '\u01E7': 'g',
        '\u0123': 'g',
        '\u01E5': 'g',
        '\u0260': 'g',
        '\uA7A1': 'g',
        '\u1D79': 'g',
        '\uA77F': 'g',
        '\u24D7': 'h',
        '\uFF48': 'h',
        '\u0125': 'h',
        '\u1E23': 'h',
        '\u1E27': 'h',
        '\u021F': 'h',
        '\u1E25': 'h',
        '\u1E29': 'h',
        '\u1E2B': 'h',
        '\u1E96': 'h',
        '\u0127': 'h',
        '\u2C68': 'h',
        '\u2C76': 'h',
        '\u0265': 'h',
        '\u0195': 'hv',
        '\u24D8': 'i',
        '\uFF49': 'i',
        '\u00EC': 'i',
        '\u00ED': 'i',
        '\u00EE': 'i',
        '\u0129': 'i',
        '\u012B': 'i',
        '\u012D': 'i',
        '\u00EF': 'i',
        '\u1E2F': 'i',
        '\u1EC9': 'i',
        '\u01D0': 'i',
        '\u0209': 'i',
        '\u020B': 'i',
        '\u1ECB': 'i',
        '\u012F': 'i',
        '\u1E2D': 'i',
        '\u0268': 'i',
        '\u0131': 'i',
        '\u24D9': 'j',
        '\uFF4A': 'j',
        '\u0135': 'j',
        '\u01F0': 'j',
        '\u0249': 'j',
        '\u24DA': 'k',
        '\uFF4B': 'k',
        '\u1E31': 'k',
        '\u01E9': 'k',
        '\u1E33': 'k',
        '\u0137': 'k',
        '\u1E35': 'k',
        '\u0199': 'k',
        '\u2C6A': 'k',
        '\uA741': 'k',
        '\uA743': 'k',
        '\uA745': 'k',
        '\uA7A3': 'k',
        '\u24DB': 'l',
        '\uFF4C': 'l',
        '\u0140': 'l',
        '\u013A': 'l',
        '\u013E': 'l',
        '\u1E37': 'l',
        '\u1E39': 'l',
        '\u013C': 'l',
        '\u1E3D': 'l',
        '\u1E3B': 'l',
        '\u017F': 'l',
        '\u0142': 'l',
        '\u019A': 'l',
        '\u026B': 'l',
        '\u2C61': 'l',
        '\uA749': 'l',
        '\uA781': 'l',
        '\uA747': 'l',
        '\u01C9': 'lj',
        '\u24DC': 'm',
        '\uFF4D': 'm',
        '\u1E3F': 'm',
        '\u1E41': 'm',
        '\u1E43': 'm',
        '\u0271': 'm',
        '\u026F': 'm',
        '\u24DD': 'n',
        '\uFF4E': 'n',
        '\u01F9': 'n',
        '\u0144': 'n',
        '\u00F1': 'n',
        '\u1E45': 'n',
        '\u0148': 'n',
        '\u1E47': 'n',
        '\u0146': 'n',
        '\u1E4B': 'n',
        '\u1E49': 'n',
        '\u019E': 'n',
        '\u0272': 'n',
        '\u0149': 'n',
        '\uA791': 'n',
        '\uA7A5': 'n',
        '\u01CC': 'nj',
        '\u24DE': 'o',
        '\uFF4F': 'o',
        '\u00F2': 'o',
        '\u00F3': 'o',
        '\u00F4': 'o',
        '\u1ED3': 'o',
        '\u1ED1': 'o',
        '\u1ED7': 'o',
        '\u1ED5': 'o',
        '\u00F5': 'o',
        '\u1E4D': 'o',
        '\u022D': 'o',
        '\u1E4F': 'o',
        '\u014D': 'o',
        '\u1E51': 'o',
        '\u1E53': 'o',
        '\u014F': 'o',
        '\u022F': 'o',
        '\u0231': 'o',
        '\u00F6': 'o',
        '\u022B': 'o',
        '\u1ECF': 'o',
        '\u0151': 'o',
        '\u01D2': 'o',
        '\u020D': 'o',
        '\u020F': 'o',
        '\u01A1': 'o',
        '\u1EDD': 'o',
        '\u1EDB': 'o',
        '\u1EE1': 'o',
        '\u1EDF': 'o',
        '\u1EE3': 'o',
        '\u1ECD': 'o',
        '\u1ED9': 'o',
        '\u01EB': 'o',
        '\u01ED': 'o',
        '\u00F8': 'o',
        '\u01FF': 'o',
        '\u0254': 'o',
        '\uA74B': 'o',
        '\uA74D': 'o',
        '\u0275': 'o',
        '\u01A3': 'oi',
        '\u0223': 'ou',
        '\uA74F': 'oo',
        '\u24DF': 'p',
        '\uFF50': 'p',
        '\u1E55': 'p',
        '\u1E57': 'p',
        '\u01A5': 'p',
        '\u1D7D': 'p',
        '\uA751': 'p',
        '\uA753': 'p',
        '\uA755': 'p',
        '\u24E0': 'q',
        '\uFF51': 'q',
        '\u024B': 'q',
        '\uA757': 'q',
        '\uA759': 'q',
        '\u24E1': 'r',
        '\uFF52': 'r',
        '\u0155': 'r',
        '\u1E59': 'r',
        '\u0159': 'r',
        '\u0211': 'r',
        '\u0213': 'r',
        '\u1E5B': 'r',
        '\u1E5D': 'r',
        '\u0157': 'r',
        '\u1E5F': 'r',
        '\u024D': 'r',
        '\u027D': 'r',
        '\uA75B': 'r',
        '\uA7A7': 'r',
        '\uA783': 'r',
        '\u24E2': 's',
        '\uFF53': 's',
        '\u00DF': 's',
        '\u015B': 's',
        '\u1E65': 's',
        '\u015D': 's',
        '\u1E61': 's',
        '\u0161': 's',
        '\u1E67': 's',
        '\u1E63': 's',
        '\u1E69': 's',
        '\u0219': 's',
        '\u015F': 's',
        '\u023F': 's',
        '\uA7A9': 's',
        '\uA785': 's',
        '\u1E9B': 's',
        '\u24E3': 't',
        '\uFF54': 't',
        '\u1E6B': 't',
        '\u1E97': 't',
        '\u0165': 't',
        '\u1E6D': 't',
        '\u021B': 't',
        '\u0163': 't',
        '\u1E71': 't',
        '\u1E6F': 't',
        '\u0167': 't',
        '\u01AD': 't',
        '\u0288': 't',
        '\u2C66': 't',
        '\uA787': 't',
        '\uA729': 'tz',
        '\u24E4': 'u',
        '\uFF55': 'u',
        '\u00F9': 'u',
        '\u00FA': 'u',
        '\u00FB': 'u',
        '\u0169': 'u',
        '\u1E79': 'u',
        '\u016B': 'u',
        '\u1E7B': 'u',
        '\u016D': 'u',
        '\u00FC': 'u',
        '\u01DC': 'u',
        '\u01D8': 'u',
        '\u01D6': 'u',
        '\u01DA': 'u',
        '\u1EE7': 'u',
        '\u016F': 'u',
        '\u0171': 'u',
        '\u01D4': 'u',
        '\u0215': 'u',
        '\u0217': 'u',
        '\u01B0': 'u',
        '\u1EEB': 'u',
        '\u1EE9': 'u',
        '\u1EEF': 'u',
        '\u1EED': 'u',
        '\u1EF1': 'u',
        '\u1EE5': 'u',
        '\u1E73': 'u',
        '\u0173': 'u',
        '\u1E77': 'u',
        '\u1E75': 'u',
        '\u0289': 'u',
        '\u24E5': 'v',
        '\uFF56': 'v',
        '\u1E7D': 'v',
        '\u1E7F': 'v',
        '\u028B': 'v',
        '\uA75F': 'v',
        '\u028C': 'v',
        '\uA761': 'vy',
        '\u24E6': 'w',
        '\uFF57': 'w',
        '\u1E81': 'w',
        '\u1E83': 'w',
        '\u0175': 'w',
        '\u1E87': 'w',
        '\u1E85': 'w',
        '\u1E98': 'w',
        '\u1E89': 'w',
        '\u2C73': 'w',
        '\u24E7': 'x',
        '\uFF58': 'x',
        '\u1E8B': 'x',
        '\u1E8D': 'x',
        '\u24E8': 'y',
        '\uFF59': 'y',
        '\u1EF3': 'y',
        '\u00FD': 'y',
        '\u0177': 'y',
        '\u1EF9': 'y',
        '\u0233': 'y',
        '\u1E8F': 'y',
        '\u00FF': 'y',
        '\u1EF7': 'y',
        '\u1E99': 'y',
        '\u1EF5': 'y',
        '\u01B4': 'y',
        '\u024F': 'y',
        '\u1EFF': 'y',
        '\u24E9': 'z',
        '\uFF5A': 'z',
        '\u017A': 'z',
        '\u1E91': 'z',
        '\u017C': 'z',
        '\u017E': 'z',
        '\u1E93': 'z',
        '\u1E95': 'z',
        '\u01B6': 'z',
        '\u0225': 'z',
        '\u0240': 'z',
        '\u2C6C': 'z',
        '\uA763': 'z',
        '\u0386': '\u0391',
        '\u0388': '\u0395',
        '\u0389': '\u0397',
        '\u038A': '\u0399',
        '\u03AA': '\u0399',
        '\u038C': '\u039F',
        '\u038E': '\u03A5',
        '\u03AB': '\u03A5',
        '\u038F': '\u03A9',
        '\u03AC': '\u03B1',
        '\u03AD': '\u03B5',
        '\u03AE': '\u03B7',
        '\u03AF': '\u03B9',
        '\u03CA': '\u03B9',
        '\u0390': '\u03B9',
        '\u03CC': '\u03BF',
        '\u03CD': '\u03C5',
        '\u03CB': '\u03C5',
        '\u03B0': '\u03C5',
        '\u03C9': '\u03C9',
        '\u03C2': '\u03C3'
      };
    
      return diacritics;
    });
    
    S2.define('select2/data/base',[
      '../utils'
    ], function (Utils) {
      function BaseAdapter ($element, options) {
        BaseAdapter.__super__.constructor.call(this);
      }
    
      Utils.Extend(BaseAdapter, Utils.Observable);
    
      BaseAdapter.prototype.current = function (callback) {
        throw new Error('The `current` method must be defined in child classes.');
      };
    
      BaseAdapter.prototype.query = function (params, callback) {
        throw new Error('The `query` method must be defined in child classes.');
      };
    
      BaseAdapter.prototype.bind = function (container, $container) {
        // Can be implemented in subclasses
      };
    
      BaseAdapter.prototype.destroy = function () {
        // Can be implemented in subclasses
      };
    
      BaseAdapter.prototype.generateResultId = function (container, data) {
        var id = container.id + '-result-';
    
        id += Utils.generateChars(4);
    
        if (data.id != null) {
          id += '-' + data.id.toString();
        } else {
          id += '-' + Utils.generateChars(4);
        }
        return id;
      };
    
      return BaseAdapter;
    });
    
    S2.define('select2/data/select',[
      './base',
      '../utils',
      'jquery'
    ], function (BaseAdapter, Utils, $) {
      function SelectAdapter ($element, options) {
        this.$element = $element;
        this.options = options;
    
        SelectAdapter.__super__.constructor.call(this);
      }
    
      Utils.Extend(SelectAdapter, BaseAdapter);
    
      SelectAdapter.prototype.current = function (callback) {
        var data = [];
        var self = this;
    
        this.$element.find(':selected').each(function () {
          var $option = $(this);
    
          var option = self.item($option);
    
          data.push(option);
        });
    
        callback(data);
      };
    
      SelectAdapter.prototype.select = function (data) {
        var self = this;
    
        data.selected = true;
    
        // If data.element is a DOM node, use it instead
        if ($(data.element).is('option')) {
          data.element.selected = true;
    
          this.$element.trigger('change');
    
          return;
        }
    
        if (this.$element.prop('multiple')) {
          this.current(function (currentData) {
            var val = [];
    
            data = [data];
            data.push.apply(data, currentData);
    
            for (var d = 0; d < data.length; d++) {
              var id = data[d].id;
    
              if ($.inArray(id, val) === -1) {
                val.push(id);
              }
            }
    
            self.$element.val(val);
            self.$element.trigger('change');
          });
        } else {
          var val = data.id;
    
          this.$element.val(val);
          this.$element.trigger('change');
        }
      };
    
      SelectAdapter.prototype.unselect = function (data) {
        var self = this;
    
        if (!this.$element.prop('multiple')) {
          return;
        }
    
        data.selected = false;
    
        if ($(data.element).is('option')) {
          data.element.selected = false;
    
          this.$element.trigger('change');
    
          return;
        }
    
        this.current(function (currentData) {
          var val = [];
    
          for (var d = 0; d < currentData.length; d++) {
            var id = currentData[d].id;
    
            if (id !== data.id && $.inArray(id, val) === -1) {
              val.push(id);
            }
          }
    
          self.$element.val(val);
    
          self.$element.trigger('change');
        });
      };
    
      SelectAdapter.prototype.bind = function (container, $container) {
        var self = this;
    
        this.container = container;
    
        container.on('select', function (params) {
          self.select(params.data);
        });
    
        container.on('unselect', function (params) {
          self.unselect(params.data);
        });
      };
    
      SelectAdapter.prototype.destroy = function () {
        // Remove anything added to child elements
        this.$element.find('*').each(function () {
          // Remove any custom data set by Select2
          $.removeData(this, 'data');
        });
      };
    
      SelectAdapter.prototype.query = function (params, callback) {
        var data = [];
        var self = this;
    
        var $options = this.$element.children();
    
        $options.each(function () {
          var $option = $(this);
    
          if (!$option.is('option') && !$option.is('optgroup')) {
            return;
          }
    
          var option = self.item($option);
    
          var matches = self.matches(params, option);
    
          if (matches !== null) {
            data.push(matches);
          }
        });
    
        callback({
          results: data
        });
      };
    
      SelectAdapter.prototype.addOptions = function ($options) {
        Utils.appendMany(this.$element, $options);
      };
    
      SelectAdapter.prototype.option = function (data) {
        var option;
    
        if (data.children) {
          option = document.createElement('optgroup');
          option.label = data.text;
        } else {
          option = document.createElement('option');
    
          if (option.textContent !== undefined) {
            option.textContent = data.text;
          } else {
            option.innerText = data.text;
          }
        }
    
        if (data.id !== undefined) {
          option.value = data.id;
        }
    
        if (data.disabled) {
          option.disabled = true;
        }
    
        if (data.selected) {
          option.selected = true;
        }
    
        if (data.title) {
          option.title = data.title;
        }
    
        var $option = $(option);
    
        var normalizedData = this._normalizeItem(data);
        normalizedData.element = option;
    
        // Override the option's data with the combined data
        $.data(option, 'data', normalizedData);
    
        return $option;
      };
    
      SelectAdapter.prototype.item = function ($option) {
        var data = {};
    
        data = $.data($option[0], 'data');
    
        if (data != null) {
          return data;
        }
    
        if ($option.is('option')) {
          data = {
            id: $option.val(),
            text: $option.text(),
            disabled: $option.prop('disabled'),
            selected: $option.prop('selected'),
            title: $option.prop('title')
          };
        } else if ($option.is('optgroup')) {
          data = {
            text: $option.prop('label'),
            children: [],
            title: $option.prop('title')
          };
    
          var $children = $option.children('option');
          var children = [];
    
          for (var c = 0; c < $children.length; c++) {
            var $child = $($children[c]);
    
            var child = this.item($child);
    
            children.push(child);
          }
    
          data.children = children;
        }
    
        data = this._normalizeItem(data);
        data.element = $option[0];
    
        $.data($option[0], 'data', data);
    
        return data;
      };
    
      SelectAdapter.prototype._normalizeItem = function (item) {
        if (!$.isPlainObject(item)) {
          item = {
            id: item,
            text: item
          };
        }
    
        item = $.extend({}, {
          text: ''
        }, item);
    
        var defaults = {
          selected: false,
          disabled: false
        };
    
        if (item.id != null) {
          item.id = item.id.toString();
        }
    
        if (item.text != null) {
          item.text = item.text.toString();
        }
    
        if (item._resultId == null && item.id && this.container != null) {
          item._resultId = this.generateResultId(this.container, item);
        }
    
        return $.extend({}, defaults, item);
      };
    
      SelectAdapter.prototype.matches = function (params, data) {
        var matcher = this.options.get('matcher');
    
        return matcher(params, data);
      };
    
      return SelectAdapter;
    });
    
    S2.define('select2/data/array',[
      './select',
      '../utils',
      'jquery'
    ], function (SelectAdapter, Utils, $) {
      function ArrayAdapter ($element, options) {
        var data = options.get('data') || [];
    
        ArrayAdapter.__super__.constructor.call(this, $element, options);
    
        this.addOptions(this.convertToOptions(data));
      }
    
      Utils.Extend(ArrayAdapter, SelectAdapter);
    
      ArrayAdapter.prototype.select = function (data) {
        var $option = this.$element.find('option').filter(function (i, elm) {
          return elm.value == data.id.toString();
        });
    
        if ($option.length === 0) {
          $option = this.option(data);
    
          this.addOptions($option);
        }
    
        ArrayAdapter.__super__.select.call(this, data);
      };
    
      ArrayAdapter.prototype.convertToOptions = function (data) {
        var self = this;
    
        var $existing = this.$element.find('option');
        var existingIds = $existing.map(function () {
          return self.item($(this)).id;
        }).get();
    
        var $options = [];
    
        // Filter out all items except for the one passed in the argument
        function onlyItem (item) {
          return function () {
            return $(this).val() == item.id;
          };
        }
    
        for (var d = 0; d < data.length; d++) {
          var item = this._normalizeItem(data[d]);
    
          // Skip items which were pre-loaded, only merge the data
          if ($.inArray(item.id, existingIds) >= 0) {
            var $existingOption = $existing.filter(onlyItem(item));
    
            var existingData = this.item($existingOption);
            var newData = $.extend(true, {}, item, existingData);
    
            var $newOption = this.option(newData);
    
            $existingOption.replaceWith($newOption);
    
            continue;
          }
    
          var $option = this.option(item);
    
          if (item.children) {
            var $children = this.convertToOptions(item.children);
    
            Utils.appendMany($option, $children);
          }
    
          $options.push($option);
        }
    
        return $options;
      };
    
      return ArrayAdapter;
    });
    
    S2.define('select2/data/ajax',[
      './array',
      '../utils',
      'jquery'
    ], function (ArrayAdapter, Utils, $) {
      function AjaxAdapter ($element, options) {
        this.ajaxOptions = this._applyDefaults(options.get('ajax'));
    
        if (this.ajaxOptions.processResults != null) {
          this.processResults = this.ajaxOptions.processResults;
        }
    
        AjaxAdapter.__super__.constructor.call(this, $element, options);
      }
    
      Utils.Extend(AjaxAdapter, ArrayAdapter);
    
      AjaxAdapter.prototype._applyDefaults = function (options) {
        var defaults = {
          data: function (params) {
            return $.extend({}, params, {
              q: params.term
            });
          },
          transport: function (params, success, failure) {
            var $request = $.ajax(params);
    
            $request.then(success);
            $request.fail(failure);
    
            return $request;
          }
        };
    
        return $.extend({}, defaults, options, true);
      };
    
      AjaxAdapter.prototype.processResults = function (results) {
        return results;
      };
    
      AjaxAdapter.prototype.query = function (params, callback) {
        var matches = [];
        var self = this;
    
        if (this._request != null) {
          // JSONP requests cannot always be aborted
          if ($.isFunction(this._request.abort)) {
            this._request.abort();
          }
    
          this._request = null;
        }
    
        var options = $.extend({
          type: 'GET'
        }, this.ajaxOptions);
    
        if (typeof options.url === 'function') {
          options.url = options.url.call(this.$element, params);
        }
    
        if (typeof options.data === 'function') {
          options.data = options.data.call(this.$element, params);
        }
    
        function request () {
          var $request = options.transport(options, function (data) {
            var results = self.processResults(data, params);
    
            if (self.options.get('debug') && window.console && console.error) {
              // Check to make sure that the response included a `results` key.
              if (!results || !results.results || !$.isArray(results.results)) {
                console.error(
                  'Select2: The AJAX results did not return an array in the ' +
                  '`results` key of the response.'
                );
              }
            }
    
            callback(results);
          }, function () {
            // Attempt to detect if a request was aborted
            // Only works if the transport exposes a status property
            if ($request.status && $request.status === '0') {
              return;
            }
    
            self.trigger('results:message', {
              message: 'errorLoading'
            });
          });
    
          self._request = $request;
        }
    
        if (this.ajaxOptions.delay && params.term != null) {
          if (this._queryTimeout) {
            window.clearTimeout(this._queryTimeout);
          }
    
          this._queryTimeout = window.setTimeout(request, this.ajaxOptions.delay);
        } else {
          request();
        }
      };
    
      return AjaxAdapter;
    });
    
    S2.define('select2/data/tags',[
      'jquery'
    ], function ($) {
      function Tags (decorated, $element, options) {
        var tags = options.get('tags');
    
        var createTag = options.get('createTag');
    
        if (createTag !== undefined) {
          this.createTag = createTag;
        }
    
        var insertTag = options.get('insertTag');
    
        if (insertTag !== undefined) {
            this.insertTag = insertTag;
        }
    
        decorated.call(this, $element, options);
    
        if ($.isArray(tags)) {
          for (var t = 0; t < tags.length; t++) {
            var tag = tags[t];
            var item = this._normalizeItem(tag);
    
            var $option = this.option(item);
    
            this.$element.append($option);
          }
        }
      }
    
      Tags.prototype.query = function (decorated, params, callback) {
        var self = this;
    
        this._removeOldTags();
    
        if (params.term == null || params.page != null) {
          decorated.call(this, params, callback);
          return;
        }
    
        function wrapper (obj, child) {
          var data = obj.results;
    
          for (var i = 0; i < data.length; i++) {
            var option = data[i];
    
            var checkChildren = (
              option.children != null &&
              !wrapper({
                results: option.children
              }, true)
            );
    
            var optionText = (option.text || '').toUpperCase();
            var paramsTerm = (params.term || '').toUpperCase();
    
            var checkText = optionText === paramsTerm;
    
            if (checkText || checkChildren) {
              if (child) {
                return false;
              }
    
              obj.data = data;
              callback(obj);
    
              return;
            }
          }
    
          if (child) {
            return true;
          }
    
          var tag = self.createTag(params);
    
          if (tag != null) {
            var $option = self.option(tag);
            $option.attr('data-select2-tag', true);
    
            self.addOptions([$option]);
    
            self.insertTag(data, tag);
          }
    
          obj.results = data;
    
          callback(obj);
        }
    
        decorated.call(this, params, wrapper);
      };
    
      Tags.prototype.createTag = function (decorated, params) {
        var term = $.trim(params.term);
    
        if (term === '') {
          return null;
        }
    
        return {
          id: term,
          text: term
        };
      };
    
      Tags.prototype.insertTag = function (_, data, tag) {
        data.unshift(tag);
      };
    
      Tags.prototype._removeOldTags = function (_) {
        var tag = this._lastTag;
    
        var $options = this.$element.find('option[data-select2-tag]');
    
        $options.each(function () {
          if (this.selected) {
            return;
          }
    
          $(this).remove();
        });
      };
    
      return Tags;
    });
    
    S2.define('select2/data/tokenizer',[
      'jquery'
    ], function ($) {
      function Tokenizer (decorated, $element, options) {
        var tokenizer = options.get('tokenizer');
    
        if (tokenizer !== undefined) {
          this.tokenizer = tokenizer;
        }
    
        decorated.call(this, $element, options);
      }
    
      Tokenizer.prototype.bind = function (decorated, container, $container) {
        decorated.call(this, container, $container);
    
        this.$search =  container.dropdown.$search || container.selection.$search ||
          $container.find('.select2-search__field');
      };
    
      Tokenizer.prototype.query = function (decorated, params, callback) {
        var self = this;
    
        function createAndSelect (data) {
          // Normalize the data object so we can use it for checks
          var item = self._normalizeItem(data);
    
          // Check if the data object already exists as a tag
          // Select it if it doesn't
          var $existingOptions = self.$element.find('option').filter(function () {
            return $(this).val() === item.id;
          });
    
          // If an existing option wasn't found for it, create the option
          if (!$existingOptions.length) {
            var $option = self.option(item);
            $option.attr('data-select2-tag', true);
    
            self._removeOldTags();
            self.addOptions([$option]);
          }
    
          // Select the item, now that we know there is an option for it
          select(item);
        }
    
        function select (data) {
          self.trigger('select', {
            data: data
          });
        }
    
        params.term = params.term || '';
    
        var tokenData = this.tokenizer(params, this.options, createAndSelect);
    
        if (tokenData.term !== params.term) {
          // Replace the search term if we have the search box
          if (this.$search.length) {
            this.$search.val(tokenData.term);
            this.$search.focus();
          }
    
          params.term = tokenData.term;
        }
    
        decorated.call(this, params, callback);
      };
    
      Tokenizer.prototype.tokenizer = function (_, params, options, callback) {
        var separators = options.get('tokenSeparators') || [];
        var term = params.term;
        var i = 0;
    
        var createTag = this.createTag || function (params) {
          return {
            id: params.term,
            text: params.term
          };
        };
    
        while (i < term.length) {
          var termChar = term[i];
    
          if ($.inArray(termChar, separators) === -1) {
            i++;
    
            continue;
          }
    
          var part = term.substr(0, i);
          var partParams = $.extend({}, params, {
            term: part
          });
    
          var data = createTag(partParams);
    
          if (data == null) {
            i++;
            continue;
          }
    
          callback(data);
    
          // Reset the term to not include the tokenized portion
          term = term.substr(i + 1) || '';
          i = 0;
        }
    
        return {
          term: term
        };
      };
    
      return Tokenizer;
    });
    
    S2.define('select2/data/minimumInputLength',[
    
    ], function () {
      function MinimumInputLength (decorated, $e, options) {
        this.minimumInputLength = options.get('minimumInputLength');
    
        decorated.call(this, $e, options);
      }
    
      MinimumInputLength.prototype.query = function (decorated, params, callback) {
        params.term = params.term || '';
    
        if (params.term.length < this.minimumInputLength) {
          this.trigger('results:message', {
            message: 'inputTooShort',
            args: {
              minimum: this.minimumInputLength,
              input: params.term,
              params: params
            }
          });
    
          return;
        }
    
        decorated.call(this, params, callback);
      };
    
      return MinimumInputLength;
    });
    
    S2.define('select2/data/maximumInputLength',[
    
    ], function () {
      function MaximumInputLength (decorated, $e, options) {
        this.maximumInputLength = options.get('maximumInputLength');
    
        decorated.call(this, $e, options);
      }
    
      MaximumInputLength.prototype.query = function (decorated, params, callback) {
        params.term = params.term || '';
    
        if (this.maximumInputLength > 0 &&
            params.term.length > this.maximumInputLength) {
          this.trigger('results:message', {
            message: 'inputTooLong',
            args: {
              maximum: this.maximumInputLength,
              input: params.term,
              params: params
            }
          });
    
          return;
        }
    
        decorated.call(this, params, callback);
      };
    
      return MaximumInputLength;
    });
    
    S2.define('select2/data/maximumSelectionLength',[
    
    ], function (){
      function MaximumSelectionLength (decorated, $e, options) {
        this.maximumSelectionLength = options.get('maximumSelectionLength');
    
        decorated.call(this, $e, options);
      }
    
      MaximumSelectionLength.prototype.query =
        function (decorated, params, callback) {
          var self = this;
    
          this.current(function (currentData) {
            var count = currentData != null ? currentData.length : 0;
            if (self.maximumSelectionLength > 0 &&
              count >= self.maximumSelectionLength) {
              self.trigger('results:message', {
                message: 'maximumSelected',
                args: {
                  maximum: self.maximumSelectionLength
                }
              });
              return;
            }
            decorated.call(self, params, callback);
          });
      };
    
      return MaximumSelectionLength;
    });
    
    S2.define('select2/dropdown',[
      'jquery',
      './utils'
    ], function ($, Utils) {
      function Dropdown ($element, options) {
        this.$element = $element;
        this.options = options;
    
        Dropdown.__super__.constructor.call(this);
      }
    
      Utils.Extend(Dropdown, Utils.Observable);
    
      Dropdown.prototype.render = function () {
        var $dropdown = $(
          '<span class="select2-dropdown">' +
            '<span class="select2-results"></span>' +
          '</span>'
        );
    
        $dropdown.attr('dir', this.options.get('dir'));
    
        this.$dropdown = $dropdown;
    
        return $dropdown;
      };
    
      Dropdown.prototype.bind = function () {
        // Should be implemented in subclasses
      };
    
      Dropdown.prototype.position = function ($dropdown, $container) {
        // Should be implmented in subclasses
      };
    
      Dropdown.prototype.destroy = function () {
        // Remove the dropdown from the DOM
        this.$dropdown.remove();
      };
    
      return Dropdown;
    });
    
    S2.define('select2/dropdown/search',[
      'jquery',
      '../utils'
    ], function ($, Utils) {
      function Search () { }
    
      Search.prototype.render = function (decorated) {
        var $rendered = decorated.call(this);
    
        var $search = $(
          '<span class="select2-search select2-search--dropdown">' +
            '<input class="select2-search__field" type="search" tabindex="-1"' +
            ' autocomplete="off" autocorrect="off" autocapitalize="off"' +
            ' spellcheck="false" role="textbox" />' +
          '</span>'
        );
    
        this.$searchContainer = $search;
        this.$search = $search.find('input');
    
        $rendered.prepend($search);
    
        return $rendered;
      };
    
      Search.prototype.bind = function (decorated, container, $container) {
        var self = this;
    
        decorated.call(this, container, $container);
    
        this.$search.on('keydown', function (evt) {
          self.trigger('keypress', evt);
    
          self._keyUpPrevented = evt.isDefaultPrevented();
        });
    
        // Workaround for browsers which do not support the `input` event
        // This will prevent double-triggering of events for browsers which support
        // both the `keyup` and `input` events.
        this.$search.on('input', function (evt) {
          // Unbind the duplicated `keyup` event
          $(this).off('keyup');
        });
    
        this.$search.on('keyup input', function (evt) {
          self.handleSearch(evt);
        });
    
        container.on('open', function () {
          self.$search.attr('tabindex', 0);
    
          self.$search.focus();
    
          window.setTimeout(function () {
            self.$search.focus();
          }, 0);
        });
    
        container.on('close', function () {
          self.$search.attr('tabindex', -1);
    
          self.$search.val('');
        });
    
        container.on('focus', function () {
          if (!container.isOpen()) {
            self.$search.focus();
          }
        });
    
        container.on('results:all', function (params) {
          if (params.query.term == null || params.query.term === '') {
            var showSearch = self.showSearch(params);
    
            if (showSearch) {
              self.$searchContainer.removeClass('select2-search--hide');
            } else {
              self.$searchContainer.addClass('select2-search--hide');
            }
          }
        });
      };
    
      Search.prototype.handleSearch = function (evt) {
        if (!this._keyUpPrevented) {
          var input = this.$search.val();
    
          this.trigger('query', {
            term: input
          });
        }
    
        this._keyUpPrevented = false;
      };
    
      Search.prototype.showSearch = function (_, params) {
        return true;
      };
    
      return Search;
    });
    
    S2.define('select2/dropdown/hidePlaceholder',[
    
    ], function () {
      function HidePlaceholder (decorated, $element, options, dataAdapter) {
        this.placeholder = this.normalizePlaceholder(options.get('placeholder'));
    
        decorated.call(this, $element, options, dataAdapter);
      }
    
      HidePlaceholder.prototype.append = function (decorated, data) {
        data.results = this.removePlaceholder(data.results);
    
        decorated.call(this, data);
      };
    
      HidePlaceholder.prototype.normalizePlaceholder = function (_, placeholder) {
        if (typeof placeholder === 'string') {
          placeholder = {
            id: '',
            text: placeholder
          };
        }
    
        return placeholder;
      };
    
      HidePlaceholder.prototype.removePlaceholder = function (_, data) {
        var modifiedData = data.slice(0);
    
        for (var d = data.length - 1; d >= 0; d--) {
          var item = data[d];
    
          if (this.placeholder.id === item.id) {
            modifiedData.splice(d, 1);
          }
        }
    
        return modifiedData;
      };
    
      return HidePlaceholder;
    });
    
    S2.define('select2/dropdown/infiniteScroll',[
      'jquery'
    ], function ($) {
      function InfiniteScroll (decorated, $element, options, dataAdapter) {
        this.lastParams = {};
    
        decorated.call(this, $element, options, dataAdapter);
    
        this.$loadingMore = this.createLoadingMore();
        this.loading = false;
      }
    
      InfiniteScroll.prototype.append = function (decorated, data) {
        this.$loadingMore.remove();
        this.loading = false;
    
        decorated.call(this, data);
    
        if (this.showLoadingMore(data)) {
          this.$results.append(this.$loadingMore);
        }
      };
    
      InfiniteScroll.prototype.bind = function (decorated, container, $container) {
        var self = this;
    
        decorated.call(this, container, $container);
    
        container.on('query', function (params) {
          self.lastParams = params;
          self.loading = true;
        });
    
        container.on('query:append', function (params) {
          self.lastParams = params;
          self.loading = true;
        });
    
        this.$results.on('scroll', function () {
          var isLoadMoreVisible = $.contains(
            document.documentElement,
            self.$loadingMore[0]
          );
    
          if (self.loading || !isLoadMoreVisible) {
            return;
          }
    
          var currentOffset = self.$results.offset().top +
            self.$results.outerHeight(false);
          var loadingMoreOffset = self.$loadingMore.offset().top +
            self.$loadingMore.outerHeight(false);
    
          if (currentOffset + 50 >= loadingMoreOffset) {
            self.loadMore();
          }
        });
      };
    
      InfiniteScroll.prototype.loadMore = function () {
        this.loading = true;
    
        var params = $.extend({}, {page: 1}, this.lastParams);
    
        params.page++;
    
        this.trigger('query:append', params);
      };
    
      InfiniteScroll.prototype.showLoadingMore = function (_, data) {
        return data.pagination && data.pagination.more;
      };
    
      InfiniteScroll.prototype.createLoadingMore = function () {
        var $option = $(
          '<li ' +
          'class="select2-results__option select2-results__option--load-more"' +
          'role="treeitem" aria-disabled="true"></li>'
        );
    
        var message = this.options.get('translations').get('loadingMore');
    
        $option.html(message(this.lastParams));
    
        return $option;
      };
    
      return InfiniteScroll;
    });
    
    S2.define('select2/dropdown/attachBody',[
      'jquery',
      '../utils'
    ], function ($, Utils) {
      function AttachBody (decorated, $element, options) {
        this.$dropdownParent = options.get('dropdownParent') || $(document.body);
    
        decorated.call(this, $element, options);
      }
    
      AttachBody.prototype.bind = function (decorated, container, $container) {
        var self = this;
    
        var setupResultsEvents = false;
    
        decorated.call(this, container, $container);
    
        container.on('open', function () {
          self._showDropdown();
          self._attachPositioningHandler(container);
    
          if (!setupResultsEvents) {
            setupResultsEvents = true;
    
            container.on('results:all', function () {
              self._positionDropdown();
              self._resizeDropdown();
            });
    
            container.on('results:append', function () {
              self._positionDropdown();
              self._resizeDropdown();
            });
          }
        });
    
        container.on('close', function () {
          self._hideDropdown();
          self._detachPositioningHandler(container);
        });
    
        this.$dropdownContainer.on('mousedown', function (evt) {
          evt.stopPropagation();
        });
      };
    
      AttachBody.prototype.destroy = function (decorated) {
        decorated.call(this);
    
        this.$dropdownContainer.remove();
      };
    
      AttachBody.prototype.position = function (decorated, $dropdown, $container) {
        // Clone all of the container classes
        $dropdown.attr('class', $container.attr('class'));
    
        $dropdown.removeClass('select2');
        $dropdown.addClass('select2-container--open');
    
        $dropdown.css({
          position: 'absolute',
          top: -999999
        });
    
        this.$container = $container;
      };
    
      AttachBody.prototype.render = function (decorated) {
        var $container = $('<span></span>');
    
        var $dropdown = decorated.call(this);
        $container.append($dropdown);
    
        this.$dropdownContainer = $container;
    
        return $container;
      };
    
      AttachBody.prototype._hideDropdown = function (decorated) {
        this.$dropdownContainer.detach();
      };
    
      AttachBody.prototype._attachPositioningHandler =
          function (decorated, container) {
        var self = this;
    
        var scrollEvent = 'scroll.select2.' + container.id;
        var resizeEvent = 'resize.select2.' + container.id;
        var orientationEvent = 'orientationchange.select2.' + container.id;
    
        var $watchers = this.$container.parents().filter(Utils.hasScroll);
        $watchers.each(function () {
          $(this).data('select2-scroll-position', {
            x: $(this).scrollLeft(),
            y: $(this).scrollTop()
          });
        });
    
        $watchers.on(scrollEvent, function (ev) {
          var position = $(this).data('select2-scroll-position');
          $(this).scrollTop(position.y);
        });
    
        $(window).on(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent,
          function (e) {
          self._positionDropdown();
          self._resizeDropdown();
        });
      };
    
      AttachBody.prototype._detachPositioningHandler =
          function (decorated, container) {
        var scrollEvent = 'scroll.select2.' + container.id;
        var resizeEvent = 'resize.select2.' + container.id;
        var orientationEvent = 'orientationchange.select2.' + container.id;
    
        var $watchers = this.$container.parents().filter(Utils.hasScroll);
        $watchers.off(scrollEvent);
    
        $(window).off(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent);
      };
    
      AttachBody.prototype._positionDropdown = function () {
        var $window = $(window);
    
        var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above');
        var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below');
    
        var newDirection = null;
    
        var offset = this.$container.offset();
    
        offset.bottom = offset.top + this.$container.outerHeight(false);
    
        var container = {
          height: this.$container.outerHeight(false)
        };
    
        container.top = offset.top;
        container.bottom = offset.top + container.height;
    
        var dropdown = {
          height: this.$dropdown.outerHeight(false)
        };
    
        var viewport = {
          top: $window.scrollTop(),
          bottom: $window.scrollTop() + $window.height()
        };
    
        var enoughRoomAbove = viewport.top < (offset.top - dropdown.height);
        var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height);
    
        var css = {
          left: offset.left,
          top: container.bottom
        };
    
        // Determine what the parent element is to use for calciulating the offset
        var $offsetParent = this.$dropdownParent;
    
        // For statically positoned elements, we need to get the element
        // that is determining the offset
        if ($offsetParent.css('position') === 'static') {
          $offsetParent = $offsetParent.offsetParent();
        }
    
        var parentOffset = $offsetParent.offset();
    
        css.top -= parentOffset.top;
        css.left -= parentOffset.left;
    
        if (!isCurrentlyAbove && !isCurrentlyBelow) {
          newDirection = 'below';
        }
    
        if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) {
          newDirection = 'above';
        } else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) {
          newDirection = 'below';
        }
    
        if (newDirection == 'above' ||
          (isCurrentlyAbove && newDirection !== 'below')) {
          css.top = container.top - parentOffset.top - dropdown.height;
        }
    
        if (newDirection != null) {
          this.$dropdown
            .removeClass('select2-dropdown--below select2-dropdown--above')
            .addClass('select2-dropdown--' + newDirection);
          this.$container
            .removeClass('select2-container--below select2-container--above')
            .addClass('select2-container--' + newDirection);
        }
    
        this.$dropdownContainer.css(css);
      };
    
      AttachBody.prototype._resizeDropdown = function () {
        var css = {
          width: this.$container.outerWidth(false) + 'px'
        };
    
        if (this.options.get('dropdownAutoWidth')) {
          css.minWidth = css.width;
          css.position = 'relative';
          css.width = 'auto';
        }
    
        this.$dropdown.css(css);
      };
    
      AttachBody.prototype._showDropdown = function (decorated) {
        this.$dropdownContainer.appendTo(this.$dropdownParent);
    
        this._positionDropdown();
        this._resizeDropdown();
      };
    
      return AttachBody;
    });
    
    S2.define('select2/dropdown/minimumResultsForSearch',[
    
    ], function () {
      function countResults (data) {
        var count = 0;
    
        for (var d = 0; d < data.length; d++) {
          var item = data[d];
    
          if (item.children) {
            count += countResults(item.children);
          } else {
            count++;
          }
        }
    
        return count;
      }
    
      function MinimumResultsForSearch (decorated, $element, options, dataAdapter) {
        this.minimumResultsForSearch = options.get('minimumResultsForSearch');
    
        if (this.minimumResultsForSearch < 0) {
          this.minimumResultsForSearch = Infinity;
        }
    
        decorated.call(this, $element, options, dataAdapter);
      }
    
      MinimumResultsForSearch.prototype.showSearch = function (decorated, params) {
        if (countResults(params.data.results) < this.minimumResultsForSearch) {
          return false;
        }
    
        return decorated.call(this, params);
      };
    
      return MinimumResultsForSearch;
    });
    
    S2.define('select2/dropdown/selectOnClose',[
    
    ], function () {
      function SelectOnClose () { }
    
      SelectOnClose.prototype.bind = function (decorated, container, $container) {
        var self = this;
    
        decorated.call(this, container, $container);
    
        container.on('close', function (params) {
          self._handleSelectOnClose(params);
        });
      };
    
      SelectOnClose.prototype._handleSelectOnClose = function (_, params) {
        if (params && params.originalSelect2Event != null) {
          var event = params.originalSelect2Event;
    
          // Don't select an item if the close event was triggered from a select or
          // unselect event
          if (event._type === 'select' || event._type === 'unselect') {
            return;
          }
        }
    
        var $highlightedResults = this.getHighlightedResults();
    
        // Only select highlighted results
        if ($highlightedResults.length < 1) {
          return;
        }
    
        var data = $highlightedResults.data('data');
    
        // Don't re-select already selected resulte
        if (
          (data.element != null && data.element.selected) ||
          (data.element == null && data.selected)
        ) {
          return;
        }
    
        this.trigger('select', {
            data: data
        });
      };
    
      return SelectOnClose;
    });
    
    S2.define('select2/dropdown/closeOnSelect',[
    
    ], function () {
      function CloseOnSelect () { }
    
      CloseOnSelect.prototype.bind = function (decorated, container, $container) {
        var self = this;
    
        decorated.call(this, container, $container);
    
        container.on('select', function (evt) {
          self._selectTriggered(evt);
        });
    
        container.on('unselect', function (evt) {
          self._selectTriggered(evt);
        });
      };
    
      CloseOnSelect.prototype._selectTriggered = function (_, evt) {
        var originalEvent = evt.originalEvent;
    
        // Don't close if the control key is being held
        if (originalEvent && originalEvent.ctrlKey) {
          return;
        }
    
        this.trigger('close', {
          originalEvent: originalEvent,
          originalSelect2Event: evt
        });
      };
    
      return CloseOnSelect;
    });
    
    S2.define('select2/i18n/en',[],function () {
      // English
      return {
        errorLoading: function () {
          return 'The results could not be loaded.';
        },
        inputTooLong: function (args) {
          var overChars = args.input.length - args.maximum;
    
          var message = 'Please delete ' + overChars + ' character';
    
          if (overChars != 1) {
            message += 's';
          }
    
          return message;
        },
        inputTooShort: function (args) {
          var remainingChars = args.minimum - args.input.length;
    
          var message = 'Please enter ' + remainingChars + ' or more characters';
    
          return message;
        },
        loadingMore: function () {
          return 'Loading more resultsâ€¦';
        },
        maximumSelected: function (args) {
          var message = 'You can only select ' + args.maximum + ' item';
    
          if (args.maximum != 1) {
            message += 's';
          }
    
          return message;
        },
        noResults: function () {
          return 'No results found';
        },
        searching: function () {
          return 'Searchingâ€¦';
        }
      };
    });
    
    S2.define('select2/defaults',[
      'jquery',
      'require',
    
      './results',
    
      './selection/single',
      './selection/multiple',
      './selection/placeholder',
      './selection/allowClear',
      './selection/search',
      './selection/eventRelay',
    
      './utils',
      './translation',
      './diacritics',
    
      './data/select',
      './data/array',
      './data/ajax',
      './data/tags',
      './data/tokenizer',
      './data/minimumInputLength',
      './data/maximumInputLength',
      './data/maximumSelectionLength',
    
      './dropdown',
      './dropdown/search',
      './dropdown/hidePlaceholder',
      './dropdown/infiniteScroll',
      './dropdown/attachBody',
      './dropdown/minimumResultsForSearch',
      './dropdown/selectOnClose',
      './dropdown/closeOnSelect',
    
      './i18n/en'
    ], function ($, require,
    
                 ResultsList,
    
                 SingleSelection, MultipleSelection, Placeholder, AllowClear,
                 SelectionSearch, EventRelay,
    
                 Utils, Translation, DIACRITICS,
    
                 SelectData, ArrayData, AjaxData, Tags, Tokenizer,
                 MinimumInputLength, MaximumInputLength, MaximumSelectionLength,
    
                 Dropdown, DropdownSearch, HidePlaceholder, InfiniteScroll,
                 AttachBody, MinimumResultsForSearch, SelectOnClose, CloseOnSelect,
    
                 EnglishTranslation) {
      function Defaults () {
        this.reset();
      }
    
      Defaults.prototype.apply = function (options) {
        options = $.extend(true, {}, this.defaults, options);
    
        if (options.dataAdapter == null) {
          if (options.ajax != null) {
            options.dataAdapter = AjaxData;
          } else if (options.data != null) {
            options.dataAdapter = ArrayData;
          } else {
            options.dataAdapter = SelectData;
          }
    
          if (options.minimumInputLength > 0) {
            options.dataAdapter = Utils.Decorate(
              options.dataAdapter,
              MinimumInputLength
            );
          }
    
          if (options.maximumInputLength > 0) {
            options.dataAdapter = Utils.Decorate(
              options.dataAdapter,
              MaximumInputLength
            );
          }
    
          if (options.maximumSelectionLength > 0) {
            options.dataAdapter = Utils.Decorate(
              options.dataAdapter,
              MaximumSelectionLength
            );
          }
    
          if (options.tags) {
            options.dataAdapter = Utils.Decorate(options.dataAdapter, Tags);
          }
    
          if (options.tokenSeparators != null || options.tokenizer != null) {
            options.dataAdapter = Utils.Decorate(
              options.dataAdapter,
              Tokenizer
            );
          }
    
          if (options.query != null) {
            var Query = require(options.amdBase + 'compat/query');
    
            options.dataAdapter = Utils.Decorate(
              options.dataAdapter,
              Query
            );
          }
    
          if (options.initSelection != null) {
            var InitSelection = require(options.amdBase + 'compat/initSelection');
    
            options.dataAdapter = Utils.Decorate(
              options.dataAdapter,
              InitSelection
            );
          }
        }
    
        if (options.resultsAdapter == null) {
          options.resultsAdapter = ResultsList;
    
          if (options.ajax != null) {
            options.resultsAdapter = Utils.Decorate(
              options.resultsAdapter,
              InfiniteScroll
            );
          }
    
          if (options.placeholder != null) {
            options.resultsAdapter = Utils.Decorate(
              options.resultsAdapter,
              HidePlaceholder
            );
          }
    
          if (options.selectOnClose) {
            options.resultsAdapter = Utils.Decorate(
              options.resultsAdapter,
              SelectOnClose
            );
          }
        }
    
        if (options.dropdownAdapter == null) {
          if (options.multiple) {
            options.dropdownAdapter = Dropdown;
          } else {
            var SearchableDropdown = Utils.Decorate(Dropdown, DropdownSearch);
    
            options.dropdownAdapter = SearchableDropdown;
          }
    
          if (options.minimumResultsForSearch !== 0) {
            options.dropdownAdapter = Utils.Decorate(
              options.dropdownAdapter,
              MinimumResultsForSearch
            );
          }
    
          if (options.closeOnSelect) {
            options.dropdownAdapter = Utils.Decorate(
              options.dropdownAdapter,
              CloseOnSelect
            );
          }
    
          if (
            options.dropdownCssClass != null ||
            options.dropdownCss != null ||
            options.adaptDropdownCssClass != null
          ) {
            var DropdownCSS = require(options.amdBase + 'compat/dropdownCss');
    
            options.dropdownAdapter = Utils.Decorate(
              options.dropdownAdapter,
              DropdownCSS
            );
          }
    
          options.dropdownAdapter = Utils.Decorate(
            options.dropdownAdapter,
            AttachBody
          );
        }
    
        if (options.selectionAdapter == null) {
          if (options.multiple) {
            options.selectionAdapter = MultipleSelection;
          } else {
            options.selectionAdapter = SingleSelection;
          }
    
          // Add the placeholder mixin if a placeholder was specified
          if (options.placeholder != null) {
            options.selectionAdapter = Utils.Decorate(
              options.selectionAdapter,
              Placeholder
            );
          }
    
          if (options.allowClear) {
            options.selectionAdapter = Utils.Decorate(
              options.selectionAdapter,
              AllowClear
            );
          }
    
          if (options.multiple) {
            options.selectionAdapter = Utils.Decorate(
              options.selectionAdapter,
              SelectionSearch
            );
          }
    
          if (
            options.containerCssClass != null ||
            options.containerCss != null ||
            options.adaptContainerCssClass != null
          ) {
            var ContainerCSS = require(options.amdBase + 'compat/containerCss');
    
            options.selectionAdapter = Utils.Decorate(
              options.selectionAdapter,
              ContainerCSS
            );
          }
    
          options.selectionAdapter = Utils.Decorate(
            options.selectionAdapter,
            EventRelay
          );
        }
    
        if (typeof options.language === 'string') {
          // Check if the language is specified with a region
          if (options.language.indexOf('-') > 0) {
            // Extract the region information if it is included
            var languageParts = options.language.split('-');
            var baseLanguage = languageParts[0];
    
            options.language = [options.language, baseLanguage];
          } else {
            options.language = [options.language];
          }
        }
    
        if ($.isArray(options.language)) {
          var languages = new Translation();
          options.language.push('en');
    
          var languageNames = options.language;
    
          for (var l = 0; l < languageNames.length; l++) {
            var name = languageNames[l];
            var language = {};
    
            try {
              // Try to load it with the original name
              language = Translation.loadPath(name);
            } catch (e) {
              try {
                // If we couldn't load it, check if it wasn't the full path
                name = this.defaults.amdLanguageBase + name;
                language = Translation.loadPath(name);
              } catch (ex) {
                // The translation could not be loaded at all. Sometimes this is
                // because of a configuration problem, other times this can be
                // because of how Select2 helps load all possible translation files.
                if (options.debug && window.console && console.warn) {
                  console.warn(
                    'Select2: The language file for "' + name + '" could not be ' +
                    'automatically loaded. A fallback will be used instead.'
                  );
                }
    
                continue;
              }
            }
    
            languages.extend(language);
          }
    
          options.translations = languages;
        } else {
          var baseTranslation = Translation.loadPath(
            this.defaults.amdLanguageBase + 'en'
          );
          var customTranslation = new Translation(options.language);
    
          customTranslation.extend(baseTranslation);
    
          options.translations = customTranslation;
        }
    
        return options;
      };
    
      Defaults.prototype.reset = function () {
        function stripDiacritics (text) {
          // Used 'uni range + named function' from http://jsperf.com/diacritics/18
          function match(a) {
            return DIACRITICS[a] || a;
          }
    
          return text.replace(/[^\u0000-\u007E]/g, match);
        }
    
        function matcher (params, data) {
          // Always return the object if there is nothing to compare
          if ($.trim(params.term) === '') {
            return data;
          }
    
          // Do a recursive check for options with children
          if (data.children && data.children.length > 0) {
            // Clone the data object if there are children
            // This is required as we modify the object to remove any non-matches
            var match = $.extend(true, {}, data);
    
            // Check each child of the option
            for (var c = data.children.length - 1; c >= 0; c--) {
              var child = data.children[c];
    
              var matches = matcher(params, child);
    
              // If there wasn't a match, remove the object in the array
              if (matches == null) {
                match.children.splice(c, 1);
              }
            }
    
            // If any children matched, return the new object
            if (match.children.length > 0) {
              return match;
            }
    
            // If there were no matching children, check just the plain object
            return matcher(params, match);
          }
    
          var original = stripDiacritics(data.text).toUpperCase();
          var term = stripDiacritics(params.term).toUpperCase();
    
          // Check if the text contains the term
          if (original.indexOf(term) > -1) {
            return data;
          }
    
          // If it doesn't contain the term, don't return anything
          return null;
        }
    
        this.defaults = {
          amdBase: './',
          amdLanguageBase: './i18n/',
          closeOnSelect: true,
          debug: false,
          dropdownAutoWidth: false,
          escapeMarkup: Utils.escapeMarkup,
          language: EnglishTranslation,
          matcher: matcher,
          minimumInputLength: 0,
          maximumInputLength: 0,
          maximumSelectionLength: 0,
          minimumResultsForSearch: 0,
          selectOnClose: false,
          sorter: function (data) {
            return data;
          },
          templateResult: function (result) {
            return result.text;
          },
          templateSelection: function (selection) {
            return selection.text;
          },
          theme: 'default',
          width: 'resolve'
        };
      };
    
      Defaults.prototype.set = function (key, value) {
        var camelKey = $.camelCase(key);
    
        var data = {};
        data[camelKey] = value;
    
        var convertedData = Utils._convertData(data);
    
        $.extend(this.defaults, convertedData);
      };
    
      var defaults = new Defaults();
    
      return defaults;
    });
    
    S2.define('select2/options',[
      'require',
      'jquery',
      './defaults',
      './utils'
    ], function (require, $, Defaults, Utils) {
      function Options (options, $element) {
        this.options = options;
    
        if ($element != null) {
          this.fromElement($element);
        }
    
        this.options = Defaults.apply(this.options);
    
        if ($element && $element.is('input')) {
          var InputCompat = require(this.get('amdBase') + 'compat/inputData');
    
          this.options.dataAdapter = Utils.Decorate(
            this.options.dataAdapter,
            InputCompat
          );
        }
      }
    
      Options.prototype.fromElement = function ($e) {
        var excludedData = ['select2'];
    
        if (this.options.multiple == null) {
          this.options.multiple = $e.prop('multiple');
        }
    
        if (this.options.disabled == null) {
          this.options.disabled = $e.prop('disabled');
        }
    
        if (this.options.language == null) {
          if ($e.prop('lang')) {
            this.options.language = $e.prop('lang').toLowerCase();
          } else if ($e.closest('[lang]').prop('lang')) {
            this.options.language = $e.closest('[lang]').prop('lang');
          }
        }
    
        if (this.options.dir == null) {
          if ($e.prop('dir')) {
            this.options.dir = $e.prop('dir');
          } else if ($e.closest('[dir]').prop('dir')) {
            this.options.dir = $e.closest('[dir]').prop('dir');
          } else {
            this.options.dir = 'ltr';
          }
        }
    
        $e.prop('disabled', this.options.disabled);
        $e.prop('multiple', this.options.multiple);
    
        if ($e.data('select2Tags')) {
          if (this.options.debug && window.console && console.warn) {
            console.warn(
              'Select2: The `data-select2-tags` attribute has been changed to ' +
              'use the `data-data` and `data-tags="true"` attributes and will be ' +
              'removed in future versions of Select2.'
            );
          }
    
          $e.data('data', $e.data('select2Tags'));
          $e.data('tags', true);
        }
    
        if ($e.data('ajaxUrl')) {
          if (this.options.debug && window.console && console.warn) {
            console.warn(
              'Select2: The `data-ajax-url` attribute has been changed to ' +
              '`data-ajax--url` and support for the old attribute will be removed' +
              ' in future versions of Select2.'
            );
          }
    
          $e.attr('ajax--url', $e.data('ajaxUrl'));
          $e.data('ajax--url', $e.data('ajaxUrl'));
        }
    
        var dataset = {};
    
        // Prefer the element's `dataset` attribute if it exists
        // jQuery 1.x does not correctly handle data attributes with multiple dashes
        if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) {
          dataset = $.extend(true, {}, $e[0].dataset, $e.data());
        } else {
          dataset = $e.data();
        }
    
        var data = $.extend(true, {}, dataset);
    
        data = Utils._convertData(data);
    
        for (var key in data) {
          if ($.inArray(key, excludedData) > -1) {
            continue;
          }
    
          if ($.isPlainObject(this.options[key])) {
            $.extend(this.options[key], data[key]);
          } else {
            this.options[key] = data[key];
          }
        }
    
        return this;
      };
    
      Options.prototype.get = function (key) {
        return this.options[key];
      };
    
      Options.prototype.set = function (key, val) {
        this.options[key] = val;
      };
    
      return Options;
    });
    
    S2.define('select2/core',[
      'jquery',
      './options',
      './utils',
      './keys'
    ], function ($, Options, Utils, KEYS) {
      var Select2 = function ($element, options) {
        if ($element.data('select2') != null) {
          $element.data('select2').destroy();
        }
    
        this.$element = $element;
    
        this.id = this._generateId($element);
    
        options = options || {};
    
        this.options = new Options(options, $element);
    
        Select2.__super__.constructor.call(this);
    
        // Set up the tabindex
    
        var tabindex = $element.attr('tabindex') || 0;
        $element.data('old-tabindex', tabindex);
        $element.attr('tabindex', '-1');
    
        // Set up containers and adapters
    
        var DataAdapter = this.options.get('dataAdapter');
        this.dataAdapter = new DataAdapter($element, this.options);
    
        var $container = this.render();
    
        this._placeContainer($container);
    
        var SelectionAdapter = this.options.get('selectionAdapter');
        this.selection = new SelectionAdapter($element, this.options);
        this.$selection = this.selection.render();
    
        this.selection.position(this.$selection, $container);
    
        var DropdownAdapter = this.options.get('dropdownAdapter');
        this.dropdown = new DropdownAdapter($element, this.options);
        this.$dropdown = this.dropdown.render();
    
        this.dropdown.position(this.$dropdown, $container);
    
        var ResultsAdapter = this.options.get('resultsAdapter');
        this.results = new ResultsAdapter($element, this.options, this.dataAdapter);
        this.$results = this.results.render();
    
        this.results.position(this.$results, this.$dropdown);
    
        // Bind events
    
        var self = this;
    
        // Bind the container to all of the adapters
        this._bindAdapters();
    
        // Register any DOM event handlers
        this._registerDomEvents();
    
        // Register any internal event handlers
        this._registerDataEvents();
        this._registerSelectionEvents();
        this._registerDropdownEvents();
        this._registerResultsEvents();
        this._registerEvents();
    
        // Set the initial state
        this.dataAdapter.current(function (initialData) {
          self.trigger('selection:update', {
            data: initialData
          });
        });
    
        // Hide the original select
        $element.addClass('select2-hidden-accessible');
        $element.attr('aria-hidden', 'true');
    
        // Synchronize any monitored attributes
        this._syncAttributes();
    
        $element.data('select2', this);
      };
    
      Utils.Extend(Select2, Utils.Observable);
    
      Select2.prototype._generateId = function ($element) {
        var id = '';
    
        if ($element.attr('id') != null) {
          id = $element.attr('id');
        } else if ($element.attr('name') != null) {
          id = $element.attr('name') + '-' + Utils.generateChars(2);
        } else {
          id = Utils.generateChars(4);
        }
    
        id = id.replace(/(:|\.|\[|\]|,)/g, '');
        id = 'select2-' + id;
    
        return id;
      };
    
      Select2.prototype._placeContainer = function ($container) {
        $container.insertAfter(this.$element);
    
        var width = this._resolveWidth(this.$element, this.options.get('width'));
    
        if (width != null) {
          $container.css('width', width);
        }
      };
    
      Select2.prototype._resolveWidth = function ($element, method) {
        var WIDTH = /^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;
    
        if (method == 'resolve') {
          var styleWidth = this._resolveWidth($element, 'style');
    
          if (styleWidth != null) {
            return styleWidth;
          }
    
          return this._resolveWidth($element, 'element');
        }
    
        if (method == 'element') {
          var elementWidth = $element.outerWidth(false);
    
          if (elementWidth <= 0) {
            return 'auto';
          }
    
          return elementWidth + 'px';
        }
    
        if (method == 'style') {
          var style = $element.attr('style');
    
          if (typeof(style) !== 'string') {
            return null;
          }
    
          var attrs = style.split(';');
    
          for (var i = 0, l = attrs.length; i < l; i = i + 1) {
            var attr = attrs[i].replace(/\s/g, '');
            var matches = attr.match(WIDTH);
    
            if (matches !== null && matches.length >= 1) {
              return matches[1];
            }
          }
    
          return null;
        }
    
        return method;
      };
    
      Select2.prototype._bindAdapters = function () {
        this.dataAdapter.bind(this, this.$container);
        this.selection.bind(this, this.$container);
    
        this.dropdown.bind(this, this.$container);
        this.results.bind(this, this.$container);
      };
    
      Select2.prototype._registerDomEvents = function () {
        var self = this;
    
        this.$element.on('change.select2', function () {
          self.dataAdapter.current(function (data) {
            self.trigger('selection:update', {
              data: data
            });
          });
        });
    
        this.$element.on('focus.select2', function (evt) {
          self.trigger('focus', evt);
        });
    
        this._syncA = Utils.bind(this._syncAttributes, this);
        this._syncS = Utils.bind(this._syncSubtree, this);
    
        if (this.$element[0].attachEvent) {
          this.$element[0].attachEvent('onpropertychange', this._syncA);
        }
    
        var observer = window.MutationObserver ||
          window.WebKitMutationObserver ||
          window.MozMutationObserver
        ;
    
        if (observer != null) {
          this._observer = new observer(function (mutations) {
            $.each(mutations, self._syncA);
            $.each(mutations, self._syncS);
          });
          this._observer.observe(this.$element[0], {
            attributes: true,
            childList: true,
            subtree: false
          });
        } else if (this.$element[0].addEventListener) {
          this.$element[0].addEventListener(
            'DOMAttrModified',
            self._syncA,
            false
          );
          this.$element[0].addEventListener(
            'DOMNodeInserted',
            self._syncS,
            false
          );
          this.$element[0].addEventListener(
            'DOMNodeRemoved',
            self._syncS,
            false
          );
        }
      };
    
      Select2.prototype._registerDataEvents = function () {
        var self = this;
    
        this.dataAdapter.on('*', function (name, params) {
          self.trigger(name, params);
        });
      };
    
      Select2.prototype._registerSelectionEvents = function () {
        var self = this;
        var nonRelayEvents = ['toggle', 'focus'];
    
        this.selection.on('toggle', function () {
          self.toggleDropdown();
        });
    
        this.selection.on('focus', function (params) {
          self.focus(params);
        });
    
        this.selection.on('*', function (name, params) {
          if ($.inArray(name, nonRelayEvents) !== -1) {
            return;
          }
    
          self.trigger(name, params);
        });
      };
    
      Select2.prototype._registerDropdownEvents = function () {
        var self = this;
    
        this.dropdown.on('*', function (name, params) {
          self.trigger(name, params);
        });
      };
    
      Select2.prototype._registerResultsEvents = function () {
        var self = this;
    
        this.results.on('*', function (name, params) {
          self.trigger(name, params);
        });
      };
    
      Select2.prototype._registerEvents = function () {
        var self = this;
    
        this.on('open', function () {
          self.$container.addClass('select2-container--open');
        });
    
        this.on('close', function () {
          self.$container.removeClass('select2-container--open');
        });
    
        this.on('enable', function () {
          self.$container.removeClass('select2-container--disabled');
        });
    
        this.on('disable', function () {
          self.$container.addClass('select2-container--disabled');
        });
    
        this.on('blur', function () {
          self.$container.removeClass('select2-container--focus');
        });
    
        this.on('query', function (params) {
          if (!self.isOpen()) {
            self.trigger('open', {});
          }
    
          this.dataAdapter.query(params, function (data) {
            self.trigger('results:all', {
              data: data,
              query: params
            });
          });
        });
    
        this.on('query:append', function (params) {
          this.dataAdapter.query(params, function (data) {
            self.trigger('results:append', {
              data: data,
              query: params
            });
          });
        });
    
        this.on('keypress', function (evt) {
          var key = evt.which;
    
          if (self.isOpen()) {
            if (key === KEYS.ESC || key === KEYS.TAB ||
                (key === KEYS.UP && evt.altKey)) {
              self.close();
    
              evt.preventDefault();
            } else if (key === KEYS.ENTER) {
              self.trigger('results:select', {});
    
              evt.preventDefault();
            } else if ((key === KEYS.SPACE && evt.ctrlKey)) {
              self.trigger('results:toggle', {});
    
              evt.preventDefault();
            } else if (key === KEYS.UP) {
              self.trigger('results:previous', {});
    
              evt.preventDefault();
            } else if (key === KEYS.DOWN) {
              self.trigger('results:next', {});
    
              evt.preventDefault();
            }
          } else {
            if (key === KEYS.ENTER || key === KEYS.SPACE ||
                (key === KEYS.DOWN && evt.altKey)) {
              self.open();
    
              evt.preventDefault();
            }
          }
        });
      };
    
      Select2.prototype._syncAttributes = function () {
        this.options.set('disabled', this.$element.prop('disabled'));
    
        if (this.options.get('disabled')) {
          if (this.isOpen()) {
            this.close();
          }
    
          this.trigger('disable', {});
        } else {
          this.trigger('enable', {});
        }
      };
    
      Select2.prototype._syncSubtree = function (evt, mutations) {
        var changed = false;
        var self = this;
    
        // Ignore any mutation events raised for elements that aren't options or
        // optgroups. This handles the case when the select element is destroyed
        if (
          evt && evt.target && (
            evt.target.nodeName !== 'OPTION' && evt.target.nodeName !== 'OPTGROUP'
          )
        ) {
          return;
        }
    
        if (!mutations) {
          // If mutation events aren't supported, then we can only assume that the
          // change affected the selections
          changed = true;
        } else if (mutations.addedNodes && mutations.addedNodes.length > 0) {
          for (var n = 0; n < mutations.addedNodes.length; n++) {
            var node = mutations.addedNodes[n];
    
            if (node.selected) {
              changed = true;
            }
          }
        } else if (mutations.removedNodes && mutations.removedNodes.length > 0) {
          changed = true;
        }
    
        // Only re-pull the data if we think there is a change
        if (changed) {
          this.dataAdapter.current(function (currentData) {
            self.trigger('selection:update', {
              data: currentData
            });
          });
        }
      };
    
      /**
       * Override the trigger method to automatically trigger pre-events when
       * there are events that can be prevented.
       */
      Select2.prototype.trigger = function (name, args) {
        var actualTrigger = Select2.__super__.trigger;
        var preTriggerMap = {
          'open': 'opening',
          'close': 'closing',
          'select': 'selecting',
          'unselect': 'unselecting'
        };
    
        if (args === undefined) {
          args = {};
        }
    
        if (name in preTriggerMap) {
          var preTriggerName = preTriggerMap[name];
          var preTriggerArgs = {
            prevented: false,
            name: name,
            args: args
          };
    
          actualTrigger.call(this, preTriggerName, preTriggerArgs);
    
          if (preTriggerArgs.prevented) {
            args.prevented = true;
    
            return;
          }
        }
    
        actualTrigger.call(this, name, args);
      };
    
      Select2.prototype.toggleDropdown = function () {
        if (this.options.get('disabled')) {
          return;
        }
    
        if (this.isOpen()) {
          this.close();
        } else {
          this.open();
        }
      };
    
      Select2.prototype.open = function () {
        if (this.isOpen()) {
          return;
        }
    
        this.trigger('query', {});
      };
    
      Select2.prototype.close = function () {
        if (!this.isOpen()) {
          return;
        }
    
        this.trigger('close', {});
      };
    
      Select2.prototype.isOpen = function () {
        return this.$container.hasClass('select2-container--open');
      };
    
      Select2.prototype.hasFocus = function () {
        return this.$container.hasClass('select2-container--focus');
      };
    
      Select2.prototype.focus = function (data) {
        // No need to re-trigger focus events if we are already focused
        if (this.hasFocus()) {
          return;
        }
    
        this.$container.addClass('select2-container--focus');
        this.trigger('focus', {});
      };
    
      Select2.prototype.enable = function (args) {
        if (this.options.get('debug') && window.console && console.warn) {
          console.warn(
            'Select2: The `select2("enable")` method has been deprecated and will' +
            ' be removed in later Select2 versions. Use $element.prop("disabled")' +
            ' instead.'
          );
        }
    
        if (args == null || args.length === 0) {
          args = [true];
        }
    
        var disabled = !args[0];
    
        this.$element.prop('disabled', disabled);
      };
    
      Select2.prototype.data = function () {
        if (this.options.get('debug') &&
            arguments.length > 0 && window.console && console.warn) {
          console.warn(
            'Select2: Data can no longer be set using `select2("data")`. You ' +
            'should consider setting the value instead using `$element.val()`.'
          );
        }
    
        var data = [];
    
        this.dataAdapter.current(function (currentData) {
          data = currentData;
        });
    
        return data;
      };
    
      Select2.prototype.val = function (args) {
        if (this.options.get('debug') && window.console && console.warn) {
          console.warn(
            'Select2: The `select2("val")` method has been deprecated and will be' +
            ' removed in later Select2 versions. Use $element.val() instead.'
          );
        }
    
        if (args == null || args.length === 0) {
          return this.$element.val();
        }
    
        var newVal = args[0];
    
        if ($.isArray(newVal)) {
          newVal = $.map(newVal, function (obj) {
            return obj.toString();
          });
        }
    
        this.$element.val(newVal).trigger('change');
      };
    
      Select2.prototype.destroy = function () {
        this.$container.remove();
    
        if (this.$element[0].detachEvent) {
          this.$element[0].detachEvent('onpropertychange', this._syncA);
        }
    
        if (this._observer != null) {
          this._observer.disconnect();
          this._observer = null;
        } else if (this.$element[0].removeEventListener) {
          this.$element[0]
            .removeEventListener('DOMAttrModified', this._syncA, false);
          this.$element[0]
            .removeEventListener('DOMNodeInserted', this._syncS, false);
          this.$element[0]
            .removeEventListener('DOMNodeRemoved', this._syncS, false);
        }
    
        this._syncA = null;
        this._syncS = null;
    
        this.$element.off('.select2');
        this.$element.attr('tabindex', this.$element.data('old-tabindex'));
    
        this.$element.removeClass('select2-hidden-accessible');
        this.$element.attr('aria-hidden', 'false');
        this.$element.removeData('select2');
    
        this.dataAdapter.destroy();
        this.selection.destroy();
        this.dropdown.destroy();
        this.results.destroy();
    
        this.dataAdapter = null;
        this.selection = null;
        this.dropdown = null;
        this.results = null;
      };
    
      Select2.prototype.render = function () {
        var $container = $(
          '<span class="select2 select2-container">' +
            '<span class="selection"></span>' +
            '<span class="dropdown-wrapper" aria-hidden="true"></span>' +
          '</span>'
        );
    
        $container.attr('dir', this.options.get('dir'));
    
        this.$container = $container;
    
        this.$container.addClass('select2-container--' + this.options.get('theme'));
    
        $container.data('element', this.$element);
    
        return $container;
      };
    
      return Select2;
    });
    
    S2.define('jquery-mousewheel',[
      'jquery'
    ], function ($) {
      // Used to shim jQuery.mousewheel for non-full builds.
      return $;
    });
    
    S2.define('jquery.select2',[
      'jquery',
      'jquery-mousewheel',
    
      './select2/core',
      './select2/defaults'
    ], function ($, _, Select2, Defaults) {
      if ($.fn.select2 == null) {
        // All methods that should return the element
        var thisMethods = ['open', 'close', 'destroy'];
    
        $.fn.select2 = function (options) {
          options = options || {};
    
          if (typeof options === 'object') {
            this.each(function () {
              var instanceOptions = $.extend(true, {}, options);
    
              var instance = new Select2($(this), instanceOptions);
            });
    
            return this;
          } else if (typeof options === 'string') {
            var ret;
            var args = Array.prototype.slice.call(arguments, 1);
    
            this.each(function () {
              var instance = $(this).data('select2');
    
              if (instance == null && window.console && console.error) {
                console.error(
                  'The select2(\'' + options + '\') method was called on an ' +
                  'element that is not using Select2.'
                );
              }
    
              ret = instance[options].apply(instance, args);
            });
    
            // Check if we should be returning `this`
            if ($.inArray(options, thisMethods) > -1) {
              return this;
            }
    
            return ret;
          } else {
            throw new Error('Invalid arguments for Select2: ' + options);
          }
        };
      }
    
      if ($.fn.select2.defaults == null) {
        $.fn.select2.defaults = Defaults;
      }
    
      return Select2;
    });
    
      // Return the AMD loader configuration so it can be used outside of this file
      return {
        define: S2.define,
        require: S2.require
      };
    }());
    
      // Autoload the jQuery bindings
      // We know that all of the modules exist above this, so we're safe
      var select2 = S2.require('jquery.select2');
    
      // Hold the AMD module references on the jQuery function that was just loaded
      // This allows Select2 to use the internal loader outside of this file, such
      // as in the language files.
      jQuery.fn.select2.amd = S2;
    
      // Return the Select2 instance for anyone who is importing it.
      return select2;
    }));
    
    /*!
     * clipboard.js v1.7.1
     * https://zenorocha.github.io/clipboard.js
     *
     * Licensed MIT Â© Zeno Rocha
     */
    (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Clipboard = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
    var DOCUMENT_NODE_TYPE = 9;
    
    /**
     * A polyfill for Element.matches()
     */
    if (typeof Element !== 'undefined' && !Element.prototype.matches) {
        var proto = Element.prototype;
    
        proto.matches = proto.matchesSelector ||
                        proto.mozMatchesSelector ||
                        proto.msMatchesSelector ||
                        proto.oMatchesSelector ||
                        proto.webkitMatchesSelector;
    }
    
    /**
     * Finds the closest parent that matches a selector.
     *
     * @param {Element} element
     * @param {String} selector
     * @return {Function}
     */
    function closest (element, selector) {
        while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
            if (typeof element.matches === 'function' &&
                element.matches(selector)) {
              return element;
            }
            element = element.parentNode;
        }
    }
    
    module.exports = closest;
    
    },{}],2:[function(require,module,exports){
    var closest = require('./closest');
    
    /**
     * Delegates event to a selector.
     *
     * @param {Element} element
     * @param {String} selector
     * @param {String} type
     * @param {Function} callback
     * @param {Boolean} useCapture
     * @return {Object}
     */
    function delegate(element, selector, type, callback, useCapture) {
        var listenerFn = listener.apply(this, arguments);
    
        element.addEventListener(type, listenerFn, useCapture);
    
        return {
            destroy: function() {
                element.removeEventListener(type, listenerFn, useCapture);
            }
        }
    }
    
    /**
     * Finds closest match and invokes callback.
     *
     * @param {Element} element
     * @param {String} selector
     * @param {String} type
     * @param {Function} callback
     * @return {Function}
     */
    function listener(element, selector, type, callback) {
        return function(e) {
            e.delegateTarget = closest(e.target, selector);
    
            if (e.delegateTarget) {
                callback.call(element, e);
            }
        }
    }
    
    module.exports = delegate;
    
    },{"./closest":1}],3:[function(require,module,exports){
    /**
     * Check if argument is a HTML element.
     *
     * @param {Object} value
     * @return {Boolean}
     */
    exports.node = function(value) {
        return value !== undefined
            && value instanceof HTMLElement
            && value.nodeType === 1;
    };
    
    /**
     * Check if argument is a list of HTML elements.
     *
     * @param {Object} value
     * @return {Boolean}
     */
    exports.nodeList = function(value) {
        var type = Object.prototype.toString.call(value);
    
        return value !== undefined
            && (type === '[object NodeList]' || type === '[object HTMLCollection]')
            && ('length' in value)
            && (value.length === 0 || exports.node(value[0]));
    };
    
    /**
     * Check if argument is a string.
     *
     * @param {Object} value
     * @return {Boolean}
     */
    exports.string = function(value) {
        return typeof value === 'string'
            || value instanceof String;
    };
    
    /**
     * Check if argument is a function.
     *
     * @param {Object} value
     * @return {Boolean}
     */
    exports.fn = function(value) {
        var type = Object.prototype.toString.call(value);
    
        return type === '[object Function]';
    };
    
    },{}],4:[function(require,module,exports){
    var is = require('./is');
    var delegate = require('delegate');
    
    /**
     * Validates all params and calls the right
     * listener function based on its target type.
     *
     * @param {String|HTMLElement|HTMLCollection|NodeList} target
     * @param {String} type
     * @param {Function} callback
     * @return {Object}
     */
    function listen(target, type, callback) {
        if (!target && !type && !callback) {
            throw new Error('Missing required arguments');
        }
    
        if (!is.string(type)) {
            throw new TypeError('Second argument must be a String');
        }
    
        if (!is.fn(callback)) {
            throw new TypeError('Third argument must be a Function');
        }
    
        if (is.node(target)) {
            return listenNode(target, type, callback);
        }
        else if (is.nodeList(target)) {
            return listenNodeList(target, type, callback);
        }
        else if (is.string(target)) {
            return listenSelector(target, type, callback);
        }
        else {
            throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
        }
    }
    
    /**
     * Adds an event listener to a HTML element
     * and returns a remove listener function.
     *
     * @param {HTMLElement} node
     * @param {String} type
     * @param {Function} callback
     * @return {Object}
     */
    function listenNode(node, type, callback) {
        node.addEventListener(type, callback);
    
        return {
            destroy: function() {
                node.removeEventListener(type, callback);
            }
        }
    }
    
    /**
     * Add an event listener to a list of HTML elements
     * and returns a remove listener function.
     *
     * @param {NodeList|HTMLCollection} nodeList
     * @param {String} type
     * @param {Function} callback
     * @return {Object}
     */
    function listenNodeList(nodeList, type, callback) {
        Array.prototype.forEach.call(nodeList, function(node) {
            node.addEventListener(type, callback);
        });
    
        return {
            destroy: function() {
                Array.prototype.forEach.call(nodeList, function(node) {
                    node.removeEventListener(type, callback);
                });
            }
        }
    }
    
    /**
     * Add an event listener to a selector
     * and returns a remove listener function.
     *
     * @param {String} selector
     * @param {String} type
     * @param {Function} callback
     * @return {Object}
     */
    function listenSelector(selector, type, callback) {
        return delegate(document.body, selector, type, callback);
    }
    
    module.exports = listen;
    
    },{"./is":3,"delegate":2}],5:[function(require,module,exports){
    function select(element) {
        var selectedText;
    
        if (element.nodeName === 'SELECT') {
            element.focus();
    
            selectedText = element.value;
        }
        else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
            var isReadOnly = element.hasAttribute('readonly');
    
            if (!isReadOnly) {
                element.setAttribute('readonly', '');
            }
    
            element.select();
            element.setSelectionRange(0, element.value.length);
    
            if (!isReadOnly) {
                element.removeAttribute('readonly');
            }
    
            selectedText = element.value;
        }
        else {
            if (element.hasAttribute('contenteditable')) {
                element.focus();
            }
    
            var selection = window.getSelection();
            var range = document.createRange();
    
            range.selectNodeContents(element);
            selection.removeAllRanges();
            selection.addRange(range);
    
            selectedText = selection.toString();
        }
    
        return selectedText;
    }
    
    module.exports = select;
    
    },{}],6:[function(require,module,exports){
    function E () {
      // Keep this empty so it's easier to inherit from
      // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
    }
    
    E.prototype = {
      on: function (name, callback, ctx) {
        var e = this.e || (this.e = {});
    
        (e[name] || (e[name] = [])).push({
          fn: callback,
          ctx: ctx
        });
    
        return this;
      },
    
      once: function (name, callback, ctx) {
        var self = this;
        function listener () {
          self.off(name, listener);
          callback.apply(ctx, arguments);
        };
    
        listener._ = callback
        return this.on(name, listener, ctx);
      },
    
      emit: function (name) {
        var data = [].slice.call(arguments, 1);
        var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
        var i = 0;
        var len = evtArr.length;
    
        for (i; i < len; i++) {
          evtArr[i].fn.apply(evtArr[i].ctx, data);
        }
    
        return this;
      },
    
      off: function (name, callback) {
        var e = this.e || (this.e = {});
        var evts = e[name];
        var liveEvents = [];
    
        if (evts && callback) {
          for (var i = 0, len = evts.length; i < len; i++) {
            if (evts[i].fn !== callback && evts[i].fn._ !== callback)
              liveEvents.push(evts[i]);
          }
        }
    
        // Remove event from queue to prevent memory leak
        // Suggested by https://github.com/lazd
        // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
    
        (liveEvents.length)
          ? e[name] = liveEvents
          : delete e[name];
    
        return this;
      }
    };
    
    module.exports = E;
    
    },{}],7:[function(require,module,exports){
    (function (global, factory) {
        if (typeof define === "function" && define.amd) {
            define(['module', 'select'], factory);
        } else if (typeof exports !== "undefined") {
            factory(module, require('select'));
        } else {
            var mod = {
                exports: {}
            };
            factory(mod, global.select);
            global.clipboardAction = mod.exports;
        }
    })(this, function (module, _select) {
        'use strict';
    
        var _select2 = _interopRequireDefault(_select);
    
        function _interopRequireDefault(obj) {
            return obj && obj.__esModule ? obj : {
                default: obj
            };
        }
    
        var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
            return typeof obj;
        } : function (obj) {
            return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
    
        function _classCallCheck(instance, Constructor) {
            if (!(instance instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
            }
        }
    
        var _createClass = function () {
            function defineProperties(target, props) {
                for (var i = 0; i < props.length; i++) {
                    var descriptor = props[i];
                    descriptor.enumerable = descriptor.enumerable || false;
                    descriptor.configurable = true;
                    if ("value" in descriptor) descriptor.writable = true;
                    Object.defineProperty(target, descriptor.key, descriptor);
                }
            }
    
            return function (Constructor, protoProps, staticProps) {
                if (protoProps) defineProperties(Constructor.prototype, protoProps);
                if (staticProps) defineProperties(Constructor, staticProps);
                return Constructor;
            };
        }();
    
        var ClipboardAction = function () {
            /**
             * @param {Object} options
             */
            function ClipboardAction(options) {
                _classCallCheck(this, ClipboardAction);
    
                this.resolveOptions(options);
                this.initSelection();
            }
    
            /**
             * Defines base properties passed from constructor.
             * @param {Object} options
             */
    
    
            _createClass(ClipboardAction, [{
                key: 'resolveOptions',
                value: function resolveOptions() {
                    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    
                    this.action = options.action;
                    this.container = options.container;
                    this.emitter = options.emitter;
                    this.target = options.target;
                    this.text = options.text;
                    this.trigger = options.trigger;
    
                    this.selectedText = '';
                }
            }, {
                key: 'initSelection',
                value: function initSelection() {
                    if (this.text) {
                        this.selectFake();
                    } else if (this.target) {
                        this.selectTarget();
                    }
                }
            }, {
                key: 'selectFake',
                value: function selectFake() {
                    var _this = this;
    
                    var isRTL = document.documentElement.getAttribute('dir') == 'rtl';
    
                    this.removeFake();
    
                    this.fakeHandlerCallback = function () {
                        return _this.removeFake();
                    };
                    this.fakeHandler = this.container.addEventListener('click', this.fakeHandlerCallback) || true;
    
                    this.fakeElem = document.createElement('textarea');
                    // Prevent zooming on iOS
                    this.fakeElem.style.fontSize = '12pt';
                    // Reset box model
                    this.fakeElem.style.border = '0';
                    this.fakeElem.style.padding = '0';
                    this.fakeElem.style.margin = '0';
                    // Move element out of screen horizontally
                    this.fakeElem.style.position = 'absolute';
                    this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px';
                    // Move element to the same position vertically
                    var yPosition = window.pageYOffset || document.documentElement.scrollTop;
                    this.fakeElem.style.top = yPosition + 'px';
    
                    this.fakeElem.setAttribute('readonly', '');
                    this.fakeElem.value = this.text;
    
                    this.container.appendChild(this.fakeElem);
    
                    this.selectedText = (0, _select2.default)(this.fakeElem);
                    this.copyText();
                }
            }, {
                key: 'removeFake',
                value: function removeFake() {
                    if (this.fakeHandler) {
                        this.container.removeEventListener('click', this.fakeHandlerCallback);
                        this.fakeHandler = null;
                        this.fakeHandlerCallback = null;
                    }
    
                    if (this.fakeElem) {
                        this.container.removeChild(this.fakeElem);
                        this.fakeElem = null;
                    }
                }
            }, {
                key: 'selectTarget',
                value: function selectTarget() {
                    this.selectedText = (0, _select2.default)(this.target);
                    this.copyText();
                }
            }, {
                key: 'copyText',
                value: function copyText() {
                    var succeeded = void 0;
    
                    try {
                        succeeded = document.execCommand(this.action);
                    } catch (err) {
                        succeeded = false;
                    }
    
                    this.handleResult(succeeded);
                }
            }, {
                key: 'handleResult',
                value: function handleResult(succeeded) {
                    this.emitter.emit(succeeded ? 'success' : 'error', {
                        action: this.action,
                        text: this.selectedText,
                        trigger: this.trigger,
                        clearSelection: this.clearSelection.bind(this)
                    });
                }
            }, {
                key: 'clearSelection',
                value: function clearSelection() {
                    if (this.trigger) {
                        this.trigger.focus();
                    }
    
                    window.getSelection().removeAllRanges();
                }
            }, {
                key: 'destroy',
                value: function destroy() {
                    this.removeFake();
                }
            }, {
                key: 'action',
                set: function set() {
                    var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy';
    
                    this._action = action;
    
                    if (this._action !== 'copy' && this._action !== 'cut') {
                        throw new Error('Invalid "action" value, use either "copy" or "cut"');
                    }
                },
                get: function get() {
                    return this._action;
                }
            }, {
                key: 'target',
                set: function set(target) {
                    if (target !== undefined) {
                        if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) {
                            if (this.action === 'copy' && target.hasAttribute('disabled')) {
                                throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');
                            }
    
                            if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) {
                                throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');
                            }
    
                            this._target = target;
                        } else {
                            throw new Error('Invalid "target" value, use a valid Element');
                        }
                    }
                },
                get: function get() {
                    return this._target;
                }
            }]);
    
            return ClipboardAction;
        }();
    
        module.exports = ClipboardAction;
    });
    
    },{"select":5}],8:[function(require,module,exports){
    (function (global, factory) {
        if (typeof define === "function" && define.amd) {
            define(['module', './clipboard-action', 'tiny-emitter', 'good-listener'], factory);
        } else if (typeof exports !== "undefined") {
            factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener'));
        } else {
            var mod = {
                exports: {}
            };
            factory(mod, global.clipboardAction, global.tinyEmitter, global.goodListener);
            global.clipboard = mod.exports;
        }
    })(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) {
        'use strict';
    
        var _clipboardAction2 = _interopRequireDefault(_clipboardAction);
    
        var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter);
    
        var _goodListener2 = _interopRequireDefault(_goodListener);
    
        function _interopRequireDefault(obj) {
            return obj && obj.__esModule ? obj : {
                default: obj
            };
        }
    
        var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
            return typeof obj;
        } : function (obj) {
            return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
    
        function _classCallCheck(instance, Constructor) {
            if (!(instance instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
            }
        }
    
        var _createClass = function () {
            function defineProperties(target, props) {
                for (var i = 0; i < props.length; i++) {
                    var descriptor = props[i];
                    descriptor.enumerable = descriptor.enumerable || false;
                    descriptor.configurable = true;
                    if ("value" in descriptor) descriptor.writable = true;
                    Object.defineProperty(target, descriptor.key, descriptor);
                }
            }
    
            return function (Constructor, protoProps, staticProps) {
                if (protoProps) defineProperties(Constructor.prototype, protoProps);
                if (staticProps) defineProperties(Constructor, staticProps);
                return Constructor;
            };
        }();
    
        function _possibleConstructorReturn(self, call) {
            if (!self) {
                throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
            }
    
            return call && (typeof call === "object" || typeof call === "function") ? call : self;
        }
    
        function _inherits(subClass, superClass) {
            if (typeof superClass !== "function" && superClass !== null) {
                throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
            }
    
            subClass.prototype = Object.create(superClass && superClass.prototype, {
                constructor: {
                    value: subClass,
                    enumerable: false,
                    writable: true,
                    configurable: true
                }
            });
            if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
        }
    
        var Clipboard = function (_Emitter) {
            _inherits(Clipboard, _Emitter);
    
            /**
             * @param {String|HTMLElement|HTMLCollection|NodeList} trigger
             * @param {Object} options
             */
            function Clipboard(trigger, options) {
                _classCallCheck(this, Clipboard);
    
                var _this = _possibleConstructorReturn(this, (Clipboard.__proto__ || Object.getPrototypeOf(Clipboard)).call(this));
    
                _this.resolveOptions(options);
                _this.listenClick(trigger);
                return _this;
            }
    
            /**
             * Defines if attributes would be resolved using internal setter functions
             * or custom functions that were passed in the constructor.
             * @param {Object} options
             */
    
    
            _createClass(Clipboard, [{
                key: 'resolveOptions',
                value: function resolveOptions() {
                    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    
                    this.action = typeof options.action === 'function' ? options.action : this.defaultAction;
                    this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;
                    this.text = typeof options.text === 'function' ? options.text : this.defaultText;
                    this.container = _typeof(options.container) === 'object' ? options.container : document.body;
                }
            }, {
                key: 'listenClick',
                value: function listenClick(trigger) {
                    var _this2 = this;
    
                    this.listener = (0, _goodListener2.default)(trigger, 'click', function (e) {
                        return _this2.onClick(e);
                    });
                }
            }, {
                key: 'onClick',
                value: function onClick(e) {
                    var trigger = e.delegateTarget || e.currentTarget;
    
                    if (this.clipboardAction) {
                        this.clipboardAction = null;
                    }
    
                    this.clipboardAction = new _clipboardAction2.default({
                        action: this.action(trigger),
                        target: this.target(trigger),
                        text: this.text(trigger),
                        container: this.container,
                        trigger: trigger,
                        emitter: this
                    });
                }
            }, {
                key: 'defaultAction',
                value: function defaultAction(trigger) {
                    return getAttributeValue('action', trigger);
                }
            }, {
                key: 'defaultTarget',
                value: function defaultTarget(trigger) {
                    var selector = getAttributeValue('target', trigger);
    
                    if (selector) {
                        return document.querySelector(selector);
                    }
                }
            }, {
                key: 'defaultText',
                value: function defaultText(trigger) {
                    return getAttributeValue('text', trigger);
                }
            }, {
                key: 'destroy',
                value: function destroy() {
                    this.listener.destroy();
    
                    if (this.clipboardAction) {
                        this.clipboardAction.destroy();
                        this.clipboardAction = null;
                    }
                }
            }], [{
                key: 'isSupported',
                value: function isSupported() {
                    var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut'];
    
                    var actions = typeof action === 'string' ? [action] : action;
                    var support = !!document.queryCommandSupported;
    
                    actions.forEach(function (action) {
                        support = support && !!document.queryCommandSupported(action);
                    });
    
                    return support;
                }
            }]);
    
            return Clipboard;
        }(_tinyEmitter2.default);
    
        /**
         * Helper function to retrieve attribute value.
         * @param {String} suffix
         * @param {Element} element
         */
        function getAttributeValue(suffix, element) {
            var attribute = 'data-clipboard-' + suffix;
    
            if (!element.hasAttribute(attribute)) {
                return;
            }
    
            return element.getAttribute(attribute);
        }
    
        module.exports = Clipboard;
    });
    
    },{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)
    });
    var SMALL_SCREEN_SIZE = 825;
    
    function searchclose() {
        $("#searchresults").slideUp();
    }
    
    function sidebarOpen() {
        $("#sidebaropen").fadeOut();
        $("#contentarea").animate({"margin-left":"209px"},1000,function() {
            $("#sidebar").fadeIn("slow");
        });
        $.post("search.php","a=maxsidebar");
    }
    function sidebarClose() {
        $("#sidebar").fadeOut("slow",function(){
            $("#contentarea").animate({"margin-left":"10px"});
            $("#sidebaropen").fadeIn();
        });
        $.post("search.php","a=minsidebar");
    }
    function notesclose(save) {
        $('#myNotes').modal('hide');
        if (save) {
            $.post(
                WHMCS.adminUtils.getAdminRouteUrl('/profile/notes'),
                $("#frmmynotes").serialize()
            );
        }
    }
    
    $(document).ready(function(){
        $(window).on("load resize", function() {
            if ($("#sidebar").is(':visible') && $(window).width() <= SMALL_SCREEN_SIZE) {
                $("#sidebar").hide();
                $("#contentarea").css('margin-left', '10px');
                $("#sidebaropen").show();
            }
        });
        $("#frmintellisearch").submit(function(e) {
            e.preventDefault();
            $("#intellisearchval").css("background-image","url('img/loading.gif')");
            $.post("search.php", $("#frmintellisearch").serialize(),
            function(data){
                $("#searchresultsscroller").html(data);
                $("#searchresults").slideDown("slow",function(){
                        $("#intellisearchval").css("background-image","url('img/icons/search.png')");
                    });
            });
        });
        $(".datepick, .date-picker").datepicker({
            dateFormat: 'dd-mm-yy',
            showOn: "button",
            buttonImage: "images/showcalendar.gif",
            buttonImageOnly: true,
            showButtonPanel: true,
            showOtherMonths: true,
            selectOtherMonths: true
        });
    
        $('div.modal').on('shown.bs.modal', function() {
            var inputs = $(this).find('input,button.btn-primary');
    
            if (inputs.length > 0) {
                $(inputs).first().focus();
            }
        });
    
        $('#btnClientLimitNotificationDismiss').click(function(e) {
            $('#clientLimitNotification').fadeOut();
            $.post(window.location, 'clientlimitdismiss=1&name=' + $('#clientLimitNotification').find('.panel-title span').html());
        });
    
        $('#btnClientLimitNotificationDontShowAgain').click(function(e) {
            $('#clientLimitNotification').fadeOut();
            $.post(window.location, 'clientlimitdontshowagain=1&name=' + $('#clientLimitNotification').find('.panel-title span').html());
        });
    
        $('.client-limit-notification-form form').submit(function(e) {
            e.preventDefault();
            var $this = $(this);
            var $fetchUrl = $this.data('fetchUrl');
            var $submit = $this.find('button[type="submit"]');
            var $submitLabel = $submit.html();
            $submit.css('width', $submit.css('width')).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
            $.post($fetchUrl, $this.serialize(),
                function(data) {
                    $this.find('.input-license-key').val(data.license_key);
                    $this.find('.input-member-data').val(data.member_data);
                    $this.off('submit').submit();
                    $submit.html($submitLabel).removeProp('disabled');
                }, 'json');
        });
    });
    
    function toggleadvsearch() {
        if (document.getElementById('searchbox').style.visibility=="hidden") {
            document.getElementById('searchbox').style.visibility="";
        } else {
            document.getElementById('searchbox').style.visibility="hidden";
        }
    }
    
    function populate(o) {
      d=document.getElementById('searchfield');
      v=o.options[o.selectedIndex].value;
      if(!d){return;}            
      var mitems=new Array();
      mitems['clients']=['Client ID','Client Name','Company Name','Email Address','Address 1','Address 2','City','State','Postcode','Country','Phone Number','CC Last Four','Notes'];
      mitems['orders']=['Order ID','Order #','Client Name','Order Date','Amount'];
      mitems['services']=['Service ID','Domain','Client Name','Product','Billing Cycle','Next Due Date','Status','Username','Dedicated IP','Assigned IPs','Subscription ID','Notes'];
      mitems['domains']=['Domain ID','Domain','Client Name','Registrar','Expiry Date','Status','Subscription ID','Notes'];
      mitems['invoices']=['Invoice #','Client Name','Line Item','Invoice Date','Due Date','Date Paid','Total Due','Status'];
      mitems['tickets']=['Ticket #','Tag','Subject','Client Name','Email Address'];
      d.options.length=0;
      cur=mitems[o.options[o.selectedIndex].value];
      if(!cur){return;}
      d.options.length=cur.length;
      for(var i=0;i<cur.length;i++) {
        d.options[i].text=cur[i];
        d.options[i].value=cur[i];
      }
      if(v == 'services' || v == 'domains' || v == "clients") { 
        document.getElementById('searchfield').selectedIndex = 1;
      }
    }
    /*!
     * iCheck v1.0.2, http://git.io/arlzeA
     * ===================================
     * Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization
     *
     * (c) 2013 Damir Sultanov, http://fronteed.com
     * MIT Licensed
     */
    
    (function($) {
    
      // Cached vars
      var _iCheck = 'iCheck',
        _iCheckHelper = _iCheck + '-helper',
        _checkbox = 'checkbox',
        _radio = 'radio',
        _checked = 'checked',
        _unchecked = 'un' + _checked,
        _disabled = 'disabled',a
        _determinate = 'determinate',
        _indeterminate = 'in' + _determinate,
        _update = 'update',
        _type = 'type',
        _click = 'click',
        _touch = 'touchbegin.i touchend.i',
        _add = 'addClass',
        _remove = 'removeClass',
        _callback = 'trigger',
        _label = 'label',
        _cursor = 'cursor',
        _mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent);
    
      // Plugin init
      $.fn[_iCheck] = function(options, fire) {
    
        // Walker
        var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]',
          stack = $(),
          walker = function(object) {
            object.each(function() {
              var self = $(this);
    
              if (self.is(handle)) {
                stack = stack.add(self);
              } else {
                stack = stack.add(self.find(handle));
              }
            });
          };
    
        // Check if we should operate with some method
        if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) {
    
          // Normalize method's name
          options = options.toLowerCase();
    
          // Find checkboxes and radio buttons
          walker(this);
    
          return stack.each(function() {
            var self = $(this);
    
            if (options == 'destroy') {
              tidy(self, 'ifDestroyed');
            } else {
              operate(self, true, options);
            }
    
            // Fire method's callback
            if ($.isFunction(fire)) {
              fire();
            }
          });
    
        // Customization
        } else if (typeof options == 'object' || !options) {
    
          // Check if any options were passed
          var settings = $.extend({
              checkedClass: _checked,
              disabledClass: _disabled,
              indeterminateClass: _indeterminate,
              labelHover: true
            }, options),
    
            selector = settings.handle,
            hoverClass = settings.hoverClass || 'hover',
            focusClass = settings.focusClass || 'focus',
            activeClass = settings.activeClass || 'active',
            labelHover = !!settings.labelHover,
            labelHoverClass = settings.labelHoverClass || 'hover',
    
            // Setup clickable area
            area = ('' + settings.increaseArea).replace('%', '') | 0;
    
          // Selector limit
          if (selector == _checkbox || selector == _radio) {
            handle = 'input[type="' + selector + '"]';
          }
    
          // Clickable area limit
          if (area < -50) {
            area = -50;
          }
    
          // Walk around the selector
          walker(this);
    
          return stack.each(function() {
            var self = $(this);
    
            // If already customized
            tidy(self);
    
            var node = this,
              id = node.id,
    
              // Layer styles
              offset = -area + '%',
              size = 100 + (area * 2) + '%',
              layer = {
                position: 'absolute',
                top: offset,
                left: offset,
                display: 'block',
                width: size,
                height: size,
                margin: 0,
                padding: 0,
                background: '#fff',
                border: 0,
                opacity: 0
              },
    
              // Choose how to hide input
              hide = _mobile ? {
                position: 'absolute',
                visibility: 'hidden'
              } : area ? layer : {
                position: 'absolute',
                opacity: 0
              },
    
              // Get proper class
              className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio,
    
              // Find assigned labels
              label = $(_label + '[for="' + id + '"]').add(self.closest(_label)),
    
              // Check ARIA option
              aria = !!settings.aria,
    
              // Set ARIA placeholder
              ariaID = _iCheck + '-' + Math.random().toString(36).substr(2,6),
    
              // Parent & helper
              parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''),
              helper;
    
            // Set ARIA "labelledby"
            if (aria) {
              label.each(function() {
                parent += 'aria-labelledby="';
    
                if (this.id) {
                  parent += this.id;
                } else {
                  this.id = ariaID;
                  parent += ariaID;
                }
    
                parent += '"';
              });
            }
    
            // Wrap input
            parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert);
    
            // Layer addition
            helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent);
    
            // Finalize customization
            self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide);
            !!settings.inheritClass && parent[_add](node.className || '');
            !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id);
            parent.css('position') == 'static' && parent.css('position', 'relative');
            operate(self, true, _update);
    
            // Label events
            if (label.length) {
              label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) {
                var type = event[_type],
                  item = $(this);
    
                // Do nothing if input is disabled
                if (!node[_disabled]) {
    
                  // Click
                  if (type == _click) {
                    if ($(event.target).is('a')) {
                      return;
                    }
                    operate(self, false, true);
    
                  // Hover state
                  } else if (labelHover) {
    
                    // mouseout|touchend
                    if (/ut|nd/.test(type)) {
                      parent[_remove](hoverClass);
                      item[_remove](labelHoverClass);
                    } else {
                      parent[_add](hoverClass);
                      item[_add](labelHoverClass);
                    }
                  }
    
                  if (_mobile) {
                    event.stopPropagation();
                  } else {
                    return false;
                  }
                }
              });
            }
    
            // Input events
            self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) {
              var type = event[_type],
                key = event.keyCode;
    
              // Click
              if (type == _click) {
                return false;
    
              // Keydown
              } else if (type == 'keydown' && key == 32) {
                if (!(node[_type] == _radio && node[_checked])) {
                  if (node[_checked]) {
                    off(self, _checked);
                  } else {
                    on(self, _checked);
                  }
                }
    
                return false;
    
              // Keyup
              } else if (type == 'keyup' && node[_type] == _radio) {
                !node[_checked] && on(self, _checked);
    
              // Focus/blur
              } else if (/us|ur/.test(type)) {
                parent[type == 'blur' ? _remove : _add](focusClass);
              }
            });
    
            // Helper events
            helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) {
              var type = event[_type],
    
                // mousedown|mouseup
                toggle = /wn|up/.test(type) ? activeClass : hoverClass;
    
              // Do nothing if input is disabled
              if (!node[_disabled]) {
    
                // Click
                if (type == _click) {
                  operate(self, false, true);
    
                // Active and hover states
                } else {
    
                  // State is on
                  if (/wn|er|in/.test(type)) {
    
                    // mousedown|mouseover|touchbegin
                    parent[_add](toggle);
    
                  // State is off
                  } else {
                    parent[_remove](toggle + ' ' + activeClass);
                  }
    
                  // Label hover
                  if (label.length && labelHover && toggle == hoverClass) {
    
                    // mouseout|touchend
                    label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass);
                  }
                }
    
                if (_mobile) {
                  event.stopPropagation();
                } else {
                  return false;
                }
              }
            });
          });
        } else {
          return this;
        }
      };
    
      // Do something with inputs
      function operate(input, direct, method) {
        var node = input[0],
          state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked,
          active = method == _update ? {
            checked: node[_checked],
            disabled: node[_disabled],
            indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false'
          } : node[state];
    
        // Check, disable or indeterminate
        if (/^(ch|di|in)/.test(method) && !active) {
          on(input, state);
    
        // Uncheck, enable or determinate
        } else if (/^(un|en|de)/.test(method) && active) {
          off(input, state);
    
        // Update
        } else if (method == _update) {
    
          // Handle states
          for (var each in active) {
            if (active[each]) {
              on(input, each, true);
            } else {
              off(input, each, true);
            }
          }
    
        } else if (!direct || method == 'toggle') {
    
          // Helper or label was clicked
          if (!direct) {
            input[_callback]('ifClicked');
          }
    
          // Toggle checked state
          if (active) {
            if (node[_type] !== _radio) {
              off(input, state);
            }
          } else {
            on(input, state);
          }
        }
      }
    
      // Add checked, disabled or indeterminate state
      function on(input, state, keep) {
        var node = input[0],
          parent = input.parent(),
          checked = state == _checked,
          indeterminate = state == _indeterminate,
          disabled = state == _disabled,
          callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
          regular = option(input, callback + capitalize(node[_type])),
          specific = option(input, state + capitalize(node[_type]));
    
        // Prevent unnecessary actions
        if (node[state] !== true) {
    
          // Toggle assigned radio buttons
          if (!keep && state == _checked && node[_type] == _radio && node.name) {
            var form = input.closest('form'),
              inputs = 'input[name="' + node.name + '"]';
    
            inputs = form.length ? form.find(inputs) : $(inputs);
    
            inputs.each(function() {
              if (this !== node && $(this).data(_iCheck)) {
                off($(this), state);
              }
            });
          }
    
          // Indeterminate state
          if (indeterminate) {
    
            // Add indeterminate state
            node[state] = true;
    
            // Remove checked state
            if (node[_checked]) {
              off(input, _checked, 'force');
            }
    
          // Checked or disabled state
          } else {
    
            // Add checked or disabled state
            if (!keep) {
              node[state] = true;
            }
    
            // Remove indeterminate state
            if (checked && node[_indeterminate]) {
              off(input, _indeterminate, false);
            }
          }
    
          // Trigger callbacks
          callbacks(input, checked, state, keep);
        }
    
        // Add proper cursor
        if (node[_disabled] && !!option(input, _cursor, true)) {
          parent.find('.' + _iCheckHelper).css(_cursor, 'default');
        }
    
        // Add state class
        parent[_add](specific || option(input, state) || '');
    
        // Set ARIA attribute
        if (!!parent.attr('role') && !indeterminate) {
          parent.attr('aria-' + (disabled ? _disabled : _checked), 'true');
        }
    
        // Remove regular state class
        parent[_remove](regular || option(input, callback) || '');
      }
    
      // Remove checked, disabled or indeterminate state
      function off(input, state, keep) {
        var node = input[0],
          parent = input.parent(),
          checked = state == _checked,
          indeterminate = state == _indeterminate,
          disabled = state == _disabled,
          callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
          regular = option(input, callback + capitalize(node[_type])),
          specific = option(input, state + capitalize(node[_type]));
    
        // Prevent unnecessary actions
        if (node[state] !== false) {
    
          // Toggle state
          if (indeterminate || !keep || keep == 'force') {
            node[state] = false;
          }
    
          // Trigger callbacks
          callbacks(input, checked, callback, keep);
        }
    
        // Add proper cursor
        if (!node[_disabled] && !!option(input, _cursor, true)) {
          parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
        }
    
        // Remove state class
        parent[_remove](specific || option(input, state) || '');
    
        // Set ARIA attribute
        if (!!parent.attr('role') && !indeterminate) {
          parent.attr('aria-' + (disabled ? _disabled : _checked), 'false');
        }
    
        // Add regular state class
        parent[_add](regular || option(input, callback) || '');
      }
    
      // Remove all traces
      function tidy(input, callback) {
        if (input.data(_iCheck)) {
    
          // Remove everything except input
          input.parent().html(input.attr('style', input.data(_iCheck).s || ''));
    
          // Callback
          if (callback) {
            input[_callback](callback);
          }
    
          // Unbind events
          input.off('.i').unwrap();
          $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i');
        }
      }
    
      // Get some option
      function option(input, state, regular) {
        if (input.data(_iCheck)) {
          return input.data(_iCheck).o[state + (regular ? '' : 'Class')];
        }
      }
    
      // Capitalize some string
      function capitalize(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
      }
    
      // Executable handlers
      function callbacks(input, checked, callback, keep) {
        if (!keep) {
          if (checked) {
            input[_callback]('ifToggled');
          }
    
          input[_callback]('ifChanged')[_callback]('if' + capitalize(callback));
        }
      }
    })(window.jQuery || window.Zepto);
    
    /* ===================================================
     * bootstrap-markdown.js v2.10.0
     * http://github.com/toopay/bootstrap-markdown
     * ===================================================
     * Copyright 2013-2016 Taufan Aditya
     *
     * 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.
     * ========================================================== */
    
    (function(factory){
        if (typeof define === "function" && define.amd) {
            //RequireJS
            define(["jquery"], factory);
        } else if (typeof exports === 'object') {
            //Backbone.js
            factory(require('jquery'));
        } else {
            //Jquery plugin
            factory(jQuery);
        }
    }(function($){
      "use strict"; // jshint ;_;
    
      /* MARKDOWN CLASS DEFINITION
       * ========================== */
    
      var Markdown = function (element, options) {
        // @TODO : remove this BC on next major release
        // @see : https://github.com/toopay/bootstrap-markdown/issues/109
        var opts = ['autofocus', 'savable', 'hideable', 'width', 
          'height', 'resize', 'iconlibrary', 'language', 
          'footer', 'fullscreen', 'hiddenButtons', 'disabledButtons'];
        $.each(opts,function(_, opt){
          if (typeof $(element).data(opt) !== 'undefined') {
            options = typeof options == 'object' ? options : {}
            options[opt] = $(element).data(opt)
          }
        });
        // End BC
    
        // Class Properties
        this.$ns           = 'bootstrap-markdown';
        this.$element      = $(element);
        this.$editable     = {el:null, type:null,attrKeys:[], attrValues:[], content:null};
        this.$options      = $.extend(true, {}, $.fn.markdown.defaults, options, this.$element.data('options'));
        this.$oldContent   = null;
        this.$isPreview    = false;
        this.$isFullscreen = false;
        this.$editor       = null;
        this.$textarea     = null;
        this.$handler      = [];
        this.$callback     = [];
        this.$nextTab      = [];
    
        this.showEditor();
      };
    
      Markdown.prototype = {
    
        constructor: Markdown
    
      , __alterButtons: function(name,alter) {
          var handler = this.$handler, isAll = (name == 'all'),that = this;
    
          $.each(handler,function(k,v) {
            var halt = true;
            if (isAll) {
              halt = false;
            } else {
              halt = v.indexOf(name) < 0;
            }
    
            if (halt === false) {
              alter(that.$editor.find('button[data-handler="'+v+'"]'));
            }
          });
        }
    
      , __buildButtons: function(buttonsArray, container) {
          var i,
              ns = this.$ns,
              handler = this.$handler,
              callback = this.$callback;
    
          for (i=0;i<buttonsArray.length;i++) {
            // Build each group container
            var y, btnGroups = buttonsArray[i];
            for (y=0;y<btnGroups.length;y++) {
              // Build each button group
              var z,
                  buttons = btnGroups[y].data,
                  btnGroupContainer = $('<div/>', {
                                        'class': 'btn-group'
                                      });
    
              for (z=0;z<buttons.length;z++) {
                var button = buttons[z],
                    buttonContainer, buttonIconContainer,
                    buttonHandler = ns+'-'+button.name,
                    buttonIcon = this.__getIcon(button.icon),
                    btnText = button.btnText ? button.btnText : '',
                    btnClass = button.btnClass ? button.btnClass : 'btn',
                    tabIndex = button.tabIndex ? button.tabIndex : '-1',
                    hotkey = typeof button.hotkey !== 'undefined' ? button.hotkey : '',
                    hotkeyCaption = typeof jQuery.hotkeys !== 'undefined' && hotkey !== '' ? ' ('+hotkey+')' : '';
    
                // Construct the button object
                buttonContainer = $('<button></button>');
                buttonContainer.text(' ' + this.__localize(btnText)).addClass('btn-default btn-sm').addClass(btnClass);
                if(btnClass.match(/btn\-(primary|success|info|warning|danger|link)/)){
                    buttonContainer.removeClass('btn-default');
                }
                buttonContainer.attr({
                    'type': 'button',
                    'title': this.__localize(button.title) + hotkeyCaption,
                    'tabindex': tabIndex,
                    'data-provider': ns,
                    'data-handler': buttonHandler,
                    'data-hotkey': hotkey
                });
                if (button.toggle === true){
                  buttonContainer.attr('data-toggle', 'button');
                }
                buttonIconContainer = $('<span/>');
                buttonIconContainer.addClass(buttonIcon);
                buttonIconContainer.prependTo(buttonContainer);
    
                // Attach the button object
                btnGroupContainer.append(buttonContainer);
    
                // Register handler and callback
                handler.push(buttonHandler);
                callback.push(button.callback);
              }
    
              // Attach the button group into container dom
              container.append(btnGroupContainer);
            }
          }
    
          return container;
        }
      , __setListener: function() {
          // Set size and resizable Properties
          var hasRows = typeof this.$textarea.attr('rows') !== 'undefined',
              maxRows = this.$textarea.val().split("\n").length > 5 ? this.$textarea.val().split("\n").length : '5',
              rowsVal = hasRows ? this.$textarea.attr('rows') : maxRows;
    
          this.$textarea.attr('rows',rowsVal);
          if (this.$options.resize) {
            this.$textarea.css('resize',this.$options.resize);
          }
    
          this.$textarea.on({
              'focus' : $.proxy(this.focus, this),
              'keyup' : $.proxy(this.keyup, this),
              'change' : $.proxy(this.change, this),
              'select' : $.proxy(this.select, this)
          });
    
          if (this.eventSupported('keydown')) {
            this.$textarea.on('keydown', $.proxy(this.keydown, this));
          }
    
          if (this.eventSupported('keypress')) {
            this.$textarea.on('keypress', $.proxy(this.keypress, this))
          }
    
          // Re-attach markdown data
          this.$textarea.data('markdown',this);
        }
    
      , __handle: function(e) {
          var target = $(e.currentTarget),
              handler = this.$handler,
              callback = this.$callback,
              handlerName = target.attr('data-handler'),
              callbackIndex = handler.indexOf(handlerName),
              callbackHandler = callback[callbackIndex];
    
          // Trigger the focusin
          $(e.currentTarget).focus();
    
          callbackHandler(this);
    
          // Trigger onChange for each button handle
          this.change(this);
    
          // Unless it was the save handler,
          // focusin the textarea
          if (handlerName.indexOf('cmdSave') < 0) {
            this.$textarea.focus();
          }
    
          e.preventDefault();
        }
    
      , __localize: function(string) {
          var messages = $.fn.markdown.messages,
              language = this.$options.language;
          if (
            typeof messages !== 'undefined' &&
            typeof messages[language] !== 'undefined' &&
            typeof messages[language][string] !== 'undefined'
          ) {
            return messages[language][string];
          }
          return string;
        }
    
      , __getIcon: function(src) {
        return typeof src == 'object' ? src[this.$options.iconlibrary] : src;
      }
    
      , setFullscreen: function(mode) {
        var $editor = this.$editor,
            $textarea = this.$textarea;
    
        if (mode === true) {
          $editor.addClass('md-fullscreen-mode');
          $('body').addClass('md-nooverflow');
          this.$options.onFullscreen(this);
        } else {
          $editor.removeClass('md-fullscreen-mode');
          $('body').removeClass('md-nooverflow');
    
          if (this.$isPreview == true) this.hidePreview().showPreview()
        }
    
        this.$isFullscreen = mode;
        $textarea.focus();
      }
    
      , showEditor: function() {
          var instance = this,
              textarea,
              ns = this.$ns,
              container = this.$element,
              originalHeigth = container.css('height'),
              originalWidth = container.css('width'),
              editable = this.$editable,
              handler = this.$handler,
              callback = this.$callback,
              options = this.$options,
              editor = $( '<div/>', {
                          'class': 'md-editor',
                          click: function() {
                            instance.focus();
                          }
                        });
    
          // Prepare the editor
          if (this.$editor === null) {
            // Create the panel
            var editorHeader = $('<div/>', {
                                'class': 'md-header btn-toolbar'
                                });
    
            // Merge the main & additional button groups together
            var allBtnGroups = [];
            if (options.buttons.length > 0) allBtnGroups = allBtnGroups.concat(options.buttons[0]);
            if (options.additionalButtons.length > 0) {
              // iterate the additional button groups
              $.each(options.additionalButtons[0], function(idx, buttonGroup){
                
                // see if the group name of the addional group matches an existing group
                var matchingGroups = $.grep(allBtnGroups, function(allButtonGroup, allIdx){
                  return allButtonGroup.name === buttonGroup.name;
                });
    
                // if it matches add the addional buttons to that group, if not just add it to the all buttons group
                if(matchingGroups.length > 0) {
                  matchingGroups[0].data = matchingGroups[0].data.concat(buttonGroup.data);
                } else {              
                  allBtnGroups.push(options.additionalButtons[0][idx]);
                }
    
              });
            } 
    
            // Reduce and/or reorder the button groups
            if (options.reorderButtonGroups.length > 0) {
              allBtnGroups = allBtnGroups
                  .filter(function(btnGroup) {
                    return options.reorderButtonGroups.indexOf(btnGroup.name) > -1;
                  })
                  .sort(function(a, b) {
                    if (options.reorderButtonGroups.indexOf(a.name) < options.reorderButtonGroups.indexOf(b.name)) return -1;
                    if (options.reorderButtonGroups.indexOf(a.name) > options.reorderButtonGroups.indexOf(b.name)) return 1;
                    return 0;
                  });
            }
    
            // Build the buttons
            if (allBtnGroups.length > 0) {
              editorHeader = this.__buildButtons([allBtnGroups], editorHeader);
            }
    
            if (options.fullscreen.enable) {
              editorHeader.append('<div class="md-controls"><a class="md-control md-control-fullscreen" href="#"><span class="'+this.__getIcon(options.fullscreen.icons.fullscreenOn)+'"></span></a></div>').on('click', '.md-control-fullscreen', function(e) {
                  e.preventDefault();
                  instance.setFullscreen(true);
              });
            }
    
            editor.append(editorHeader);
    
            // Wrap the textarea
            if (container.is('textarea')) {
              container.before(editor);
              textarea = container;
              textarea.addClass('md-input');
              editor.append(textarea);
            } else {
              var rawContent = (typeof toMarkdown == 'function') ? toMarkdown(container.html()) : container.html(),
                  currentContent = $.trim(rawContent);
    
              // This is some arbitrary content that could be edited
              textarea = $('<textarea/>', {
                           'class': 'md-input',
                           'val' : currentContent
                          });
    
              editor.append(textarea);
    
              // Save the editable
              editable.el = container;
              editable.type = container.prop('tagName').toLowerCase();
              editable.content = container.html();
    
              $(container[0].attributes).each(function(){
                editable.attrKeys.push(this.nodeName);
                editable.attrValues.push(this.nodeValue);
              });
    
              // Set editor to blocked the original container
              container.replaceWith(editor);
            }
    
            var editorFooter = $('<div/>', {
                               'class': 'md-footer'
                             }),
                createFooter = false,
                footer = '';
            // Create the footer if savable
            if (options.savable) {
              createFooter = true;
              var saveHandler = 'cmdSave';
    
              // Register handler and callback
              handler.push(saveHandler);
              callback.push(options.onSave);
    
              editorFooter.append('<button class="btn btn-success" data-provider="'
                                  + ns
                                  + '" data-handler="'
                                  + saveHandler
                                  + '"><i class="icon icon-white icon-ok"></i> '
                                  + this.__localize('Save')
                                  + '</button>');
    
    
            }
    
            footer = typeof options.footer === 'function' ? options.footer(this) : options.footer;
    
            if ($.trim(footer) !== '') {
              createFooter = true;
              editorFooter.append(footer);
            }
    
            if (createFooter) editor.append(editorFooter);
    
            // Set width
            if (options.width && options.width !== 'inherit') {
              if (jQuery.isNumeric(options.width)) {
                editor.css('display', 'table');
                textarea.css('width', options.width + 'px');
              } else {
                editor.addClass(options.width);
              }
            }
    
            // Set height
            if (options.height && options.height !== 'inherit') {
              if (jQuery.isNumeric(options.height)) {
                var height = options.height;
                if (editorHeader) height = Math.max(0, height - editorHeader.outerHeight());
                if (editorFooter) height = Math.max(0, height - editorFooter.outerHeight());
                textarea.css('height', height + 'px');
              } else {
                editor.addClass(options.height);
              }
            }
    
            // Reference
            this.$editor     = editor;
            this.$textarea   = textarea;
            this.$editable   = editable;
            this.$oldContent = this.getContent();
    
            this.__setListener();
    
            // Set editor attributes, data short-hand API and listener
            this.$editor.attr('id',(new Date()).getTime());
            this.$editor.on('click', '[data-provider="bootstrap-markdown"]', $.proxy(this.__handle, this));
    
            if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
              this.$editor.addClass('md-editor-disabled');
              this.disableButtons('all');
            }
    
            if (this.eventSupported('keydown') && typeof jQuery.hotkeys === 'object') {
              editorHeader.find('[data-provider="bootstrap-markdown"]').each(function() {
                var $button = $(this),
                    hotkey = $button.attr('data-hotkey');
                if (hotkey.toLowerCase() !== '') {
                  textarea.bind('keydown', hotkey, function() {
                    $button.trigger('click');
                    return false;
                  });
                }
              });
            }
    
            if (options.initialstate === 'preview') {
              this.showPreview();
            } else if (options.initialstate === 'fullscreen' && options.fullscreen.enable) {
              this.setFullscreen(true);
            }
    
          } else {
            this.$editor.show();
          }
    
          if (options.autofocus) {
            this.$textarea.focus();
            this.$editor.addClass('active');
          }
    
          if (options.fullscreen.enable && options.fullscreen !== false) {
            this.$editor.append('<div class="md-fullscreen-controls">'
                            + '<a href="#" class="exit-fullscreen" title="Exit fullscreen"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOff) + '">'
                            + '</span></a>'
                            + '</div>');
            this.$editor.on('click', '.exit-fullscreen', function(e) {
              e.preventDefault();
              instance.setFullscreen(false);
            });
          }
    
          // hide hidden buttons from options
          this.hideButtons(options.hiddenButtons);
    
          // disable disabled buttons from options
          this.disableButtons(options.disabledButtons);
    
          // Trigger the onShow hook
          options.onShow(this);
    
          return this;
        }
    
      , parseContent: function(val) {
          var content;
    
          // parse with supported markdown parser
          var val = val || this.$textarea.val();
    
          if (this.$options.parser) {
            content = this.$options.parser(val);
          } else if (typeof markdown == 'object') {
            content = markdown.toHTML(val);
          } else if (typeof marked == 'function') {
            content = marked(val);
          } else {
            content = val;
          }
    
          return content;
        }
    
      , showPreview: function() {
          var options = this.$options,
              container = this.$textarea,
              afterContainer = container.next(),
              replacementContainer = $('<div/>',{'class':'md-preview','data-provider':'markdown-preview'}),
              content,
              callbackContent;
    
          if (this.$isPreview == true) {
            // Avoid sequenced element creation on missused scenario
            // @see https://github.com/toopay/bootstrap-markdown/issues/170
            return this;
          }
          
          // Give flag that tell the editor enter preview mode
          this.$isPreview = true;
          // Disable all buttons
          this.disableButtons('all').enableButtons('cmdPreview');
    
          // Try to get the content from callback
          callbackContent = options.onPreview(this);
          // Set the content based from the callback content if string otherwise parse value from textarea
          content = typeof callbackContent == 'string' ? callbackContent : this.parseContent();
    
          // Build preview element
          replacementContainer.html(content);
    
          if (afterContainer && afterContainer.attr('class') == 'md-footer') {
            // If there is footer element, insert the preview container before it
            replacementContainer.insertBefore(afterContainer);
          } else {
            // Otherwise, just append it after textarea
            container.parent().append(replacementContainer);
          }
    
          // Set the preview element dimensions
          replacementContainer.css({
            width: container.outerWidth() + 'px',
            height: container.outerHeight() + 'px'
          });
    
          if (this.$options.resize) {
            replacementContainer.css('resize',this.$options.resize);
          }
    
          // Hide the last-active textarea
          container.hide();
    
          // Attach the editor instances
          replacementContainer.data('markdown',this);
    
          if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
            this.$editor.addClass('md-editor-disabled');
            this.disableButtons('all');
          }
    
          return this;
        }
    
      , hidePreview: function() {
          // Give flag that tell the editor quit preview mode
          this.$isPreview = false;
    
          // Obtain the preview container
          var container = this.$editor.find('div[data-provider="markdown-preview"]');
    
          // Remove the preview container
          container.remove();
    
          // Enable all buttons
          this.enableButtons('all');
          // Disable configured disabled buttons
          this.disableButtons(this.$options.disabledButtons);
    
          // Back to the editor
          this.$textarea.show();
          this.__setListener();
    
          return this;
        }
    
      , isDirty: function() {
          return this.$oldContent != this.getContent();
        }
    
      , getContent: function() {
          return this.$textarea.val();
        }
    
      , setContent: function(content) {
          this.$textarea.val(content);
    
          return this;
        }
    
      , findSelection: function(chunk) {
        var content = this.getContent(), startChunkPosition;
    
        if (startChunkPosition = content.indexOf(chunk), startChunkPosition >= 0 && chunk.length > 0) {
          var oldSelection = this.getSelection(), selection;
    
          this.setSelection(startChunkPosition,startChunkPosition+chunk.length);
          selection = this.getSelection();
    
          this.setSelection(oldSelection.start,oldSelection.end);
    
          return selection;
        } else {
          return null;
        }
      }
    
      , getSelection: function() {
    
          var e = this.$textarea[0];
    
          return (
    
              ('selectionStart' in e && function() {
                  var l = e.selectionEnd - e.selectionStart;
                  return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
              }) ||
    
              /* browser not supported */
              function() {
                return null;
              }
    
          )();
    
        }
    
      , setSelection: function(start,end) {
    
          var e = this.$textarea[0];
    
          return (
    
              ('selectionStart' in e && function() {
                  e.selectionStart = start;
                  e.selectionEnd = end;
                  return;
              }) ||
    
              /* browser not supported */
              function() {
                return null;
              }
    
          )();
    
        }
    
      , replaceSelection: function(text) {
    
          var e = this.$textarea[0];
    
          return (
    
              ('selectionStart' in e && function() {
                  e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
                  // Set cursor to the last replacement end
                  e.selectionStart = e.value.length;
                  return this;
              }) ||
    
              /* browser not supported */
              function() {
                  e.value += text;
                  return jQuery(e);
              }
    
          )();
        }
    
      , getNextTab: function() {
          // Shift the nextTab
          if (this.$nextTab.length === 0) {
            return null;
          } else {
            var nextTab, tab = this.$nextTab.shift();
    
            if (typeof tab == 'function') {
              nextTab = tab();
            } else if (typeof tab == 'object' && tab.length > 0) {
              nextTab = tab;
            }
    
            return nextTab;
          }
        }
    
      , setNextTab: function(start,end) {
          // Push new selection into nextTab collections
          if (typeof start == 'string') {
            var that = this;
            this.$nextTab.push(function(){
              return that.findSelection(start);
            });
          } else if (typeof start == 'number' && typeof end == 'number') {
            var oldSelection = this.getSelection();
    
            this.setSelection(start,end);
            this.$nextTab.push(this.getSelection());
    
            this.setSelection(oldSelection.start,oldSelection.end);
          }
    
          return;
        }
    
      , __parseButtonNameParam: function (names) {
          return typeof names == 'string' ?
                          names.split(' ') :
                          names;
    
        }
    
      , enableButtons: function(name) {
          var buttons = this.__parseButtonNameParam(name),
            that = this;
    
          $.each(buttons, function(i, v) {
            that.__alterButtons(buttons[i], function (el) {
              el.removeAttr('disabled');
            });
          });
    
          return this;
        }
    
      , disableButtons: function(name) {
          var buttons = this.__parseButtonNameParam(name),
            that = this;
    
          $.each(buttons, function(i, v) {
            that.__alterButtons(buttons[i], function (el) {
              el.attr('disabled','disabled');
            });
          });
    
          return this;
        }
    
      , hideButtons: function(name) {
          var buttons = this.__parseButtonNameParam(name),
            that = this;
    
          $.each(buttons, function(i, v) {
            that.__alterButtons(buttons[i], function (el) {
              el.addClass('hidden');
            });
          });
    
          return this;
        }
    
      , showButtons: function(name) {
          var buttons = this.__parseButtonNameParam(name),
            that = this;
    
          $.each(buttons, function(i, v) {
            that.__alterButtons(buttons[i], function (el) {
              el.removeClass('hidden');
            });
          });
    
          return this;
        }
    
      , eventSupported: function(eventName) {
          var isSupported = eventName in this.$element;
          if (!isSupported) {
            this.$element.setAttribute(eventName, 'return;');
            isSupported = typeof this.$element[eventName] === 'function';
          }
          return isSupported;
        }
    
      , keyup: function (e) {
          var blocked = false;
          switch(e.keyCode) {
            case 40: // down arrow
            case 38: // up arrow
            case 16: // shift
            case 17: // ctrl
            case 18: // alt
              break;
    
            case 9: // tab
              var nextTab;
              if (nextTab = this.getNextTab(),nextTab !== null) {
                // Get the nextTab if exists
                var that = this;
                setTimeout(function(){
                  that.setSelection(nextTab.start,nextTab.end);
                },500);
    
                blocked = true;
              } else {
                // The next tab memory contains nothing...
                // check the cursor position to determine tab action
                var cursor = this.getSelection();
    
                if (cursor.start == cursor.end && cursor.end == this.getContent().length) {
                  // The cursor already reach the end of the content
                  blocked = false;
                } else {
                  // Put the cursor to the end
                  this.setSelection(this.getContent().length,this.getContent().length);
    
                  blocked = true;
                }
              }
    
              break;
    
            case 13: // enter
              blocked = false;
              break;
            case 27: // escape
              if (this.$isFullscreen) this.setFullscreen(false);
              blocked = false;
              break;
    
            default:
              blocked = false;
          }
    
          if (blocked) {
            e.stopPropagation();
            e.preventDefault();
          }
    
          this.$options.onChange(this);
        }
    
      , change: function(e) {
          this.$options.onChange(this);
          return this;
        }
      , select: function (e) {
          this.$options.onSelect(this);
          return this;
        }
      , focus: function (e) {
          var options = this.$options,
              isHideable = options.hideable,
              editor = this.$editor;
    
          editor.addClass('active');
    
          // Blur other markdown(s)
          $(document).find('.md-editor').each(function(){
            if ($(this).attr('id') !== editor.attr('id')) {
              var attachedMarkdown;
    
              if (attachedMarkdown = $(this).find('textarea').data('markdown'),
                  attachedMarkdown === null) {
                  attachedMarkdown = $(this).find('div[data-provider="markdown-preview"]').data('markdown');
              }
    
              if (attachedMarkdown) {
                attachedMarkdown.blur();
              }
            }
          });
    
          // Trigger the onFocus hook
          options.onFocus(this);
    
          return this;
        }
    
      , blur: function (e) {
          var options = this.$options,
              isHideable = options.hideable,
              editor = this.$editor,
              editable = this.$editable;
    
          if (editor.hasClass('active') || this.$element.parent().length === 0) {
            editor.removeClass('active');
    
            if (isHideable) {
              // Check for editable elements
              if (editable.el !== null) {
                // Build the original element
                var oldElement = $('<'+editable.type+'/>'),
                    content = this.getContent(),
                    currentContent = this.parseContent(content);
    
                $(editable.attrKeys).each(function(k,v) {
                  oldElement.attr(editable.attrKeys[k],editable.attrValues[k]);
                });
    
                // Get the editor content
                oldElement.html(currentContent);
    
                editor.replaceWith(oldElement);
              } else {
                editor.hide();
              }
            }
    
            // Trigger the onBlur hook
            options.onBlur(this);
          }
    
          return this;
        }
    
      };
    
     /* MARKDOWN PLUGIN DEFINITION
      * ========================== */
    
      var old = $.fn.markdown;
    
      $.fn.markdown = function (option) {
        return this.each(function () {
          var $this = $(this)
            , data = $this.data('markdown')
            , options = typeof option == 'object' && option;
          if (!data) $this.data('markdown', (data = new Markdown(this, options)))
        })
      };
    
      $.fn.markdown.messages = {};
    
      $.fn.markdown.defaults = {
        /* Editor Properties */
        autofocus: false,
        hideable: false,
        savable: false,
        width: 'inherit',
        height: 'inherit',
        resize: 'none',
        iconlibrary: 'glyph',
        language: 'en',
        initialstate: 'editor',
        parser: null,
    
        /* Buttons Properties */
        buttons: [
          [{
            name: 'groupFont',
            data: [{
              name: 'cmdBold',
              hotkey: 'Ctrl+B',
              title: 'Bold',
              icon: { glyph: 'glyphicon glyphicon-bold', fa: 'fa fa-bold', 'fa-3': 'icon-bold' },
              callback: function(e){
                // Give/remove ** surround the selection
                var chunk, cursor, selected = e.getSelection(), content = e.getContent();
    
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('strong text');
                } else {
                  chunk = selected.text;
                }
    
                // transform selection and set the cursor into chunked text
                if (content.substr(selected.start-2,2) === '**'
                    && content.substr(selected.end,2) === '**' ) {
                  e.setSelection(selected.start-2,selected.end+2);
                  e.replaceSelection(chunk);
                  cursor = selected.start-2;
                } else {
                  e.replaceSelection('**'+chunk+'**');
                  cursor = selected.start+2;
                }
    
                // Set the cursor
                e.setSelection(cursor,cursor+chunk.length);
              }
            },{
              name: 'cmdItalic',
              title: 'Italic',
              hotkey: 'Ctrl+I',
              icon: { glyph: 'glyphicon glyphicon-italic', fa: 'fa fa-italic', 'fa-3': 'icon-italic' },
              callback: function(e){
                // Give/remove * surround the selection
                var chunk, cursor, selected = e.getSelection(), content = e.getContent();
    
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('emphasized text');
                } else {
                  chunk = selected.text;
                }
    
                // transform selection and set the cursor into chunked text
                if (content.substr(selected.start-1,1) === '_'
                    && content.substr(selected.end,1) === '_' ) {
                  e.setSelection(selected.start-1,selected.end+1);
                  e.replaceSelection(chunk);
                  cursor = selected.start-1;
                } else {
                  e.replaceSelection('_'+chunk+'_');
                  cursor = selected.start+1;
                }
    
                // Set the cursor
                e.setSelection(cursor,cursor+chunk.length);
              }
            },{
              name: 'cmdHeading',
              title: 'Heading',
              hotkey: 'Ctrl+H',
              icon: { glyph: 'glyphicon glyphicon-header', fa: 'fa fa-header', 'fa-3': 'icon-font' },
              callback: function(e){
                // Append/remove ### surround the selection
                var chunk, cursor, selected = e.getSelection(), content = e.getContent(), pointer, prevChar;
    
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('heading text');
                } else {
                  chunk = selected.text + '\n';
                }
    
                // transform selection and set the cursor into chunked text
                if ((pointer = 4, content.substr(selected.start-pointer,pointer) === '### ')
                    || (pointer = 3, content.substr(selected.start-pointer,pointer) === '###')) {
                  e.setSelection(selected.start-pointer,selected.end);
                  e.replaceSelection(chunk);
                  cursor = selected.start-pointer;
                } else if (selected.start > 0 && (prevChar = content.substr(selected.start-1,1), !!prevChar && prevChar != '\n')) {
                  e.replaceSelection('\n\n### '+chunk);
                  cursor = selected.start+6;
                } else {
                  // Empty string before element
                  e.replaceSelection('### '+chunk);
                  cursor = selected.start+4;
                }
    
                // Set the cursor
                e.setSelection(cursor,cursor+chunk.length);
              }
            }]
          },{
            name: 'groupLink',
            data: [{
              name: 'cmdUrl',
              title: 'URL/Link',
              hotkey: 'Ctrl+L',
              icon: { glyph: 'glyphicon glyphicon-link', fa: 'fa fa-link', 'fa-3': 'icon-link' },
              callback: function(e){
                // Give [] surround the selection and prepend the link
                var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
    
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('enter link description here');
                } else {
                  chunk = selected.text;
                }
    
                link = prompt(e.__localize('Insert Hyperlink'),'http://');
    
                var urlRegex = new RegExp('^((http|https)://|(mailto:)|(//))[a-z0-9]', 'i');
                if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
                  var sanitizedLink = $('<div>'+link+'</div>').text();
    
                  // transform selection and set the cursor into chunked text
                  e.replaceSelection('['+chunk+']('+sanitizedLink+')');
                  cursor = selected.start+1;
    
                  // Set the cursor
                  e.setSelection(cursor,cursor+chunk.length);
                }
              }
            },{
              name: 'cmdImage',
              title: 'Image',
              hotkey: 'Ctrl+G',
              icon: { glyph: 'glyphicon glyphicon-picture', fa: 'fa fa-picture-o', 'fa-3': 'icon-picture' },
              callback: function(e){
                // Give ![] surround the selection and prepend the image link
                var chunk, cursor, selected = e.getSelection(), content = e.getContent(), link;
    
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('enter image description here');
                } else {
                  chunk = selected.text;
                }
    
                link = prompt(e.__localize('Insert Image Hyperlink'),'http://');
    
                var urlRegex = new RegExp('^((http|https)://|(//))[a-z0-9]', 'i');
                if (link !== null && link !== '' && link !== 'http://' && urlRegex.test(link)) {
                  var sanitizedLink = $('<div>'+link+'</div>').text();
    
                  // transform selection and set the cursor into chunked text
                  e.replaceSelection('!['+chunk+']('+sanitizedLink+' "'+e.__localize('enter image title here')+'")');
                  cursor = selected.start+2;
    
                  // Set the next tab
                  e.setNextTab(e.__localize('enter image title here'));
    
                  // Set the cursor
                  e.setSelection(cursor,cursor+chunk.length);
                }
              }
            }]
          },{
            name: 'groupMisc',
            data: [{
              name: 'cmdList',
              hotkey: 'Ctrl+U',
              title: 'Unordered List',
              icon: { glyph: 'glyphicon glyphicon-list', fa: 'fa fa-list', 'fa-3': 'icon-list-ul' },
              callback: function(e){
                // Prepend/Give - surround the selection
                var chunk, cursor, selected = e.getSelection(), content = e.getContent();
    
                // transform selection and set the cursor into chunked text
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('list text here');
    
                  e.replaceSelection('- '+chunk);
                  // Set the cursor
                  cursor = selected.start+2;
                } else {
                  if (selected.text.indexOf('\n') < 0) {
                    chunk = selected.text;
    
                    e.replaceSelection('- '+chunk);
    
                    // Set the cursor
                    cursor = selected.start+2;
                  } else {
                    var list = [];
    
                    list = selected.text.split('\n');
                    chunk = list[0];
    
                    $.each(list,function(k,v) {
                      list[k] = '- '+v;
                    });
    
                    e.replaceSelection('\n\n'+list.join('\n'));
    
                    // Set the cursor
                    cursor = selected.start+4;
                  }
                }
    
                // Set the cursor
                e.setSelection(cursor,cursor+chunk.length);
              }
            },
            {
              name: 'cmdListO',
              hotkey: 'Ctrl+O',
              title: 'Ordered List',
              icon: { glyph: 'glyphicon glyphicon-th-list', fa: 'fa fa-list-ol', 'fa-3': 'icon-list-ol' },
              callback: function(e) {
    
                // Prepend/Give - surround the selection
                var chunk, cursor, selected = e.getSelection(), content = e.getContent();
    
                // transform selection and set the cursor into chunked text
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('list text here');
                  e.replaceSelection('1. '+chunk);
                  // Set the cursor
                  cursor = selected.start+3;
                } else {
                  if (selected.text.indexOf('\n') < 0) {
                    chunk = selected.text;
    
                    e.replaceSelection('1. '+chunk);
    
                    // Set the cursor
                    cursor = selected.start+3;
                  } else {
                    var list = [];
    
                    list = selected.text.split('\n');
                    chunk = list[0];
    
                    $.each(list,function(k,v) {
                      list[k] = '1. '+v;
                    });
    
                    e.replaceSelection('\n\n'+list.join('\n'));
    
                    // Set the cursor
                    cursor = selected.start+5;
                  }
                }
    
                // Set the cursor
                e.setSelection(cursor,cursor+chunk.length);
              }
            },
            {
              name: 'cmdCode',
              hotkey: 'Ctrl+K',
              title: 'Code',
              icon: { glyph: 'glyphicon glyphicon-asterisk', fa: 'fa fa-code', 'fa-3': 'icon-code' },
              callback: function(e) {
                // Give/remove ** surround the selection
                var chunk, cursor, selected = e.getSelection(), content = e.getContent();
    
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('code text here');
                } else {
                  chunk = selected.text;
                }
    
                // transform selection and set the cursor into chunked text
                if (content.substr(selected.start-4,4) === '```\n'
                    && content.substr(selected.end,4) === '\n```') {
                  e.setSelection(selected.start-4, selected.end+4);
                  e.replaceSelection(chunk);
                  cursor = selected.start-4;
                } else if (content.substr(selected.start-1,1) === '`'
                    && content.substr(selected.end,1) === '`') {
                  e.setSelection(selected.start-1,selected.end+1);
                  e.replaceSelection(chunk);
                  cursor = selected.start-1;
                } else if (content.indexOf('\n') > -1) {
                  e.replaceSelection('```\n'+chunk+'\n```');
                  cursor = selected.start+4;
                } else {
                  e.replaceSelection('`'+chunk+'`');
                  cursor = selected.start+1;
                }
    
                // Set the cursor
                e.setSelection(cursor,cursor+chunk.length);
              }
            },
            {
              name: 'cmdQuote',
              hotkey: 'Ctrl+Q',
              title: 'Quote',
              icon: { glyph: 'glyphicon glyphicon-comment', fa: 'fa fa-quote-left', 'fa-3': 'icon-quote-left' },
              callback: function(e) {
                // Prepend/Give - surround the selection
                var chunk, cursor, selected = e.getSelection(), content = e.getContent();
    
                // transform selection and set the cursor into chunked text
                if (selected.length === 0) {
                  // Give extra word
                  chunk = e.__localize('quote here');
    
                  e.replaceSelection('> '+chunk);
    
                  // Set the cursor
                  cursor = selected.start+2;
                } else {
                  if (selected.text.indexOf('\n') < 0) {
                    chunk = selected.text;
    
                    e.replaceSelection('> '+chunk);
    
                    // Set the cursor
                    cursor = selected.start+2;
                  } else {
                    var list = [];
    
                    list = selected.text.split('\n');
                    chunk = list[0];
    
                    $.each(list,function(k,v) {
                      list[k] = '> '+v;
                    });
    
                    e.replaceSelection('\n\n'+list.join('\n'));
    
                    // Set the cursor
                    cursor = selected.start+4;
                  }
                }
    
                // Set the cursor
                e.setSelection(cursor,cursor+chunk.length);
              }
            }]
          },{
            name: 'groupUtil',
            data: [{
              name: 'cmdPreview',
              toggle: true,
              hotkey: 'Ctrl+P',
              title: 'Preview',
              btnText: 'Preview',
              btnClass: 'btn btn-primary btn-sm',
              icon: { glyph: 'glyphicon glyphicon-search', fa: 'fa fa-search', 'fa-3': 'icon-search' },
              callback: function(e){
                // Check the preview mode and toggle based on this flag
                var isPreview = e.$isPreview,content;
    
                if (isPreview === false) {
                  // Give flag that tell the editor enter preview mode
                  e.showPreview();
                } else {
                  e.hidePreview();
                }
              }
            }]
          }]
        ],
        additionalButtons:[], // Place to hook more buttons by code
        reorderButtonGroups:[],
        hiddenButtons:[], // Default hidden buttons
        disabledButtons:[], // Default disabled buttons
        footer: '',
        fullscreen: {
          enable: true,
          icons: {
            fullscreenOn: {
              fa: 'fa fa-expand',
              glyph: 'glyphicon glyphicon-fullscreen',
              'fa-3': 'icon-resize-full'
            },
            fullscreenOff: {
              fa: 'fa fa-compress',
              glyph: 'glyphicon glyphicon-fullscreen',
              'fa-3': 'icon-resize-small'
            }
          }
        },
    
        /* Events hook */
        onShow: function (e) {},
        onPreview: function (e) {},
        onSave: function (e) {},
        onBlur: function (e) {},
        onFocus: function (e) {},
        onChange: function(e) {},
        onFullscreen: function(e) {},
        onSelect: function (e) {}
      };
    
      $.fn.markdown.Constructor = Markdown;
    
    
     /* MARKDOWN NO CONFLICT
      * ==================== */
    
      $.fn.markdown.noConflict = function () {
        $.fn.markdown = old;
        return this;
      };
    
      /* MARKDOWN GLOBAL FUNCTION & DATA-API
      * ==================================== */
      var initMarkdown = function(el) {
        var $this = el;
    
        if ($this.data('markdown')) {
          $this.data('markdown').showEditor();
          return;
        }
    
        $this.markdown()
      };
    
      var blurNonFocused = function(e) {
        var $activeElement = $(document.activeElement);
    
        // Blur event
        $(document).find('.md-editor').each(function(){
          var $this            = $(this),
              focused          = $activeElement.closest('.md-editor')[0] === this,
              attachedMarkdown = $this.find('textarea').data('markdown') ||
                                 $this.find('div[data-provider="markdown-preview"]').data('markdown');
    
          if (attachedMarkdown && !focused) {
            attachedMarkdown.blur();
          }
        })
      };
    
      $(document)
        .on('click.markdown.data-api', '[data-provide="markdown-editable"]', function (e) {
          initMarkdown($(this));
          e.preventDefault();
        })
        .on('click focusin', function (e) {
          blurNonFocused(e);
        })
        .ready(function(){
          $('textarea[data-provide="markdown"]').each(function(){
            initMarkdown($(this));
          })
        });
    
    }));
    
    /*
     * Arabic translation for bootstrap-markdown
     * George Ajam <george.ejaam@gmail.com>
     */
    (function ($) {
      $.fn.markdown.messages.nl = {
        'Bold': "ØºØ§Ù…Ù‚",
        'Italic': "Ù…Ø§Ø¦Ù„",
        'Heading': "Ø¹Ù†ÙˆØ§Ù†",
        'URL/Link': "URL/Ø±Ø§Ø¨Ø·",
        'Image': "ØµÙˆØ±Ø©",
        'List': "Ù‚Ø§Ø¦Ù…Ø©",
        'Preview': "Ø§Ø³ØªØ¹Ø±Ø§Ø¶",
        'strong text': "Ù†Øµ ØºØ§Ù…Ù‚",
        'emphasized text': "Ù†Øµ Ù‡Ø§Ù…",
        'heading text': "Ø§Ù„Ø¹Ù†ÙˆØ§Ù†",
        'enter link description here': "Ø§Ø¯Ø®Ù„ ÙˆØµÙ Ø§Ù„Ø±Ø§Ø¨Ø· Ù‡Ù†Ø§",
        'Insert Hyperlink': "Ø§Ø¯Ø®Ù„ Ø§Ù„Ø±Ø§Ø¨Ø· Ù‡Ù†Ø§",
        'enter image description here': "Ø§Ø¯Ø®Ù„ ÙˆØµÙ Ø§Ù„ØµÙˆØ±Ø© Ù‡Ù†Ø§",
        'Insert Image Hyperlink': "Ø§Ø¯Ø®Ù„ Ø±Ø§Ø¨Ø· Ø§Ù„ØµÙˆØ±Ø© Ù‡Ù†Ø§",
        'enter image title here': "Ø§Ø¯Ø®Ù„ Ø¹Ù†ÙˆØ§Ù† Ø§Ù„ØµÙˆØ±Ø© Ù‡Ù†Ø§",
        'list text here': "Ø§ÙƒØªØ¨ Ø§Ù„Ù†Øµ Ù‡Ù†Ø§"
      };
    }(jQuery));
    
    /**
     * Czech translation for bootstrap-markdown
     * VÃ­t Kabele <vit@kabele.me>
     */
    (function ($) {
      $.fn.markdown.messages.cs = {
        'Bold': "TuÄnÄ›",
        'Italic': "KurzÃ­va",
        'Heading': "Nadpis",
        'URL/Link': "URL/Odkaz",
        'Image': "ObrÃ¡zek",
        'Unordered List': "Seznam",
        'Ordered List': "SeÅ™azenÃ½ seznam",
        'Code': "Ãšsek kÃ³du",
        'Quote': "Citace",
        'Preview': "NÃ¡hled",
        'strong text': "tuÄnÃ½ text",
        'emphasized text': "zdÅ¯raznÄ›nÃ½ text",
        'heading text': "text nadpisu",
        'enter link description here': "sem vloÅ¾ popis odkazu",
        'Insert Hyperlink': "VloÅ¾it Hyperlink",
        'enter image description here': "sem vloÅ¾ popis obrÃ¡zku",
        'Insert Image Hyperlink': "VloÅ¾ adresu obrÃ¡zku",
        'enter image title here': "sem vloÅ¾ popis obrÃ¡zku",
        'list text here': "poloÅ¾ka seznamu"
      };
    }(jQuery));
    
    /**
     * Danish translation for bootstrap-markdown
     * Dan Storm <storm@catalystcode.net>
     */
    (function ($) {
      $.fn.markdown.messages.nb = {
        'Bold': 'Fed',
        'Italic': 'Kursiv',
        'Heading': 'Overskrift',
        'URL/Link': 'URL/Link',
        'Image': 'Billede',
        'List': 'Liste',
        'Preview': 'ForhÃ¥ndsvisning',
        'strong text': 'stÃ¦rk tekst',
        'emphasized text': 'fremhÃ¦vet tekst',
        'heading text': 'overskrift tekst',
        'enter link description here': 'Skriv link beskrivelse her',
        'Insert Hyperlink': 'IndsÃ¦t link',
        'enter image description here': 'IndsÃ¦t billede beskrivelse her',
        'Insert Image Hyperlink': 'IndsÃ¦t billede link',
        'enter image title here': 'IndsÃ¦t billede titel',
        'list text here': 'IndsÃ¦t liste tekst her',
        'quote here': 'IndsÃ¦t citat her',
        'code text here': 'IndsÃ¦t kode her'
      };
    }(jQuery));
    
    /**
     * German translation for bootstrap-markdown
     * Tobias Nitsche <tobias-nitsche@gmx.net>
     */
    (function ($) {
      $.fn.markdown.messages.de = {
        'Bold': "Fett",
        'Italic': "Kursiv",
        'Heading': "Ãœberschrift",
        'URL/Link': "Link hinzufÃ¼gen",
        'Image': "Bild hinzufÃ¼gen",
        'Unordered List': "Unnummerierte Liste",
        'Ordered List': "Nummerierte Liste",
        'Code': "Quelltext",
        'Quote': "Zitat",
        'Preview': "Vorschau",
        'strong text': "Sehr betonter Text",
        'emphasized text': "Betonter Text",
        'heading text': "Ãœberschrift Text",
        'enter link description here': "Linkbeschreibung",
        'Insert Hyperlink': "URL",
        'enter image description here': "Bildbeschreibung",
        'Insert Image Hyperlink': "Bild-URL",
        'enter image title here': "Titel des Bildes",
        'list text here': "AufzÃ¤hlungs-Text"
      };
    }(jQuery));
    
    /**
     * Spanish translation for bootstrap-markdown
     * by Leandro Poblet <leandrodrhouse@gmail.com>
     */
    ;(function($){
      $.fn.markdown.messages['es'] = {
        'Bold': "Negrita",
        'Italic': "ItÃ¡lica",
        'Heading': "TÃ­tulo",
        'URL/Link': "Inserte un link",
        'Image': "Inserte una imagen",
        'List': "Lista de items",
        'Preview': "Previsualizar",
        'strong text': "texto importante",
        'emphasized text': "texto con Ã©nfasis",
        'heading text': "texto titular",
        'enter link description here': "descripciÃ³n del link",
        'Insert Hyperlink': "Inserte un hipervÃ­nculo",
        'enter image description here': "descripciÃ³n de la imagen",
        'Insert Image Hyperlink': "Inserte una imagen con un hipervÃ­nculo",
        'enter image title here': "Inserte una imagen con tÃ­tulo",
        'list text here': "lista con texto"
      };
    }(jQuery));
    
    /**
     * Persian(Farsi) translation for bootstrap-markdown
     * Sajad Dehshiri <Pelakweb.ir>
     */
    (function ($) {
      $.fn.markdown.messages.fa = {
        'Bold': "ØªÙˆÙ¾Ø±",
        'Italic': "Ù…ÙˆØ±Ø¨",
        'Heading': "Ø¹Ù†ÙˆØ§Ù†",
        'URL/Link': "Ù¾ÛŒÙˆÙ†Ø¯",
        'Image': "ØªØµÙˆÛŒØ±",
        'List': "ÙÙ‡Ø±Ø³Øª",
        'Preview': "Ù¾ÛŒØ´ Ù†Ù…Ø§ÛŒØ´",
        'strong text': "Ù…ØªÙ† Ø¶Ø®ÛŒÙ…",
        'emphasized text': "Ù†ÙˆØ´ØªÙ‡ ØªØ§Ú©ÛŒØ¯ÛŒ",
        'heading text': "Ø¹Ù†ÙˆØ§Ù†",
        'enter link description here': "ØªÙˆØ¶ÛŒØ­Ø§Øª Ù¾ÛŒÙˆÙ†Ø¯ Ø±Ø§ Ø¨Ù†ÙˆÛŒØ³ÛŒØ¯.",
        'Insert Hyperlink': "Ù¾ÛŒÙˆÙ†Ø¯ Ø±Ø§ Ø¯Ø±Ø¬ Ù†Ù…Ø§ÛŒÛŒØ¯:",
        'enter image description here': "ØªÙˆØ¶ÛŒØ­ÛŒ Ø¨Ø±Ø§ÛŒ ØªØµÙˆÛŒ Ø¨Ù†ÙˆÛŒØ³ÛŒØ¯.",
        'Insert Image Hyperlink': "Ø¢Ø¯Ø±Ø³ ØªØµÙˆÛŒØ± Ø±Ø§ Ø¨Ù†ÙˆÛŒØ³ÛŒØ¯.",
        'enter image title here': "Ø¹Ù†ÙˆØ§Ù† ØªØµÙˆÛŒØ± Ø±Ø§ Ø§ÛŒÙ†Ø¬Ø§ Ø¨Ù†ÙˆÛŒØ³ÛŒØ¯",
        'list text here': "Ù…Ø­Ù„ Ù…ØªÙ† ÙÙ‡Ø±Ø³Øª"
      };
    }(jQuery));
    
    /**
     * French translation for bootstrap-markdown
     * BenoÃ®t Bourgeois <bierdok@gmail.com>
     */
    (function ($) {
      $.fn.markdown.messages.fr = {
        'Bold': "Gras",
        'Italic': "Italique",
        'Heading': "Titre",
        'URL/Link': "InsÃ©rer un lien HTTP",
        'Image': "InsÃ©rer une image",
        'List': "Liste Ã  puces",
        'Preview': "PrÃ©visualiser",
        'strong text': "texte important",
        'emphasized text': "texte en italique",
        'heading text': "texte d'entÃªte",
        'enter link description here': "entrez la description du lien ici",
        'Insert Hyperlink': "InsÃ©rez le lien hypertexte",
        'enter image description here': "entrez la description de l'image ici",
        'Insert Image Hyperlink': "InsÃ©rez le lien hypertexte de l'image",
        'enter image title here': "entrez le titre de l'image ici",
        'list text here': "texte Ã  puce ici",
        'Save': "Sauvegarder",
        'Ordered List': "Liste ordonnÃ©e",
        'Unordered List': "Liste dÃ©sordonnÃ©e",
        'Quote': "Citation",
        'quote here': "Votre citation",
        'Code': "Code",
        'code text here': "Ã©crire du code ici"
      };
    }(jQuery));
    
    /**
     * Japanese translation for bootstrap-markdown
     * Kenta Murakami <kntmrkm@gmail.com>
     */
    (function ($) {
      $.fn.markdown.messages['ja'] = {
        'Bold': "å¤ªå­—",
        'Italic': "æ–œä½“",
        'Heading': "è¦‹å‡ºã—",
        'URL/Link': "ãƒªãƒ³ã‚¯",
        'Image': "ç”»åƒ",
        'Unordered List': "ãƒªã‚¹ãƒˆ",
        'Ordered List': "æ•°å­—ãƒªã‚¹ãƒˆ",
        'Code': "ã‚³ãƒ¼ãƒ‰",
        'Quote': "å¼•ç”¨",
        'Preview': "ãƒ—ãƒ¬ãƒ“ãƒ¥ãƒ¼",
        'strong text': "å¤ªå­—",
        'emphasized text': "å¼·èª¿",
        'heading text': "è¦‹å‡ºã—",
        'enter link description here': "ãƒªãƒ³ã‚¯èª¬æ˜Ž",
        'Insert Hyperlink': "ãƒªãƒ³ã‚¯æŒ¿å…¥",
        'enter image description here': "ç”»åƒèª¬æ˜Ž",
        'Insert Image Hyperlink': "ç”»åƒæŒ¿å…¥",
        'enter image title here': "ç”»åƒã‚¿ã‚¤ãƒˆãƒ«",
        'list text here': "ãƒªã‚¹ãƒˆæŒ¿å…¥",
        'code text here': "ã‚³ãƒ¼ãƒ‰",
        'quote here': "å¼•ç”¨æŒ¿å…¥"
      };
    }(jQuery));
    
    /**
     + * Korean translation for bootstrap-markdown
     + * WoongBi Kim <ssinss@gmail.com>
     + */
    ;(function($){
      $.fn.markdown.messages['kr'] = {
        'Bold': "ì§„í•˜ê²Œ",
        'Italic': "ì´íƒ¤ë¦­ì²´",
        'Heading': "ë¨¸ë¦¬ê¸€",
        'URL/Link': "ë§í¬ì£¼ì†Œ",
        'Image': "ì´ë¯¸ì§€",
        'List': "ë¦¬ìŠ¤íŠ¸",
        'Preview': "ë¯¸ë¦¬ë³´ê¸°",
        'strong text': "ê°•í•œ ê°•ì¡° í…ìŠ¤íŠ¸",
        'emphasized text': "ê°•ì¡° í…ìŠ¤íŠ¸",
        'heading text': "ë¨¸ë¦¬ê¸€ í…ìŠ¤íŠ¸",
        'enter link description here': "ì—¬ê¸°ì— ë§í¬ì˜ ì„¤ëª…ì„ ì ìœ¼ì„¸ìš”",
        'Insert Hyperlink': "í•˜ì´í¼ë§í¬ ì‚½ìž…",
        'enter image description here': "ì—¬ê¸°ì„¸ ì´ë¯¸ì§€ ì„¤ëª…ì„ ì ìœ¼ì„¸ìš”",
        'Insert Image Hyperlink': "ì´ë¯¸ì§€ ë§í¬ ì‚½ìž…",
        'enter image title here': "ì—¬ê¸°ì— ì´ë¯¸ì§€ ì œëª©ì„ ì ìœ¼ì„¸ìš”",
        'list text here': "ë¦¬ìŠ¤íŠ¸ í…ìŠ¤íŠ¸"
      };
    }(jQuery));
    
    /**
     * Norwegian bokmÃ¥l translation for bootstrap-markdown
     * Tobias Bohwalli <hi@futhr.io>
     */
    (function ($) {
      $.fn.markdown.messages.nb = {
        'Bold': 'Fet',
        'Italic': 'Kursiv',
        'Heading': 'Overskrift',
        'URL/Link': 'URL/Lenke',
        'Image': 'Bilde',
        'List': 'Liste',
        'Preview': 'ForhÃ¥ndsvisning',
        'strong text': 'sterk tekst',
        'emphasized text': 'streket tekst',
        'heading text': 'overskriften tekst',
        'enter link description here': 'Skriv linken beskrivelse her',
        'Insert Hyperlink': 'Sett inn lenke',
        'enter image description here': 'Angi bildebeskrivelse her',
        'Insert Image Hyperlink': 'Sett inn lenke for bilde',
        'enter image title here': 'Angi bildetittel her',
        'list text here': 'liste tekst her'
      };
    }(jQuery));
    
    /**
     * Dutch translation for bootstrap-markdown
     * Jeroen Thora <jeroenthora@gmail.com>
     */
    (function ($) {
      $.fn.markdown.messages.nl = {
        'Bold': "Vet",
        'Italic': "Cursief",
        'Heading': "Titel",
        'URL/Link': "URL/Link",
        'Image': "Afbeelding",
        'List': "Lijst",
        'Preview': "Voorbeeld",
        'strong text': "vet gedrukte tekst",
        'emphasized text': "schuin gedrukte tekst",
        'heading text': "Titel",
        'enter link description here': "Voer een link beschrijving in",
        'Insert Hyperlink': "Voer een http link in",
        'enter image description here': "Voer een afbeelding beschrijving in",
        'Insert Image Hyperlink': "Voer een afbeelding link in",
        'enter image title here': "Voer de afbeelding titel in",
        'list text here': "lijst item"
      };
    }(jQuery));
    
    /**
     * Polish translation for bootstrap-markdown
     * Marek Kaput
     */
    (function ($) {
      $.fn.markdown.messages.pl = {
        'Bold': "Pogrubienie",
        'Italic': "Kursywa",
        'Heading': "NagÅ‚Ã³wek",
        'URL/Link': "Wstaw link",
        'Image': "Wstaw obrazek",
        'Unordered List': "Lista punktowana",
        'Ordered List': "Lista numerowana",
        'Code': "Kod ÅºrÃ³dÅ‚owy",
        'Quote': "Cytat",
        'Preview': "PodglÄ…d",
        'strong text': "pogrubiony tekst",
        'emphasized text': "pochylony tekst",
        'heading text': "nagÅ‚Ã³wek",
        'enter link description here': "opis linka",
        'Insert Hyperlink': "Wstaw link",
        'enter image description here': "opis obrazka",
        'Insert Image Hyperlink': "Wstaw obrazek",
        'enter image title here': "tytuÅ‚ obrazka",
        'list text here': "lista"
      };
    }(jQuery));
    
    /**
     * Slovenian translation for bootstrap-markdown
     * Davor Padovan <davor.padovan@gmail.com>
     */
    (function ($) {
      $.fn.markdown.messages.sl = {
        'Bold': "Odebeljeno",
        'Italic': "PoÅ¡evno",
        'Heading': "Naslov",
        'URL/Link': "Povezava",
        'Image': "Slika",
        'Unordered List': "Neurejen seznam",
        'Ordered List': "Urejen seznam",
        'Code': "Koda",
        'Quote': "Citat",
        'Preview': "Predogled",
        'strong text': "odebeljeno besedilo",
        'emphasized text': "poÅ¡evno besedilo",
        'heading text': "naslov",
        'enter link description here': "opis povezave",
        'Insert Hyperlink': "Vstavi povezavo",
        'enter image description here': "opis slike",
        'Insert Image Hyperlink': "Vstavi povezavo do slike",
        'enter image title here': "naslov slike",
        'list text here': "seznam"
      };
    }(jQuery));
    
    /**
     * Swedish translation for bootstrap-markdown
     * Tobias Bohwalli <hi@futhr.io>
     */
    (function ($) {
      $.fn.markdown.messages.sv = {
        'Bold': 'Fet',
        'Italic': 'Kursiv',
        'Heading': 'Rubrik',
        'URL/Link': 'URL/LÃ¤nk',
        'Image': 'Bild',
        'List': 'Lista',
        'Preview': 'FÃ¶rhandsgranska',
        'strong text': 'fet text',
        'emphasized text': 'Ã¶verstruken text',
        'heading text': 'Rubrik',
        'enter link description here': 'Ange lÃ¤nk beskrivning hÃ¤r',
        'Insert Hyperlink': 'SÃ¤tt in lÃ¤nk',
        'enter image description here': 'Ange bild beskrivning hÃ¤r',
        'Insert Image Hyperlink': 'SÃ¤tt in lÃ¤nk fÃ¶r bild',
        'enter image title here': 'Ange bild rubrik hÃ¤r',
        'list text here': 'list text'
      };
    }(jQuery));
    
    /**
     * Turkish translation for bootstrap-markdown
     * Serkan Algur <info@wpadami.com>
     */
    (function ($) {
      $.fn.markdown.messages.tr = {
        'Bold': "KalÄ±n",
        'Italic': "Ä°talik",
        'Heading': "BaÅŸlÄ±k",
        'URL/Link': "Link ekle",
        'Image': "Resim ekle",
        'List': "Liste OluÅŸturun",
        'Preview': "Ã–nizleme",
        'strong text': "kalÄ±n yazÄ±",
        'emphasized text': "italik yazÄ±",
        'heading text': "BaÅŸlÄ±k YazÄ±sÄ±",
        'enter link description here': "Link aÃ§Ä±klamasÄ±nÄ± buraya girin",
        'Insert Hyperlink': "Ä°nternet adresi girin",
        'enter image description here': "resim aÃ§Ä±klamasÄ±nÄ± buraya ekleyin",
        'Insert Image Hyperlink': "Resim linkini ekleyin",
        'enter image title here': "resim baÅŸlÄ±ÄŸÄ±nÄ± buraya ekleyin",
        'list text here': "liste yazÄ±sÄ±",
        'Save' : "Kaydet",
        'Ordered List' : "NumaralÄ± Liste",
        'Unordered List' : "Madde imli liste",
        'Quote' : "AlÄ±ntÄ±",
        'quote here' : "alÄ±ntÄ±yÄ± buraya ekleyin",
        'Code' : "Kod",
        'code text here' : "kodu buraya ekleyin"
      };
    }(jQuery));
    
    /**
     * Chinese translation for bootstrap-markdown
     * benhaile <denghaier@163.com>
     */
    (function ($) {
      $.fn.markdown.messages.zh = {
        'Bold': "ç²—ä½“",
        'Italic': "æ–œä½“",
        'Heading': "æ ‡é¢˜",
        'URL/Link': "é“¾æŽ¥",
        'Image': "å›¾ç‰‡",
        'List': "åˆ—è¡¨",
        'Unordered List': "æ— åºåˆ—è¡¨",
        'Ordered List': "æœ‰åºåˆ—è¡¨",
        'Code': "ä»£ç ",
        'Quote': "å¼•ç”¨",
        'Preview': "é¢„è§ˆ",
        'strong text': "ç²—ä½“",
        'emphasized text': "å¼ºè°ƒ",
        'heading text': "æ ‡é¢˜",
        'enter link description here': "è¾“å…¥é“¾æŽ¥è¯´æ˜Ž",
        'Insert Hyperlink': "URLåœ°å€",
        'enter image description here': "è¾“å…¥å›¾ç‰‡è¯´æ˜Ž",
        'Insert Image Hyperlink': "å›¾ç‰‡URLåœ°å€",
        'enter image title here': "åœ¨è¿™é‡Œè¾“å…¥å›¾ç‰‡æ ‡é¢˜",
        'list text here': "è¿™é‡Œæ˜¯åˆ—è¡¨æ–‡æœ¬",
        'code text here': "è¿™é‡Œè¾“å…¥ä»£ç ",
        'quote here': "è¿™é‡Œè¾“å…¥å¼•ç”¨æ–‡æœ¬"
    
    
      };
    }(jQuery));
    
    /**
     * Owl Carousel v2.2.1
     * Copyright 2013-2017 David Deutsch
     * Licensed under  ()
     */
    /**
     * Owl carousel
     * @version 2.1.6
     * @author Bartosz Wojciechowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     * @todo Lazy Load Icon
     * @todo prevent animationend bubling
     * @todo itemsScaleUp
     * @todo Test Zepto
     * @todo stagePadding calculate wrong active classes
     */
    ;(function($, window, document, undefined) {
    
        /**
         * Creates a carousel.
         * @class The Owl Carousel.
         * @public
         * @param {HTMLElement|jQuery} element - The element to create the carousel for.
         * @param {Object} [options] - The options
         */
        function Owl(element, options) {
    
            /**
             * Current settings for the carousel.
             * @public
             */
            this.settings = null;
    
            /**
             * Current options set by the caller including defaults.
             * @public
             */
            this.options = $.extend({}, Owl.Defaults, options);
    
            /**
             * Plugin element.
             * @public
             */
            this.$element = $(element);
    
            /**
             * Proxied event handlers.
             * @protected
             */
            this._handlers = {};
    
            /**
             * References to the running plugins of this carousel.
             * @protected
             */
            this._plugins = {};
    
            /**
             * Currently suppressed events to prevent them from beeing retriggered.
             * @protected
             */
            this._supress = {};
    
            /**
             * Absolute current position.
             * @protected
             */
            this._current = null;
    
            /**
             * Animation speed in milliseconds.
             * @protected
             */
            this._speed = null;
    
            /**
             * Coordinates of all items in pixel.
             * @todo The name of this member is missleading.
             * @protected
             */
            this._coordinates = [];
    
            /**
             * Current breakpoint.
             * @todo Real media queries would be nice.
             * @protected
             */
            this._breakpoint = null;
    
            /**
             * Current width of the plugin element.
             */
            this._width = null;
    
            /**
             * All real items.
             * @protected
             */
            this._items = [];
    
            /**
             * All cloned items.
             * @protected
             */
            this._clones = [];
    
            /**
             * Merge values of all items.
             * @todo Maybe this could be part of a plugin.
             * @protected
             */
            this._mergers = [];
    
            /**
             * Widths of all items.
             */
            this._widths = [];
    
            /**
             * Invalidated parts within the update process.
             * @protected
             */
            this._invalidated = {};
    
            /**
             * Ordered list of workers for the update process.
             * @protected
             */
            this._pipe = [];
    
            /**
             * Current state information for the drag operation.
             * @todo #261
             * @protected
             */
            this._drag = {
                time: null,
                target: null,
                pointer: null,
                stage: {
                    start: null,
                    current: null
                },
                direction: null
            };
    
            /**
             * Current state information and their tags.
             * @type {Object}
             * @protected
             */
            this._states = {
                current: {},
                tags: {
                    'initializing': [ 'busy' ],
                    'animating': [ 'busy' ],
                    'dragging': [ 'interacting' ]
                }
            };
    
            $.each([ 'onResize', 'onThrottledResize' ], $.proxy(function(i, handler) {
                this._handlers[handler] = $.proxy(this[handler], this);
            }, this));
    
            $.each(Owl.Plugins, $.proxy(function(key, plugin) {
                this._plugins[key.charAt(0).toLowerCase() + key.slice(1)]
                    = new plugin(this);
            }, this));
    
            $.each(Owl.Workers, $.proxy(function(priority, worker) {
                this._pipe.push({
                    'filter': worker.filter,
                    'run': $.proxy(worker.run, this)
                });
            }, this));
    
            this.setup();
            this.initialize();
        }
    
        /**
         * Default options for the carousel.
         * @public
         */
        Owl.Defaults = {
            items: 3,
            loop: false,
            center: false,
            rewind: false,
    
            mouseDrag: true,
            touchDrag: true,
            pullDrag: true,
            freeDrag: false,
    
            margin: 0,
            stagePadding: 0,
    
            merge: false,
            mergeFit: true,
            autoWidth: false,
    
            startPosition: 0,
            rtl: false,
    
            smartSpeed: 250,
            fluidSpeed: false,
            dragEndSpeed: false,
    
            responsive: {},
            responsiveRefreshRate: 200,
            responsiveBaseElement: window,
    
            fallbackEasing: 'swing',
    
            info: false,
    
            nestedItemSelector: false,
            itemElement: 'div',
            stageElement: 'div',
    
            refreshClass: 'owl-refresh',
            loadedClass: 'owl-loaded',
            loadingClass: 'owl-loading',
            rtlClass: 'owl-rtl',
            responsiveClass: 'owl-responsive',
            dragClass: 'owl-drag',
            itemClass: 'owl-item',
            stageClass: 'owl-stage',
            stageOuterClass: 'owl-stage-outer',
            grabClass: 'owl-grab'
        };
    
        /**
         * Enumeration for width.
         * @public
         * @readonly
         * @enum {String}
         */
        Owl.Width = {
            Default: 'default',
            Inner: 'inner',
            Outer: 'outer'
        };
    
        /**
         * Enumeration for types.
         * @public
         * @readonly
         * @enum {String}
         */
        Owl.Type = {
            Event: 'event',
            State: 'state'
        };
    
        /**
         * Contains all registered plugins.
         * @public
         */
        Owl.Plugins = {};
    
        /**
         * List of workers involved in the update process.
         */
        Owl.Workers = [ {
            filter: [ 'width', 'settings' ],
            run: function() {
                this._width = this.$element.width();
            }
        }, {
            filter: [ 'width', 'items', 'settings' ],
            run: function(cache) {
                cache.current = this._items && this._items[this.relative(this._current)];
            }
        }, {
            filter: [ 'items', 'settings' ],
            run: function() {
                this.$stage.children('.cloned').remove();
            }
        }, {
            filter: [ 'width', 'items', 'settings' ],
            run: function(cache) {
                var margin = this.settings.margin || '',
                    grid = !this.settings.autoWidth,
                    rtl = this.settings.rtl,
                    css = {
                        'width': 'auto',
                        'margin-left': rtl ? margin : '',
                        'margin-right': rtl ? '' : margin
                    };
    
                !grid && this.$stage.children().css(css);
    
                cache.css = css;
            }
        }, {
            filter: [ 'width', 'items', 'settings' ],
            run: function(cache) {
                var width = (this.width() / this.settings.items).toFixed(3) - this.settings.margin,
                    merge = null,
                    iterator = this._items.length,
                    grid = !this.settings.autoWidth,
                    widths = [];
    
                cache.items = {
                    merge: false,
                    width: width
                };
    
                while (iterator--) {
                    merge = this._mergers[iterator];
                    merge = this.settings.mergeFit && Math.min(merge, this.settings.items) || merge;
    
                    cache.items.merge = merge > 1 || cache.items.merge;
    
                    widths[iterator] = !grid ? this._items[iterator].width() : width * merge;
                }
    
                this._widths = widths;
            }
        }, {
            filter: [ 'items', 'settings' ],
            run: function() {
                var clones = [],
                    items = this._items,
                    settings = this.settings,
                    // TODO: Should be computed from number of min width items in stage
                    view = Math.max(settings.items * 2, 4),
                    size = Math.ceil(items.length / 2) * 2,
                    repeat = settings.loop && items.length ? settings.rewind ? view : Math.max(view, size) : 0,
                    append = '',
                    prepend = '';
    
                repeat /= 2;
    
                while (repeat--) {
                    // Switch to only using appended clones
                    clones.push(this.normalize(clones.length / 2, true));
                    append = append + items[clones[clones.length - 1]][0].outerHTML;
                    clones.push(this.normalize(items.length - 1 - (clones.length - 1) / 2, true));
                    prepend = items[clones[clones.length - 1]][0].outerHTML + prepend;
                }
    
                this._clones = clones;
    
                $(append).addClass('cloned').appendTo(this.$stage);
                $(prepend).addClass('cloned').prependTo(this.$stage);
            }
        }, {
            filter: [ 'width', 'items', 'settings' ],
            run: function() {
                var rtl = this.settings.rtl ? 1 : -1,
                    size = this._clones.length + this._items.length,
                    iterator = -1,
                    previous = 0,
                    current = 0,
                    coordinates = [];
    
                while (++iterator < size) {
                    previous = coordinates[iterator - 1] || 0;
                    current = this._widths[this.relative(iterator)] + this.settings.margin;
                    coordinates.push(previous + current * rtl);
                }
    
                this._coordinates = coordinates;
            }
        }, {
            filter: [ 'width', 'items', 'settings' ],
            run: function() {
                var padding = this.settings.stagePadding,
                    coordinates = this._coordinates,
                    css = {
                        'width': Math.ceil(Math.abs(coordinates[coordinates.length - 1])) + padding * 2,
                        'padding-left': padding || '',
                        'padding-right': padding || ''
                    };
    
                this.$stage.css(css);
            }
        }, {
            filter: [ 'width', 'items', 'settings' ],
            run: function(cache) {
                var iterator = this._coordinates.length,
                    grid = !this.settings.autoWidth,
                    items = this.$stage.children();
    
                if (grid && cache.items.merge) {
                    while (iterator--) {
                        cache.css.width = this._widths[this.relative(iterator)];
                        items.eq(iterator).css(cache.css);
                    }
                } else if (grid) {
                    cache.css.width = cache.items.width;
                    items.css(cache.css);
                }
            }
        }, {
            filter: [ 'items' ],
            run: function() {
                this._coordinates.length < 1 && this.$stage.removeAttr('style');
            }
        }, {
            filter: [ 'width', 'items', 'settings' ],
            run: function(cache) {
                cache.current = cache.current ? this.$stage.children().index(cache.current) : 0;
                cache.current = Math.max(this.minimum(), Math.min(this.maximum(), cache.current));
                this.reset(cache.current);
            }
        }, {
            filter: [ 'position' ],
            run: function() {
                this.animate(this.coordinates(this._current));
            }
        }, {
            filter: [ 'width', 'position', 'items', 'settings' ],
            run: function() {
                var rtl = this.settings.rtl ? 1 : -1,
                    padding = this.settings.stagePadding * 2,
                    begin = this.coordinates(this.current()) + padding,
                    end = begin + this.width() * rtl,
                    inner, outer, matches = [], i, n;
    
                for (i = 0, n = this._coordinates.length; i < n; i++) {
                    inner = this._coordinates[i - 1] || 0;
                    outer = Math.abs(this._coordinates[i]) + padding * rtl;
    
                    if ((this.op(inner, '<=', begin) && (this.op(inner, '>', end)))
                        || (this.op(outer, '<', begin) && this.op(outer, '>', end))) {
                        matches.push(i);
                    }
                }
    
                this.$stage.children('.active').removeClass('active');
                this.$stage.children(':eq(' + matches.join('), :eq(') + ')').addClass('active');
    
                if (this.settings.center) {
                    this.$stage.children('.center').removeClass('center');
                    this.$stage.children().eq(this.current()).addClass('center');
                }
            }
        } ];
    
        /**
         * Initializes the carousel.
         * @protected
         */
        Owl.prototype.initialize = function() {
            this.enter('initializing');
            this.trigger('initialize');
    
            this.$element.toggleClass(this.settings.rtlClass, this.settings.rtl);
    
            if (this.settings.autoWidth && !this.is('pre-loading')) {
                var imgs, nestedSelector, width;
                imgs = this.$element.find('img');
                nestedSelector = this.settings.nestedItemSelector ? '.' + this.settings.nestedItemSelector : undefined;
                width = this.$element.children(nestedSelector).width();
    
                if (imgs.length && width <= 0) {
                    this.preloadAutoWidthImages(imgs);
                }
            }
    
            this.$element.addClass(this.options.loadingClass);
    
            // create stage
            this.$stage = $('<' + this.settings.stageElement + ' class="' + this.settings.stageClass + '"/>')
                .wrap('<div class="' + this.settings.stageOuterClass + '"/>');
    
            // append stage
            this.$element.append(this.$stage.parent());
    
            // append content
            this.replace(this.$element.children().not(this.$stage.parent()));
    
            // check visibility
            if (this.$element.is(':visible')) {
                // update view
                this.refresh();
            } else {
                // invalidate width
                this.invalidate('width');
            }
    
            this.$element
                .removeClass(this.options.loadingClass)
                .addClass(this.options.loadedClass);
    
            // register event handlers
            this.registerEventHandlers();
    
            this.leave('initializing');
            this.trigger('initialized');
        };
    
        /**
         * Setups the current settings.
         * @todo Remove responsive classes. Why should adaptive designs be brought into IE8?
         * @todo Support for media queries by using `matchMedia` would be nice.
         * @public
         */
        Owl.prototype.setup = function() {
            var viewport = this.viewport(),
                overwrites = this.options.responsive,
                match = -1,
                settings = null;
    
            if (!overwrites) {
                settings = $.extend({}, this.options);
            } else {
                $.each(overwrites, function(breakpoint) {
                    if (breakpoint <= viewport && breakpoint > match) {
                        match = Number(breakpoint);
                    }
                });
    
                settings = $.extend({}, this.options, overwrites[match]);
                if (typeof settings.stagePadding === 'function') {
                    settings.stagePadding = settings.stagePadding();
                }
                delete settings.responsive;
    
                // responsive class
                if (settings.responsiveClass) {
                    this.$element.attr('class',
                        this.$element.attr('class').replace(new RegExp('(' + this.options.responsiveClass + '-)\\S+\\s', 'g'), '$1' + match)
                    );
                }
            }
    
            this.trigger('change', { property: { name: 'settings', value: settings } });
            this._breakpoint = match;
            this.settings = settings;
            this.invalidate('settings');
            this.trigger('changed', { property: { name: 'settings', value: this.settings } });
        };
    
        /**
         * Updates option logic if necessery.
         * @protected
         */
        Owl.prototype.optionsLogic = function() {
            if (this.settings.autoWidth) {
                this.settings.stagePadding = false;
                this.settings.merge = false;
            }
        };
    
        /**
         * Prepares an item before add.
         * @todo Rename event parameter `content` to `item`.
         * @protected
         * @returns {jQuery|HTMLElement} - The item container.
         */
        Owl.prototype.prepare = function(item) {
            var event = this.trigger('prepare', { content: item });
    
            if (!event.data) {
                event.data = $('<' + this.settings.itemElement + '/>')
                    .addClass(this.options.itemClass).append(item)
            }
    
            this.trigger('prepared', { content: event.data });
    
            return event.data;
        };
    
        /**
         * Updates the view.
         * @public
         */
        Owl.prototype.update = function() {
            var i = 0,
                n = this._pipe.length,
                filter = $.proxy(function(p) { return this[p] }, this._invalidated),
                cache = {};
    
            while (i < n) {
                if (this._invalidated.all || $.grep(this._pipe[i].filter, filter).length > 0) {
                    this._pipe[i].run(cache);
                }
                i++;
            }
    
            this._invalidated = {};
    
            !this.is('valid') && this.enter('valid');
        };
    
        /**
         * Gets the width of the view.
         * @public
         * @param {Owl.Width} [dimension=Owl.Width.Default] - The dimension to return.
         * @returns {Number} - The width of the view in pixel.
         */
        Owl.prototype.width = function(dimension) {
            dimension = dimension || Owl.Width.Default;
            switch (dimension) {
                case Owl.Width.Inner:
                case Owl.Width.Outer:
                    return this._width;
                default:
                    return this._width - this.settings.stagePadding * 2 + this.settings.margin;
            }
        };
    
        /**
         * Refreshes the carousel primarily for adaptive purposes.
         * @public
         */
        Owl.prototype.refresh = function() {
            this.enter('refreshing');
            this.trigger('refresh');
    
            this.setup();
    
            this.optionsLogic();
    
            this.$element.addClass(this.options.refreshClass);
    
            this.update();
    
            this.$element.removeClass(this.options.refreshClass);
    
            this.leave('refreshing');
            this.trigger('refreshed');
        };
    
        /**
         * Checks window `resize` event.
         * @protected
         */
        Owl.prototype.onThrottledResize = function() {
            window.clearTimeout(this.resizeTimer);
            this.resizeTimer = window.setTimeout(this._handlers.onResize, this.settings.responsiveRefreshRate);
        };
    
        /**
         * Checks window `resize` event.
         * @protected
         */
        Owl.prototype.onResize = function() {
            if (!this._items.length) {
                return false;
            }
    
            if (this._width === this.$element.width()) {
                return false;
            }
    
            if (!this.$element.is(':visible')) {
                return false;
            }
    
            this.enter('resizing');
    
            if (this.trigger('resize').isDefaultPrevented()) {
                this.leave('resizing');
                return false;
            }
    
            this.invalidate('width');
    
            this.refresh();
    
            this.leave('resizing');
            this.trigger('resized');
        };
    
        /**
         * Registers event handlers.
         * @todo Check `msPointerEnabled`
         * @todo #261
         * @protected
         */
        Owl.prototype.registerEventHandlers = function() {
            if ($.support.transition) {
                this.$stage.on($.support.transition.end + '.owl.core', $.proxy(this.onTransitionEnd, this));
            }
    
            if (this.settings.responsive !== false) {
                this.on(window, 'resize', this._handlers.onThrottledResize);
            }
    
            if (this.settings.mouseDrag) {
                this.$element.addClass(this.options.dragClass);
                this.$stage.on('mousedown.owl.core', $.proxy(this.onDragStart, this));
                this.$stage.on('dragstart.owl.core selectstart.owl.core', function() { return false });
            }
    
            if (this.settings.touchDrag){
                this.$stage.on('touchstart.owl.core', $.proxy(this.onDragStart, this));
                this.$stage.on('touchcancel.owl.core', $.proxy(this.onDragEnd, this));
            }
        };
    
        /**
         * Handles `touchstart` and `mousedown` events.
         * @todo Horizontal swipe threshold as option
         * @todo #261
         * @protected
         * @param {Event} event - The event arguments.
         */
        Owl.prototype.onDragStart = function(event) {
            var stage = null;
    
            if (event.which === 3) {
                return;
            }
    
            if ($.support.transform) {
                stage = this.$stage.css('transform').replace(/.*\(|\)| /g, '').split(',');
                stage = {
                    x: stage[stage.length === 16 ? 12 : 4],
                    y: stage[stage.length === 16 ? 13 : 5]
                };
            } else {
                stage = this.$stage.position();
                stage = {
                    x: this.settings.rtl ?
                        stage.left + this.$stage.width() - this.width() + this.settings.margin :
                        stage.left,
                    y: stage.top
                };
            }
    
            if (this.is('animating')) {
                $.support.transform ? this.animate(stage.x) : this.$stage.stop()
                this.invalidate('position');
            }
    
            this.$element.toggleClass(this.options.grabClass, event.type === 'mousedown');
    
            this.speed(0);
    
            this._drag.time = new Date().getTime();
            this._drag.target = $(event.target);
            this._drag.stage.start = stage;
            this._drag.stage.current = stage;
            this._drag.pointer = this.pointer(event);
    
            $(document).on('mouseup.owl.core touchend.owl.core', $.proxy(this.onDragEnd, this));
    
            $(document).one('mousemove.owl.core touchmove.owl.core', $.proxy(function(event) {
                var delta = this.difference(this._drag.pointer, this.pointer(event));
    
                $(document).on('mousemove.owl.core touchmove.owl.core', $.proxy(this.onDragMove, this));
    
                if (Math.abs(delta.x) < Math.abs(delta.y) && this.is('valid')) {
                    return;
                }
    
                event.preventDefault();
    
                this.enter('dragging');
                this.trigger('drag');
            }, this));
        };
    
        /**
         * Handles the `touchmove` and `mousemove` events.
         * @todo #261
         * @protected
         * @param {Event} event - The event arguments.
         */
        Owl.prototype.onDragMove = function(event) {
            var minimum = null,
                maximum = null,
                pull = null,
                delta = this.difference(this._drag.pointer, this.pointer(event)),
                stage = this.difference(this._drag.stage.start, delta);
    
            if (!this.is('dragging')) {
                return;
            }
    
            event.preventDefault();
    
            if (this.settings.loop) {
                minimum = this.coordinates(this.minimum());
                maximum = this.coordinates(this.maximum() + 1) - minimum;
                stage.x = (((stage.x - minimum) % maximum + maximum) % maximum) + minimum;
            } else {
                minimum = this.settings.rtl ? this.coordinates(this.maximum()) : this.coordinates(this.minimum());
                maximum = this.settings.rtl ? this.coordinates(this.minimum()) : this.coordinates(this.maximum());
                pull = this.settings.pullDrag ? -1 * delta.x / 5 : 0;
                stage.x = Math.max(Math.min(stage.x, minimum + pull), maximum + pull);
            }
    
            this._drag.stage.current = stage;
    
            this.animate(stage.x);
        };
    
        /**
         * Handles the `touchend` and `mouseup` events.
         * @todo #261
         * @todo Threshold for click event
         * @protected
         * @param {Event} event - The event arguments.
         */
        Owl.prototype.onDragEnd = function(event) {
            var delta = this.difference(this._drag.pointer, this.pointer(event)),
                stage = this._drag.stage.current,
                direction = delta.x > 0 ^ this.settings.rtl ? 'left' : 'right';
    
            $(document).off('.owl.core');
    
            this.$element.removeClass(this.options.grabClass);
    
            if (delta.x !== 0 && this.is('dragging') || !this.is('valid')) {
                this.speed(this.settings.dragEndSpeed || this.settings.smartSpeed);
                this.current(this.closest(stage.x, delta.x !== 0 ? direction : this._drag.direction));
                this.invalidate('position');
                this.update();
    
                this._drag.direction = direction;
    
                if (Math.abs(delta.x) > 3 || new Date().getTime() - this._drag.time > 300) {
                    this._drag.target.one('click.owl.core', function() { return false; });
                }
            }
    
            if (!this.is('dragging')) {
                return;
            }
    
            this.leave('dragging');
            this.trigger('dragged');
        };
    
        /**
         * Gets absolute position of the closest item for a coordinate.
         * @todo Setting `freeDrag` makes `closest` not reusable. See #165.
         * @protected
         * @param {Number} coordinate - The coordinate in pixel.
         * @param {String} direction - The direction to check for the closest item. Ether `left` or `right`.
         * @return {Number} - The absolute position of the closest item.
         */
        Owl.prototype.closest = function(coordinate, direction) {
            var position = -1,
                pull = 30,
                width = this.width(),
                coordinates = this.coordinates();
    
            if (!this.settings.freeDrag) {
                // check closest item
                $.each(coordinates, $.proxy(function(index, value) {
                    // on a left pull, check on current index
                    if (direction === 'left' && coordinate > value - pull && coordinate < value + pull) {
                        position = index;
                    // on a right pull, check on previous index
                    // to do so, subtract width from value and set position = index + 1
                    } else if (direction === 'right' && coordinate > value - width - pull && coordinate < value - width + pull) {
                        position = index + 1;
                    } else if (this.op(coordinate, '<', value)
                        && this.op(coordinate, '>', coordinates[index + 1] || value - width)) {
                        position = direction === 'left' ? index + 1 : index;
                    }
                    return position === -1;
                }, this));
            }
    
            if (!this.settings.loop) {
                // non loop boundries
                if (this.op(coordinate, '>', coordinates[this.minimum()])) {
                    position = coordinate = this.minimum();
                } else if (this.op(coordinate, '<', coordinates[this.maximum()])) {
                    position = coordinate = this.maximum();
                }
            }
    
            return position;
        };
    
        /**
         * Animates the stage.
         * @todo #270
         * @public
         * @param {Number} coordinate - The coordinate in pixels.
         */
        Owl.prototype.animate = function(coordinate) {
            var animate = this.speed() > 0;
    
            this.is('animating') && this.onTransitionEnd();
    
            if (animate) {
                this.enter('animating');
                this.trigger('translate');
            }
    
            if ($.support.transform3d && $.support.transition) {
                this.$stage.css({
                    transform: 'translate3d(' + coordinate + 'px,0px,0px)',
                    transition: (this.speed() / 1000) + 's'
                });
            } else if (animate) {
                this.$stage.animate({
                    left: coordinate + 'px'
                }, this.speed(), this.settings.fallbackEasing, $.proxy(this.onTransitionEnd, this));
            } else {
                this.$stage.css({
                    left: coordinate + 'px'
                });
            }
        };
    
        /**
         * Checks whether the carousel is in a specific state or not.
         * @param {String} state - The state to check.
         * @returns {Boolean} - The flag which indicates if the carousel is busy.
         */
        Owl.prototype.is = function(state) {
            return this._states.current[state] && this._states.current[state] > 0;
        };
    
        /**
         * Sets the absolute position of the current item.
         * @public
         * @param {Number} [position] - The new absolute position or nothing to leave it unchanged.
         * @returns {Number} - The absolute position of the current item.
         */
        Owl.prototype.current = function(position) {
            if (position === undefined) {
                return this._current;
            }
    
            if (this._items.length === 0) {
                return undefined;
            }
    
            position = this.normalize(position);
    
            if (this._current !== position) {
                var event = this.trigger('change', { property: { name: 'position', value: position } });
    
                if (event.data !== undefined) {
                    position = this.normalize(event.data);
                }
    
                this._current = position;
    
                this.invalidate('position');
    
                this.trigger('changed', { property: { name: 'position', value: this._current } });
            }
    
            return this._current;
        };
    
        /**
         * Invalidates the given part of the update routine.
         * @param {String} [part] - The part to invalidate.
         * @returns {Array.<String>} - The invalidated parts.
         */
        Owl.prototype.invalidate = function(part) {
            if ($.type(part) === 'string') {
                this._invalidated[part] = true;
                this.is('valid') && this.leave('valid');
            }
            return $.map(this._invalidated, function(v, i) { return i });
        };
    
        /**
         * Resets the absolute position of the current item.
         * @public
         * @param {Number} position - The absolute position of the new item.
         */
        Owl.prototype.reset = function(position) {
            position = this.normalize(position);
    
            if (position === undefined) {
                return;
            }
    
            this._speed = 0;
            this._current = position;
    
            this.suppress([ 'translate', 'translated' ]);
    
            this.animate(this.coordinates(position));
    
            this.release([ 'translate', 'translated' ]);
        };
    
        /**
         * Normalizes an absolute or a relative position of an item.
         * @public
         * @param {Number} position - The absolute or relative position to normalize.
         * @param {Boolean} [relative=false] - Whether the given position is relative or not.
         * @returns {Number} - The normalized position.
         */
        Owl.prototype.normalize = function(position, relative) {
            var n = this._items.length,
                m = relative ? 0 : this._clones.length;
    
            if (!this.isNumeric(position) || n < 1) {
                position = undefined;
            } else if (position < 0 || position >= n + m) {
                position = ((position - m / 2) % n + n) % n + m / 2;
            }
    
            return position;
        };
    
        /**
         * Converts an absolute position of an item into a relative one.
         * @public
         * @param {Number} position - The absolute position to convert.
         * @returns {Number} - The converted position.
         */
        Owl.prototype.relative = function(position) {
            position -= this._clones.length / 2;
            return this.normalize(position, true);
        };
    
        /**
         * Gets the maximum position for the current item.
         * @public
         * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
         * @returns {Number}
         */
        Owl.prototype.maximum = function(relative) {
            var settings = this.settings,
                maximum = this._coordinates.length,
                iterator,
                reciprocalItemsWidth,
                elementWidth;
    
            if (settings.loop) {
                maximum = this._clones.length / 2 + this._items.length - 1;
            } else if (settings.autoWidth || settings.merge) {
                iterator = this._items.length;
                reciprocalItemsWidth = this._items[--iterator].width();
                elementWidth = this.$element.width();
                while (iterator--) {
                    reciprocalItemsWidth += this._items[iterator].width() + this.settings.margin;
                    if (reciprocalItemsWidth > elementWidth) {
                        break;
                    }
                }
                maximum = iterator + 1;
            } else if (settings.center) {
                maximum = this._items.length - 1;
            } else {
                maximum = this._items.length - settings.items;
            }
    
            if (relative) {
                maximum -= this._clones.length / 2;
            }
    
            return Math.max(maximum, 0);
        };
    
        /**
         * Gets the minimum position for the current item.
         * @public
         * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
         * @returns {Number}
         */
        Owl.prototype.minimum = function(relative) {
            return relative ? 0 : this._clones.length / 2;
        };
    
        /**
         * Gets an item at the specified relative position.
         * @public
         * @param {Number} [position] - The relative position of the item.
         * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
         */
        Owl.prototype.items = function(position) {
            if (position === undefined) {
                return this._items.slice();
            }
    
            position = this.normalize(position, true);
            return this._items[position];
        };
    
        /**
         * Gets an item at the specified relative position.
         * @public
         * @param {Number} [position] - The relative position of the item.
         * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
         */
        Owl.prototype.mergers = function(position) {
            if (position === undefined) {
                return this._mergers.slice();
            }
    
            position = this.normalize(position, true);
            return this._mergers[position];
        };
    
        /**
         * Gets the absolute positions of clones for an item.
         * @public
         * @param {Number} [position] - The relative position of the item.
         * @returns {Array.<Number>} - The absolute positions of clones for the item or all if no position was given.
         */
        Owl.prototype.clones = function(position) {
            var odd = this._clones.length / 2,
                even = odd + this._items.length,
                map = function(index) { return index % 2 === 0 ? even + index / 2 : odd - (index + 1) / 2 };
    
            if (position === undefined) {
                return $.map(this._clones, function(v, i) { return map(i) });
            }
    
            return $.map(this._clones, function(v, i) { return v === position ? map(i) : null });
        };
    
        /**
         * Sets the current animation speed.
         * @public
         * @param {Number} [speed] - The animation speed in milliseconds or nothing to leave it unchanged.
         * @returns {Number} - The current animation speed in milliseconds.
         */
        Owl.prototype.speed = function(speed) {
            if (speed !== undefined) {
                this._speed = speed;
            }
    
            return this._speed;
        };
    
        /**
         * Gets the coordinate of an item.
         * @todo The name of this method is missleanding.
         * @public
         * @param {Number} position - The absolute position of the item within `minimum()` and `maximum()`.
         * @returns {Number|Array.<Number>} - The coordinate of the item in pixel or all coordinates.
         */
        Owl.prototype.coordinates = function(position) {
            var multiplier = 1,
                newPosition = position - 1,
                coordinate;
    
            if (position === undefined) {
                return $.map(this._coordinates, $.proxy(function(coordinate, index) {
                    return this.coordinates(index);
                }, this));
            }
    
            if (this.settings.center) {
                if (this.settings.rtl) {
                    multiplier = -1;
                    newPosition = position + 1;
                }
    
                coordinate = this._coordinates[position];
                coordinate += (this.width() - coordinate + (this._coordinates[newPosition] || 0)) / 2 * multiplier;
            } else {
                coordinate = this._coordinates[newPosition] || 0;
            }
    
            coordinate = Math.ceil(coordinate);
    
            return coordinate;
        };
    
        /**
         * Calculates the speed for a translation.
         * @protected
         * @param {Number} from - The absolute position of the start item.
         * @param {Number} to - The absolute position of the target item.
         * @param {Number} [factor=undefined] - The time factor in milliseconds.
         * @returns {Number} - The time in milliseconds for the translation.
         */
        Owl.prototype.duration = function(from, to, factor) {
            if (factor === 0) {
                return 0;
            }
    
            return Math.min(Math.max(Math.abs(to - from), 1), 6) * Math.abs((factor || this.settings.smartSpeed));
        };
    
        /**
         * Slides to the specified item.
         * @public
         * @param {Number} position - The position of the item.
         * @param {Number} [speed] - The time in milliseconds for the transition.
         */
        Owl.prototype.to = function(position, speed) {
            var current = this.current(),
                revert = null,
                distance = position - this.relative(current),
                direction = (distance > 0) - (distance < 0),
                items = this._items.length,
                minimum = this.minimum(),
                maximum = this.maximum();
    
            if (this.settings.loop) {
                if (!this.settings.rewind && Math.abs(distance) > items / 2) {
                    distance += direction * -1 * items;
                }
    
                position = current + distance;
                revert = ((position - minimum) % items + items) % items + minimum;
    
                if (revert !== position && revert - distance <= maximum && revert - distance > 0) {
                    current = revert - distance;
                    position = revert;
                    this.reset(current);
                }
            } else if (this.settings.rewind) {
                maximum += 1;
                position = (position % maximum + maximum) % maximum;
            } else {
                position = Math.max(minimum, Math.min(maximum, position));
            }
    
            this.speed(this.duration(current, position, speed));
            this.current(position);
    
            if (this.$element.is(':visible')) {
                this.update();
            }
        };
    
        /**
         * Slides to the next item.
         * @public
         * @param {Number} [speed] - The time in milliseconds for the transition.
         */
        Owl.prototype.next = function(speed) {
            speed = speed || false;
            this.to(this.relative(this.current()) + 1, speed);
        };
    
        /**
         * Slides to the previous item.
         * @public
         * @param {Number} [speed] - The time in milliseconds for the transition.
         */
        Owl.prototype.prev = function(speed) {
            speed = speed || false;
            this.to(this.relative(this.current()) - 1, speed);
        };
    
        /**
         * Handles the end of an animation.
         * @protected
         * @param {Event} event - The event arguments.
         */
        Owl.prototype.onTransitionEnd = function(event) {
    
            // if css2 animation then event object is undefined
            if (event !== undefined) {
                event.stopPropagation();
    
                // Catch only owl-stage transitionEnd event
                if ((event.target || event.srcElement || event.originalTarget) !== this.$stage.get(0)) {
                    return false;
                }
            }
    
            this.leave('animating');
            this.trigger('translated');
        };
    
        /**
         * Gets viewport width.
         * @protected
         * @return {Number} - The width in pixel.
         */
        Owl.prototype.viewport = function() {
            var width;
            if (this.options.responsiveBaseElement !== window) {
                width = $(this.options.responsiveBaseElement).width();
            } else if (window.innerWidth) {
                width = window.innerWidth;
            } else if (document.documentElement && document.documentElement.clientWidth) {
                width = document.documentElement.clientWidth;
            } else {
                console.warn('Can not detect viewport width.');
            }
            return width;
        };
    
        /**
         * Replaces the current content.
         * @public
         * @param {HTMLElement|jQuery|String} content - The new content.
         */
        Owl.prototype.replace = function(content) {
            this.$stage.empty();
            this._items = [];
    
            if (content) {
                content = (content instanceof jQuery) ? content : $(content);
            }
    
            if (this.settings.nestedItemSelector) {
                content = content.find('.' + this.settings.nestedItemSelector);
            }
    
            content.filter(function() {
                return this.nodeType === 1;
            }).each($.proxy(function(index, item) {
                item = this.prepare(item);
                this.$stage.append(item);
                this._items.push(item);
                this._mergers.push(item.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
            }, this));
    
            this.reset(this.isNumeric(this.settings.startPosition) ? this.settings.startPosition : 0);
    
            this.invalidate('items');
        };
    
        /**
         * Adds an item.
         * @todo Use `item` instead of `content` for the event arguments.
         * @public
         * @param {HTMLElement|jQuery|String} content - The item content to add.
         * @param {Number} [position] - The relative position at which to insert the item otherwise the item will be added to the end.
         */
        Owl.prototype.add = function(content, position) {
            var current = this.relative(this._current);
    
            position = position === undefined ? this._items.length : this.normalize(position, true);
            content = content instanceof jQuery ? content : $(content);
    
            this.trigger('add', { content: content, position: position });
    
            content = this.prepare(content);
    
            if (this._items.length === 0 || position === this._items.length) {
                this._items.length === 0 && this.$stage.append(content);
                this._items.length !== 0 && this._items[position - 1].after(content);
                this._items.push(content);
                this._mergers.push(content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
            } else {
                this._items[position].before(content);
                this._items.splice(position, 0, content);
                this._mergers.splice(position, 0, content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
            }
    
            this._items[current] && this.reset(this._items[current].index());
    
            this.invalidate('items');
    
            this.trigger('added', { content: content, position: position });
        };
    
        /**
         * Removes an item by its position.
         * @todo Use `item` instead of `content` for the event arguments.
         * @public
         * @param {Number} position - The relative position of the item to remove.
         */
        Owl.prototype.remove = function(position) {
            position = this.normalize(position, true);
    
            if (position === undefined) {
                return;
            }
    
            this.trigger('remove', { content: this._items[position], position: position });
    
            this._items[position].remove();
            this._items.splice(position, 1);
            this._mergers.splice(position, 1);
    
            this.invalidate('items');
    
            this.trigger('removed', { content: null, position: position });
        };
    
        /**
         * Preloads images with auto width.
         * @todo Replace by a more generic approach
         * @protected
         */
        Owl.prototype.preloadAutoWidthImages = function(images) {
            images.each($.proxy(function(i, element) {
                this.enter('pre-loading');
                element = $(element);
                $(new Image()).one('load', $.proxy(function(e) {
                    element.attr('src', e.target.src);
                    element.css('opacity', 1);
                    this.leave('pre-loading');
                    !this.is('pre-loading') && !this.is('initializing') && this.refresh();
                }, this)).attr('src', element.attr('src') || element.attr('data-src') || element.attr('data-src-retina'));
            }, this));
        };
    
        /**
         * Destroys the carousel.
         * @public
         */
        Owl.prototype.destroy = function() {
    
            this.$element.off('.owl.core');
            this.$stage.off('.owl.core');
            $(document).off('.owl.core');
    
            if (this.settings.responsive !== false) {
                window.clearTimeout(this.resizeTimer);
                this.off(window, 'resize', this._handlers.onThrottledResize);
            }
    
            for (var i in this._plugins) {
                this._plugins[i].destroy();
            }
    
            this.$stage.children('.cloned').remove();
    
            this.$stage.unwrap();
            this.$stage.children().contents().unwrap();
            this.$stage.children().unwrap();
    
            this.$element
                .removeClass(this.options.refreshClass)
                .removeClass(this.options.loadingClass)
                .removeClass(this.options.loadedClass)
                .removeClass(this.options.rtlClass)
                .removeClass(this.options.dragClass)
                .removeClass(this.options.grabClass)
                .attr('class', this.$element.attr('class').replace(new RegExp(this.options.responsiveClass + '-\\S+\\s', 'g'), ''))
                .removeData('owl.carousel');
        };
    
        /**
         * Operators to calculate right-to-left and left-to-right.
         * @protected
         * @param {Number} [a] - The left side operand.
         * @param {String} [o] - The operator.
         * @param {Number} [b] - The right side operand.
         */
        Owl.prototype.op = function(a, o, b) {
            var rtl = this.settings.rtl;
            switch (o) {
                case '<':
                    return rtl ? a > b : a < b;
                case '>':
                    return rtl ? a < b : a > b;
                case '>=':
                    return rtl ? a <= b : a >= b;
                case '<=':
                    return rtl ? a >= b : a <= b;
                default:
                    break;
            }
        };
    
        /**
         * Attaches to an internal event.
         * @protected
         * @param {HTMLElement} element - The event source.
         * @param {String} event - The event name.
         * @param {Function} listener - The event handler to attach.
         * @param {Boolean} capture - Wether the event should be handled at the capturing phase or not.
         */
        Owl.prototype.on = function(element, event, listener, capture) {
            if (element.addEventListener) {
                element.addEventListener(event, listener, capture);
            } else if (element.attachEvent) {
                element.attachEvent('on' + event, listener);
            }
        };
    
        /**
         * Detaches from an internal event.
         * @protected
         * @param {HTMLElement} element - The event source.
         * @param {String} event - The event name.
         * @param {Function} listener - The attached event handler to detach.
         * @param {Boolean} capture - Wether the attached event handler was registered as a capturing listener or not.
         */
        Owl.prototype.off = function(element, event, listener, capture) {
            if (element.removeEventListener) {
                element.removeEventListener(event, listener, capture);
            } else if (element.detachEvent) {
                element.detachEvent('on' + event, listener);
            }
        };
    
        /**
         * Triggers a public event.
         * @todo Remove `status`, `relatedTarget` should be used instead.
         * @protected
         * @param {String} name - The event name.
         * @param {*} [data=null] - The event data.
         * @param {String} [namespace=carousel] - The event namespace.
         * @param {String} [state] - The state which is associated with the event.
         * @param {Boolean} [enter=false] - Indicates if the call enters the specified state or not.
         * @returns {Event} - The event arguments.
         */
        Owl.prototype.trigger = function(name, data, namespace, state, enter) {
            var status = {
                item: { count: this._items.length, index: this.current() }
            }, handler = $.camelCase(
                $.grep([ 'on', name, namespace ], function(v) { return v })
                    .join('-').toLowerCase()
            ), event = $.Event(
                [ name, 'owl', namespace || 'carousel' ].join('.').toLowerCase(),
                $.extend({ relatedTarget: this }, status, data)
            );
    
            if (!this._supress[name]) {
                $.each(this._plugins, function(name, plugin) {
                    if (plugin.onTrigger) {
                        plugin.onTrigger(event);
                    }
                });
    
                this.register({ type: Owl.Type.Event, name: name });
                this.$element.trigger(event);
    
                if (this.settings && typeof this.settings[handler] === 'function') {
                    this.settings[handler].call(this, event);
                }
            }
    
            return event;
        };
    
        /**
         * Enters a state.
         * @param name - The state name.
         */
        Owl.prototype.enter = function(name) {
            $.each([ name ].concat(this._states.tags[name] || []), $.proxy(function(i, name) {
                if (this._states.current[name] === undefined) {
                    this._states.current[name] = 0;
                }
    
                this._states.current[name]++;
            }, this));
        };
    
        /**
         * Leaves a state.
         * @param name - The state name.
         */
        Owl.prototype.leave = function(name) {
            $.each([ name ].concat(this._states.tags[name] || []), $.proxy(function(i, name) {
                this._states.current[name]--;
            }, this));
        };
    
        /**
         * Registers an event or state.
         * @public
         * @param {Object} object - The event or state to register.
         */
        Owl.prototype.register = function(object) {
            if (object.type === Owl.Type.Event) {
                if (!$.event.special[object.name]) {
                    $.event.special[object.name] = {};
                }
    
                if (!$.event.special[object.name].owl) {
                    var _default = $.event.special[object.name]._default;
                    $.event.special[object.name]._default = function(e) {
                        if (_default && _default.apply && (!e.namespace || e.namespace.indexOf('owl') === -1)) {
                            return _default.apply(this, arguments);
                        }
                        return e.namespace && e.namespace.indexOf('owl') > -1;
                    };
                    $.event.special[object.name].owl = true;
                }
            } else if (object.type === Owl.Type.State) {
                if (!this._states.tags[object.name]) {
                    this._states.tags[object.name] = object.tags;
                } else {
                    this._states.tags[object.name] = this._states.tags[object.name].concat(object.tags);
                }
    
                this._states.tags[object.name] = $.grep(this._states.tags[object.name], $.proxy(function(tag, i) {
                    return $.inArray(tag, this._states.tags[object.name]) === i;
                }, this));
            }
        };
    
        /**
         * Suppresses events.
         * @protected
         * @param {Array.<String>} events - The events to suppress.
         */
        Owl.prototype.suppress = function(events) {
            $.each(events, $.proxy(function(index, event) {
                this._supress[event] = true;
            }, this));
        };
    
        /**
         * Releases suppressed events.
         * @protected
         * @param {Array.<String>} events - The events to release.
         */
        Owl.prototype.release = function(events) {
            $.each(events, $.proxy(function(index, event) {
                delete this._supress[event];
            }, this));
        };
    
        /**
         * Gets unified pointer coordinates from event.
         * @todo #261
         * @protected
         * @param {Event} - The `mousedown` or `touchstart` event.
         * @returns {Object} - Contains `x` and `y` coordinates of current pointer position.
         */
        Owl.prototype.pointer = function(event) {
            var result = { x: null, y: null };
    
            event = event.originalEvent || event || window.event;
    
            event = event.touches && event.touches.length ?
                event.touches[0] : event.changedTouches && event.changedTouches.length ?
                    event.changedTouches[0] : event;
    
            if (event.pageX) {
                result.x = event.pageX;
                result.y = event.pageY;
            } else {
                result.x = event.clientX;
                result.y = event.clientY;
            }
    
            return result;
        };
    
        /**
         * Determines if the input is a Number or something that can be coerced to a Number
         * @protected
         * @param {Number|String|Object|Array|Boolean|RegExp|Function|Symbol} - The input to be tested
         * @returns {Boolean} - An indication if the input is a Number or can be coerced to a Number
         */
        Owl.prototype.isNumeric = function(number) {
            return !isNaN(parseFloat(number));
        };
    
        /**
         * Gets the difference of two vectors.
         * @todo #261
         * @protected
         * @param {Object} - The first vector.
         * @param {Object} - The second vector.
         * @returns {Object} - The difference.
         */
        Owl.prototype.difference = function(first, second) {
            return {
                x: first.x - second.x,
                y: first.y - second.y
            };
        };
    
        /**
         * The jQuery Plugin for the Owl Carousel
         * @todo Navigation plugin `next` and `prev`
         * @public
         */
        $.fn.owlCarousel = function(option) {
            var args = Array.prototype.slice.call(arguments, 1);
    
            return this.each(function() {
                var $this = $(this),
                    data = $this.data('owl.carousel');
    
                if (!data) {
                    data = new Owl(this, typeof option == 'object' && option);
                    $this.data('owl.carousel', data);
    
                    $.each([
                        'next', 'prev', 'to', 'destroy', 'refresh', 'replace', 'add', 'remove'
                    ], function(i, event) {
                        data.register({ type: Owl.Type.Event, name: event });
                        data.$element.on(event + '.owl.carousel.core', $.proxy(function(e) {
                            if (e.namespace && e.relatedTarget !== this) {
                                this.suppress([ event ]);
                                data[event].apply(this, [].slice.call(arguments, 1));
                                this.release([ event ]);
                            }
                        }, data));
                    });
                }
    
                if (typeof option == 'string' && option.charAt(0) !== '_') {
                    data[option].apply(data, args);
                }
            });
        };
    
        /**
         * The constructor for the jQuery Plugin
         * @public
         */
        $.fn.owlCarousel.Constructor = Owl;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * AutoRefresh Plugin
     * @version 2.1.0
     * @author Artus Kolanowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
    
        /**
         * Creates the auto refresh plugin.
         * @class The Auto Refresh Plugin
         * @param {Owl} carousel - The Owl Carousel
         */
        var AutoRefresh = function(carousel) {
            /**
             * Reference to the core.
             * @protected
             * @type {Owl}
             */
            this._core = carousel;
    
            /**
             * Refresh interval.
             * @protected
             * @type {number}
             */
            this._interval = null;
    
            /**
             * Whether the element is currently visible or not.
             * @protected
             * @type {Boolean}
             */
            this._visible = null;
    
            /**
             * All event handlers.
             * @protected
             * @type {Object}
             */
            this._handlers = {
                'initialized.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.autoRefresh) {
                        this.watch();
                    }
                }, this)
            };
    
            // set default options
            this._core.options = $.extend({}, AutoRefresh.Defaults, this._core.options);
    
            // register event handlers
            this._core.$element.on(this._handlers);
        };
    
        /**
         * Default options.
         * @public
         */
        AutoRefresh.Defaults = {
            autoRefresh: true,
            autoRefreshInterval: 500
        };
    
        /**
         * Watches the element.
         */
        AutoRefresh.prototype.watch = function() {
            if (this._interval) {
                return;
            }
    
            this._visible = this._core.$element.is(':visible');
            this._interval = window.setInterval($.proxy(this.refresh, this), this._core.settings.autoRefreshInterval);
        };
    
        /**
         * Refreshes the element.
         */
        AutoRefresh.prototype.refresh = function() {
            if (this._core.$element.is(':visible') === this._visible) {
                return;
            }
    
            this._visible = !this._visible;
    
            this._core.$element.toggleClass('owl-hidden', !this._visible);
    
            this._visible && (this._core.invalidate('width') && this._core.refresh());
        };
    
        /**
         * Destroys the plugin.
         */
        AutoRefresh.prototype.destroy = function() {
            var handler, property;
    
            window.clearInterval(this._interval);
    
            for (handler in this._handlers) {
                this._core.$element.off(handler, this._handlers[handler]);
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.AutoRefresh = AutoRefresh;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * Lazy Plugin
     * @version 2.1.0
     * @author Bartosz Wojciechowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
    
        /**
         * Creates the lazy plugin.
         * @class The Lazy Plugin
         * @param {Owl} carousel - The Owl Carousel
         */
        var Lazy = function(carousel) {
    
            /**
             * Reference to the core.
             * @protected
             * @type {Owl}
             */
            this._core = carousel;
    
            /**
             * Already loaded items.
             * @protected
             * @type {Array.<jQuery>}
             */
            this._loaded = [];
    
            /**
             * Event handlers.
             * @protected
             * @type {Object}
             */
            this._handlers = {
                'initialized.owl.carousel change.owl.carousel resized.owl.carousel': $.proxy(function(e) {
                    if (!e.namespace) {
                        return;
                    }
    
                    if (!this._core.settings || !this._core.settings.lazyLoad) {
                        return;
                    }
    
                    if ((e.property && e.property.name == 'position') || e.type == 'initialized') {
                        var settings = this._core.settings,
                            n = (settings.center && Math.ceil(settings.items / 2) || settings.items),
                            i = ((settings.center && n * -1) || 0),
                            position = (e.property && e.property.value !== undefined ? e.property.value : this._core.current()) + i,
                            clones = this._core.clones().length,
                            load = $.proxy(function(i, v) { this.load(v) }, this);
    
                        while (i++ < n) {
                            this.load(clones / 2 + this._core.relative(position));
                            clones && $.each(this._core.clones(this._core.relative(position)), load);
                            position++;
                        }
                    }
                }, this)
            };
    
            // set the default options
            this._core.options = $.extend({}, Lazy.Defaults, this._core.options);
    
            // register event handler
            this._core.$element.on(this._handlers);
        };
    
        /**
         * Default options.
         * @public
         */
        Lazy.Defaults = {
            lazyLoad: false
        };
    
        /**
         * Loads all resources of an item at the specified position.
         * @param {Number} position - The absolute position of the item.
         * @protected
         */
        Lazy.prototype.load = function(position) {
            var $item = this._core.$stage.children().eq(position),
                $elements = $item && $item.find('.owl-lazy');
    
            if (!$elements || $.inArray($item.get(0), this._loaded) > -1) {
                return;
            }
    
            $elements.each($.proxy(function(index, element) {
                var $element = $(element), image,
                    url = (window.devicePixelRatio > 1 && $element.attr('data-src-retina')) || $element.attr('data-src');
    
                this._core.trigger('load', { element: $element, url: url }, 'lazy');
    
                if ($element.is('img')) {
                    $element.one('load.owl.lazy', $.proxy(function() {
                        $element.css('opacity', 1);
                        this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
                    }, this)).attr('src', url);
                } else {
                    image = new Image();
                    image.onload = $.proxy(function() {
                        $element.css({
                            'background-image': 'url("' + url + '")',
                            'opacity': '1'
                        });
                        this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
                    }, this);
                    image.src = url;
                }
            }, this));
    
            this._loaded.push($item.get(0));
        };
    
        /**
         * Destroys the plugin.
         * @public
         */
        Lazy.prototype.destroy = function() {
            var handler, property;
    
            for (handler in this.handlers) {
                this._core.$element.off(handler, this.handlers[handler]);
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.Lazy = Lazy;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * AutoHeight Plugin
     * @version 2.1.0
     * @author Bartosz Wojciechowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
    
        /**
         * Creates the auto height plugin.
         * @class The Auto Height Plugin
         * @param {Owl} carousel - The Owl Carousel
         */
        var AutoHeight = function(carousel) {
            /**
             * Reference to the core.
             * @protected
             * @type {Owl}
             */
            this._core = carousel;
    
            /**
             * All event handlers.
             * @protected
             * @type {Object}
             */
            this._handlers = {
                'initialized.owl.carousel refreshed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.autoHeight) {
                        this.update();
                    }
                }, this),
                'changed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.autoHeight && e.property.name == 'position'){
                        this.update();
                    }
                }, this),
                'loaded.owl.lazy': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.autoHeight
                        && e.element.closest('.' + this._core.settings.itemClass).index() === this._core.current()) {
                        this.update();
                    }
                }, this)
            };
    
            // set default options
            this._core.options = $.extend({}, AutoHeight.Defaults, this._core.options);
    
            // register event handlers
            this._core.$element.on(this._handlers);
        };
    
        /**
         * Default options.
         * @public
         */
        AutoHeight.Defaults = {
            autoHeight: false,
            autoHeightClass: 'owl-height'
        };
    
        /**
         * Updates the view.
         */
        AutoHeight.prototype.update = function() {
            var start = this._core._current,
                end = start + this._core.settings.items,
                visible = this._core.$stage.children().toArray().slice(start, end),
                heights = [],
                maxheight = 0;
    
            $.each(visible, function(index, item) {
                heights.push($(item).height());
            });
    
            maxheight = Math.max.apply(null, heights);
    
            this._core.$stage.parent()
                .height(maxheight)
                .addClass(this._core.settings.autoHeightClass);
        };
    
        AutoHeight.prototype.destroy = function() {
            var handler, property;
    
            for (handler in this._handlers) {
                this._core.$element.off(handler, this._handlers[handler]);
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.AutoHeight = AutoHeight;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * Video Plugin
     * @version 2.1.0
     * @author Bartosz Wojciechowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
    
        /**
         * Creates the video plugin.
         * @class The Video Plugin
         * @param {Owl} carousel - The Owl Carousel
         */
        var Video = function(carousel) {
            /**
             * Reference to the core.
             * @protected
             * @type {Owl}
             */
            this._core = carousel;
    
            /**
             * Cache all video URLs.
             * @protected
             * @type {Object}
             */
            this._videos = {};
    
            /**
             * Current playing item.
             * @protected
             * @type {jQuery}
             */
            this._playing = null;
    
            /**
             * All event handlers.
             * @todo The cloned content removale is too late
             * @protected
             * @type {Object}
             */
            this._handlers = {
                'initialized.owl.carousel': $.proxy(function(e) {
                    if (e.namespace) {
                        this._core.register({ type: 'state', name: 'playing', tags: [ 'interacting' ] });
                    }
                }, this),
                'resize.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.video && this.isInFullScreen()) {
                        e.preventDefault();
                    }
                }, this),
                'refreshed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.is('resizing')) {
                        this._core.$stage.find('.cloned .owl-video-frame').remove();
                    }
                }, this),
                'changed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && e.property.name === 'position' && this._playing) {
                        this.stop();
                    }
                }, this),
                'prepared.owl.carousel': $.proxy(function(e) {
                    if (!e.namespace) {
                        return;
                    }
    
                    var $element = $(e.content).find('.owl-video');
    
                    if ($element.length) {
                        $element.css('display', 'none');
                        this.fetch($element, $(e.content));
                    }
                }, this)
            };
    
            // set default options
            this._core.options = $.extend({}, Video.Defaults, this._core.options);
    
            // register event handlers
            this._core.$element.on(this._handlers);
    
            this._core.$element.on('click.owl.video', '.owl-video-play-icon', $.proxy(function(e) {
                this.play(e);
            }, this));
        };
    
        /**
         * Default options.
         * @public
         */
        Video.Defaults = {
            video: false,
            videoHeight: false,
            videoWidth: false
        };
    
        /**
         * Gets the video ID and the type (YouTube/Vimeo/vzaar only).
         * @protected
         * @param {jQuery} target - The target containing the video data.
         * @param {jQuery} item - The item containing the video.
         */
        Video.prototype.fetch = function(target, item) {
                var type = (function() {
                        if (target.attr('data-vimeo-id')) {
                            return 'vimeo';
                        } else if (target.attr('data-vzaar-id')) {
                            return 'vzaar'
                        } else {
                            return 'youtube';
                        }
                    })(),
                    id = target.attr('data-vimeo-id') || target.attr('data-youtube-id') || target.attr('data-vzaar-id'),
                    width = target.attr('data-width') || this._core.settings.videoWidth,
                    height = target.attr('data-height') || this._core.settings.videoHeight,
                    url = target.attr('href');
    
            if (url) {
    
                /*
                        Parses the id's out of the following urls (and probably more):
                        https://www.youtube.com/watch?v=:id
                        https://youtu.be/:id
                        https://vimeo.com/:id
                        https://vimeo.com/channels/:channel/:id
                        https://vimeo.com/groups/:group/videos/:id
                        https://app.vzaar.com/videos/:id
    
                        Visual example: https://regexper.com/#(http%3A%7Chttps%3A%7C)%5C%2F%5C%2F(player.%7Cwww.%7Capp.)%3F(vimeo%5C.com%7Cyoutu(be%5C.com%7C%5C.be%7Cbe%5C.googleapis%5C.com)%7Cvzaar%5C.com)%5C%2F(video%5C%2F%7Cvideos%5C%2F%7Cembed%5C%2F%7Cchannels%5C%2F.%2B%5C%2F%7Cgroups%5C%2F.%2B%5C%2F%7Cwatch%5C%3Fv%3D%7Cv%5C%2F)%3F(%5BA-Za-z0-9._%25-%5D*)(%5C%26%5CS%2B)%3F
                */
    
                id = url.match(/(http:|https:|)\/\/(player.|www.|app.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com)|vzaar\.com)\/(video\/|videos\/|embed\/|channels\/.+\/|groups\/.+\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);
    
                if (id[3].indexOf('youtu') > -1) {
                    type = 'youtube';
                } else if (id[3].indexOf('vimeo') > -1) {
                    type = 'vimeo';
                } else if (id[3].indexOf('vzaar') > -1) {
                    type = 'vzaar';
                } else {
                    throw new Error('Video URL not supported.');
                }
                id = id[6];
            } else {
                throw new Error('Missing video URL.');
            }
    
            this._videos[url] = {
                type: type,
                id: id,
                width: width,
                height: height
            };
    
            item.attr('data-video', url);
    
            this.thumbnail(target, this._videos[url]);
        };
    
        /**
         * Creates video thumbnail.
         * @protected
         * @param {jQuery} target - The target containing the video data.
         * @param {Object} info - The video info object.
         * @see `fetch`
         */
        Video.prototype.thumbnail = function(target, video) {
            var tnLink,
                icon,
                path,
                dimensions = video.width && video.height ? 'style="width:' + video.width + 'px;height:' + video.height + 'px;"' : '',
                customTn = target.find('img'),
                srcType = 'src',
                lazyClass = '',
                settings = this._core.settings,
                create = function(path) {
                    icon = '<div class="owl-video-play-icon"></div>';
    
                    if (settings.lazyLoad) {
                        tnLink = '<div class="owl-video-tn ' + lazyClass + '" ' + srcType + '="' + path + '"></div>';
                    } else {
                        tnLink = '<div class="owl-video-tn" style="opacity:1;background-image:url(' + path + ')"></div>';
                    }
                    target.after(tnLink);
                    target.after(icon);
                };
    
            // wrap video content into owl-video-wrapper div
            target.wrap('<div class="owl-video-wrapper"' + dimensions + '></div>');
    
            if (this._core.settings.lazyLoad) {
                srcType = 'data-src';
                lazyClass = 'owl-lazy';
            }
    
            // custom thumbnail
            if (customTn.length) {
                create(customTn.attr(srcType));
                customTn.remove();
                return false;
            }
    
            if (video.type === 'youtube') {
                path = "//img.youtube.com/vi/" + video.id + "/hqdefault.jpg";
                create(path);
            } else if (video.type === 'vimeo') {
                $.ajax({
                    type: 'GET',
                    url: '//vimeo.com/api/v2/video/' + video.id + '.json',
                    jsonp: 'callback',
                    dataType: 'jsonp',
                    success: function(data) {
                        path = data[0].thumbnail_large;
                        create(path);
                    }
                });
            } else if (video.type === 'vzaar') {
                $.ajax({
                    type: 'GET',
                    url: '//vzaar.com/api/videos/' + video.id + '.json',
                    jsonp: 'callback',
                    dataType: 'jsonp',
                    success: function(data) {
                        path = data.framegrab_url;
                        create(path);
                    }
                });
            }
        };
    
        /**
         * Stops the current video.
         * @public
         */
        Video.prototype.stop = function() {
            this._core.trigger('stop', null, 'video');
            this._playing.find('.owl-video-frame').remove();
            this._playing.removeClass('owl-video-playing');
            this._playing = null;
            this._core.leave('playing');
            this._core.trigger('stopped', null, 'video');
        };
    
        /**
         * Starts the current video.
         * @public
         * @param {Event} event - The event arguments.
         */
        Video.prototype.play = function(event) {
            var target = $(event.target),
                item = target.closest('.' + this._core.settings.itemClass),
                video = this._videos[item.attr('data-video')],
                width = video.width || '100%',
                height = video.height || this._core.$stage.height(),
                html;
    
            if (this._playing) {
                return;
            }
    
            this._core.enter('playing');
            this._core.trigger('play', null, 'video');
    
            item = this._core.items(this._core.relative(item.index()));
    
            this._core.reset(item.index());
    
            if (video.type === 'youtube') {
                html = '<iframe width="' + width + '" height="' + height + '" src="//www.youtube.com/embed/' +
                    video.id + '?autoplay=1&rel=0&v=' + video.id + '" frameborder="0" allowfullscreen></iframe>';
            } else if (video.type === 'vimeo') {
                html = '<iframe src="//player.vimeo.com/video/' + video.id +
                    '?autoplay=1" width="' + width + '" height="' + height +
                    '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
            } else if (video.type === 'vzaar') {
                html = '<iframe frameborder="0"' + 'height="' + height + '"' + 'width="' + width +
                    '" allowfullscreen mozallowfullscreen webkitAllowFullScreen ' +
                    'src="//view.vzaar.com/' + video.id + '/player?autoplay=true"></iframe>';
            }
    
            $('<div class="owl-video-frame">' + html + '</div>').insertAfter(item.find('.owl-video'));
    
            this._playing = item.addClass('owl-video-playing');
        };
    
        /**
         * Checks whether an video is currently in full screen mode or not.
         * @todo Bad style because looks like a readonly method but changes members.
         * @protected
         * @returns {Boolean}
         */
        Video.prototype.isInFullScreen = function() {
            var element = document.fullscreenElement || document.mozFullScreenElement ||
                    document.webkitFullscreenElement;
    
            return element && $(element).parent().hasClass('owl-video-frame');
        };
    
        /**
         * Destroys the plugin.
         */
        Video.prototype.destroy = function() {
            var handler, property;
    
            this._core.$element.off('click.owl.video');
    
            for (handler in this._handlers) {
                this._core.$element.off(handler, this._handlers[handler]);
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.Video = Video;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * Animate Plugin
     * @version 2.1.0
     * @author Bartosz Wojciechowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
    
        /**
         * Creates the animate plugin.
         * @class The Navigation Plugin
         * @param {Owl} scope - The Owl Carousel
         */
        var Animate = function(scope) {
            this.core = scope;
            this.core.options = $.extend({}, Animate.Defaults, this.core.options);
            this.swapping = true;
            this.previous = undefined;
            this.next = undefined;
    
            this.handlers = {
                'change.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && e.property.name == 'position') {
                        this.previous = this.core.current();
                        this.next = e.property.value;
                    }
                }, this),
                'drag.owl.carousel dragged.owl.carousel translated.owl.carousel': $.proxy(function(e) {
                    if (e.namespace) {
                        this.swapping = e.type == 'translated';
                    }
                }, this),
                'translate.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this.swapping && (this.core.options.animateOut || this.core.options.animateIn)) {
                        this.swap();
                    }
                }, this)
            };
    
            this.core.$element.on(this.handlers);
        };
    
        /**
         * Default options.
         * @public
         */
        Animate.Defaults = {
            animateOut: false,
            animateIn: false
        };
    
        /**
         * Toggles the animation classes whenever an translations starts.
         * @protected
         * @returns {Boolean|undefined}
         */
        Animate.prototype.swap = function() {
    
            if (this.core.settings.items !== 1) {
                return;
            }
    
            if (!$.support.animation || !$.support.transition) {
                return;
            }
    
            this.core.speed(0);
    
            var left,
                clear = $.proxy(this.clear, this),
                previous = this.core.$stage.children().eq(this.previous),
                next = this.core.$stage.children().eq(this.next),
                incoming = this.core.settings.animateIn,
                outgoing = this.core.settings.animateOut;
    
            if (this.core.current() === this.previous) {
                return;
            }
    
            if (outgoing) {
                left = this.core.coordinates(this.previous) - this.core.coordinates(this.next);
                previous.one($.support.animation.end, clear)
                    .css( { 'left': left + 'px' } )
                    .addClass('animated owl-animated-out')
                    .addClass(outgoing);
            }
    
            if (incoming) {
                next.one($.support.animation.end, clear)
                    .addClass('animated owl-animated-in')
                    .addClass(incoming);
            }
        };
    
        Animate.prototype.clear = function(e) {
            $(e.target).css( { 'left': '' } )
                .removeClass('animated owl-animated-out owl-animated-in')
                .removeClass(this.core.settings.animateIn)
                .removeClass(this.core.settings.animateOut);
            this.core.onTransitionEnd();
        };
    
        /**
         * Destroys the plugin.
         * @public
         */
        Animate.prototype.destroy = function() {
            var handler, property;
    
            for (handler in this.handlers) {
                this.core.$element.off(handler, this.handlers[handler]);
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.Animate = Animate;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * Autoplay Plugin
     * @version 2.1.0
     * @author Bartosz Wojciechowski
     * @author Artus Kolanowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
    
        /**
         * Creates the autoplay plugin.
         * @class The Autoplay Plugin
         * @param {Owl} scope - The Owl Carousel
         */
        var Autoplay = function(carousel) {
            /**
             * Reference to the core.
             * @protected
             * @type {Owl}
             */
            this._core = carousel;
    
            /**
             * The autoplay timeout.
             * @type {Timeout}
             */
            this._timeout = null;
    
            /**
             * Indicates whenever the autoplay is paused.
             * @type {Boolean}
             */
            this._paused = false;
    
            /**
             * All event handlers.
             * @protected
             * @type {Object}
             */
            this._handlers = {
                'changed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && e.property.name === 'settings') {
                        if (this._core.settings.autoplay) {
                            this.play();
                        } else {
                            this.stop();
                        }
                    } else if (e.namespace && e.property.name === 'position') {
                        //console.log('play?', e);
                        if (this._core.settings.autoplay) {
                            this._setAutoPlayInterval();
                        }
                    }
                }, this),
                'initialized.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.autoplay) {
                        this.play();
                    }
                }, this),
                'play.owl.autoplay': $.proxy(function(e, t, s) {
                    if (e.namespace) {
                        this.play(t, s);
                    }
                }, this),
                'stop.owl.autoplay': $.proxy(function(e) {
                    if (e.namespace) {
                        this.stop();
                    }
                }, this),
                'mouseover.owl.autoplay': $.proxy(function() {
                    if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
                        this.pause();
                    }
                }, this),
                'mouseleave.owl.autoplay': $.proxy(function() {
                    if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
                        this.play();
                    }
                }, this),
                'touchstart.owl.core': $.proxy(function() {
                    if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
                        this.pause();
                    }
                }, this),
                'touchend.owl.core': $.proxy(function() {
                    if (this._core.settings.autoplayHoverPause) {
                        this.play();
                    }
                }, this)
            };
    
            // register event handlers
            this._core.$element.on(this._handlers);
    
            // set default options
            this._core.options = $.extend({}, Autoplay.Defaults, this._core.options);
        };
    
        /**
         * Default options.
         * @public
         */
        Autoplay.Defaults = {
            autoplay: false,
            autoplayTimeout: 5000,
            autoplayHoverPause: false,
            autoplaySpeed: false
        };
    
        /**
         * Starts the autoplay.
         * @public
         * @param {Number} [timeout] - The interval before the next animation starts.
         * @param {Number} [speed] - The animation speed for the animations.
         */
        Autoplay.prototype.play = function(timeout, speed) {
            this._paused = false;
    
            if (this._core.is('rotating')) {
                return;
            }
    
            this._core.enter('rotating');
    
            this._setAutoPlayInterval();
        };
    
        /**
         * Gets a new timeout
         * @private
         * @param {Number} [timeout] - The interval before the next animation starts.
         * @param {Number} [speed] - The animation speed for the animations.
         * @return {Timeout}
         */
        Autoplay.prototype._getNextTimeout = function(timeout, speed) {
            if ( this._timeout ) {
                window.clearTimeout(this._timeout);
            }
            return window.setTimeout($.proxy(function() {
                if (this._paused || this._core.is('busy') || this._core.is('interacting') || document.hidden) {
                    return;
                }
                this._core.next(speed || this._core.settings.autoplaySpeed);
            }, this), timeout || this._core.settings.autoplayTimeout);
        };
    
        /**
         * Sets autoplay in motion.
         * @private
         */
        Autoplay.prototype._setAutoPlayInterval = function() {
            this._timeout = this._getNextTimeout();
        };
    
        /**
         * Stops the autoplay.
         * @public
         */
        Autoplay.prototype.stop = function() {
            if (!this._core.is('rotating')) {
                return;
            }
    
            window.clearTimeout(this._timeout);
            this._core.leave('rotating');
        };
    
        /**
         * Stops the autoplay.
         * @public
         */
        Autoplay.prototype.pause = function() {
            if (!this._core.is('rotating')) {
                return;
            }
    
            this._paused = true;
        };
    
        /**
         * Destroys the plugin.
         */
        Autoplay.prototype.destroy = function() {
            var handler, property;
    
            this.stop();
    
            for (handler in this._handlers) {
                this._core.$element.off(handler, this._handlers[handler]);
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.autoplay = Autoplay;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * Navigation Plugin
     * @version 2.1.0
     * @author Artus Kolanowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
        'use strict';
    
        /**
         * Creates the navigation plugin.
         * @class The Navigation Plugin
         * @param {Owl} carousel - The Owl Carousel.
         */
        var Navigation = function(carousel) {
            /**
             * Reference to the core.
             * @protected
             * @type {Owl}
             */
            this._core = carousel;
    
            /**
             * Indicates whether the plugin is initialized or not.
             * @protected
             * @type {Boolean}
             */
            this._initialized = false;
    
            /**
             * The current paging indexes.
             * @protected
             * @type {Array}
             */
            this._pages = [];
    
            /**
             * All DOM elements of the user interface.
             * @protected
             * @type {Object}
             */
            this._controls = {};
    
            /**
             * Markup for an indicator.
             * @protected
             * @type {Array.<String>}
             */
            this._templates = [];
    
            /**
             * The carousel element.
             * @type {jQuery}
             */
            this.$element = this._core.$element;
    
            /**
             * Overridden methods of the carousel.
             * @protected
             * @type {Object}
             */
            this._overrides = {
                next: this._core.next,
                prev: this._core.prev,
                to: this._core.to
            };
    
            /**
             * All event handlers.
             * @protected
             * @type {Object}
             */
            this._handlers = {
                'prepared.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.dotsData) {
                        this._templates.push('<div class="' + this._core.settings.dotClass + '">' +
                            $(e.content).find('[data-dot]').addBack('[data-dot]').attr('data-dot') + '</div>');
                    }
                }, this),
                'added.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.dotsData) {
                        this._templates.splice(e.position, 0, this._templates.pop());
                    }
                }, this),
                'remove.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.dotsData) {
                        this._templates.splice(e.position, 1);
                    }
                }, this),
                'changed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && e.property.name == 'position') {
                        this.draw();
                    }
                }, this),
                'initialized.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && !this._initialized) {
                        this._core.trigger('initialize', null, 'navigation');
                        this.initialize();
                        this.update();
                        this.draw();
                        this._initialized = true;
                        this._core.trigger('initialized', null, 'navigation');
                    }
                }, this),
                'refreshed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._initialized) {
                        this._core.trigger('refresh', null, 'navigation');
                        this.update();
                        this.draw();
                        this._core.trigger('refreshed', null, 'navigation');
                    }
                }, this)
            };
    
            // set default options
            this._core.options = $.extend({}, Navigation.Defaults, this._core.options);
    
            // register event handlers
            this.$element.on(this._handlers);
        };
    
        /**
         * Default options.
         * @public
         * @todo Rename `slideBy` to `navBy`
         */
        Navigation.Defaults = {
            nav: false,
            navText: [ 'prev', 'next' ],
            navSpeed: false,
            navElement: 'div',
            navContainer: false,
            navContainerClass: 'owl-nav',
            navClass: [ 'owl-prev', 'owl-next' ],
            slideBy: 1,
            dotClass: 'owl-dot',
            dotsClass: 'owl-dots',
            dots: true,
            dotsEach: false,
            dotsData: false,
            dotsSpeed: false,
            dotsContainer: false
        };
    
        /**
         * Initializes the layout of the plugin and extends the carousel.
         * @protected
         */
        Navigation.prototype.initialize = function() {
            var override,
                settings = this._core.settings;
    
            // create DOM structure for relative navigation
            this._controls.$relative = (settings.navContainer ? $(settings.navContainer)
                : $('<div>').addClass(settings.navContainerClass).appendTo(this.$element)).addClass('disabled');
    
            this._controls.$previous = $('<' + settings.navElement + '>')
                .addClass(settings.navClass[0])
                .html(settings.navText[0])
                .prependTo(this._controls.$relative)
                .on('click', $.proxy(function(e) {
                    this.prev(settings.navSpeed);
                }, this));
            this._controls.$next = $('<' + settings.navElement + '>')
                .addClass(settings.navClass[1])
                .html(settings.navText[1])
                .appendTo(this._controls.$relative)
                .on('click', $.proxy(function(e) {
                    this.next(settings.navSpeed);
                }, this));
    
            // create DOM structure for absolute navigation
            if (!settings.dotsData) {
                this._templates = [ $('<div>')
                    .addClass(settings.dotClass)
                    .append($('<span>'))
                    .prop('outerHTML') ];
            }
    
            this._controls.$absolute = (settings.dotsContainer ? $(settings.dotsContainer)
                : $('<div>').addClass(settings.dotsClass).appendTo(this.$element)).addClass('disabled');
    
            this._controls.$absolute.on('click', 'div', $.proxy(function(e) {
                var index = $(e.target).parent().is(this._controls.$absolute)
                    ? $(e.target).index() : $(e.target).parent().index();
    
                e.preventDefault();
    
                this.to(index, settings.dotsSpeed);
            }, this));
    
            // override public methods of the carousel
            for (override in this._overrides) {
                this._core[override] = $.proxy(this[override], this);
            }
        };
    
        /**
         * Destroys the plugin.
         * @protected
         */
        Navigation.prototype.destroy = function() {
            var handler, control, property, override;
    
            for (handler in this._handlers) {
                this.$element.off(handler, this._handlers[handler]);
            }
            for (control in this._controls) {
                this._controls[control].remove();
            }
            for (override in this.overides) {
                this._core[override] = this._overrides[override];
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        /**
         * Updates the internal state.
         * @protected
         */
        Navigation.prototype.update = function() {
            var i, j, k,
                lower = this._core.clones().length / 2,
                upper = lower + this._core.items().length,
                maximum = this._core.maximum(true),
                settings = this._core.settings,
                size = settings.center || settings.autoWidth || settings.dotsData
                    ? 1 : settings.dotsEach || settings.items;
    
            if (settings.slideBy !== 'page') {
                settings.slideBy = Math.min(settings.slideBy, settings.items);
            }
    
            if (settings.dots || settings.slideBy == 'page') {
                this._pages = [];
    
                for (i = lower, j = 0, k = 0; i < upper; i++) {
                    if (j >= size || j === 0) {
                        this._pages.push({
                            start: Math.min(maximum, i - lower),
                            end: i - lower + size - 1
                        });
                        if (Math.min(maximum, i - lower) === maximum) {
                            break;
                        }
                        j = 0, ++k;
                    }
                    j += this._core.mergers(this._core.relative(i));
                }
            }
        };
    
        /**
         * Draws the user interface.
         * @todo The option `dotsData` wont work.
         * @protected
         */
        Navigation.prototype.draw = function() {
            var difference,
                settings = this._core.settings,
                disabled = this._core.items().length <= settings.items,
                index = this._core.relative(this._core.current()),
                loop = settings.loop || settings.rewind;
    
            this._controls.$relative.toggleClass('disabled', !settings.nav || disabled);
    
            if (settings.nav) {
                this._controls.$previous.toggleClass('disabled', !loop && index <= this._core.minimum(true));
                this._controls.$next.toggleClass('disabled', !loop && index >= this._core.maximum(true));
            }
    
            this._controls.$absolute.toggleClass('disabled', !settings.dots || disabled);
    
            if (settings.dots) {
                difference = this._pages.length - this._controls.$absolute.children().length;
    
                if (settings.dotsData && difference !== 0) {
                    this._controls.$absolute.html(this._templates.join(''));
                } else if (difference > 0) {
                    this._controls.$absolute.append(new Array(difference + 1).join(this._templates[0]));
                } else if (difference < 0) {
                    this._controls.$absolute.children().slice(difference).remove();
                }
    
                this._controls.$absolute.find('.active').removeClass('active');
                this._controls.$absolute.children().eq($.inArray(this.current(), this._pages)).addClass('active');
            }
        };
    
        /**
         * Extends event data.
         * @protected
         * @param {Event} event - The event object which gets thrown.
         */
        Navigation.prototype.onTrigger = function(event) {
            var settings = this._core.settings;
    
            event.page = {
                index: $.inArray(this.current(), this._pages),
                count: this._pages.length,
                size: settings && (settings.center || settings.autoWidth || settings.dotsData
                    ? 1 : settings.dotsEach || settings.items)
            };
        };
    
        /**
         * Gets the current page position of the carousel.
         * @protected
         * @returns {Number}
         */
        Navigation.prototype.current = function() {
            var current = this._core.relative(this._core.current());
            return $.grep(this._pages, $.proxy(function(page, index) {
                return page.start <= current && page.end >= current;
            }, this)).pop();
        };
    
        /**
         * Gets the current succesor/predecessor position.
         * @protected
         * @returns {Number}
         */
        Navigation.prototype.getPosition = function(successor) {
            var position, length,
                settings = this._core.settings;
    
            if (settings.slideBy == 'page') {
                position = $.inArray(this.current(), this._pages);
                length = this._pages.length;
                successor ? ++position : --position;
                position = this._pages[((position % length) + length) % length].start;
            } else {
                position = this._core.relative(this._core.current());
                length = this._core.items().length;
                successor ? position += settings.slideBy : position -= settings.slideBy;
            }
    
            return position;
        };
    
        /**
         * Slides to the next item or page.
         * @public
         * @param {Number} [speed=false] - The time in milliseconds for the transition.
         */
        Navigation.prototype.next = function(speed) {
            $.proxy(this._overrides.to, this._core)(this.getPosition(true), speed);
        };
    
        /**
         * Slides to the previous item or page.
         * @public
         * @param {Number} [speed=false] - The time in milliseconds for the transition.
         */
        Navigation.prototype.prev = function(speed) {
            $.proxy(this._overrides.to, this._core)(this.getPosition(false), speed);
        };
    
        /**
         * Slides to the specified item or page.
         * @public
         * @param {Number} position - The position of the item or page.
         * @param {Number} [speed] - The time in milliseconds for the transition.
         * @param {Boolean} [standard=false] - Whether to use the standard behaviour or not.
         */
        Navigation.prototype.to = function(position, speed, standard) {
            var length;
    
            if (!standard && this._pages.length) {
                length = this._pages.length;
                $.proxy(this._overrides.to, this._core)(this._pages[((position % length) + length) % length].start, speed);
            } else {
                $.proxy(this._overrides.to, this._core)(position, speed);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.Navigation = Navigation;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * Hash Plugin
     * @version 2.1.0
     * @author Artus Kolanowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
        'use strict';
    
        /**
         * Creates the hash plugin.
         * @class The Hash Plugin
         * @param {Owl} carousel - The Owl Carousel
         */
        var Hash = function(carousel) {
            /**
             * Reference to the core.
             * @protected
             * @type {Owl}
             */
            this._core = carousel;
    
            /**
             * Hash index for the items.
             * @protected
             * @type {Object}
             */
            this._hashes = {};
    
            /**
             * The carousel element.
             * @type {jQuery}
             */
            this.$element = this._core.$element;
    
            /**
             * All event handlers.
             * @protected
             * @type {Object}
             */
            this._handlers = {
                'initialized.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && this._core.settings.startPosition === 'URLHash') {
                        $(window).trigger('hashchange.owl.navigation');
                    }
                }, this),
                'prepared.owl.carousel': $.proxy(function(e) {
                    if (e.namespace) {
                        var hash = $(e.content).find('[data-hash]').addBack('[data-hash]').attr('data-hash');
    
                        if (!hash) {
                            return;
                        }
    
                        this._hashes[hash] = e.content;
                    }
                }, this),
                'changed.owl.carousel': $.proxy(function(e) {
                    if (e.namespace && e.property.name === 'position') {
                        var current = this._core.items(this._core.relative(this._core.current())),
                            hash = $.map(this._hashes, function(item, hash) {
                                return item === current ? hash : null;
                            }).join();
    
                        if (!hash || window.location.hash.slice(1) === hash) {
                            return;
                        }
    
                        window.location.hash = hash;
                    }
                }, this)
            };
    
            // set default options
            this._core.options = $.extend({}, Hash.Defaults, this._core.options);
    
            // register the event handlers
            this.$element.on(this._handlers);
    
            // register event listener for hash navigation
            $(window).on('hashchange.owl.navigation', $.proxy(function(e) {
                var hash = window.location.hash.substring(1),
                    items = this._core.$stage.children(),
                    position = this._hashes[hash] && items.index(this._hashes[hash]);
    
                if (position === undefined || position === this._core.current()) {
                    return;
                }
    
                this._core.to(this._core.relative(position), false, true);
            }, this));
        };
    
        /**
         * Default options.
         * @public
         */
        Hash.Defaults = {
            URLhashListener: false
        };
    
        /**
         * Destroys the plugin.
         * @public
         */
        Hash.prototype.destroy = function() {
            var handler, property;
    
            $(window).off('hashchange.owl.navigation');
    
            for (handler in this._handlers) {
                this._core.$element.off(handler, this._handlers[handler]);
            }
            for (property in Object.getOwnPropertyNames(this)) {
                typeof this[property] != 'function' && (this[property] = null);
            }
        };
    
        $.fn.owlCarousel.Constructor.Plugins.Hash = Hash;
    
    })(window.Zepto || window.jQuery, window, document);
    
    /**
     * Support Plugin
     *
     * @version 2.1.0
     * @author Vivid Planet Software GmbH
     * @author Artus Kolanowski
     * @author David Deutsch
     * @license The MIT License (MIT)
     */
    ;(function($, window, document, undefined) {
    
        var style = $('<support>').get(0).style,
            prefixes = 'Webkit Moz O ms'.split(' '),
            events = {
                transition: {
                    end: {
                        WebkitTransition: 'webkitTransitionEnd',
                        MozTransition: 'transitionend',
                        OTransition: 'oTransitionEnd',
                        transition: 'transitionend'
                    }
                },
                animation: {
                    end: {
                        WebkitAnimation: 'webkitAnimationEnd',
                        MozAnimation: 'animationend',
                        OAnimation: 'oAnimationEnd',
                        animation: 'animationend'
                    }
                }
            },
            tests = {
                csstransforms: function() {
                    return !!test('transform');
                },
                csstransforms3d: function() {
                    return !!test('perspective');
                },
                csstransitions: function() {
                    return !!test('transition');
                },
                cssanimations: function() {
                    return !!test('animation');
                }
            };
    
        function test(property, prefixed) {
            var result = false,
                upper = property.charAt(0).toUpperCase() + property.slice(1);
    
            $.each((property + ' ' + prefixes.join(upper + ' ') + upper).split(' '), function(i, property) {
                if (style[property] !== undefined) {
                    result = prefixed ? property : true;
                    return false;
                }
            });
    
            return result;
        }
    
        function prefixed(property) {
            return test(property, true);
        }
    
        if (tests.csstransitions()) {
            /* jshint -W053 */
            $.support.transition = new String(prefixed('transition'))
            $.support.transition.end = events.transition.end[ $.support.transition ];
        }
    
        if (tests.cssanimations()) {
            /* jshint -W053 */
            $.support.animation = new String(prefixed('animation'))
            $.support.animation.end = events.animation.end[ $.support.animation ];
        }
    
        if (tests.csstransforms()) {
            /* jshint -W053 */
            $.support.transform = new String(prefixed('transform'));
            $.support.transform3d = tests.csstransforms3d();
        }
    
    })(window.Zepto || window.jQuery, window, document);
    
    /*
     *  Bootstrap Duallistbox - v3.0.6
     *  A responsive dual listbox widget optimized for Twitter Bootstrap. It works on all modern browsers and on touch devices.
     *  http://www.virtuosoft.eu/code/bootstrap-duallistbox/
     *
     *  Made by IstvÃ¡n Ujj-MÃ©szÃ¡ros
     *  Under Apache License v2.0 License
     */
    ;(function ($, window, document, undefined) {
      // Create the defaults once
      var pluginName = 'bootstrapDualListbox',
        defaults = {
          bootstrap2Compatible: false,
          filterTextClear: 'show all',
          filterPlaceHolder: 'Filter',
          moveSelectedLabel: 'Move selected',
          moveAllLabel: 'Move all',
          removeSelectedLabel: 'Remove selected',
          removeAllLabel: 'Remove all',
          moveOnSelect: true,                                                                 // true/false (forced true on androids, see the comment later)
          preserveSelectionOnMove: false,                                                     // 'all' / 'moved' / false
          selectedListLabel: false,                                                           // 'string', false
          nonSelectedListLabel: false,                                                        // 'string', false
          helperSelectNamePostfix: '_helper',                                                 // 'string_of_postfix' / false
          selectorMinimalHeight: 100,
          showFilterInputs: true,                                                             // whether to show filter inputs
          nonSelectedFilter: '',                                                              // string, filter the non selected options
          selectedFilter: '',                                                                 // string, filter the selected options
          infoText: 'Showing all {0}',                                                        // text when all options are visible / false for no info text
          infoTextFiltered: '<span class="label label-warning">Filtered</span> {0} from {1}', // when not all of the options are visible due to the filter
          infoTextEmpty: 'Empty list',                                                        // when there are no options present in the list
          filterOnValues: false,                                                              // filter by selector's values, boolean
          sortByInputOrder: false,
          eventMoveOverride: false,                                                           // boolean, allows user to unbind default event behaviour and run their own instead
          eventMoveAllOverride: false,                                                        // boolean, allows user to unbind default event behaviour and run their own instead
          eventRemoveOverride: false,                                                         // boolean, allows user to unbind default event behaviour and run their own instead
          eventRemoveAllOverride: false                                                       // boolean, allows user to unbind default event behaviour and run their own instead
        },
        // Selections are invisible on android if the containing select is styled with CSS
        // http://code.google.com/p/android/issues/detail?id=16922
        isBuggyAndroid = /android/i.test(navigator.userAgent.toLowerCase());
    
      // The actual plugin constructor
      function BootstrapDualListbox(element, options) {
        this.element = $(element);
        // jQuery has an extend method which merges the contents of two or
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
      }
    
      function triggerChangeEvent(dualListbox) {
        dualListbox.element.trigger('change');
      }
    
      function updateSelectionStates(dualListbox) {
        dualListbox.element.find('option').each(function(index, item) {
          var $item = $(item);
          if (typeof($item.data('original-index')) === 'undefined') {
            $item.data('original-index', dualListbox.elementCount++);
          }
          if (typeof($item.data('_selected')) === 'undefined') {
            $item.data('_selected', false);
          }
        });
      }
    
      function changeSelectionState(dualListbox, original_index, selected) {
        dualListbox.element.find('option').each(function(index, item) {
          var $item = $(item);
          if ($item.data('original-index') === original_index) {
            $item.prop('selected', selected);
            if(selected){
              $item.attr('data-sortindex', dualListbox.sortIndex);
              dualListbox.sortIndex++;
            } else {
              $item.removeAttr('data-sortindex');
            }
          }
        });
      }
    
      function formatString(s, args) {
        return s.replace(/\{(\d+)\}/g, function(match, number) {
          return typeof args[number] !== 'undefined' ? args[number] : match;
        });
      }
    
      function refreshInfo(dualListbox) {
        if (!dualListbox.settings.infoText) {
          return;
        }
    
        var visible1 = dualListbox.elements.select1.find('option').length,
          visible2 = dualListbox.elements.select2.find('option').length,
          all1 = dualListbox.element.find('option').length - dualListbox.selectedElements,
          all2 = dualListbox.selectedElements,
          content = '';
    
        if (all1 === 0) {
          content = dualListbox.settings.infoTextEmpty;
        } else if (visible1 === all1) {
          content = formatString(dualListbox.settings.infoText, [visible1, all1]);
        } else {
          content = formatString(dualListbox.settings.infoTextFiltered, [visible1, all1]);
        }
    
        dualListbox.elements.info1.html(content);
        dualListbox.elements.box1.toggleClass('filtered', !(visible1 === all1 || all1 === 0));
    
        if (all2 === 0) {
          content = dualListbox.settings.infoTextEmpty;
        } else if (visible2 === all2) {
          content = formatString(dualListbox.settings.infoText, [visible2, all2]);
        } else {
          content = formatString(dualListbox.settings.infoTextFiltered, [visible2, all2]);
        }
    
        dualListbox.elements.info2.html(content);
        dualListbox.elements.box2.toggleClass('filtered', !(visible2 === all2 || all2 === 0));
      }
    
      function refreshSelects(dualListbox) {
        dualListbox.selectedElements = 0;
    
        dualListbox.elements.select1.empty();
        dualListbox.elements.select2.empty();
    
        dualListbox.element.find('option').each(function(index, item) {
          var $item = $(item);
          if ($item.prop('selected')) {
            dualListbox.selectedElements++;
            dualListbox.elements.select2.append($item.clone(true).prop('selected', $item.data('_selected')));
          } else {
            dualListbox.elements.select1.append($item.clone(true).prop('selected', $item.data('_selected')));
          }
        });
    
        if (dualListbox.settings.showFilterInputs) {
          filter(dualListbox, 1);
          filter(dualListbox, 2);
        }
        refreshInfo(dualListbox);
      }
    
      function filter(dualListbox, selectIndex) {
        if (!dualListbox.settings.showFilterInputs) {
          return;
        }
    
        saveSelections(dualListbox, selectIndex);
    
        dualListbox.elements['select'+selectIndex].empty().scrollTop(0);
        var regex = new RegExp($.trim(dualListbox.elements['filterInput'+selectIndex].val()), 'gi'),
          allOptions = dualListbox.element.find('option'),
          options = dualListbox.element;
    
        if (selectIndex === 1) {
          options = allOptions.not(':selected');
        } else  {
          options = options.find('option:selected');
        }
    
        options.each(function(index, item) {
          var $item = $(item),
            isFiltered = true;
          if (item.text.match(regex) || (dualListbox.settings.filterOnValues && $item.attr('value').match(regex) ) ) {
            isFiltered = false;
            dualListbox.elements['select'+selectIndex].append($item.clone(true).prop('selected', $item.data('_selected')));
          }
          allOptions.eq($item.data('original-index')).data('filtered'+selectIndex, isFiltered);
        });
    
        refreshInfo(dualListbox);
      }
    
      function saveSelections(dualListbox, selectIndex) {
        var options = dualListbox.element.find('option');
        dualListbox.elements['select'+selectIndex].find('option').each(function(index, item) {
          var $item = $(item);
          options.eq($item.data('original-index')).data('_selected', $item.prop('selected'));
        });
      }
    
      function sortOptionsByInputOrder(select){
        var selectopt = select.children('option');
    
        selectopt.sort(function(a,b){
          var an = parseInt(a.getAttribute('data-sortindex')),
              bn = parseInt(b.getAttribute('data-sortindex'));
    
              if(an > bn) {
                 return 1;
              }
              if(an < bn) {
                return -1;
              }
              return 0;
        });
    
        selectopt.detach().appendTo(select);
      }
    
      function sortOptions(select) {
        select.find('option').sort(function(a, b) {
          return ($(a).data('original-index') > $(b).data('original-index')) ? 1 : -1;
        }).appendTo(select);
      }
    
      function clearSelections(dualListbox) {
        dualListbox.elements.select1.find('option').each(function() {
          dualListbox.element.find('option').data('_selected', false);
        });
      }
    
      function move(dualListbox) {
        if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 1);
          saveSelections(dualListbox, 2);
        } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 1);
        }
    
        dualListbox.elements.select1.find('option:selected').each(function(index, item) {
          var $item = $(item);
          if (!$item.data('filtered1')) {
            changeSelectionState(dualListbox, $item.data('original-index'), true);
          }
        });
    
        refreshSelects(dualListbox);
        triggerChangeEvent(dualListbox);
        if(dualListbox.settings.sortByInputOrder){
            sortOptionsByInputOrder(dualListbox.elements.select2);
        } else {
            sortOptions(dualListbox.elements.select2);
        }
      }
    
      function remove(dualListbox) {
        if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 1);
          saveSelections(dualListbox, 2);
        } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 2);
        }
    
        dualListbox.elements.select2.find('option:selected').each(function(index, item) {
          var $item = $(item);
          if (!$item.data('filtered2')) {
            changeSelectionState(dualListbox, $item.data('original-index'), false);
          }
        });
    
        refreshSelects(dualListbox);
        triggerChangeEvent(dualListbox);
        sortOptions(dualListbox.elements.select1);
        if(dualListbox.settings.sortByInputOrder){
            sortOptionsByInputOrder(dualListbox.elements.select2);
        }
      }
    
      function moveAll(dualListbox) {
        if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 1);
          saveSelections(dualListbox, 2);
        } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 1);
        }
    
        dualListbox.element.find('option').each(function(index, item) {
          var $item = $(item);
          if (!$item.data('filtered1')) {
            $item.prop('selected', true);
            $item.attr('data-sortindex', dualListbox.sortIndex);
            dualListbox.sortIndex++;
          }
        });
    
        refreshSelects(dualListbox);
        triggerChangeEvent(dualListbox);
      }
    
      function removeAll(dualListbox) {
        if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 1);
          saveSelections(dualListbox, 2);
        } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
          saveSelections(dualListbox, 2);
        }
    
        dualListbox.element.find('option').each(function(index, item) {
          var $item = $(item);
          if (!$item.data('filtered2')) {
            $item.prop('selected', false);
            $item.removeAttr('data-sortindex');
          }
        });
    
        refreshSelects(dualListbox);
        triggerChangeEvent(dualListbox);
      }
    
      function bindEvents(dualListbox) {
        dualListbox.elements.form.submit(function(e) {
          if (dualListbox.elements.filterInput1.is(':focus')) {
            e.preventDefault();
            dualListbox.elements.filterInput1.focusout();
          } else if (dualListbox.elements.filterInput2.is(':focus')) {
            e.preventDefault();
            dualListbox.elements.filterInput2.focusout();
          }
        });
    
        dualListbox.element.on('bootstrapDualListbox.refresh', function(e, mustClearSelections){
          dualListbox.refresh(mustClearSelections);
        });
    
        dualListbox.elements.filterClear1.on('click', function() {
          dualListbox.setNonSelectedFilter('', true);
        });
    
        dualListbox.elements.filterClear2.on('click', function() {
          dualListbox.setSelectedFilter('', true);
        });
    
        if (dualListbox.settings.eventMoveOverride === false) {
          dualListbox.elements.moveButton.on('click', function() {
            move(dualListbox);
          });
        }
    
        if (dualListbox.settings.eventMoveAllOverride === false) {
          dualListbox.elements.moveAllButton.on('click', function() {
            moveAll(dualListbox);
          });
        }
    
        if (dualListbox.settings.eventRemoveOverride === false) {
          dualListbox.elements.removeButton.on('click', function() {
            remove(dualListbox);
          });
        }
    
        if (dualListbox.settings.eventRemoveAllOverride === false) {
          dualListbox.elements.removeAllButton.on('click', function() {
            removeAll(dualListbox);
          });
        }
    
        dualListbox.elements.filterInput1.on('change keyup', function() {
          filter(dualListbox, 1);
        });
    
        dualListbox.elements.filterInput2.on('change keyup', function() {
          filter(dualListbox, 2);
        });
      }
    
      BootstrapDualListbox.prototype = {
        init: function () {
          // Add the custom HTML template
          this.container = $('' +
            '<div class="bootstrap-duallistbox-container">' +
            ' <div class="box1">' +
            '   <label></label>' +
            '   <span class="info-container">' +
            '     <span class="info"></span>' +
            '     <button type="button" class="btn clear1 pull-right"></button>' +
            '   </span>' +
            '   <input class="filter" type="text">' +
            '   <div class="btn-group buttons">' +
            '     <button type="button" class="btn moveall">' +
            '       <i></i>' +
            '       <i></i>' +
            '     </button>' +
            '     <button type="button" class="btn move">' +
            '       <i></i>' +
            '     </button>' +
            '   </div>' +
            '   <select multiple="multiple"></select>' +
            ' </div>' +
            ' <div class="box2">' +
            '   <label></label>' +
            '   <span class="info-container">' +
            '     <span class="info"></span>' +
            '     <button type="button" class="btn clear2 pull-right"></button>' +
            '   </span>' +
            '   <input class="filter" type="text">' +
            '   <div class="btn-group buttons">' +
            '     <button type="button" class="btn remove">' +
            '       <i></i>' +
            '     </button>' +
            '     <button type="button" class="btn removeall">' +
            '       <i></i>' +
            '       <i></i>' +
            '     </button>' +
            '   </div>' +
            '   <select multiple="multiple"></select>' +
            ' </div>' +
            '</div>')
            .insertBefore(this.element);
    
          // Cache the inner elements
          this.elements = {
            originalSelect: this.element,
            box1: $('.box1', this.container),
            box2: $('.box2', this.container),
            filterInput1: $('.box1 .filter', this.container),
            filterInput2: $('.box2 .filter', this.container),
            filterClear1: $('.box1 .clear1', this.container),
            filterClear2: $('.box2 .clear2', this.container),
            label1: $('.box1 > label', this.container),
            label2: $('.box2 > label', this.container),
            info1: $('.box1 .info', this.container),
            info2: $('.box2 .info', this.container),
            select1: $('.box1 select', this.container),
            select2: $('.box2 select', this.container),
            moveButton: $('.box1 .move', this.container),
            removeButton: $('.box2 .remove', this.container),
            moveAllButton: $('.box1 .moveall', this.container),
            removeAllButton: $('.box2 .removeall', this.container),
            form: $($('.box1 .filter', this.container)[0].form)
          };
    
          // Set select IDs
          this.originalSelectName = this.element.attr('name') || '';
          var select1Id = 'bootstrap-duallistbox-nonselected-list_' + this.originalSelectName,
            select2Id = 'bootstrap-duallistbox-selected-list_' + this.originalSelectName;
          this.elements.select1.attr('id', select1Id);
          this.elements.select2.attr('id', select2Id);
          this.elements.label1.attr('for', select1Id);
          this.elements.label2.attr('for', select2Id);
    
          // Apply all settings
          this.selectedElements = 0;
          this.sortIndex = 0;
          this.elementCount = 0;
          this.setBootstrap2Compatible(this.settings.bootstrap2Compatible);
          this.setFilterTextClear(this.settings.filterTextClear);
          this.setFilterPlaceHolder(this.settings.filterPlaceHolder);
          this.setMoveSelectedLabel(this.settings.moveSelectedLabel);
          this.setMoveAllLabel(this.settings.moveAllLabel);
          this.setRemoveSelectedLabel(this.settings.removeSelectedLabel);
          this.setRemoveAllLabel(this.settings.removeAllLabel);
          this.setMoveOnSelect(this.settings.moveOnSelect);
          this.setPreserveSelectionOnMove(this.settings.preserveSelectionOnMove);
          this.setSelectedListLabel(this.settings.selectedListLabel);
          this.setNonSelectedListLabel(this.settings.nonSelectedListLabel);
          this.setHelperSelectNamePostfix(this.settings.helperSelectNamePostfix);
          this.setSelectOrMinimalHeight(this.settings.selectorMinimalHeight);
    
          updateSelectionStates(this);
    
          this.setShowFilterInputs(this.settings.showFilterInputs);
          this.setNonSelectedFilter(this.settings.nonSelectedFilter);
          this.setSelectedFilter(this.settings.selectedFilter);
          this.setInfoText(this.settings.infoText);
          this.setInfoTextFiltered(this.settings.infoTextFiltered);
          this.setInfoTextEmpty(this.settings.infoTextEmpty);
          this.setFilterOnValues(this.settings.filterOnValues);
          this.setSortByInputOrder(this.settings.sortByInputOrder);
          this.setEventMoveOverride(this.settings.eventMoveOverride);
          this.setEventMoveAllOverride(this.settings.eventMoveAllOverride);
          this.setEventRemoveOverride(this.settings.eventRemoveOverride);
          this.setEventRemoveAllOverride(this.settings.eventRemoveAllOverride);
    
          // Hide the original select
          this.element.hide();
    
          bindEvents(this);
          refreshSelects(this);
    
          return this.element;
        },
        setBootstrap2Compatible: function(value, refresh) {
          this.settings.bootstrap2Compatible = value;
          if (value) {
            this.container.removeClass('row').addClass('row-fluid bs2compatible');
            this.container.find('.box1, .box2').removeClass('col-md-6').addClass('span6');
            this.container.find('.clear1, .clear2').removeClass('btn-default btn-xs').addClass('btn-mini');
            this.container.find('input, select').removeClass('form-control');
            this.container.find('.btn').removeClass('btn-default');
            this.container.find('.moveall > i, .move > i').removeClass('glyphicon glyphicon-arrow-right').addClass('icon-arrow-right');
            this.container.find('.removeall > i, .remove > i').removeClass('glyphicon glyphicon-arrow-left').addClass('icon-arrow-left');
          } else {
            this.container.removeClass('row-fluid bs2compatible').addClass('row');
            this.container.find('.box1, .box2').removeClass('span6').addClass('col-md-6');
            this.container.find('.clear1, .clear2').removeClass('btn-mini').addClass('btn-default btn-xs');
            this.container.find('input, select').addClass('form-control');
            this.container.find('.btn').addClass('btn-default');
            this.container.find('.moveall > i, .move > i').removeClass('icon-arrow-right').addClass('glyphicon glyphicon-arrow-right');
            this.container.find('.removeall > i, .remove > i').removeClass('icon-arrow-left').addClass('glyphicon glyphicon-arrow-left');
          }
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setFilterTextClear: function(value, refresh) {
          this.settings.filterTextClear = value;
          this.elements.filterClear1.html(value);
          this.elements.filterClear2.html(value);
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setFilterPlaceHolder: function(value, refresh) {
          this.settings.filterPlaceHolder = value;
          this.elements.filterInput1.attr('placeholder', value);
          this.elements.filterInput2.attr('placeholder', value);
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setMoveSelectedLabel: function(value, refresh) {
          this.settings.moveSelectedLabel = value;
          this.elements.moveButton.attr('title', value);
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setMoveAllLabel: function(value, refresh) {
          this.settings.moveAllLabel = value;
          this.elements.moveAllButton.attr('title', value);
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setRemoveSelectedLabel: function(value, refresh) {
          this.settings.removeSelectedLabel = value;
          this.elements.removeButton.attr('title', value);
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setRemoveAllLabel: function(value, refresh) {
          this.settings.removeAllLabel = value;
          this.elements.removeAllButton.attr('title', value);
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setMoveOnSelect: function(value, refresh) {
          if (isBuggyAndroid) {
            value = true;
          }
          this.settings.moveOnSelect = value;
          if (this.settings.moveOnSelect) {
            this.container.addClass('moveonselect');
            var self = this;
            this.elements.select1.on('change', function() {
              move(self);
            });
            this.elements.select2.on('change', function() {
              remove(self);
            });
          } else {
            this.container.removeClass('moveonselect');
            this.elements.select1.off('change');
            this.elements.select2.off('change');
          }
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setPreserveSelectionOnMove: function(value, refresh) {
          // We are forcing to move on select and disabling preserveSelectionOnMove on Android
          if (isBuggyAndroid) {
            value = false;
          }
          this.settings.preserveSelectionOnMove = value;
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setSelectedListLabel: function(value, refresh) {
          this.settings.selectedListLabel = value;
          if (value) {
            this.elements.label2.show().html(value);
          } else {
            this.elements.label2.hide().html(value);
          }
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setNonSelectedListLabel: function(value, refresh) {
          this.settings.nonSelectedListLabel = value;
          if (value) {
            this.elements.label1.show().html(value);
          } else {
            this.elements.label1.hide().html(value);
          }
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setHelperSelectNamePostfix: function(value, refresh) {
          this.settings.helperSelectNamePostfix = value;
          if (value) {
            this.elements.select1.attr('name', this.originalSelectName + value + '1');
            this.elements.select2.attr('name', this.originalSelectName + value + '2');
          } else {
            this.elements.select1.removeAttr('name');
            this.elements.select2.removeAttr('name');
          }
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setSelectOrMinimalHeight: function(value, refresh) {
          this.settings.selectorMinimalHeight = value;
          var height = this.element.height();
          if (this.element.height() < value) {
            height = value;
          }
          this.elements.select1.height(height);
          this.elements.select2.height(height);
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setShowFilterInputs: function(value, refresh) {
          if (!value) {
            this.setNonSelectedFilter('');
            this.setSelectedFilter('');
            refreshSelects(this);
            this.elements.filterInput1.hide();
            this.elements.filterInput2.hide();
          } else {
            this.elements.filterInput1.show();
            this.elements.filterInput2.show();
          }
          this.settings.showFilterInputs = value;
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setNonSelectedFilter: function(value, refresh) {
          if (this.settings.showFilterInputs) {
            this.settings.nonSelectedFilter = value;
            this.elements.filterInput1.val(value);
            if (refresh) {
              refreshSelects(this);
            }
            return this.element;
          }
        },
        setSelectedFilter: function(value, refresh) {
          if (this.settings.showFilterInputs) {
            this.settings.selectedFilter = value;
            this.elements.filterInput2.val(value);
            if (refresh) {
              refreshSelects(this);
            }
            return this.element;
          }
        },
        setInfoText: function(value, refresh) {
          this.settings.infoText = value;
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setInfoTextFiltered: function(value, refresh) {
          this.settings.infoTextFiltered = value;
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setInfoTextEmpty: function(value, refresh) {
          this.settings.infoTextEmpty = value;
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setFilterOnValues: function(value, refresh) {
          this.settings.filterOnValues = value;
          if (refresh) {
            refreshSelects(this);
          }
          return this.element;
        },
        setSortByInputOrder: function(value, refresh){
            this.settings.sortByInputOrder = value;
            if (refresh) {
              refreshSelects(this);
            }
            return this.element;
        },
        setEventMoveOverride: function(value, refresh) {
            this.settings.eventMoveOverride = value;
            if (refresh) {
              refreshSelects(this);
            }
            return this.element;
        },
        setEventMoveAllOverride: function(value, refresh) {
            this.settings.eventMoveAllOverride = value;
            if (refresh) {
              refreshSelects(this);
            }
            return this.element;
        },
        setEventRemoveOverride: function(value, refresh) {
            this.settings.eventRemoveOverride = value;
            if (refresh) {
              refreshSelects(this);
            }
            return this.element;
        },
        setEventRemoveAllOverride: function(value, refresh) {
            this.settings.eventRemoveAllOverride = value;
            if (refresh) {
              refreshSelects(this);
            }
            return this.element;
        },
        getContainer: function() {
          return this.container;
        },
        refresh: function(mustClearSelections) {
          updateSelectionStates(this);
    
          if (!mustClearSelections) {
            saveSelections(this, 1);
            saveSelections(this, 2);
          } else {
            clearSelections(this);
          }
    
          refreshSelects(this);
        },
        destroy: function() {
          this.container.remove();
          this.element.show();
          $.data(this, 'plugin_' + pluginName, null);
          return this.element;
        }
      };
    
      // A really lightweight plugin wrapper around the constructor,
      // preventing against multiple instantiations
      $.fn[ pluginName ] = function (options) {
        var args = arguments;
    
        // Is the first parameter an object (options), or was omitted, instantiate a new instance of the plugin.
        if (options === undefined || typeof options === 'object') {
          return this.each(function () {
            // If this is not a select
            if (!$(this).is('select')) {
              $(this).find('select').each(function(index, item) {
                // For each nested select, instantiate the Dual List Box
                $(item).bootstrapDualListbox(options);
              });
            } else if (!$.data(this, 'plugin_' + pluginName)) {
              // Only allow the plugin to be instantiated once so we check that the element has no plugin instantiation yet
    
              // if it has no instance, create a new one, pass options to our plugin constructor,
              // and store the plugin instance in the elements jQuery data object.
              $.data(this, 'plugin_' + pluginName, new BootstrapDualListbox(this, options));
            }
          });
          // If the first parameter is a string and it doesn't start with an underscore or "contains" the `init`-function,
          // treat this as a call to a public method.
        } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
    
          // Cache the method call to make it possible to return a value
          var returns;
    
          this.each(function () {
            var instance = $.data(this, 'plugin_' + pluginName);
            // Tests that there's already a plugin-instance and checks that the requested public method exists
            if (instance instanceof BootstrapDualListbox && typeof instance[options] === 'function') {
              // Call the method of our plugin instance, and pass it the supplied arguments.
              returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
            }
          });
    
          // If the earlier cached method gives a value back return the value,
          // otherwise return this to preserve chainability.
          return returns !== undefined ? returns : this;
        }
    
      };
    
    })(jQuery, window, document);
    
    /**
     * WHMCS core JS library reference
     *
     * @copyright Copyright (c) WHMCS Limited 2005-2017
     * @license http://www.whmcs.com/license/ WHMCS Eula
     */
    
    (function (window, factory) {
        if (typeof window.WHMCS !== 'object') {
            window.WHMCS = factory;
        }
    }(
        window,
        {
            hasModule: function (name) {
                return (typeof WHMCS[name] !== 'undefined'
                    && Object.getOwnPropertyNames(WHMCS[name]).length > 0);
            },
            loadModule: function (name, module) {
                if (this.hasModule(name)) {
                    return;
                }
    
                WHMCS[name] = {};
                if (typeof module === 'function') {
                    (module).apply(WHMCS[name]);
                } else {
                    for (var key in module) {
                        if (module.hasOwnProperty(key)) {
                            WHMCS[name][key] = {};
                            (module[key]).apply(WHMCS[name][key]);
                        }
                    }
                }
            }
        }
    ));
    
    /**
     * General utilities module
     *
     * @copyright Copyright (c) WHMCS Limited 2005-2017
     * @license http://www.whmcs.com/license/ WHMCS Eula
     */
    (function(module) {
        if (!WHMCS.hasModule('adminUtils')) {
            WHMCS.loadModule('adminUtils', module);
        }
    })(
    function () {
        this.getAdminRouteUrl = function (path) {
            return whmcsBaseUrl + "/index.php?rp=" + adminBaseRoutePath + path;
        };
    
        return this;
    });
    
    jQuery(document).ready(function(){
        jQuery('[data-toggle="tooltip"]').tooltip();
        jQuery('[data-toggle="popover"]').popover();
        jQuery('.inline-editable').editable({
            mode: 'inline',
            params: function(params) {
                params.action = 'savefield';
                params.token = csrfToken;
                return params;
            }
        });
        $("select.form-control.enhanced").select2({
            theme: 'bootstrap'
        });
    
        var clipboard = new Clipboard('.copy-to-clipboard');
        clipboard.on('success', function(e) {
            setTooltip(e.trigger, 'Copied!');
            hideTooltip(e.trigger);
        });
        clipboard.on('error', function(e) {
            setTooltip(e.trigger, 'Press Ctrl+C to copy');
            hideTooltip(e.trigger);
        });
        $('.copy-to-clipboard').tooltip({
            trigger: 'click',
            placement: 'bottom'
        });
    
        jQuery(".credit-card-type li a").click(function() {
            jQuery("#selectedCard").html(jQuery(this).html());
            jQuery("#cctype").val(jQuery('span.type', this).html());
        });
    
        jQuery('body').on('click', 'a.autoLinked', function (e) {
            e.preventDefault();
    
            var child = window.open();
            child.opener = null;
            child.location = e.target.href;
        });
    
        jQuery('#tblModuleSettings').on('click', '.icon-refresh', function() {
            fetchModuleSettings(jQuery(this).data('product-id'), 'simple');
        });
    
        jQuery('#mode-switch').click(function() {
            fetchModuleSettings(jQuery(this).data('product-id'), jQuery(this).attr('data-mode'));
        });
    
        $('body').on('click', '.modal-wizard .modal-submit', function() {
            var modal = $('#modalAjax');
            modal.find('.loader').show();
            modal.find('.modal-submit').prop('disabled', true);
    
            $('.modal-wizard .wizard-step:hidden :input').attr('disabled', true);
    
            var form = document.forms.namedItem('frmWizardContent'),
                oData = new FormData(form),
                currentStep = $('.modal-wizard .wizard-step:visible').data('step-number'),
                ccGatewayFormSubmitted = $('#ccGatewayFormSubmitted').val(),
                enomFormSubmitted = $('#enomFormSubmitted').val(),
                oReq = new XMLHttpRequest();
    
            if ((ccGatewayFormSubmitted && currentStep == 3) || (enomFormSubmitted && currentStep == 5)) {
                wizardStepTransition(false, true);
                fadeoutLoaderAndAllowSubmission(modal);
            } else {
    
                oReq.open('POST', $('#frmWizardContent').attr('action'), true);
    
                oReq.send(oData);
                oReq.onload = function () {
                    if (oReq.status == 200) {
                        try {
                            var data = JSON.parse(oReq.responseText),
                                doNotShow = $('#btnWizardDoNotShow');
                            if (doNotShow.is(':visible')) {
                                doNotShow.fadeOut('slow', function () {
                                    $('#btnWizardSkip').hide().removeClass('hidden').fadeIn('slow');
                                });
                            }
    
                            if (data.success) {
                                if (data.approveremails) {
                                    for (i = 0; i < data.approveremails.length; i++) {
                                        var email = data.approveremails[i];
                                        $('.modal-wizard .cert-approver-emails').append('<label class="radio-inline"><input type="radio" name="approver_email" value="' + email + '"> ' + email + '</label><br>');
                                    }
                                } else if (data.fileAuth) {
                                    $('.modal-wizard .cert-further-instructions').hide();
                                    $('.modal-wizard .cert-file-auth').removeClass('hidden');
                                    $('.modal-wizard .cert-file-auth-filename').val(data.fileAuthFilename);
                                    $('.modal-wizard .cert-file-auth-contents').val(data.fileAuthContents);
                                }
                                wizardStepTransition(data.skipNextStep, false);
                            } else {
                                wizardError(data.error);
                            }
                        } catch (err) {
                            wizardError('An error occurred while communicating with the server. Please try again.');
                        } finally {
                            fadeoutLoaderAndAllowSubmission(modal);
                        }
                    } else {
                        alert('An error occurred while communicating with the server. Please try again.');
                        modal.find('.loader').fadeOut();
                    }
                };
            }
        }).on('click', '#btnWizardSkip', function(e) {
            e.preventDefault();
            wizardStepTransition(false, true);
        }).on('click', '#btnWizardBack', function(e) {
            e.preventDefault();
            wizardStepBackTransition();
        }).on('click', '#btnWizardDoNotShow', function(e) {
            e.preventDefault();
            $.post('wizard.php', 'dismiss=true', function() {
                //Success or no, still hide now
                $('#modalAjax').modal('hide');
            });
        });
    
        $('#modalAjax').on('hidden.bs.modal', function (e) {
            if ($('#modalAjax').hasClass('modal-wizard')) {
                $('#btnWizardSkip').remove();
                $('#btnWizardBack').remove();
                $('#btnWizardDoNotShow').remove();
            }
        });
    
        $('#prodsall').click(function () {
            var checkboxes = $('.checkprods');
            checkboxes.filter(':visible').prop('checked', $(this).prop('checked')).end();
            if ($(this).prop('checked')) {
                checkboxes.filter(':hidden').prop('checked', !$(this).prop('checked')).end();
            }
        });
        $('#addonsall').click(function () {
            var checkboxes = $('.checkaddons');
            checkboxes.filter(':visible').prop('checked', $(this).prop('checked')).end();
            if ($(this).prop('checked')) {
                checkboxes.filter(':hidden').prop('checked', !$(this).prop('checked')).end();
            }
        });
        $('#domainsall').click(function () {
            var checkboxes = $('.checkdomains');
            checkboxes.filter(':visible').prop('checked', $(this).prop('checked')).end();
            if ($(this).prop('checked')) {
                checkboxes.filter(':hidden').prop('checked', !$(this).prop('checked')).end();
            }
        });
    
        jQuery('#addPayment').submit(function (e) {
            e.preventDefault();
            addingPayment = false;
            jQuery('#btnAddPayment').attr('disabled', 'disabled');
            jQuery('#paymentText').hide('fast', function() {
                jQuery('#paymentLoading').removeClass('hidden').show('fast');
            });
    
            var postData = jQuery(this).serialize().replace('action=edit', 'action=checkTransactionId'),
                post = jQuery.post(
                'invoices.php',
                postData + '&ajax=1'
            );
    
            post.done(function (data) {
                if (data.unique == false) {
                    jQuery('#modalDuplicateTransaction').modal('show');
                } else {
                    addInvoicePayment();
                }
            });
        });
    
        $('#modalDuplicateTransaction').on('hidden.bs.modal', function () {
            if (addingPayment === false) {
                jQuery('#paymentLoading').hide('fast', function() {
                    jQuery('#paymentText').show('fast');
                    jQuery('#btnAddPayment').removeAttr('disabled');
                });
            }
        });
    
        jQuery(document).on('click', '.feature-highlights-content .btn-action-1, .feature-highlights-content .btn-action-2', function() {
            var linkId = jQuery(this).data('link'),
                linkTitle = jQuery(this).data('link-title');
    
            jQuery.post(
                'whatsnew.php',
                {
                    action: "link-click",
                    linkId: linkId,
                    linkTitle: linkTitle,
                    token: csrfToken
                }
            );
        });
    });
    var addingPayment = false;
    
    function updateServerGroups(requiredModule) {
        var optionServerTypes = '';
        var doShowOption = false;
    
        $('#inputServerGroup').find('option:not([value=0])').each(function() {
            optionServerTypes = $(this).attr('data-server-types');
    
            if (requiredModule) {
                doShowOption = (optionServerTypes.indexOf(',' + requiredModule + ',') > -1);
            } else {
                doShowOption = true;
            }
    
            if (doShowOption) {
                $(this).attr('disabled', false);
            } else {
                $(this).attr('disabled', true);
    
                if ($(this).is(':selected')) {
                    $('#inputServerGroup').val('0');
                }
            }
        });
    }
    
    function fetchModuleSettings(productId, mode) {
        var gotValidResponse = false;
        var dataResponse = '';
        var switchLink = $('#mode-switch');
        var module = $('#inputModule').val();
    
        if (module === "") {
            $('#tblModuleSettings').find('tr').not(':first').remove();
            $('#noModuleSelectedRow').removeClass('hidden');
            $('#tblModuleAutomationSettings').find('input[type=radio]').attr('disabled', true);
            return;
        }
    
        mode = mode || 'simple';
        if (mode != 'simple' && mode != 'advanced') {
            mode = 'simple';
        }
        requestedMode = mode;
        $('#tblModuleSettings').addClass('module-settings-loading');
        $('#tblModuleAutomationSettings').addClass('module-settings-loading');
        $('#serverReturnedError').addClass('hidden');
        $('#moduleSettingsLoader').show();
        switchLink.attr('data-product-id', productId);
        $.post(window.location.pathname, {
            'action': 'module-settings',
            'module': module,
            'servergroup': $('#inputServerGroup').val(),
            'id': productId,
            'mode': mode
        },
        function(data) {
            gotValidResponse = true;
            $('#tblModuleSettings').removeClass('module-settings-loading');
            $('#tblModuleAutomationSettings').removeClass('module-settings-loading');
            $('#tblModuleSettings tr').not(':first').remove();
            switchLink.addClass('hidden');
            if (module && data.error) {
                $('#serverReturnedErrorText').html(data.error);
                $('#serverReturnedError').removeClass('hidden');
            }
            if (module && data.content) {
                $('#noModuleSelectedRow').addClass('hidden');
                $('#tblModuleSettings').append(data.content);
                $('#tblModuleAutomationSettings').find('input[type=radio]').removeAttr('disabled');
                if (data.mode == 'simple') {
                    switchLink.attr('data-mode', 'advanced').find('a').find('span').addClass('hidden').parent().find('.text-advanced').removeClass('hidden');
                    switchLink.removeClass('hidden');
                } else {
                    if (data.mode == 'advanced' && requestedMode == 'advanced') {
                        switchLink.attr('data-mode', 'simple').find('a').find('span').addClass('hidden').parent().find('.text-simple').removeClass('hidden');
                        switchLink.removeClass('hidden');
                    } else {
                        switchLink.addClass('hidden');
                    }
                }
            } else {
                $('#noModuleSelectedRow').removeClass('hidden');
                $('#tblModuleAutomationSettings').find('input[type=radio]').attr('disabled', true);
            }
            $('#moduleSettingsLoader').fadeOut();
            jQuery('[data-toggle="tooltip"]').tooltip();
        }, "json")
        .always(function() {
            updateServerGroups(gotValidResponse ? module : '');
    
            if (!gotValidResponse) {
                // non json response, likely session expired
            }
        });
        return dataResponse;
    }
    
    function wizardCall(action, request, handler) {
        var requestString = 'wizard=' + $('input[name="wizard"]').val()
            + '&step=' + $('input[name="step"]').val()
            + '&token=' + $('input[name="token"]').val()
            + '&action=' + action
            + '&' + request;
    
        $.post('wizard.php', requestString, handler);
    }
    
    function wizardError(errorMsg) {
        $('.modal-wizard .wizard-content').css('overflow', 'hidden');
        $('.info-alert:visible:first').html(errorMsg).addClass('alert-danger').effect('shake', function() {
            $('.modal-wizard .wizard-content').css('overflow', 'auto');
        });
    }
    
    function wizardStepTransition(skipNextStep, skip) {
        var currentStepNumber = $('.modal-wizard .wizard-step:visible').data('step-number');
        if (skipNextStep) {
            increment = 2;
        } else {
            increment = 1;
        }
        var lastStep = $('.modal-wizard .wizard-step:visible');
        var nextStepNumber = currentStepNumber + increment;
        if ($('#wizardStep' + nextStepNumber).length) {
            $('#wizardStep' + currentStepNumber).fadeOut('', function() {
                var newClass = 'completed';
                if (skip) {
                    newClass = 'skipped';
                    $('#wizardStepLabel' + currentStepNumber + ' i').removeClass('fa-check-circle-o').addClass('fa-minus-circle');
                } else {
                    lastStep.find('.signup-frm').hide();
                    lastStep.find('.signup-frm-success').removeClass('hidden');
    
                    if (currentStepNumber == 3) {
                        lastStep.find('.signup-frm-success')
                            .append('<input type="hidden" id="ccGatewayFormSubmitted" name="ccGatewayFormSubmitted" value="1" />');
                    } else if (currentStepNumber == 5) {
                        lastStep.find('.signup-frm-success')
                            .append('<input type="hidden" id="enomFormSubmitted" name="enomFormSubmitted" value="1" />');
                    }
    
                }
    
                if (nextStepNumber > 0) {
                    // Show the BACK button.
                    if (!$('#btnWizardBack').is(':visible')) {
                        $('#btnWizardBack').hide().removeClass('hidden').fadeIn('slow');
                    }
                } else {
                    $('#btnWizardBack').fadeOut('slow');
                    $('#btnWizardDoNotShow').fadeIn('slow');
                    $('#btnWizardSkip').fadeOut('slow');
                }
                $('#wizardStepLabel' + currentStepNumber).removeClass('current').addClass(newClass);
                $('.modal-wizard .wizard-step:visible :input').attr('disabled', true);
                $('#wizardStep' + nextStepNumber + ' :input').removeAttr('disabled');
                $('#wizardStep' + nextStepNumber).fadeIn();
                $('#inputWizardStep').val(nextStepNumber);
                $('#wizardStepLabel' + nextStepNumber).addClass('current');
            });
            if (!$('#wizardStep' + (nextStepNumber + 1)).length) {
                $('#btnWizardSkip').fadeOut('slow');
                $('#btnWizardBack').fadeOut('slow');
                $('.modal-submit').html('Finish');
            }
        } else {
            // end of steps
            $('#modalAjax').modal('hide');
        }
    }
    
    function wizardStepBackTransition() {
        var currentStepNumber = $('.modal-wizard .wizard-step:visible').data('step-number');
        var previousStepNumber = parseInt(currentStepNumber) - 1;
    
        $('#wizardStep' + currentStepNumber).fadeOut('', function() {
            if (previousStepNumber < 1) {
                $('#btnWizardBack').fadeOut('slow');
                $('#btnWizardDoNotShow').fadeIn('slow');
                $('#btnWizardSkip').addClass('hidden');
            }
    
            $('.modal-wizard .wizard-step:visible :input').attr('disabled', true);
            $('#wizardStep' + previousStepNumber + ' :input').removeAttr('disabled');
            $('#wizardStep' + previousStepNumber).fadeIn();
            $('#inputWizardStep').val(previousStepNumber);
            $('#wizardStepLabel' + previousStepNumber).addClass('current');
            $('#wizardStepLabel' + currentStepNumber).removeClass('current');
        });
    }
    
    function fadeoutLoaderAndAllowSubmission(modal) {
        modal.find('.loader').fadeOut();
        modal.find('.modal-submit').removeProp('disabled');
    }
    
    function openSetupWizard() {
        $('#modalFooterLeft').html('<a href="#" id="btnWizardSkip" class="btn btn-link pull-left hidden">Skip Step</a>' +
            '<a href="#" id="btnWizardDoNotShow" class="btn btn-link pull-left">Do not show this again</a>' +
            '</div>');
        $('#modalAjaxSubmit').before('<a href="#" id="btnWizardBack" class="btn btn-default hidden">Back</a>');
        openModal('wizard.php?wizard=GettingStarted', '', 'Getting Started Wizard', 'modal-lg', 'modal-wizard modal-setup-wizard', 'Next', '', true);
    }
    
    function setTooltip(btn, message) {
        $(btn).tooltip('hide')
            .attr('data-original-title', message)
            .tooltip('show');
    }
    
    function addInvoicePayment() {
        addingPayment = true;
        jQuery('#modalDuplicateTransaction').modal('hide');
        jQuery.post(
            'invoices.php',
            jQuery('#addPayment').serialize() + '&ajax=1',
            function (data) {
                if (data.redirectUri) {
                    window.location = data.redirectUri;
                }
            }
        );
    }
    
    function cancelAddPayment() {
        jQuery('#paymentLoading').fadeOut('fast', function() {
            jQuery('#paymentText').fadeIn('fast');
            jQuery('#btnAddPayment').removeAttr('disabled');
        });
        jQuery('#modalDuplicateTransaction').modal('hide');
    }
    
    function openFeatureHighlights() {
        openModal('whatsnew.php?modal=1', '', 'What\'s new in Version ...', '', 'modal-feature-highlights', '', '', true);
    }
    
    
    function hideTooltip(btn) {
        setTimeout(function() {
            $(btn).tooltip('hide');
        }, 1000);
    }
    
    /*!
     * WHMCS Ajax Driven Modal Framework
     *
     * @copyright Copyright (c) WHMCS Limited 2005-2016
     * @license http://www.whmcs.com/license/ WHMCS Eula
     */
    jQuery(document).ready(function(){
        jQuery(document).on('click', '.open-modal', function(e) {
            e.preventDefault();
            var url = jQuery(this).attr('href'),
                modalSize = jQuery(this).data('modal-size'),
                modalClass = jQuery(this).data('modal-class'),
                modalTitle = jQuery(this).data('modal-title'),
                submitId = jQuery(this).data('btn-submit-id'),
                submitLabel = jQuery(this).data('btn-submit-label'),
                hideClose = jQuery(this).data('btn-close-hide'),
                disabled = jQuery(this).attr('disabled');
    
            if (!disabled) {
                openModal(url, '', modalTitle, modalSize, modalClass, submitLabel, submitId, hideClose);
            }
        });
    
        // define modal close reset action
        jQuery('#modalAjax').on('hidden.bs.modal', function (e) {
            if (jQuery(this).hasClass('modal-feature-highlights')) {
                var dismissForVersion = jQuery('#cbFeatureHighlightsDismissForVersion').is(':checked');
                jQuery.ajax(
                    'whatsnew.php?dismiss=1&until_next_update=' + (dismissForVersion ? '1' : '0'),
                    {
                        dataType: 'json'
                    }
                );
            }
    
            jQuery('#modalAjax').find('.modal-body').empty();
            jQuery('#modalAjax').children('div.modal-dialog').removeClass('modal-lg');
            jQuery('#modalAjax').removeClass().addClass('modal whmcs-modal fade');
            jQuery('#modalAjax .modal-title').html('Title');
            jQuery('#modalAjax .modal-submit').html('Submit')
                .removeClass()
                .addClass('btn btn-primary modal-submit')
                .removeAttr('id')
                .removeAttr('disabled');
            jQuery('#modalAjax .loader').show();
        });
    });
    
    function openModal(url, postData, modalTitle, modalSize, modalClass, submitLabel, submitId, hideClose) {
        //set the text of the modal title
        jQuery('#modalAjax .modal-title').html(modalTitle);
    
        // set the modal size via a class attribute
        if (modalSize) {
            jQuery('#modalAjax').children('div[class="modal-dialog"]').addClass(modalSize);
        }
        // set the modal class
        if (modalClass) {
            jQuery('#modalAjax').addClass(modalClass);
        }
    
        // set the modal class
        if (modalClass) {
            jQuery('#modalAjax').addClass(modalClass);
        }
    
        // set the text of the submit button
        if(!submitLabel){
           jQuery('#modalAjax .modal-submit').hide();
        } else {
            jQuery('#modalAjax .modal-submit').show().html(submitLabel);
            // set the button id so we can target the click function of it.
            if (submitId) {
                jQuery('#modalAjax .modal-submit').attr('id', submitId);
            }
        }
    
        if (hideClose) {
            jQuery('#modalAjaxClose').hide();
        }
    
        jQuery('#modalAjax .modal-body').html('');
    
        jQuery('#modalSkip').hide();
        jQuery('#modalAjax .modal-submit').prop('disabled', true);
    
        // show modal
        jQuery('#modalAjax').modal('show');
    
        // fetch modal content
        jQuery.post(url, postData, function(data) {
            updateAjaxModal(data);
        }, 'json').fail(function() {
            jQuery('#modalAjax .modal-body').html('An error occurred while communicating with the server. Please try again.');
            jQuery('#modalAjax .loader').fadeOut();
        });
    
        //define modal submit button click
        if (submitId) {
            /**
             * Reloading ajax modal multiple times on the same page can add
             * multiple "on" click events which submits the same form over
             * and over.
             * Remove the on click event with "off" to avoid multiple growl
             * and save events being run.
             *
             * @see http://api.jquery.com/off/
             */
            var submitButton = jQuery('#' + submitId);
            submitButton.off('click');
            submitButton.on('click', function() {
                var modalForm = jQuery('#modalAjax').find('form');
                jQuery('#modalAjax .loader').show();
                var modalPost = jQuery.post(modalForm.attr('action'), modalForm.serialize(),
                    function(data) {
                        updateAjaxModal(data);
                    }, 'json').fail(function() {
                        jQuery('#modalAjax .modal-body').html('An error occurred while communicating with the server. Please try again.');
                        jQuery('#modalAjax .loader').fadeOut();
                    }
                );
            })
        }
    }
    
    function updateAjaxModal(data) {
        if (data.dismiss) {
            dialogClose();
        }
        if (data.successMsg) {
            jQuery.growl.notice({ title: data.successMsgTitle, message: data.successMsg });
        }
        if (data.errorMsg) {
            jQuery.growl.warning({ title: data.errorMsgTitle, message: data.errorMsg });
        }
        if (data.title) {
            jQuery('#modalAjax .modal-title').html(data.title);
        }
        if (data.body) {
            jQuery('#modalAjax .modal-body').html(data.body);
        } else {
            if (data.url) {
                jQuery.post(data.url, '', function(data2) {
                    jQuery('#modalAjax').find('.modal-body').html(data2.body);
                }, 'json').fail(function() {
                    jQuery('#modalAjax').find('.modal-body').html('An error occurred while communicating with the server. Please try again.');
                    jQuery('#modalAjax').find('.loader').fadeOut();
                });
            }
        }
        if (data.submitlabel) {
            jQuery('#modalAjax .modal-submit').html(data.submitlabel).show();
            if (data.submitId) {
                jQuery('#modalAjax').find('.modal-submit').attr('id', data.submitId);
            }
        }
    
        if (data.submitId) {
            /**
             * Reloading ajax modal multiple times on the same page can add
             * multiple "on" click events which submits the same form over
             * and over.
             * Remove the on click event with "off" to avoid multiple growl
             * and save events being run.
             *
             * @see http://api.jquery.com/off/
             */
            var submitButton = jQuery('#' + data.submitId);
            submitButton.off('click');
            submitButton.on('click', function() {
                var modalForm = jQuery('#modalAjax').find('form');
                jQuery('#modalAjax .loader').show();
                var modalPost = jQuery.post(modalForm.attr('action'), modalForm.serialize(),
                    function(data) {
                        updateAjaxModal(data);
                    }, 'json').fail(function() {
                        jQuery('#modalAjax .modal-body').html('An error occurred while communicating with the server. Please try again.');
                        jQuery('#modalAjax .loader').fadeOut();
                    }
                );
            })
        }
    
        jQuery('#modalAjax .loader').fadeOut();
        jQuery('#modalAjax .modal-submit').removeProp('disabled');
    }
    
    // backwards compat for older dialog implementations
    
    function dialogSubmit() {
        jQuery('#modalAjax .modal-submit').prop("disabled", true);
        jQuery('#modalAjax .loader').show();
        jQuery.post('', jQuery('#modalAjax').find('form').serialize(),
            function(data) {
                updateAjaxModal(data);
            }, 'json').fail(function() {
                jQuery('#modalAjax .modal-body').html('An error occurred while communicating with the server. Please try again.');
                jQuery('#modalAjax .loader').fadeOut();
            });
    }
    
    function dialogClose() {
        jQuery('#modalAjax').modal('hide');
    }
    
    /*!
     * WHMCS Dynamic Dropdown Library
     *
     * Based upon Selectize.js
     *
     * @copyright Copyright (c) WHMCS Limited 2005-2016
     * @license http://www.whmcs.com/license/ WHMCS Eula
     */
    
    jQuery(document).ready(
        function()
        {
            var multiSelectize = jQuery('.selectize-multi-select'),
                standardSelectize = jQuery('.selectize-select'),
                tags = jQuery('.selectize-tags'),
                currentValue = '';
    
            jQuery(multiSelectize).selectize(
                {
                    plugins: ['remove_button', 'drag_drop'],
                    valueField: jQuery(multiSelectize).attr('data-value-field'),
                    labelField: 'name',
                    searchField: 'name',
                    allowEmptyOption: true,
                    create: false,
                    maxItems: null,
                    render: {
                        item: function(item, escape) {
                            return '<div><span class="name">' + escape(item.name) + '</span></div>';
                        },
                        option: function(item, escape) {
                            return '<div><span class="name">' + escape(item.name) + '</span></div>';
                        }
                    },
                    onItemRemove: function(value) {
                        if (jQuery(this)[0].$input[0].id == 'multi-view' && value != 'any' && value != 'flagged') {
                            jQuery(this)[0].removeItem('any', true);
                        }
                    }
                }
            );
    
            jQuery(standardSelectize).selectize(
                {
                    valueField: jQuery(standardSelectize).attr('data-value-field'),
                    labelField: 'name',
                    searchField: 'name',
                    allowEmptyOption: jQuery(standardSelectize).attr('data-allow-empty-option'),
                    create: false,
                    maxItems: 1,
                    render: {
                        item: function(item, escape) {
                            var colour = '';
                            if (typeof item.colour !== 'undefined' && item.colour !== '#FFF') {
                                colour = ' style="background-color: ' + escape(item.colour) + ';"';
                            }
                            return '<div' + colour + '><span class="name">' + escape(item.name) + '</span></div>';
                        },
                        option: function(item, escape) {
                            var colour = '';
                            if (typeof item.colour !== 'undefined' && item.colour !== '#FFF') {
                                colour = ' style="background-color: ' + escape(item.colour) + ';"';
                            }
                            return '<div' + colour + '><span class="name">' + escape(item.name) + '</span></div>';
                        }
                    },
                    onFocus: function() {
                        currentValue = this.getValue();
                        this.clear();
                    },
                    onBlur: function()
                    {
                        if (this.getValue() == '') {
                            this.setValue(currentValue);
                        }
                        if (
                            jQuery(standardSelectize).hasClass('selectize-auto-submit')
                            && currentValue !== this.getValue()
                        ) {
                            this.setValue(this.getValue());
                            jQuery(standardSelectize).parent('form').submit();
                        }
                    }
                }
            );
    
            jQuery(tags).selectize(
                {
                    plugins: ['remove_button'],
                    valueField: 'text',
                    searchField: ['text'],
                    delimiter: ',',
                    persist: false,
                    create: function(input) {
                        return {
                            value: input,
                            text: input
                        }
                    },
                    render: {
                        item: function(item, escape) {
                            return '<div><span class="item">' + escape(item.text) + '</span></div>';
                        },
                        option: function(item, escape) {
                            return '<div><span class="item">' + escape(item.text) + '</span></div>';
                        }
                    },
                    load: function(query, callback) {
                        if (!query.length) return callback();
                        jQuery.ajax({
                            url: window.location.href,
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                action: 'gettags',
                                q: query,
                                token: csrfToken
                            },
                            error: function() {
                                callback();
                            },
                            success: function(res) {
                                callback(res);
                            }
                        });
                    },
                    onItemAdd: function (value)
                    {
                        jQuery.ajax({
                            url: window.location.href,
                            type: 'POST',
                            data: {
                                action: 'addTag',
                                newTag: value,
                                token: csrfToken
                            }
                        });
    
                    },
                    onItemRemove: function(value)
                    {
                        jQuery.ajax(
                            {
                                url: window.location.href,
                                type: 'POST',
                                data: {
                                    action: 'removeTag',
                                    removeTag: value,
                                    token: csrfToken
                                }
                            }
                        );
                    }
                }
            );
        }
    );
    
    $(document).ready(function(){
        var minimisedWidgets = null;
        if(typeof(Storage) !== "undefined") {
            minimisedWidgets = JSON.parse(localStorage.getItem("minimisedWidgets"));
        }
        if (!minimisedWidgets) {
            minimisedWidgets = [];
        }
        $(".widget-minimise").click(function(e) {
            e.preventDefault();
            var obj = $(this);
            var icon = obj.find('i'),
                widget = obj.closest('.panel').data('widget');
            if (icon.hasClass('fa-chevron-up')) {
                obj.closest('.panel').find('.panel-body').slideUp('fast', function() {
                    icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
                    $('.home-widgets-container').masonry().masonry('reloadItems');
                });
                if (minimisedWidgets.indexOf(widget) == -1) {
                    minimisedWidgets.push(widget);
                }
            } else {
                obj.closest('.panel').find('.panel-body').slideDown('fast', function() {
                    icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
                    $('.home-widgets-container').masonry().masonry('reloadItems');
                });
                minimisedWidgets.splice(minimisedWidgets.indexOf(widget), 1);
            }
            if(typeof(Storage) !== "undefined") {
                localStorage.setItem("minimisedWidgets", JSON.stringify(minimisedWidgets));
            }
        });
        $(".widget-refresh").click(function(e) {
            e.preventDefault();
            var obj = $(this);
            var icon = obj.find('i');
            var widget = obj.closest('.panel').data('widget');
            var panelBody = obj.closest('.panel').find('.panel-body');
            icon.addClass('fa-spin');
            refreshWidget(widget, 'refresh=1');
        });
        var completedToggle = false;
        $(".widget-hide").click(function(e) {
            e.preventDefault();
            var obj = $(this),
                widget = obj.closest('.panel').data('widget');
            completedToggle = true;
    
            $('#panel' + widget).slideUp('fast', function() {
                $(this).addClass('hidden');
                $.post(WHMCS.adminUtils.getAdminRouteUrl('/widget/display/toggle/' + widget)).always(function() {
                    $('input[data-widget="' + widget + '"]').iCheck('uncheck');
                    completedToggle = false;
                });
                $('.home-widgets-container').masonry().masonry('reloadItems');
            });
        });
    
        $(document).on('ifToggled', '.display-widget', function(event) {
            var self = $(this),
                widget = $(this).data('widget'),
                widgetPanel = $('#panel' + widget);
    
            if (completedToggle) {
                return;
            }
    
            self.iCheck('disable');
            if (self.prop('checked')) {
                if (widgetPanel.hasClass('hidden')) {
                    self.parent('div').parent('label').parent('li').addClass('active');
                    widgetPanel.hide().removeClass('hidden').slideDown('fast', function() {
                        $.post(WHMCS.adminUtils.getAdminRouteUrl('/widget/display/toggle/' + widget))
                        .always(function() {
                            $('.home-widgets-container').masonry().masonry('reloadItems');
                            widgetPanel.find('.widget-refresh').click();
                            if ($('#widgetSettingsDropdown').hasClass('open') === false) {
                                $('#widgetSettings').dropdown('toggle');
                            }
                            self.iCheck('enable');
                        });
                    });
                }
            } else {
                if (widgetPanel.hasClass('hidden') === false) {
                    self.parent('div').parent('label').parent('li').removeClass('active');
                    widgetPanel.slideUp('fast', function() {
                        $(this).addClass('hidden');
                        $('.home-widgets-container').masonry().masonry('reloadItems');
                        $.post(WHMCS.adminUtils.getAdminRouteUrl('/widget/display/toggle/' + widget), function() {
                            if ($('#widgetSettingsDropdown').hasClass('open') === false) {
                                $('#widgetSettings').dropdown('toggle');
                            }
                        }, 'json').always(function() {
                            self.iCheck('enable');
                        });
                    });
                }
            }
        });
    
        $('input.display-widget').each(function(){
            var self = $(this),
                label = self.next(),
                label_text = label.text();
    
            label.remove();
            self.iCheck({
                inheritID: true,
                checkboxClass: 'icheckbox_flat-blue',
                increaseArea: '20%'
            });
        });
    
        minimisedWidgets.forEach(function(currentValue) {
            $('#panel' + currentValue).find('.panel-body').hide().end()
                .find('i.fa-chevron-up').removeClass('fa-chevron-up').addClass('fa-chevron-down');
        });
    });
    
    function refreshWidget(widgetName, requestString) {
        var obj = $('.panel[data-widget="' + widgetName + '"]');
        var panelBody = obj.find('.panel-body');
        var icon = obj.find('i.fa-refresh');
        panelBody.addClass('panel-loading');
        var jqxhr = $.post(WHMCS.adminUtils.getAdminRouteUrl('/widget/refresh&widget=' + widgetName + '&' + requestString),
            function(data) {
                panelBody.html(data.widgetOutput);
                panelBody.removeClass('panel-loading');
            }, 'json')
            .always(function() {
                icon.removeClass('fa-spin');
            });
    }
    
    /*!
     * Automation Status Javascript.
     *
     * @copyright Copyright (c) WHMCS Limited 2005-2016
     * @license http://www.whmcs.com/license/ WHMCS Eula
     */
     $(document).ready(function(){
        $('#statsContainer').on('click', '.btn-day-nav', function (e){
            e.preventDefault();
            loadAutomationStatsForDate($(this).data('date'));
        });
        $('#statsContainer').on('click', '.btn-viewing', function (e){
            e.preventDefault();
        });
        $('#graphContainer').on('click', '.graph-filter-metric a', function (e){
            e.preventDefault();
            $('.graph-filter-metric a').removeClass('active');
            $(this).addClass('active');
            refreshGraph();
        });
        $('#graphContainer').on('click', '.graph-filter-period a', function (e){
            e.preventDefault();
            $('.graph-filter-period a').removeClass('active');
            $(this).addClass('active');
            refreshGraph();
        });
    });
    
    function loadAutomationStatsForDate(date) {
        $('#statsContainer').css('opacity', '0.5');
            var jqxhr = $.post( "automationstatus.php", 'action=stats&date=' + date,
                function(data) {
                    $('#statsContainer').html(data.body);
                }).fail(function() {
                    jQuery.growl({ title: "", message: "Your session has expired. Please refresh to continue." });
                }).always(function() {
                    $('#statsContainer').css('opacity', '1');
                });
    }
    
    function refreshGraph() {
        $('#graphContainer').css('opacity', '0.5');
            var jqxhr = $.post( "automationstatus.php",'action=graph&metric=' + $('.graph-filter-metric a.active').attr('href') + '&period=' + $('.graph-filter-period a.active').attr('href'),
                function(data) {
                    $('#graphContainer').html(data.body);
                }).fail(function() {
                    jQuery.growl({ title: "", message: "Your session has expired. Please refresh to continue." });
                }).always(function() {
                    $('#graphContainer').css('opacity', '1');
                });
    }
    
    jQuery(document).ready(function() {
        var backupsContainer = jQuery('.database-backups');
    
        backupsContainer.find('.activate').on('click', function() {
            var self = jQuery(this),
                form = self.parent('form'),
                type = self.data('type'),
                request = form.serialize();
    
            self.prop('disabled', true).addClass('disabled');
    
            request += '&action=save&activate=1&type=' + type + '&token=' + csrfToken;
            jQuery.post(
                window.location.href,
                request,
                function(data) {
                    if (data.success === true) {
                        jQuery.growl.notice(
                            {
                                title: data.successMessageTitle,
                                message: data.successMessage
                            }
                        );
                        form.find('.save, .deactivate-start').removeClass('hidden');
                        self.addClass('hidden');
                        jQuery('#' + type + 'Label').toggleClass('label-default label-success').text(data.activeText);
                    } else {
                        jQuery.growl.error(
                            {
                                title: data.errorMessageTitle,
                                message: data.errorMessage
                            }
                        );
                    }
                },
                'json'
            ).always(function() {
                self.prop('disabled', false).removeClass('disabled');
            });
        });
    
        backupsContainer.find('.save').on('click', function() {
            var self = jQuery(this),
                form = self.parent('form'),
                type = self.data('type'),
                request = form.serialize();
    
    
            self.prop('disabled', true).addClass('disabled');
    
            request += '&action=save&type=' + type + '&token=' + csrfToken;
            jQuery.post(
                window.location.href,
                request,
                function(data) {
                    if (data.success === true) {
                        jQuery.growl.notice(
                            {
                                title: data.successMessageTitle,
                                message: data.successMessage
                            }
                        );
                    } else {
                        jQuery.growl.error(
                            {
                                title: data.errorMessageTitle,
                                message: data.errorMessage
                            }
                        );
                    }
                },
                'json'
            ).always(function() {
                self.prop('disabled', false).removeClass('disabled');
            });
        });
    
        backupsContainer.find('.test').on('click', function() {
            var self = jQuery(this),
                form = self.parent('form'),
                type = self.data('type'),
                request = form.serialize();
    
            self.prop('disabled', true).addClass('disabled');
            jQuery('#' + type + 'Container').removeClass('hidden');
            request += '&action=test&type=' + type + '&token=' + csrfToken;
            jQuery('#' + type + 'Test').hide()
                .removeClass('hidden alert-success alert-danger')
                .addClass('alert-default')
                .find('.extra-text').addClass('hidden').text('').end()
                .find('.default-text').removeClass('hidden').end()
                .slideDown('fast');
            jQuery.post(
                window.location.href,
                request,
                function(data) {
                    if (data.success === true) {
                        jQuery('#' + type + 'Test')
                            .addClass('alert-success')
                            .removeClass('alert-default alert-danger')
                            .find('.default-text').addClass('hidden').end()
                            .find('.extra-text').text(data.successMessage).removeClass('hidden').end()
                            .delay(3000).slideUp('slow');
                        form.find('.activate').prop('disabled', false).removeClass('disabled');
                    } else {
                        jQuery('#' + type + 'Test')
                            .addClass('alert-danger')
                            .removeClass('alert-default alert-success')
                            .find('.default-text').addClass('hidden').end()
                            .find('.extra-text').text(data.errorMessageTitle + ': ' + data.errorMessage).removeClass('hidden').end()
                            .delay(3000).slideUp('slow');
                    }
                },
                'json'
            ).always(function() {
                self.prop('disabled', false).removeClass('disabled');
                jQuery('#' + type + 'Container').addClass('hidden');
            });
    
        });
    
        backupsContainer.find('.deactivate-start').on('click', function() {
            var self = jQuery(this),
                form = self.parent('form'),
                type = self.data('type'),
                modal = jQuery('#modalConfirmDeactivate');
    
    
            jQuery('#confirmDeactivateYes').data('type', type);
            modal.modal('show');
        });
    
        jQuery('#modalConfirmDeactivate').find('.deactivate').on('click', function() {
            var self = jQuery(this),
                modal = jQuery('#modalConfirmDeactivate'),
                form = modal.parent('form'),
                type = self.data('type'),
                request = 'action=deactivate&type=' + type + '&token=' + csrfToken,
                mainForm = jQuery('.deactivate-start[data-type="' + type + '"]').parent('form');
    
            self.prop('disabled', true).addClass('disabled');
    
            jQuery.post(
                window.location.href,
                request,
                function(data) {
                    if (data.success === true) {
                        jQuery.growl.notice(
                            {
                                title: data.successMessageTitle,
                                message: data.successMessage
                            }
                        );
                        mainForm.find('.save, .deactivate-start').addClass('hidden');
                        mainForm.find('.activate').removeClass('hidden').prop('disabled', true);
                        if (type === 'email') {
                            mainForm.find('.activate').prop('disabled', false);
                        }
                        jQuery('#' + type + 'Label').toggleClass('label-default label-success').text(data.inactiveText);
                    } else {
                        jQuery.growl.error(
                            {
                                title: data.errorMessageTitle,
                                message: data.errorMessage
                            }
                        );
                    }
                },
                'json'
            ).always(function() {
                self.prop('disabled', false).removeClass('disabled');
                modal.modal('hide');
            });
        });
    
        backupsContainer.find('#inputDestination').on('change', function() {
            var destinationData = jQuery('#destinationData'),
                value = jQuery(this).val();
    
            if (value !== 'homedir' && destinationData.hasClass('hidden')) {
                destinationData.hide().removeClass('hidden').slideDown('fast');
            } else if (value === 'homedir' && !(destinationData.hasClass('hidden'))) {
                destinationData.slideUp('fast').addClass('hidden');
            }
        });
    });
    
    /*!
     * WHMCS Module Queue Javascript Functions
     *
     * @copyright Copyright (c) WHMCS Limited 2005-2016
     * @license http://www.whmcs.com/license/ WHMCS Eula
     */
    jQuery(document).ready(function() {
        var moduleQueueRetryAll = jQuery('button.retry-all');
        if (moduleQueueRetryAll.length) {
            var processed = false,
                queueTimeout = null,
                count = 0;
    
            jQuery('button.retry').click(function() {
                processed = false;
                var self = jQuery(this),
                    entryId = jQuery(this).data('entry-id'),
                    processingEntry = jQuery('div#processing-entry-' + entryId);
    
                self.attr('disabled', 'disabled').addClass('disabled').find('i').addClass('fa-spin').end();
                if (queueTimeout) {
                    processingEntry.find('div.queued').hide().end()
                        .find('div.processing').show().end();
                } else {
                    processingEntry.find('div.messages').children('div').hide().end()
                        .find('div.processing').show().end().end()
                        .hide().removeClass('hidden').slideDown('fast');
                }
                var connection = jQuery.post(
                    window.location.pathname,
                    {
                        token: csrfToken,
                        action: 'retry',
                        id: entryId
                    },
                    'json'
                );
    
                connection.done(function(data) {
                    if (data.error) {
                        processingEntry.find('div.processing').hide().end()
                            .find('div.error').find('span').html(data.message).parent().show().end();
                        jQuery('#last-error-' + entryId).html(data.errorMessage);
                        jQuery('div#entry-' + entryId).find('small.last-attempt').find('span').html(data.lastAttempt);
                        self.removeAttr('disabled').removeClass('disabled').find('i').removeClass('fa-spin').end();
                        count++;
                    }
                    if (data.completed) {
                        jQuery('div#entry-' + entryId).find('div.action-buttons').find('button').removeClass('retry')
                            .attr('disabled', 'disabled').addClass('disabled')
                            .find('i.fa-spin').removeClass('fa-spin').end();
                        processingEntry.find('div.processing').slideUp('fast').end()
                            .find('div.success').slideDown('fast').end();
                    }
                });
    
                connection.always(function() {
                    processed = true;
                });
            });
    
            jQuery('button.resolve').click(function() {
                var self = jQuery(this),
                    entryId = jQuery(this).data('entry-id'),
                    processingEntry = jQuery('div#processing-entry-' + entryId);
    
                self.attr('disabled', 'disabled').addClass('disabled');
    
                processingEntry.find('div.messages').children('div').hide().end()
                    .find('div.processing').show().end().end()
                    .hide().removeClass('hidden').slideDown('fast');
    
                var connection = jQuery.post(
                    window.location.pathname,
                    {
                        token: csrfToken,
                        action: 'resolve',
                        id: entryId
                    },
                    'json'
                );
    
                connection.done(function(data) {
                    if (data.completed) {
                        jQuery('div#entry-' + entryId).find('div.action-buttons').find('button').removeClass('retry')
                            .attr('disabled', 'disabled').addClass('disabled').end();
                        processingEntry.find('div.processing').slideUp('fast').end()
                            .find('div.success').find('span').html(data.message).parent().slideDown('fast').end();
                    } else {
                        processingEntry.find('div.processing').slideUp('fast').end()
                            .find('div.error').find('span').html(data.message).parent().slideDown('fast').end();
                        self.removeAttr('disabled').removeClass('disabled');
                    }
    
                });
            });
    
            moduleQueueRetryAll.click(function () {
                jQuery(this).attr('disabled', 'disabled').addClass('disabled')
                    .find('i').addClass('fa-spin').end();
                var items = jQuery('button.retry');
                processed = true;
                count = 0;
    
                items.each(function(index) {
                    var entryId = jQuery(this).data('entry-id');
                    jQuery('div#processing-entry-' + entryId).find('div.messages').children('div').hide().end()
                        .find('div.queued').show().end().end()
                        .hide().removeClass('hidden').slideDown('fast');
                });
    
                queueTimeout = setTimeout(nextClick, 1000);
            });
    
            function nextClick()
            {
                if (processed) {
                    var button = jQuery('button.retry:eq(' + count + ')');
                    if (button.length) {
                        button.click();
                    } else {
                        clearTimeout(queueTimeout);
                        queueTimeout = null;
                        moduleQueueRetryAll.removeAttr('disabled').removeClass('disabled')
                            .find('i').removeClass('fa-spin').end();
                        return;
                    }
                }
                queueTimeout = setTimeout(nextClick, 1000);
            }
        }
    });
    
    /*!
     * WHMCS MarketConnect Admin JS Functions
     *
     * @copyright Copyright (c) WHMCS Limited 2005-2017
     * @license http://www.whmcs.com/license/ WHMCS Eula
     */
    jQuery(document).ready(function() {
        jQuery(document).on('click', '#btnMcServiceRefresh', function(e) {
            e.preventDefault();
            var btn = $(this);
            btn.find('i').addClass('fa-spin');
            $.post({
                url: 'clientsservices.php',
                data: btn.attr('href') + '&token=' + csrfToken,
                success: function (data) {
                    $('#mcServiceManagementWrapper').replaceWith(data.statusOutput);
                    btn.find('i').removeClass('fa-spin');
                }
            });
        });
        jQuery(document).on('click', '#btnMcCancelOrder', function(e) {
            swal({
                title: 'Are you sure?',
                html: true,
                text: 'Cancelling this order will result in the service immediately ceasing to function.<br><br>You will automatically receive a credit if within the credit period. <a href="https://go.whmcs.com/1281/marketconnect-credit-terms" target="_blank">See credit period terms</a>',
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, cancel it',
                cancelButtonText: 'No'
            },
            function(){
                runModuleCommand('terminate');
            });
        });
        jQuery(document).on('click', '#mcServiceManagementWrapper .btn:not(.open-modal,.btn-refresh,.btn-cancel)', function(e) {
            e.preventDefault();
            var button = $(this);
            var request = button.attr('href');
    
            // If button is disabled, don't execute action
            if (button.attr('disabled') == 'disabled') {
                return;
            }
    
            button.find('i').addClass('fa-spin').addClass('fa-spinner');
    
            $.post('clientsservices.php', request + '&token=' + csrfToken,
                function(data) {
    
                    if (data.redirectUrl) {
    
                        window.open(data.redirectUrl);
    
                    } else if (data.growl) {
    
                        if (data.growl.type == 'error') {
                            $.growl.error({ title: '', message: data.growl.message });
                        } else {
                            $.growl.notice({ title: '', message: data.growl.message });
                        }
    
                    }
    
                    button.find('i').removeClass('fa-spin').removeClass('fa-spinner');
                }, 'json');
        });
    });
    
    /*! DataTables 1.10.12
     * Â©2008-2015 SpryMedia Ltd - datatables.net/license
     */
    
    /**
     * @summary     DataTables
     * @description Paginate, search and order HTML tables
     * @version     1.10.12
     * @file        jquery.dataTables.js
     * @author      SpryMedia Ltd (www.sprymedia.co.uk)
     * @contact     www.sprymedia.co.uk/contact
     * @copyright   Copyright 2008-2015 SpryMedia Ltd.
     *
     * This source file is free software, available under the following license:
     *   MIT license - http://datatables.net/license
     *
     * This source file is distributed in the hope that it will be useful, but
     * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
     * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
     *
     * For details please refer to: http://www.datatables.net
     */
    
    /*jslint evil: true, undef: true, browser: true */
    /*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/
    
    (function( factory ) {
        "use strict";
    
        if ( typeof define === 'function' && define.amd ) {
            // AMD
            define( ['jquery'], function ( $ ) {
                return factory( $, window, document );
            } );
        }
        else if ( typeof exports === 'object' ) {
            // CommonJS
            module.exports = function (root, $) {
                if ( ! root ) {
                    // CommonJS environments without a window global must pass a
                    // root. This will give an error otherwise
                    root = window;
                }
    
                if ( ! $ ) {
                    $ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
                        require('jquery') :
                        require('jquery')( root );
                }
    
                return factory( $, root, root.document );
            };
        }
        else {
            // Browser
            factory( jQuery, window, document );
        }
    }
    (function( $, window, document, undefined ) {
        "use strict";
    
        /**
         * DataTables is a plug-in for the jQuery Javascript library. It is a highly
         * flexible tool, based upon the foundations of progressive enhancement,
         * which will add advanced interaction controls to any HTML table. For a
         * full list of features please refer to
         * [DataTables.net](href="http://datatables.net).
         *
         * Note that the `DataTable` object is not a global variable but is aliased
         * to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
         * be  accessed.
         *
         *  @class
         *  @param {object} [init={}] Configuration object for DataTables. Options
         *    are defined by {@link DataTable.defaults}
         *  @requires jQuery 1.7+
         *
         *  @example
         *    // Basic initialisation
         *    $(document).ready( function {
         *      $('#example').dataTable();
         *    } );
         *
         *  @example
         *    // Initialisation with configuration options - in this case, disable
         *    // pagination and sorting.
         *    $(document).ready( function {
         *      $('#example').dataTable( {
         *        "paginate": false,
         *        "sort": false
         *      } );
         *    } );
         */
        var DataTable = function ( options )
        {
            /**
             * Perform a jQuery selector action on the table's TR elements (from the tbody) and
             * return the resulting jQuery object.
             *  @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
             *  @param {object} [oOpts] Optional parameters for modifying the rows to be included
             *  @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
             *    criterion ("applied") or all TR elements (i.e. no filter).
             *  @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
             *    Can be either 'current', whereby the current sorting of the table is used, or
             *    'original' whereby the original order the data was read into the table is used.
             *  @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
             *    ("current") or not ("all"). If 'current' is given, then order is assumed to be
             *    'current' and filter is 'applied', regardless of what they might be given as.
             *  @returns {object} jQuery object, filtered by the given selector.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Highlight every second row
             *      oTable.$('tr:odd').css('backgroundColor', 'blue');
             *    } );
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Filter to rows with 'Webkit' in them, add a background colour and then
             *      // remove the filter, thus highlighting the 'Webkit' rows only.
             *      oTable.fnFilter('Webkit');
             *      oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
             *      oTable.fnFilter('');
             *    } );
             */
            this.$ = function ( sSelector, oOpts )
            {
                return this.api(true).$( sSelector, oOpts );
            };
            
            
            /**
             * Almost identical to $ in operation, but in this case returns the data for the matched
             * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
             * rather than any descendants, so the data can be obtained for the row/cell. If matching
             * rows are found, the data returned is the original data array/object that was used to
             * create the row (or a generated array if from a DOM source).
             *
             * This method is often useful in-combination with $ where both functions are given the
             * same parameters and the array indexes will match identically.
             *  @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
             *  @param {object} [oOpts] Optional parameters for modifying the rows to be included
             *  @param {string} [oOpts.filter=none] Select elements that meet the current filter
             *    criterion ("applied") or all elements (i.e. no filter).
             *  @param {string} [oOpts.order=current] Order of the data in the processed array.
             *    Can be either 'current', whereby the current sorting of the table is used, or
             *    'original' whereby the original order the data was read into the table is used.
             *  @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
             *    ("current") or not ("all"). If 'current' is given, then order is assumed to be
             *    'current' and filter is 'applied', regardless of what they might be given as.
             *  @returns {array} Data for the matched elements. If any elements, as a result of the
             *    selector, were not TR, TD or TH elements in the DataTable, they will have a null
             *    entry in the array.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Get the data from the first row in the table
             *      var data = oTable._('tr:first');
             *
             *      // Do something useful with the data
             *      alert( "First cell is: "+data[0] );
             *    } );
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Filter to 'Webkit' and get all data for
             *      oTable.fnFilter('Webkit');
             *      var data = oTable._('tr', {"search": "applied"});
             *
             *      // Do something with the data
             *      alert( data.length+" rows matched the search" );
             *    } );
             */
            this._ = function ( sSelector, oOpts )
            {
                return this.api(true).rows( sSelector, oOpts ).data();
            };
            
            
            /**
             * Create a DataTables Api instance, with the currently selected tables for
             * the Api's context.
             * @param {boolean} [traditional=false] Set the API instance's context to be
             *   only the table referred to by the `DataTable.ext.iApiIndex` option, as was
             *   used in the API presented by DataTables 1.9- (i.e. the traditional mode),
             *   or if all tables captured in the jQuery object should be used.
             * @return {DataTables.Api}
             */
            this.api = function ( traditional )
            {
                return traditional ?
                    new _Api(
                        _fnSettingsFromNode( this[ _ext.iApiIndex ] )
                    ) :
                    new _Api( this );
            };
            
            
            /**
             * Add a single new row or multiple rows of data to the table. Please note
             * that this is suitable for client-side processing only - if you are using
             * server-side processing (i.e. "bServerSide": true), then to add data, you
             * must add it to the data source, i.e. the server-side, through an Ajax call.
             *  @param {array|object} data The data to be added to the table. This can be:
             *    <ul>
             *      <li>1D array of data - add a single row with the data provided</li>
             *      <li>2D array of arrays - add multiple rows in a single call</li>
             *      <li>object - data object when using <i>mData</i></li>
             *      <li>array of objects - multiple data objects when using <i>mData</i></li>
             *    </ul>
             *  @param {bool} [redraw=true] redraw the table or not
             *  @returns {array} An array of integers, representing the list of indexes in
             *    <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
             *    the table.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    // Global var for counter
             *    var giCount = 2;
             *
             *    $(document).ready(function() {
             *      $('#example').dataTable();
             *    } );
             *
             *    function fnClickAddRow() {
             *      $('#example').dataTable().fnAddData( [
             *        giCount+".1",
             *        giCount+".2",
             *        giCount+".3",
             *        giCount+".4" ]
             *      );
             *
             *      giCount++;
             *    }
             */
            this.fnAddData = function( data, redraw )
            {
                var api = this.api( true );
            
                /* Check if we want to add multiple rows or not */
                var rows = $.isArray(data) && ( $.isArray(data[0]) || $.isPlainObject(data[0]) ) ?
                    api.rows.add( data ) :
                    api.row.add( data );
            
                if ( redraw === undefined || redraw ) {
                    api.draw();
                }
            
                return rows.flatten().toArray();
            };
            
            
            /**
             * This function will make DataTables recalculate the column sizes, based on the data
             * contained in the table and the sizes applied to the columns (in the DOM, CSS or
             * through the sWidth parameter). This can be useful when the width of the table's
             * parent element changes (for example a window resize).
             *  @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable( {
             *        "sScrollY": "200px",
             *        "bPaginate": false
             *      } );
             *
             *      $(window).bind('resize', function () {
             *        oTable.fnAdjustColumnSizing();
             *      } );
             *    } );
             */
            this.fnAdjustColumnSizing = function ( bRedraw )
            {
                var api = this.api( true ).columns.adjust();
                var settings = api.settings()[0];
                var scroll = settings.oScroll;
            
                if ( bRedraw === undefined || bRedraw ) {
                    api.draw( false );
                }
                else if ( scroll.sX !== "" || scroll.sY !== "" ) {
                    /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
                    _fnScrollDraw( settings );
                }
            };
            
            
            /**
             * Quickly and simply clear a table
             *  @param {bool} [bRedraw=true] redraw the table or not
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
             *      oTable.fnClearTable();
             *    } );
             */
            this.fnClearTable = function( bRedraw )
            {
                var api = this.api( true ).clear();
            
                if ( bRedraw === undefined || bRedraw ) {
                    api.draw();
                }
            };
            
            
            /**
             * The exact opposite of 'opening' a row, this function will close any rows which
             * are currently 'open'.
             *  @param {node} nTr the table row to 'close'
             *  @returns {int} 0 on success, or 1 if failed (can't find the row)
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable;
             *
             *      // 'open' an information row when a row is clicked on
             *      $('#example tbody tr').click( function () {
             *        if ( oTable.fnIsOpen(this) ) {
             *          oTable.fnClose( this );
             *        } else {
             *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
             *        }
             *      } );
             *
             *      oTable = $('#example').dataTable();
             *    } );
             */
            this.fnClose = function( nTr )
            {
                this.api( true ).row( nTr ).child.hide();
            };
            
            
            /**
             * Remove a row for the table
             *  @param {mixed} target The index of the row from aoData to be deleted, or
             *    the TR element you want to delete
             *  @param {function|null} [callBack] Callback function
             *  @param {bool} [redraw=true] Redraw the table or not
             *  @returns {array} The row that was deleted
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Immediately remove the first row
             *      oTable.fnDeleteRow( 0 );
             *    } );
             */
            this.fnDeleteRow = function( target, callback, redraw )
            {
                var api = this.api( true );
                var rows = api.rows( target );
                var settings = rows.settings()[0];
                var data = settings.aoData[ rows[0][0] ];
            
                rows.remove();
            
                if ( callback ) {
                    callback.call( this, settings, data );
                }
            
                if ( redraw === undefined || redraw ) {
                    api.draw();
                }
            
                return data;
            };
            
            
            /**
             * Restore the table to it's original state in the DOM by removing all of DataTables
             * enhancements, alterations to the DOM structure of the table and event listeners.
             *  @param {boolean} [remove=false] Completely remove the table from the DOM
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      // This example is fairly pointless in reality, but shows how fnDestroy can be used
             *      var oTable = $('#example').dataTable();
             *      oTable.fnDestroy();
             *    } );
             */
            this.fnDestroy = function ( remove )
            {
                this.api( true ).destroy( remove );
            };
            
            
            /**
             * Redraw the table
             *  @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
             *      oTable.fnDraw();
             *    } );
             */
            this.fnDraw = function( complete )
            {
                // Note that this isn't an exact match to the old call to _fnDraw - it takes
                // into account the new data, but can hold position.
                this.api( true ).draw( complete );
            };
            
            
            /**
             * Filter the input based on data
             *  @param {string} sInput String to filter the table on
             *  @param {int|null} [iColumn] Column to limit filtering to
             *  @param {bool} [bRegex=false] Treat as regular expression or not
             *  @param {bool} [bSmart=true] Perform smart filtering or not
             *  @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
             *  @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Sometime later - filter...
             *      oTable.fnFilter( 'test string' );
             *    } );
             */
            this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive )
            {
                var api = this.api( true );
            
                if ( iColumn === null || iColumn === undefined ) {
                    api.search( sInput, bRegex, bSmart, bCaseInsensitive );
                }
                else {
                    api.column( iColumn ).search( sInput, bRegex, bSmart, bCaseInsensitive );
                }
            
                api.draw();
            };
            
            
            /**
             * Get the data for the whole table, an individual row or an individual cell based on the
             * provided parameters.
             *  @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as
             *    a TR node then the data source for the whole row will be returned. If given as a
             *    TD/TH cell node then iCol will be automatically calculated and the data for the
             *    cell returned. If given as an integer, then this is treated as the aoData internal
             *    data index for the row (see fnGetPosition) and the data for that row used.
             *  @param {int} [col] Optional column index that you want the data of.
             *  @returns {array|object|string} If mRow is undefined, then the data for all rows is
             *    returned. If mRow is defined, just data for that row, and is iCol is
             *    defined, only data for the designated cell is returned.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    // Row data
             *    $(document).ready(function() {
             *      oTable = $('#example').dataTable();
             *
             *      oTable.$('tr').click( function () {
             *        var data = oTable.fnGetData( this );
             *        // ... do something with the array / object of data for the row
             *      } );
             *    } );
             *
             *  @example
             *    // Individual cell data
             *    $(document).ready(function() {
             *      oTable = $('#example').dataTable();
             *
             *      oTable.$('td').click( function () {
             *        var sData = oTable.fnGetData( this );
             *        alert( 'The cell clicked on had the value of '+sData );
             *      } );
             *    } );
             */
            this.fnGetData = function( src, col )
            {
                var api = this.api( true );
            
                if ( src !== undefined ) {
                    var type = src.nodeName ? src.nodeName.toLowerCase() : '';
            
                    return col !== undefined || type == 'td' || type == 'th' ?
                        api.cell( src, col ).data() :
                        api.row( src ).data() || null;
                }
            
                return api.data().toArray();
            };
            
            
            /**
             * Get an array of the TR nodes that are used in the table's body. Note that you will
             * typically want to use the '$' API method in preference to this as it is more
             * flexible.
             *  @param {int} [iRow] Optional row index for the TR element you want
             *  @returns {array|node} If iRow is undefined, returns an array of all TR elements
             *    in the table's body, or iRow is defined, just the TR element requested.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Get the nodes from the table
             *      var nNodes = oTable.fnGetNodes( );
             *    } );
             */
            this.fnGetNodes = function( iRow )
            {
                var api = this.api( true );
            
                return iRow !== undefined ?
                    api.row( iRow ).node() :
                    api.rows().nodes().flatten().toArray();
            };
            
            
            /**
             * Get the array indexes of a particular cell from it's DOM element
             * and column index including hidden columns
             *  @param {node} node this can either be a TR, TD or TH in the table's body
             *  @returns {int} If nNode is given as a TR, then a single index is returned, or
             *    if given as a cell, an array of [row index, column index (visible),
             *    column index (all)] is given.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      $('#example tbody td').click( function () {
             *        // Get the position of the current data from the node
             *        var aPos = oTable.fnGetPosition( this );
             *
             *        // Get the data array for this row
             *        var aData = oTable.fnGetData( aPos[0] );
             *
             *        // Update the data array and return the value
             *        aData[ aPos[1] ] = 'clicked';
             *        this.innerHTML = 'clicked';
             *      } );
             *
             *      // Init DataTables
             *      oTable = $('#example').dataTable();
             *    } );
             */
            this.fnGetPosition = function( node )
            {
                var api = this.api( true );
                var nodeName = node.nodeName.toUpperCase();
            
                if ( nodeName == 'TR' ) {
                    return api.row( node ).index();
                }
                else if ( nodeName == 'TD' || nodeName == 'TH' ) {
                    var cell = api.cell( node ).index();
            
                    return [
                        cell.row,
                        cell.columnVisible,
                        cell.column
                    ];
                }
                return null;
            };
            
            
            /**
             * Check to see if a row is 'open' or not.
             *  @param {node} nTr the table row to check
             *  @returns {boolean} true if the row is currently open, false otherwise
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable;
             *
             *      // 'open' an information row when a row is clicked on
             *      $('#example tbody tr').click( function () {
             *        if ( oTable.fnIsOpen(this) ) {
             *          oTable.fnClose( this );
             *        } else {
             *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
             *        }
             *      } );
             *
             *      oTable = $('#example').dataTable();
             *    } );
             */
            this.fnIsOpen = function( nTr )
            {
                return this.api( true ).row( nTr ).child.isShown();
            };
            
            
            /**
             * This function will place a new row directly after a row which is currently
             * on display on the page, with the HTML contents that is passed into the
             * function. This can be used, for example, to ask for confirmation that a
             * particular record should be deleted.
             *  @param {node} nTr The table row to 'open'
             *  @param {string|node|jQuery} mHtml The HTML to put into the row
             *  @param {string} sClass Class to give the new TD cell
             *  @returns {node} The row opened. Note that if the table row passed in as the
             *    first parameter, is not found in the table, this method will silently
             *    return.
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable;
             *
             *      // 'open' an information row when a row is clicked on
             *      $('#example tbody tr').click( function () {
             *        if ( oTable.fnIsOpen(this) ) {
             *          oTable.fnClose( this );
             *        } else {
             *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
             *        }
             *      } );
             *
             *      oTable = $('#example').dataTable();
             *    } );
             */
            this.fnOpen = function( nTr, mHtml, sClass )
            {
                return this.api( true )
                    .row( nTr )
                    .child( mHtml, sClass )
                    .show()
                    .child()[0];
            };
            
            
            /**
             * Change the pagination - provides the internal logic for pagination in a simple API
             * function. With this function you can have a DataTables table go to the next,
             * previous, first or last pages.
             *  @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
             *    or page number to jump to (integer), note that page 0 is the first page.
             *  @param {bool} [bRedraw=true] Redraw the table or not
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *      oTable.fnPageChange( 'next' );
             *    } );
             */
            this.fnPageChange = function ( mAction, bRedraw )
            {
                var api = this.api( true ).page( mAction );
            
                if ( bRedraw === undefined || bRedraw ) {
                    api.draw(false);
                }
            };
            
            
            /**
             * Show a particular column
             *  @param {int} iCol The column whose display should be changed
             *  @param {bool} bShow Show (true) or hide (false) the column
             *  @param {bool} [bRedraw=true] Redraw the table or not
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Hide the second column after initialisation
             *      oTable.fnSetColumnVis( 1, false );
             *    } );
             */
            this.fnSetColumnVis = function ( iCol, bShow, bRedraw )
            {
                var api = this.api( true ).column( iCol ).visible( bShow );
            
                if ( bRedraw === undefined || bRedraw ) {
                    api.columns.adjust().draw();
                }
            };
            
            
            /**
             * Get the settings for a particular table for external manipulation
             *  @returns {object} DataTables settings object. See
             *    {@link DataTable.models.oSettings}
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *      var oSettings = oTable.fnSettings();
             *
             *      // Show an example parameter from the settings
             *      alert( oSettings._iDisplayStart );
             *    } );
             */
            this.fnSettings = function()
            {
                return _fnSettingsFromNode( this[_ext.iApiIndex] );
            };
            
            
            /**
             * Sort the table by a particular column
             *  @param {int} iCol the data index to sort on. Note that this will not match the
             *    'display index' if you have hidden data entries
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Sort immediately with columns 0 and 1
             *      oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
             *    } );
             */
            this.fnSort = function( aaSort )
            {
                this.api( true ).order( aaSort ).draw();
            };
            
            
            /**
             * Attach a sort listener to an element for a given column
             *  @param {node} nNode the element to attach the sort listener to
             *  @param {int} iColumn the column that a click on this node will sort on
             *  @param {function} [fnCallback] callback function when sort is run
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *
             *      // Sort on column 1, when 'sorter' is clicked on
             *      oTable.fnSortListener( document.getElementById('sorter'), 1 );
             *    } );
             */
            this.fnSortListener = function( nNode, iColumn, fnCallback )
            {
                this.api( true ).order.listener( nNode, iColumn, fnCallback );
            };
            
            
            /**
             * Update a table cell or row - this method will accept either a single value to
             * update the cell with, an array of values with one element for each column or
             * an object in the same format as the original data source. The function is
             * self-referencing in order to make the multi column updates easier.
             *  @param {object|array|string} mData Data to update the cell/row with
             *  @param {node|int} mRow TR element you want to update or the aoData index
             *  @param {int} [iColumn] The column to update, give as null or undefined to
             *    update a whole row.
             *  @param {bool} [bRedraw=true] Redraw the table or not
             *  @param {bool} [bAction=true] Perform pre-draw actions or not
             *  @returns {int} 0 on success, 1 on error
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *      oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
             *      oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row
             *    } );
             */
            this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction )
            {
                var api = this.api( true );
            
                if ( iColumn === undefined || iColumn === null ) {
                    api.row( mRow ).data( mData );
                }
                else {
                    api.cell( mRow, iColumn ).data( mData );
                }
            
                if ( bAction === undefined || bAction ) {
                    api.columns.adjust();
                }
            
                if ( bRedraw === undefined || bRedraw ) {
                    api.draw();
                }
                return 0;
            };
            
            
            /**
             * Provide a common method for plug-ins to check the version of DataTables being used, in order
             * to ensure compatibility.
             *  @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
             *    formats "X" and "X.Y" are also acceptable.
             *  @returns {boolean} true if this version of DataTables is greater or equal to the required
             *    version, or false if this version of DataTales is not suitable
             *  @method
             *  @dtopt API
             *  @deprecated Since v1.10
             *
             *  @example
             *    $(document).ready(function() {
             *      var oTable = $('#example').dataTable();
             *      alert( oTable.fnVersionCheck( '1.9.0' ) );
             *    } );
             */
            this.fnVersionCheck = _ext.fnVersionCheck;
            
    
            var _that = this;
            var emptyInit = options === undefined;
            var len = this.length;
    
            if ( emptyInit ) {
                options = {};
            }
    
            this.oApi = this.internal = _ext.internal;
    
            // Extend with old style plug-in API methods
            for ( var fn in DataTable.ext.internal ) {
                if ( fn ) {
                    this[fn] = _fnExternApiFunc(fn);
                }
            }
    
            this.each(function() {
                // For each initialisation we want to give it a clean initialisation
                // object that can be bashed around
                var o = {};
                var oInit = len > 1 ? // optimisation for single table case
                    _fnExtend( o, options, true ) :
                    options;
    
                /*global oInit,_that,emptyInit*/
                var i=0, iLen, j, jLen, k, kLen;
                var sId = this.getAttribute( 'id' );
                var bInitHandedOff = false;
                var defaults = DataTable.defaults;
                var $this = $(this);
                
                
                /* Sanity check */
                if ( this.nodeName.toLowerCase() != 'table' )
                {
                    _fnLog( null, 0, 'Non-table node initialisation ('+this.nodeName+')', 2 );
                    return;
                }
                
                /* Backwards compatibility for the defaults */
                _fnCompatOpts( defaults );
                _fnCompatCols( defaults.column );
                
                /* Convert the camel-case defaults to Hungarian */
                _fnCamelToHungarian( defaults, defaults, true );
                _fnCamelToHungarian( defaults.column, defaults.column, true );
                
                /* Setting up the initialisation object */
                _fnCamelToHungarian( defaults, $.extend( oInit, $this.data() ) );
                
                
                
                /* Check to see if we are re-initialising a table */
                var allSettings = DataTable.settings;
                for ( i=0, iLen=allSettings.length ; i<iLen ; i++ )
                {
                    var s = allSettings[i];
                
                    /* Base check on table node */
                    if ( s.nTable == this || s.nTHead.parentNode == this || (s.nTFoot && s.nTFoot.parentNode == this) )
                    {
                        var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve;
                        var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy;
                
                        if ( emptyInit || bRetrieve )
                        {
                            return s.oInstance;
                        }
                        else if ( bDestroy )
                        {
                            s.oInstance.fnDestroy();
                            break;
                        }
                        else
                        {
                            _fnLog( s, 0, 'Cannot reinitialise DataTable', 3 );
                            return;
                        }
                    }
                
                    /* If the element we are initialising has the same ID as a table which was previously
                     * initialised, but the table nodes don't match (from before) then we destroy the old
                     * instance by simply deleting it. This is under the assumption that the table has been
                     * destroyed by other methods. Anyone using non-id selectors will need to do this manually
                     */
                    if ( s.sTableId == this.id )
                    {
                        allSettings.splice( i, 1 );
                        break;
                    }
                }
                
                /* Ensure the table has an ID - required for accessibility */
                if ( sId === null || sId === "" )
                {
                    sId = "DataTables_Table_"+(DataTable.ext._unique++);
                    this.id = sId;
                }
                
                /* Create the settings object for this table and set some of the default parameters */
                var oSettings = $.extend( true, {}, DataTable.models.oSettings, {
                    "sDestroyWidth": $this[0].style.width,
                    "sInstance":     sId,
                    "sTableId":      sId
                } );
                oSettings.nTable = this;
                oSettings.oApi   = _that.internal;
                oSettings.oInit  = oInit;
                
                allSettings.push( oSettings );
                
                // Need to add the instance after the instance after the settings object has been added
                // to the settings array, so we can self reference the table instance if more than one
                oSettings.oInstance = (_that.length===1) ? _that : $this.dataTable();
                
                // Backwards compatibility, before we apply all the defaults
                _fnCompatOpts( oInit );
                
                if ( oInit.oLanguage )
                {
                    _fnLanguageCompat( oInit.oLanguage );
                }
                
                // If the length menu is given, but the init display length is not, use the length menu
                if ( oInit.aLengthMenu && ! oInit.iDisplayLength )
                {
                    oInit.iDisplayLength = $.isArray( oInit.aLengthMenu[0] ) ?
                        oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0];
                }
                
                // Apply the defaults and init options to make a single init object will all
                // options defined from defaults and instance options.
                oInit = _fnExtend( $.extend( true, {}, defaults ), oInit );
                
                
                // Map the initialisation options onto the settings object
                _fnMap( oSettings.oFeatures, oInit, [
                    "bPaginate",
                    "bLengthChange",
                    "bFilter",
                    "bSort",
                    "bSortMulti",
                    "bInfo",
                    "bProcessing",
                    "bAutoWidth",
                    "bSortClasses",
                    "bServerSide",
                    "bDeferRender"
                ] );
                _fnMap( oSettings, oInit, [
                    "asStripeClasses",
                    "ajax",
                    "fnServerData",
                    "fnFormatNumber",
                    "sServerMethod",
                    "aaSorting",
                    "aaSortingFixed",
                    "aLengthMenu",
                    "sPaginationType",
                    "sAjaxSource",
                    "sAjaxDataProp",
                    "iStateDuration",
                    "sDom",
                    "bSortCellsTop",
                    "iTabIndex",
                    "fnStateLoadCallback",
                    "fnStateSaveCallback",
                    "renderer",
                    "searchDelay",
                    "rowId",
                    [ "iCookieDuration", "iStateDuration" ], // backwards compat
                    [ "oSearch", "oPreviousSearch" ],
                    [ "aoSearchCols", "aoPreSearchCols" ],
                    [ "iDisplayLength", "_iDisplayLength" ],
                    [ "bJQueryUI", "bJUI" ]
                ] );
                _fnMap( oSettings.oScroll, oInit, [
                    [ "sScrollX", "sX" ],
                    [ "sScrollXInner", "sXInner" ],
                    [ "sScrollY", "sY" ],
                    [ "bScrollCollapse", "bCollapse" ]
                ] );
                _fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" );
                
                /* Callback functions which are array driven */
                _fnCallbackReg( oSettings, 'aoDrawCallback',       oInit.fnDrawCallback,      'user' );
                _fnCallbackReg( oSettings, 'aoServerParams',       oInit.fnServerParams,      'user' );
                _fnCallbackReg( oSettings, 'aoStateSaveParams',    oInit.fnStateSaveParams,   'user' );
                _fnCallbackReg( oSettings, 'aoStateLoadParams',    oInit.fnStateLoadParams,   'user' );
                _fnCallbackReg( oSettings, 'aoStateLoaded',        oInit.fnStateLoaded,       'user' );
                _fnCallbackReg( oSettings, 'aoRowCallback',        oInit.fnRowCallback,       'user' );
                _fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow,        'user' );
                _fnCallbackReg( oSettings, 'aoHeaderCallback',     oInit.fnHeaderCallback,    'user' );
                _fnCallbackReg( oSettings, 'aoFooterCallback',     oInit.fnFooterCallback,    'user' );
                _fnCallbackReg( oSettings, 'aoInitComplete',       oInit.fnInitComplete,      'user' );
                _fnCallbackReg( oSettings, 'aoPreDrawCallback',    oInit.fnPreDrawCallback,   'user' );
                
                oSettings.rowIdFn = _fnGetObjectDataFn( oInit.rowId );
                
                /* Browser support detection */
                _fnBrowserDetect( oSettings );
                
                var oClasses = oSettings.oClasses;
                
                // @todo Remove in 1.11
                if ( oInit.bJQueryUI )
                {
                    /* Use the JUI classes object for display. You could clone the oStdClasses object if
                     * you want to have multiple tables with multiple independent classes
                     */
                    $.extend( oClasses, DataTable.ext.oJUIClasses, oInit.oClasses );
                
                    if ( oInit.sDom === defaults.sDom && defaults.sDom === "lfrtip" )
                    {
                        /* Set the DOM to use a layout suitable for jQuery UI's theming */
                        oSettings.sDom = '<"H"lfr>t<"F"ip>';
                    }
                
                    if ( ! oSettings.renderer ) {
                        oSettings.renderer = 'jqueryui';
                    }
                    else if ( $.isPlainObject( oSettings.renderer ) && ! oSettings.renderer.header ) {
                        oSettings.renderer.header = 'jqueryui';
                    }
                }
                else
                {
                    $.extend( oClasses, DataTable.ext.classes, oInit.oClasses );
                }
                $this.addClass( oClasses.sTable );
                
                
                if ( oSettings.iInitDisplayStart === undefined )
                {
                    /* Display start point, taking into account the save saving */
                    oSettings.iInitDisplayStart = oInit.iDisplayStart;
                    oSettings._iDisplayStart = oInit.iDisplayStart;
                }
                
                if ( oInit.iDeferLoading !== null )
                {
                    oSettings.bDeferLoading = true;
                    var tmp = $.isArray( oInit.iDeferLoading );
                    oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading;
                    oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
                }
                
                /* Language definitions */
                var oLanguage = oSettings.oLanguage;
                $.extend( true, oLanguage, oInit.oLanguage );
                
                if ( oLanguage.sUrl !== "" )
                {
                    /* Get the language definitions from a file - because this Ajax call makes the language
                     * get async to the remainder of this function we use bInitHandedOff to indicate that
                     * _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
                     */
                    $.ajax( {
                        dataType: 'json',
                        url: oLanguage.sUrl,
                        success: function ( json ) {
                            _fnLanguageCompat( json );
                            _fnCamelToHungarian( defaults.oLanguage, json );
                            $.extend( true, oLanguage, json );
                            _fnInitialise( oSettings );
                        },
                        error: function () {
                            // Error occurred loading language file, continue on as best we can
                            _fnInitialise( oSettings );
                        }
                    } );
                    bInitHandedOff = true;
                }
                
                /*
                 * Stripes
                 */
                if ( oInit.asStripeClasses === null )
                {
                    oSettings.asStripeClasses =[
                        oClasses.sStripeOdd,
                        oClasses.sStripeEven
                    ];
                }
                
                /* Remove row stripe classes if they are already on the table row */
                var stripeClasses = oSettings.asStripeClasses;
                var rowOne = $this.children('tbody').find('tr').eq(0);
                if ( $.inArray( true, $.map( stripeClasses, function(el, i) {
                    return rowOne.hasClass(el);
                } ) ) !== -1 ) {
                    $('tbody tr', this).removeClass( stripeClasses.join(' ') );
                    oSettings.asDestroyStripes = stripeClasses.slice();
                }
                
                /*
                 * Columns
                 * See if we should load columns automatically or use defined ones
                 */
                var anThs = [];
                var aoColumnsInit;
                var nThead = this.getElementsByTagName('thead');
                if ( nThead.length !== 0 )
                {
                    _fnDetectHeader( oSettings.aoHeader, nThead[0] );
                    anThs = _fnGetUniqueThs( oSettings );
                }
                
                /* If not given a column array, generate one with nulls */
                if ( oInit.aoColumns === null )
                {
                    aoColumnsInit = [];
                    for ( i=0, iLen=anThs.length ; i<iLen ; i++ )
                    {
                        aoColumnsInit.push( null );
                    }
                }
                else
                {
                    aoColumnsInit = oInit.aoColumns;
                }
                
                /* Add the columns */
                for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ )
                {
                    _fnAddColumn( oSettings, anThs ? anThs[i] : null );
                }
                
                /* Apply the column definitions */
                _fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) {
                    _fnColumnOptions( oSettings, iCol, oDef );
                } );
                
                /* HTML5 attribute detection - build an mData object automatically if the
                 * attributes are found
                 */
                if ( rowOne.length ) {
                    var a = function ( cell, name ) {
                        return cell.getAttribute( 'data-'+name ) !== null ? name : null;
                    };
                
                    $( rowOne[0] ).children('th, td').each( function (i, cell) {
                        var col = oSettings.aoColumns[i];
                
                        if ( col.mData === i ) {
                            var sort = a( cell, 'sort' ) || a( cell, 'order' );
                            var filter = a( cell, 'filter' ) || a( cell, 'search' );
                
                            if ( sort !== null || filter !== null ) {
                                col.mData = {
                                    _:      i+'.display',
                                    sort:   sort !== null   ? i+'.@data-'+sort   : undefined,
                                    type:   sort !== null   ? i+'.@data-'+sort   : undefined,
                                    filter: filter !== null ? i+'.@data-'+filter : undefined
                                };
                
                                _fnColumnOptions( oSettings, i );
                            }
                        }
                    } );
                }
                
                var features = oSettings.oFeatures;
                
                /* Must be done after everything which can be overridden by the state saving! */
                if ( oInit.bStateSave )
                {
                    features.bStateSave = true;
                    _fnLoadState( oSettings, oInit );
                    _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' );
                }
                
                
                /*
                 * Sorting
                 * @todo For modularisation (1.11) this needs to do into a sort start up handler
                 */
                
                // If aaSorting is not defined, then we use the first indicator in asSorting
                // in case that has been altered, so the default sort reflects that option
                if ( oInit.aaSorting === undefined )
                {
                    var sorting = oSettings.aaSorting;
                    for ( i=0, iLen=sorting.length ; i<iLen ; i++ )
                    {
                        sorting[i][1] = oSettings.aoColumns[ i ].asSorting[0];
                    }
                }
                
                /* Do a first pass on the sorting classes (allows any size changes to be taken into
                 * account, and also will apply sorting disabled classes if disabled
                 */
                _fnSortingClasses( oSettings );
                
                if ( features.bSort )
                {
                    _fnCallbackReg( oSettings, 'aoDrawCallback', function () {
                        if ( oSettings.bSorted ) {
                            var aSort = _fnSortFlatten( oSettings );
                            var sortedColumns = {};
                
                            $.each( aSort, function (i, val) {
                                sortedColumns[ val.src ] = val.dir;
                            } );
                
                            _fnCallbackFire( oSettings, null, 'order', [oSettings, aSort, sortedColumns] );
                            _fnSortAria( oSettings );
                        }
                    } );
                }
                
                _fnCallbackReg( oSettings, 'aoDrawCallback', function () {
                    if ( oSettings.bSorted || _fnDataSource( oSettings ) === 'ssp' || features.bDeferRender ) {
                        _fnSortingClasses( oSettings );
                    }
                }, 'sc' );
                
                
                /*
                 * Final init
                 * Cache the header, body and footer as required, creating them if needed
                 */
                
                // Work around for Webkit bug 83867 - store the caption-side before removing from doc
                var captions = $this.children('caption').each( function () {
                    this._captionSide = $this.css('caption-side');
                } );
                
                var thead = $this.children('thead');
                if ( thead.length === 0 )
                {
                    thead = $('<thead/>').appendTo(this);
                }
                oSettings.nTHead = thead[0];
                
                var tbody = $this.children('tbody');
                if ( tbody.length === 0 )
                {
                    tbody = $('<tbody/>').appendTo(this);
                }
                oSettings.nTBody = tbody[0];
                
                var tfoot = $this.children('tfoot');
                if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") )
                {
                    // If we are a scrolling table, and no footer has been given, then we need to create
                    // a tfoot element for the caption element to be appended to
                    tfoot = $('<tfoot/>').appendTo(this);
                }
                
                if ( tfoot.length === 0 || tfoot.children().length === 0 ) {
                    $this.addClass( oClasses.sNoFooter );
                }
                else if ( tfoot.length > 0 ) {
                    oSettings.nTFoot = tfoot[0];
                    _fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot );
                }
                
                /* Check if there is data passing into the constructor */
                if ( oInit.aaData )
                {
                    for ( i=0 ; i<oInit.aaData.length ; i++ )
                    {
                        _fnAddData( oSettings, oInit.aaData[ i ] );
                    }
                }
                else if ( oSettings.bDeferLoading || _fnDataSource( oSettings ) == 'dom' )
                {
                    /* Grab the data from the page - only do this when deferred loading or no Ajax
                     * source since there is no point in reading the DOM data if we are then going
                     * to replace it with Ajax data
                     */
                    _fnAddTr( oSettings, $(oSettings.nTBody).children('tr') );
                }
                
                /* Copy the data index array */
                oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
                
                /* Initialisation complete - table can be drawn */
                oSettings.bInitialised = true;
                
                /* Check if we need to initialise the table (it might not have been handed off to the
                 * language processor)
                 */
                if ( bInitHandedOff === false )
                {
                    _fnInitialise( oSettings );
                }
            } );
            _that = null;
            return this;
        };
    
        
        /*
         * It is useful to have variables which are scoped locally so only the
         * DataTables functions can access them and they don't leak into global space.
         * At the same time these functions are often useful over multiple files in the
         * core and API, so we list, or at least document, all variables which are used
         * by DataTables as private variables here. This also ensures that there is no
         * clashing of variable names and that they can easily referenced for reuse.
         */
        
        
        // Defined else where
        //  _selector_run
        //  _selector_opts
        //  _selector_first
        //  _selector_row_indexes
        
        var _ext; // DataTable.ext
        var _Api; // DataTable.Api
        var _api_register; // DataTable.Api.register
        var _api_registerPlural; // DataTable.Api.registerPlural
        
        var _re_dic = {};
        var _re_new_lines = /[\r\n]/g;
        var _re_html = /<.*?>/g;
        var _re_date_start = /^[\w\+\-]/;
        var _re_date_end = /[\w\+\-]$/;
        
        // Escape regular expression special characters
        var _re_escape_regex = new RegExp( '(\\' + [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ].join('|\\') + ')', 'g' );
        
        // http://en.wikipedia.org/wiki/Foreign_exchange_market
        // - \u20BD - Russian ruble.
        // - \u20a9 - South Korean Won
        // - \u20BA - Turkish Lira
        // - \u20B9 - Indian Rupee
        // - R - Brazil (R$) and South Africa
        // - fr - Swiss Franc
        // - kr - Swedish krona, Norwegian krone and Danish krone
        // - \u2009 is thin space and \u202F is narrow no-break space, both used in many
        //   standards as thousands separators.
        var _re_formatted_numeric = /[',$Â£â‚¬Â¥%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi;
        
        
        var _empty = function ( d ) {
            return !d || d === true || d === '-' ? true : false;
        };
        
        
        var _intVal = function ( s ) {
            var integer = parseInt( s, 10 );
            return !isNaN(integer) && isFinite(s) ? integer : null;
        };
        
        // Convert from a formatted number with characters other than `.` as the
        // decimal place, to a Javascript number
        var _numToDecimal = function ( num, decimalPoint ) {
            // Cache created regular expressions for speed as this function is called often
            if ( ! _re_dic[ decimalPoint ] ) {
                _re_dic[ decimalPoint ] = new RegExp( _fnEscapeRegex( decimalPoint ), 'g' );
            }
            return typeof num === 'string' && decimalPoint !== '.' ?
                num.replace( /\./g, '' ).replace( _re_dic[ decimalPoint ], '.' ) :
                num;
        };
        
        
        var _isNumber = function ( d, decimalPoint, formatted ) {
            var strType = typeof d === 'string';
        
            // If empty return immediately so there must be a number if it is a
            // formatted string (this stops the string "k", or "kr", etc being detected
            // as a formatted number for currency
            if ( _empty( d ) ) {
                return true;
            }
        
            if ( decimalPoint && strType ) {
                d = _numToDecimal( d, decimalPoint );
            }
        
            if ( formatted && strType ) {
                d = d.replace( _re_formatted_numeric, '' );
            }
        
            return !isNaN( parseFloat(d) ) && isFinite( d );
        };
        
        
        // A string without HTML in it can be considered to be HTML still
        var _isHtml = function ( d ) {
            return _empty( d ) || typeof d === 'string';
        };
        
        
        var _htmlNumeric = function ( d, decimalPoint, formatted ) {
            if ( _empty( d ) ) {
                return true;
            }
        
            var html = _isHtml( d );
            return ! html ?
                null :
                _isNumber( _stripHtml( d ), decimalPoint, formatted ) ?
                    true :
                    null;
        };
        
        
        var _pluck = function ( a, prop, prop2 ) {
            var out = [];
            var i=0, ien=a.length;
        
            // Could have the test in the loop for slightly smaller code, but speed
            // is essential here
            if ( prop2 !== undefined ) {
                for ( ; i<ien ; i++ ) {
                    if ( a[i] && a[i][ prop ] ) {
                        out.push( a[i][ prop ][ prop2 ] );
                    }
                }
            }
            else {
                for ( ; i<ien ; i++ ) {
                    if ( a[i] ) {
                        out.push( a[i][ prop ] );
                    }
                }
            }
        
            return out;
        };
        
        
        // Basically the same as _pluck, but rather than looping over `a` we use `order`
        // as the indexes to pick from `a`
        var _pluck_order = function ( a, order, prop, prop2 )
        {
            var out = [];
            var i=0, ien=order.length;
        
            // Could have the test in the loop for slightly smaller code, but speed
            // is essential here
            if ( prop2 !== undefined ) {
                for ( ; i<ien ; i++ ) {
                    if ( a[ order[i] ][ prop ] ) {
                        out.push( a[ order[i] ][ prop ][ prop2 ] );
                    }
                }
            }
            else {
                for ( ; i<ien ; i++ ) {
                    out.push( a[ order[i] ][ prop ] );
                }
            }
        
            return out;
        };
        
        
        var _range = function ( len, start )
        {
            var out = [];
            var end;
        
            if ( start === undefined ) {
                start = 0;
                end = len;
            }
            else {
                end = start;
                start = len;
            }
        
            for ( var i=start ; i<end ; i++ ) {
                out.push( i );
            }
        
            return out;
        };
        
        
        var _removeEmpty = function ( a )
        {
            var out = [];
        
            for ( var i=0, ien=a.length ; i<ien ; i++ ) {
                if ( a[i] ) { // careful - will remove all falsy values!
                    out.push( a[i] );
                }
            }
        
            return out;
        };
        
        
        var _stripHtml = function ( d ) {
            return d.replace( _re_html, '' );
        };
        
        
        /**
         * Find the unique elements in a source array.
         *
         * @param  {array} src Source array
         * @return {array} Array of unique items
         * @ignore
         */
        var _unique = function ( src )
        {
            // A faster unique method is to use object keys to identify used values,
            // but this doesn't work with arrays or objects, which we must also
            // consider. See jsperf.com/compare-array-unique-versions/4 for more
            // information.
            var
                out = [],
                val,
                i, ien=src.length,
                j, k=0;
        
            again: for ( i=0 ; i<ien ; i++ ) {
                val = src[i];
        
                for ( j=0 ; j<k ; j++ ) {
                    if ( out[j] === val ) {
                        continue again;
                    }
                }
        
                out.push( val );
                k++;
            }
        
            return out;
        };
        
        
        /**
         * DataTables utility methods
         * 
         * This namespace provides helper methods that DataTables uses internally to
         * create a DataTable, but which are not exclusively used only for DataTables.
         * These methods can be used by extension authors to save the duplication of
         * code.
         *
         *  @namespace
         */
        DataTable.util = {
            /**
             * Throttle the calls to a function. Arguments and context are maintained
             * for the throttled function.
             *
             * @param {function} fn Function to be called
             * @param {integer} freq Call frequency in mS
             * @return {function} Wrapped function
             */
            throttle: function ( fn, freq ) {
                var
                    frequency = freq !== undefined ? freq : 200,
                    last,
                    timer;
        
                return function () {
                    var
                        that = this,
                        now  = +new Date(),
                        args = arguments;
        
                    if ( last && now < last + frequency ) {
                        clearTimeout( timer );
        
                        timer = setTimeout( function () {
                            last = undefined;
                            fn.apply( that, args );
                        }, frequency );
                    }
                    else {
                        last = now;
                        fn.apply( that, args );
                    }
                };
            },
        
        
            /**
             * Escape a string such that it can be used in a regular expression
             *
             *  @param {string} val string to escape
             *  @returns {string} escaped string
             */
            escapeRegex: function ( val ) {
                return val.replace( _re_escape_regex, '\\$1' );
            }
        };
        
        
        
        /**
         * Create a mapping object that allows camel case parameters to be looked up
         * for their Hungarian counterparts. The mapping is stored in a private
         * parameter called `_hungarianMap` which can be accessed on the source object.
         *  @param {object} o
         *  @memberof DataTable#oApi
         */
        function _fnHungarianMap ( o )
        {
            var
                hungarian = 'a aa ai ao as b fn i m o s ',
                match,
                newKey,
                map = {};
        
            $.each( o, function (key, val) {
                match = key.match(/^([^A-Z]+?)([A-Z])/);
        
                if ( match && hungarian.indexOf(match[1]+' ') !== -1 )
                {
                    newKey = key.replace( match[0], match[2].toLowerCase() );
                    map[ newKey ] = key;
        
                    if ( match[1] === 'o' )
                    {
                        _fnHungarianMap( o[key] );
                    }
                }
            } );
        
            o._hungarianMap = map;
        }
        
        
        /**
         * Convert from camel case parameters to Hungarian, based on a Hungarian map
         * created by _fnHungarianMap.
         *  @param {object} src The model object which holds all parameters that can be
         *    mapped.
         *  @param {object} user The object to convert from camel case to Hungarian.
         *  @param {boolean} force When set to `true`, properties which already have a
         *    Hungarian value in the `user` object will be overwritten. Otherwise they
         *    won't be.
         *  @memberof DataTable#oApi
         */
        function _fnCamelToHungarian ( src, user, force )
        {
            if ( ! src._hungarianMap ) {
                _fnHungarianMap( src );
            }
        
            var hungarianKey;
        
            $.each( user, function (key, val) {
                hungarianKey = src._hungarianMap[ key ];
        
                if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) )
                {
                    // For objects, we need to buzz down into the object to copy parameters
                    if ( hungarianKey.charAt(0) === 'o' )
                    {
                        // Copy the camelCase options over to the hungarian
                        if ( ! user[ hungarianKey ] ) {
                            user[ hungarianKey ] = {};
                        }
                        $.extend( true, user[hungarianKey], user[key] );
        
                        _fnCamelToHungarian( src[hungarianKey], user[hungarianKey], force );
                    }
                    else {
                        user[hungarianKey] = user[ key ];
                    }
                }
            } );
        }
        
        
        /**
         * Language compatibility - when certain options are given, and others aren't, we
         * need to duplicate the values over, in order to provide backwards compatibility
         * with older language files.
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnLanguageCompat( lang )
        {
            var defaults = DataTable.defaults.oLanguage;
            var zeroRecords = lang.sZeroRecords;
        
            /* Backwards compatibility - if there is no sEmptyTable given, then use the same as
             * sZeroRecords - assuming that is given.
             */
            if ( ! lang.sEmptyTable && zeroRecords &&
                defaults.sEmptyTable === "No data available in table" )
            {
                _fnMap( lang, lang, 'sZeroRecords', 'sEmptyTable' );
            }
        
            /* Likewise with loading records */
            if ( ! lang.sLoadingRecords && zeroRecords &&
                defaults.sLoadingRecords === "Loading..." )
            {
                _fnMap( lang, lang, 'sZeroRecords', 'sLoadingRecords' );
            }
        
            // Old parameter name of the thousands separator mapped onto the new
            if ( lang.sInfoThousands ) {
                lang.sThousands = lang.sInfoThousands;
            }
        
            var decimal = lang.sDecimal;
            if ( decimal ) {
                _addNumericSort( decimal );
            }
        }
        
        
        /**
         * Map one parameter onto another
         *  @param {object} o Object to map
         *  @param {*} knew The new parameter name
         *  @param {*} old The old parameter name
         */
        var _fnCompatMap = function ( o, knew, old ) {
            if ( o[ knew ] !== undefined ) {
                o[ old ] = o[ knew ];
            }
        };
        
        
        /**
         * Provide backwards compatibility for the main DT options. Note that the new
         * options are mapped onto the old parameters, so this is an external interface
         * change only.
         *  @param {object} init Object to map
         */
        function _fnCompatOpts ( init )
        {
            _fnCompatMap( init, 'ordering',      'bSort' );
            _fnCompatMap( init, 'orderMulti',    'bSortMulti' );
            _fnCompatMap( init, 'orderClasses',  'bSortClasses' );
            _fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' );
            _fnCompatMap( init, 'order',         'aaSorting' );
            _fnCompatMap( init, 'orderFixed',    'aaSortingFixed' );
            _fnCompatMap( init, 'paging',        'bPaginate' );
            _fnCompatMap( init, 'pagingType',    'sPaginationType' );
            _fnCompatMap( init, 'pageLength',    'iDisplayLength' );
            _fnCompatMap( init, 'searching',     'bFilter' );
        
            // Boolean initialisation of x-scrolling
            if ( typeof init.sScrollX === 'boolean' ) {
                init.sScrollX = init.sScrollX ? '100%' : '';
            }
            if ( typeof init.scrollX === 'boolean' ) {
                init.scrollX = init.scrollX ? '100%' : '';
            }
        
            // Column search objects are in an array, so it needs to be converted
            // element by element
            var searchCols = init.aoSearchCols;
        
            if ( searchCols ) {
                for ( var i=0, ien=searchCols.length ; i<ien ; i++ ) {
                    if ( searchCols[i] ) {
                        _fnCamelToHungarian( DataTable.models.oSearch, searchCols[i] );
                    }
                }
            }
        }
        
        
        /**
         * Provide backwards compatibility for column options. Note that the new options
         * are mapped onto the old parameters, so this is an external interface change
         * only.
         *  @param {object} init Object to map
         */
        function _fnCompatCols ( init )
        {
            _fnCompatMap( init, 'orderable',     'bSortable' );
            _fnCompatMap( init, 'orderData',     'aDataSort' );
            _fnCompatMap( init, 'orderSequence', 'asSorting' );
            _fnCompatMap( init, 'orderDataType', 'sortDataType' );
        
            // orderData can be given as an integer
            var dataSort = init.aDataSort;
            if ( dataSort && ! $.isArray( dataSort ) ) {
                init.aDataSort = [ dataSort ];
            }
        }
        
        
        /**
         * Browser feature detection for capabilities, quirks
         *  @param {object} settings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnBrowserDetect( settings )
        {
            // We don't need to do this every time DataTables is constructed, the values
            // calculated are specific to the browser and OS configuration which we
            // don't expect to change between initialisations
            if ( ! DataTable.__browser ) {
                var browser = {};
                DataTable.__browser = browser;
        
                // Scrolling feature / quirks detection
                var n = $('<div/>')
                    .css( {
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        height: 1,
                        width: 1,
                        overflow: 'hidden'
                    } )
                    .append(
                        $('<div/>')
                            .css( {
                                position: 'absolute',
                                top: 1,
                                left: 1,
                                width: 100,
                                overflow: 'scroll'
                            } )
                            .append(
                                $('<div/>')
                                    .css( {
                                        width: '100%',
                                        height: 10
                                    } )
                            )
                    )
                    .appendTo( 'body' );
        
                var outer = n.children();
                var inner = outer.children();
        
                // Numbers below, in order, are:
                // inner.offsetWidth, inner.clientWidth, outer.offsetWidth, outer.clientWidth
                //
                // IE6 XP:                           100 100 100  83
                // IE7 Vista:                        100 100 100  83
                // IE 8+ Windows:                     83  83 100  83
                // Evergreen Windows:                 83  83 100  83
                // Evergreen Mac with scrollbars:     85  85 100  85
                // Evergreen Mac without scrollbars: 100 100 100 100
        
                // Get scrollbar width
                browser.barWidth = outer[0].offsetWidth - outer[0].clientWidth;
        
                // IE6/7 will oversize a width 100% element inside a scrolling element, to
                // include the width of the scrollbar, while other browsers ensure the inner
                // element is contained without forcing scrolling
                browser.bScrollOversize = inner[0].offsetWidth === 100 && outer[0].clientWidth !== 100;
        
                // In rtl text layout, some browsers (most, but not all) will place the
                // scrollbar on the left, rather than the right.
                browser.bScrollbarLeft = Math.round( inner.offset().left ) !== 1;
        
                // IE8- don't provide height and width for getBoundingClientRect
                browser.bBounding = n[0].getBoundingClientRect().width ? true : false;
        
                n.remove();
            }
        
            $.extend( settings.oBrowser, DataTable.__browser );
            settings.oScroll.iBarWidth = DataTable.__browser.barWidth;
        }
        
        
        /**
         * Array.prototype reduce[Right] method, used for browsers which don't support
         * JS 1.6. Done this way to reduce code size, since we iterate either way
         *  @param {object} settings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnReduce ( that, fn, init, start, end, inc )
        {
            var
                i = start,
                value,
                isSet = false;
        
            if ( init !== undefined ) {
                value = init;
                isSet = true;
            }
        
            while ( i !== end ) {
                if ( ! that.hasOwnProperty(i) ) {
                    continue;
                }
        
                value = isSet ?
                    fn( value, that[i], i, that ) :
                    that[i];
        
                isSet = true;
                i += inc;
            }
        
            return value;
        }
        
        /**
         * Add a column to the list used for the table with default values
         *  @param {object} oSettings dataTables settings object
         *  @param {node} nTh The th element for this column
         *  @memberof DataTable#oApi
         */
        function _fnAddColumn( oSettings, nTh )
        {
            // Add column to aoColumns array
            var oDefaults = DataTable.defaults.column;
            var iCol = oSettings.aoColumns.length;
            var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, {
                "nTh": nTh ? nTh : document.createElement('th'),
                "sTitle":    oDefaults.sTitle    ? oDefaults.sTitle    : nTh ? nTh.innerHTML : '',
                "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
                "mData": oDefaults.mData ? oDefaults.mData : iCol,
                idx: iCol
            } );
            oSettings.aoColumns.push( oCol );
        
            // Add search object for column specific search. Note that the `searchCols[ iCol ]`
            // passed into extend can be undefined. This allows the user to give a default
            // with only some of the parameters defined, and also not give a default
            var searchCols = oSettings.aoPreSearchCols;
            searchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch, searchCols[ iCol ] );
        
            // Use the default column options function to initialise classes etc
            _fnColumnOptions( oSettings, iCol, $(nTh).data() );
        }
        
        
        /**
         * Apply options for a column
         *  @param {object} oSettings dataTables settings object
         *  @param {int} iCol column index to consider
         *  @param {object} oOptions object with sType, bVisible and bSearchable etc
         *  @memberof DataTable#oApi
         */
        function _fnColumnOptions( oSettings, iCol, oOptions )
        {
            var oCol = oSettings.aoColumns[ iCol ];
            var oClasses = oSettings.oClasses;
            var th = $(oCol.nTh);
        
            // Try to get width information from the DOM. We can't get it from CSS
            // as we'd need to parse the CSS stylesheet. `width` option can override
            if ( ! oCol.sWidthOrig ) {
                // Width attribute
                oCol.sWidthOrig = th.attr('width') || null;
        
                // Style attribute
                var t = (th.attr('style') || '').match(/width:\s*(\d+[pxem%]+)/);
                if ( t ) {
                    oCol.sWidthOrig = t[1];
                }
            }
        
            /* User specified column options */
            if ( oOptions !== undefined && oOptions !== null )
            {
                // Backwards compatibility
                _fnCompatCols( oOptions );
        
                // Map camel case parameters to their Hungarian counterparts
                _fnCamelToHungarian( DataTable.defaults.column, oOptions );
        
                /* Backwards compatibility for mDataProp */
                if ( oOptions.mDataProp !== undefined && !oOptions.mData )
                {
                    oOptions.mData = oOptions.mDataProp;
                }
        
                if ( oOptions.sType )
                {
                    oCol._sManualType = oOptions.sType;
                }
        
                // `class` is a reserved word in Javascript, so we need to provide
                // the ability to use a valid name for the camel case input
                if ( oOptions.className && ! oOptions.sClass )
                {
                    oOptions.sClass = oOptions.className;
                }
        
                $.extend( oCol, oOptions );
                _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" );
        
                /* iDataSort to be applied (backwards compatibility), but aDataSort will take
                 * priority if defined
                 */
                if ( oOptions.iDataSort !== undefined )
                {
                    oCol.aDataSort = [ oOptions.iDataSort ];
                }
                _fnMap( oCol, oOptions, "aDataSort" );
            }
        
            /* Cache the data get and set functions for speed */
            var mDataSrc = oCol.mData;
            var mData = _fnGetObjectDataFn( mDataSrc );
            var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null;
        
            var attrTest = function( src ) {
                return typeof src === 'string' && src.indexOf('@') !== -1;
            };
            oCol._bAttrSrc = $.isPlainObject( mDataSrc ) && (
                attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter)
            );
            oCol._setter = null;
        
            oCol.fnGetData = function (rowData, type, meta) {
                var innerData = mData( rowData, type, undefined, meta );
        
                return mRender && type ?
                    mRender( innerData, type, rowData, meta ) :
                    innerData;
            };
            oCol.fnSetData = function ( rowData, val, meta ) {
                return _fnSetObjectDataFn( mDataSrc )( rowData, val, meta );
            };
        
            // Indicate if DataTables should read DOM data as an object or array
            // Used in _fnGetRowElements
            if ( typeof mDataSrc !== 'number' ) {
                oSettings._rowReadObject = true;
            }
        
            /* Feature sorting overrides column specific when off */
            if ( !oSettings.oFeatures.bSort )
            {
                oCol.bSortable = false;
                th.addClass( oClasses.sSortableNone ); // Have to add class here as order event isn't called
            }
        
            /* Check that the class assignment is correct for sorting */
            var bAsc = $.inArray('asc', oCol.asSorting) !== -1;
            var bDesc = $.inArray('desc', oCol.asSorting) !== -1;
            if ( !oCol.bSortable || (!bAsc && !bDesc) )
            {
                oCol.sSortingClass = oClasses.sSortableNone;
                oCol.sSortingClassJUI = "";
            }
            else if ( bAsc && !bDesc )
            {
                oCol.sSortingClass = oClasses.sSortableAsc;
                oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed;
            }
            else if ( !bAsc && bDesc )
            {
                oCol.sSortingClass = oClasses.sSortableDesc;
                oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed;
            }
            else
            {
                oCol.sSortingClass = oClasses.sSortable;
                oCol.sSortingClassJUI = oClasses.sSortJUI;
            }
        }
        
        
        /**
         * Adjust the table column widths for new data. Note: you would probably want to
         * do a redraw after calling this function!
         *  @param {object} settings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnAdjustColumnSizing ( settings )
        {
            /* Not interested in doing column width calculation if auto-width is disabled */
            if ( settings.oFeatures.bAutoWidth !== false )
            {
                var columns = settings.aoColumns;
        
                _fnCalculateColumnWidths( settings );
                for ( var i=0 , iLen=columns.length ; i<iLen ; i++ )
                {
                    columns[i].nTh.style.width = columns[i].sWidth;
                }
            }
        
            var scroll = settings.oScroll;
            if ( scroll.sY !== '' || scroll.sX !== '')
            {
                _fnScrollDraw( settings );
            }
        
            _fnCallbackFire( settings, null, 'column-sizing', [settings] );
        }
        
        
        /**
         * Covert the index of a visible column to the index in the data array (take account
         * of hidden columns)
         *  @param {object} oSettings dataTables settings object
         *  @param {int} iMatch Visible column index to lookup
         *  @returns {int} i the data index
         *  @memberof DataTable#oApi
         */
        function _fnVisibleToColumnIndex( oSettings, iMatch )
        {
            var aiVis = _fnGetColumns( oSettings, 'bVisible' );
        
            return typeof aiVis[iMatch] === 'number' ?
                aiVis[iMatch] :
                null;
        }
        
        
        /**
         * Covert the index of an index in the data array and convert it to the visible
         *   column index (take account of hidden columns)
         *  @param {int} iMatch Column index to lookup
         *  @param {object} oSettings dataTables settings object
         *  @returns {int} i the data index
         *  @memberof DataTable#oApi
         */
        function _fnColumnIndexToVisible( oSettings, iMatch )
        {
            var aiVis = _fnGetColumns( oSettings, 'bVisible' );
            var iPos = $.inArray( iMatch, aiVis );
        
            return iPos !== -1 ? iPos : null;
        }
        
        
        /**
         * Get the number of visible columns
         *  @param {object} oSettings dataTables settings object
         *  @returns {int} i the number of visible columns
         *  @memberof DataTable#oApi
         */
        function _fnVisbleColumns( oSettings )
        {
            var vis = 0;
        
            // No reduce in IE8, use a loop for now
            $.each( oSettings.aoColumns, function ( i, col ) {
                if ( col.bVisible && $(col.nTh).css('display') !== 'none' ) {
                    vis++;
                }
            } );
        
            return vis;
        }
        
        
        /**
         * Get an array of column indexes that match a given property
         *  @param {object} oSettings dataTables settings object
         *  @param {string} sParam Parameter in aoColumns to look for - typically
         *    bVisible or bSearchable
         *  @returns {array} Array of indexes with matched properties
         *  @memberof DataTable#oApi
         */
        function _fnGetColumns( oSettings, sParam )
        {
            var a = [];
        
            $.map( oSettings.aoColumns, function(val, i) {
                if ( val[sParam] ) {
                    a.push( i );
                }
            } );
        
            return a;
        }
        
        
        /**
         * Calculate the 'type' of a column
         *  @param {object} settings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnColumnTypes ( settings )
        {
            var columns = settings.aoColumns;
            var data = settings.aoData;
            var types = DataTable.ext.type.detect;
            var i, ien, j, jen, k, ken;
            var col, cell, detectedType, cache;
        
            // For each column, spin over the 
            for ( i=0, ien=columns.length ; i<ien ; i++ ) {
                col = columns[i];
                cache = [];
        
                if ( ! col.sType && col._sManualType ) {
                    col.sType = col._sManualType;
                }
                else if ( ! col.sType ) {
                    for ( j=0, jen=types.length ; j<jen ; j++ ) {
                        for ( k=0, ken=data.length ; k<ken ; k++ ) {
                            // Use a cache array so we only need to get the type data
                            // from the formatter once (when using multiple detectors)
                            if ( cache[k] === undefined ) {
                                cache[k] = _fnGetCellData( settings, k, i, 'type' );
                            }
        
                            detectedType = types[j]( cache[k], settings );
        
                            // If null, then this type can't apply to this column, so
                            // rather than testing all cells, break out. There is an
                            // exception for the last type which is `html`. We need to
                            // scan all rows since it is possible to mix string and HTML
                            // types
                            if ( ! detectedType && j !== types.length-1 ) {
                                break;
                            }
        
                            // Only a single match is needed for html type since it is
                            // bottom of the pile and very similar to string
                            if ( detectedType === 'html' ) {
                                break;
                            }
                        }
        
                        // Type is valid for all data points in the column - use this
                        // type
                        if ( detectedType ) {
                            col.sType = detectedType;
                            break;
                        }
                    }
        
                    // Fall back - if no type was detected, always use string
                    if ( ! col.sType ) {
                        col.sType = 'string';
                    }
                }
            }
        }
        
        
        /**
         * Take the column definitions and static columns arrays and calculate how
         * they relate to column indexes. The callback function will then apply the
         * definition found for a column to a suitable configuration object.
         *  @param {object} oSettings dataTables settings object
         *  @param {array} aoColDefs The aoColumnDefs array that is to be applied
         *  @param {array} aoCols The aoColumns array that defines columns individually
         *  @param {function} fn Callback function - takes two parameters, the calculated
         *    column index and the definition for that column.
         *  @memberof DataTable#oApi
         */
        function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
        {
            var i, iLen, j, jLen, k, kLen, def;
            var columns = oSettings.aoColumns;
        
            // Column definitions with aTargets
            if ( aoColDefs )
            {
                /* Loop over the definitions array - loop in reverse so first instance has priority */
                for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
                {
                    def = aoColDefs[i];
        
                    /* Each definition can target multiple columns, as it is an array */
                    var aTargets = def.targets !== undefined ?
                        def.targets :
                        def.aTargets;
        
                    if ( ! $.isArray( aTargets ) )
                    {
                        aTargets = [ aTargets ];
                    }
        
                    for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
                    {
                        if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
                        {
                            /* Add columns that we don't yet know about */
                            while( columns.length <= aTargets[j] )
                            {
                                _fnAddColumn( oSettings );
                            }
        
                            /* Integer, basic index */
                            fn( aTargets[j], def );
                        }
                        else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
                        {
                            /* Negative integer, right to left column counting */
                            fn( columns.length+aTargets[j], def );
                        }
                        else if ( typeof aTargets[j] === 'string' )
                        {
                            /* Class name matching on TH element */
                            for ( k=0, kLen=columns.length ; k<kLen ; k++ )
                            {
                                if ( aTargets[j] == "_all" ||
                                     $(columns[k].nTh).hasClass( aTargets[j] ) )
                                {
                                    fn( k, def );
                                }
                            }
                        }
                    }
                }
            }
        
            // Statically defined columns array
            if ( aoCols )
            {
                for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
                {
                    fn( i, aoCols[i] );
                }
            }
        }
        
        /**
         * Add a data array to the table, creating DOM node etc. This is the parallel to
         * _fnGatherData, but for adding rows from a Javascript source, rather than a
         * DOM source.
         *  @param {object} oSettings dataTables settings object
         *  @param {array} aData data array to be added
         *  @param {node} [nTr] TR element to add to the table - optional. If not given,
         *    DataTables will create a row automatically
         *  @param {array} [anTds] Array of TD|TH elements for the row - must be given
         *    if nTr is.
         *  @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
         *  @memberof DataTable#oApi
         */
        function _fnAddData ( oSettings, aDataIn, nTr, anTds )
        {
            /* Create the object for storing information about this new row */
            var iRow = oSettings.aoData.length;
            var oData = $.extend( true, {}, DataTable.models.oRow, {
                src: nTr ? 'dom' : 'data',
                idx: iRow
            } );
        
            oData._aData = aDataIn;
            oSettings.aoData.push( oData );
        
            /* Create the cells */
            var nTd, sThisType;
            var columns = oSettings.aoColumns;
        
            // Invalidate the column types as the new data needs to be revalidated
            for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
            {
                columns[i].sType = null;
            }
        
            /* Add to the display array */
            oSettings.aiDisplayMaster.push( iRow );
        
            var id = oSettings.rowIdFn( aDataIn );
            if ( id !== undefined ) {
                oSettings.aIds[ id ] = oData;
            }
        
            /* Create the DOM information, or register it if already present */
            if ( nTr || ! oSettings.oFeatures.bDeferRender )
            {
                _fnCreateTr( oSettings, iRow, nTr, anTds );
            }
        
            return iRow;
        }
        
        
        /**
         * Add one or more TR elements to the table. Generally we'd expect to
         * use this for reading data from a DOM sourced table, but it could be
         * used for an TR element. Note that if a TR is given, it is used (i.e.
         * it is not cloned).
         *  @param {object} settings dataTables settings object
         *  @param {array|node|jQuery} trs The TR element(s) to add to the table
         *  @returns {array} Array of indexes for the added rows
         *  @memberof DataTable#oApi
         */
        function _fnAddTr( settings, trs )
        {
            var row;
        
            // Allow an individual node to be passed in
            if ( ! (trs instanceof $) ) {
                trs = $(trs);
            }
        
            return trs.map( function (i, el) {
                row = _fnGetRowElements( settings, el );
                return _fnAddData( settings, row.data, el, row.cells );
            } );
        }
        
        
        /**
         * Take a TR element and convert it to an index in aoData
         *  @param {object} oSettings dataTables settings object
         *  @param {node} n the TR element to find
         *  @returns {int} index if the node is found, null if not
         *  @memberof DataTable#oApi
         */
        function _fnNodeToDataIndex( oSettings, n )
        {
            return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;
        }
        
        
        /**
         * Take a TD element and convert it into a column data index (not the visible index)
         *  @param {object} oSettings dataTables settings object
         *  @param {int} iRow The row number the TD/TH can be found in
         *  @param {node} n The TD/TH element to find
         *  @returns {int} index if the node is found, -1 if not
         *  @memberof DataTable#oApi
         */
        function _fnNodeToColumnIndex( oSettings, iRow, n )
        {
            return $.inArray( n, oSettings.aoData[ iRow ].anCells );
        }
        
        
        /**
         * Get the data for a given cell from the internal cache, taking into account data mapping
         *  @param {object} settings dataTables settings object
         *  @param {int} rowIdx aoData row id
         *  @param {int} colIdx Column index
         *  @param {string} type data get type ('display', 'type' 'filter' 'sort')
         *  @returns {*} Cell data
         *  @memberof DataTable#oApi
         */
        function _fnGetCellData( settings, rowIdx, colIdx, type )
        {
            var draw           = settings.iDraw;
            var col            = settings.aoColumns[colIdx];
            var rowData        = settings.aoData[rowIdx]._aData;
            var defaultContent = col.sDefaultContent;
            var cellData       = col.fnGetData( rowData, type, {
                settings: settings,
                row:      rowIdx,
                col:      colIdx
            } );
        
            if ( cellData === undefined ) {
                if ( settings.iDrawError != draw && defaultContent === null ) {
                    _fnLog( settings, 0, "Requested unknown parameter "+
                        (typeof col.mData=='function' ? '{function}' : "'"+col.mData+"'")+
                        " for row "+rowIdx+", column "+colIdx, 4 );
                    settings.iDrawError = draw;
                }
                return defaultContent;
            }
        
            // When the data source is null and a specific data type is requested (i.e.
            // not the original data), we can use default column data
            if ( (cellData === rowData || cellData === null) && defaultContent !== null && type !== undefined ) {
                cellData = defaultContent;
            }
            else if ( typeof cellData === 'function' ) {
                // If the data source is a function, then we run it and use the return,
                // executing in the scope of the data object (for instances)
                return cellData.call( rowData );
            }
        
            if ( cellData === null && type == 'display' ) {
                return '';
            }
            return cellData;
        }
        
        
        /**
         * Set the value for a specific cell, into the internal data cache
         *  @param {object} settings dataTables settings object
         *  @param {int} rowIdx aoData row id
         *  @param {int} colIdx Column index
         *  @param {*} val Value to set
         *  @memberof DataTable#oApi
         */
        function _fnSetCellData( settings, rowIdx, colIdx, val )
        {
            var col     = settings.aoColumns[colIdx];
            var rowData = settings.aoData[rowIdx]._aData;
        
            col.fnSetData( rowData, val, {
                settings: settings,
                row:      rowIdx,
                col:      colIdx
            }  );
        }
        
        
        // Private variable that is used to match action syntax in the data property object
        var __reArray = /\[.*?\]$/;
        var __reFn = /\(\)$/;
        
        /**
         * Split string on periods, taking into account escaped periods
         * @param  {string} str String to split
         * @return {array} Split string
         */
        function _fnSplitObjNotation( str )
        {
            return $.map( str.match(/(\\.|[^\.])+/g) || [''], function ( s ) {
                return s.replace(/\\./g, '.');
            } );
        }
        
        
        /**
         * Return a function that can be used to get data from a source object, taking
         * into account the ability to use nested objects as a source
         *  @param {string|int|function} mSource The data source for the object
         *  @returns {function} Data get function
         *  @memberof DataTable#oApi
         */
        function _fnGetObjectDataFn( mSource )
        {
            if ( $.isPlainObject( mSource ) )
            {
                /* Build an object of get functions, and wrap them in a single call */
                var o = {};
                $.each( mSource, function (key, val) {
                    if ( val ) {
                        o[key] = _fnGetObjectDataFn( val );
                    }
                } );
        
                return function (data, type, row, meta) {
                    var t = o[type] || o._;
                    return t !== undefined ?
                        t(data, type, row, meta) :
                        data;
                };
            }
            else if ( mSource === null )
            {
                /* Give an empty string for rendering / sorting etc */
                return function (data) { // type, row and meta also passed, but not used
                    return data;
                };
            }
            else if ( typeof mSource === 'function' )
            {
                return function (data, type, row, meta) {
                    return mSource( data, type, row, meta );
                };
            }
            else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
                      mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
            {
                /* If there is a . in the source string then the data source is in a
                 * nested object so we loop over the data for each level to get the next
                 * level down. On each loop we test for undefined, and if found immediately
                 * return. This allows entire objects to be missing and sDefaultContent to
                 * be used if defined, rather than throwing an error
                 */
                var fetchData = function (data, type, src) {
                    var arrayNotation, funcNotation, out, innerSrc;
        
                    if ( src !== "" )
                    {
                        var a = _fnSplitObjNotation( src );
        
                        for ( var i=0, iLen=a.length ; i<iLen ; i++ )
                        {
                            // Check if we are dealing with special notation
                            arrayNotation = a[i].match(__reArray);
                            funcNotation = a[i].match(__reFn);
        
                            if ( arrayNotation )
                            {
                                // Array notation
                                a[i] = a[i].replace(__reArray, '');
        
                                // Condition allows simply [] to be passed in
                                if ( a[i] !== "" ) {
                                    data = data[ a[i] ];
                                }
                                out = [];
        
                                // Get the remainder of the nested object to get
                                a.splice( 0, i+1 );
                                innerSrc = a.join('.');
        
                                // Traverse each entry in the array getting the properties requested
                                if ( $.isArray( data ) ) {
                                    for ( var j=0, jLen=data.length ; j<jLen ; j++ ) {
                                        out.push( fetchData( data[j], type, innerSrc ) );
                                    }
                                }
        
                                // If a string is given in between the array notation indicators, that
                                // is used to join the strings together, otherwise an array is returned
                                var join = arrayNotation[0].substring(1, arrayNotation[0].length-1);
                                data = (join==="") ? out : out.join(join);
        
                                // The inner call to fetchData has already traversed through the remainder
                                // of the source requested, so we exit from the loop
                                break;
                            }
                            else if ( funcNotation )
                            {
                                // Function call
                                a[i] = a[i].replace(__reFn, '');
                                data = data[ a[i] ]();
                                continue;
                            }
        
                            if ( data === null || data[ a[i] ] === undefined )
                            {
                                return undefined;
                            }
                            data = data[ a[i] ];
                        }
                    }
        
                    return data;
                };
        
                return function (data, type) { // row and meta also passed, but not used
                    return fetchData( data, type, mSource );
                };
            }
            else
            {
                /* Array or flat object mapping */
                return function (data, type) { // row and meta also passed, but not used
                    return data[mSource];
                };
            }
        }
        
        
        /**
         * Return a function that can be used to set data from a source object, taking
         * into account the ability to use nested objects as a source
         *  @param {string|int|function} mSource The data source for the object
         *  @returns {function} Data set function
         *  @memberof DataTable#oApi
         */
        function _fnSetObjectDataFn( mSource )
        {
            if ( $.isPlainObject( mSource ) )
            {
                /* Unlike get, only the underscore (global) option is used for for
                 * setting data since we don't know the type here. This is why an object
                 * option is not documented for `mData` (which is read/write), but it is
                 * for `mRender` which is read only.
                 */
                return _fnSetObjectDataFn( mSource._ );
            }
            else if ( mSource === null )
            {
                /* Nothing to do when the data source is null */
                return function () {};
            }
            else if ( typeof mSource === 'function' )
            {
                return function (data, val, meta) {
                    mSource( data, 'set', val, meta );
                };
            }
            else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
                      mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
            {
                /* Like the get, we need to get data from a nested object */
                var setData = function (data, val, src) {
                    var a = _fnSplitObjNotation( src ), b;
                    var aLast = a[a.length-1];
                    var arrayNotation, funcNotation, o, innerSrc;
        
                    for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
                    {
                        // Check if we are dealing with an array notation request
                        arrayNotation = a[i].match(__reArray);
                        funcNotation = a[i].match(__reFn);
        
                        if ( arrayNotation )
                        {
                            a[i] = a[i].replace(__reArray, '');
                            data[ a[i] ] = [];
        
                            // Get the remainder of the nested object to set so we can recurse
                            b = a.slice();
                            b.splice( 0, i+1 );
                            innerSrc = b.join('.');
        
                            // Traverse each entry in the array setting the properties requested
                            if ( $.isArray( val ) )
                            {
                                for ( var j=0, jLen=val.length ; j<jLen ; j++ )
                                {
                                    o = {};
                                    setData( o, val[j], innerSrc );
                                    data[ a[i] ].push( o );
                                }
                            }
                            else
                            {
                                // We've been asked to save data to an array, but it
                                // isn't array data to be saved. Best that can be done
                                // is to just save the value.
                                data[ a[i] ] = val;
                            }
        
                            // The inner call to setData has already traversed through the remainder
                            // of the source and has set the data, thus we can exit here
                            return;
                        }
                        else if ( funcNotation )
                        {
                            // Function call
                            a[i] = a[i].replace(__reFn, '');
                            data = data[ a[i] ]( val );
                        }
        
                        // If the nested object doesn't currently exist - since we are
                        // trying to set the value - create it
                        if ( data[ a[i] ] === null || data[ a[i] ] === undefined )
                        {
                            data[ a[i] ] = {};
                        }
                        data = data[ a[i] ];
                    }
        
                    // Last item in the input - i.e, the actual set
                    if ( aLast.match(__reFn ) )
                    {
                        // Function call
                        data = data[ aLast.replace(__reFn, '') ]( val );
                    }
                    else
                    {
                        // If array notation is used, we just want to strip it and use the property name
                        // and assign the value. If it isn't used, then we get the result we want anyway
                        data[ aLast.replace(__reArray, '') ] = val;
                    }
                };
        
                return function (data, val) { // meta is also passed in, but not used
                    return setData( data, val, mSource );
                };
            }
            else
            {
                /* Array or flat object mapping */
                return function (data, val) { // meta is also passed in, but not used
                    data[mSource] = val;
                };
            }
        }
        
        
        /**
         * Return an array with the full table data
         *  @param {object} oSettings dataTables settings object
         *  @returns array {array} aData Master data array
         *  @memberof DataTable#oApi
         */
        function _fnGetDataMaster ( settings )
        {
            return _pluck( settings.aoData, '_aData' );
        }
        
        
        /**
         * Nuke the table
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnClearTable( settings )
        {
            settings.aoData.length = 0;
            settings.aiDisplayMaster.length = 0;
            settings.aiDisplay.length = 0;
            settings.aIds = {};
        }
        
        
         /**
         * Take an array of integers (index array) and remove a target integer (value - not
         * the key!)
         *  @param {array} a Index array to target
         *  @param {int} iTarget value to find
         *  @memberof DataTable#oApi
         */
        function _fnDeleteIndex( a, iTarget, splice )
        {
            var iTargetIndex = -1;
        
            for ( var i=0, iLen=a.length ; i<iLen ; i++ )
            {
                if ( a[i] == iTarget )
                {
                    iTargetIndex = i;
                }
                else if ( a[i] > iTarget )
                {
                    a[i]--;
                }
            }
        
            if ( iTargetIndex != -1 && splice === undefined )
            {
                a.splice( iTargetIndex, 1 );
            }
        }
        
        
        /**
         * Mark cached data as invalid such that a re-read of the data will occur when
         * the cached data is next requested. Also update from the data source object.
         *
         * @param {object} settings DataTables settings object
         * @param {int}    rowIdx   Row index to invalidate
         * @param {string} [src]    Source to invalidate from: undefined, 'auto', 'dom'
         *     or 'data'
         * @param {int}    [colIdx] Column index to invalidate. If undefined the whole
         *     row will be invalidated
         * @memberof DataTable#oApi
         *
         * @todo For the modularisation of v1.11 this will need to become a callback, so
         *   the sort and filter methods can subscribe to it. That will required
         *   initialisation options for sorting, which is why it is not already baked in
         */
        function _fnInvalidate( settings, rowIdx, src, colIdx )
        {
            var row = settings.aoData[ rowIdx ];
            var i, ien;
            var cellWrite = function ( cell, col ) {
                // This is very frustrating, but in IE if you just write directly
                // to innerHTML, and elements that are overwritten are GC'ed,
                // even if there is a reference to them elsewhere
                while ( cell.childNodes.length ) {
                    cell.removeChild( cell.firstChild );
                }
        
                cell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' );
            };
        
            // Are we reading last data from DOM or the data object?
            if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {
                // Read the data from the DOM
                row._aData = _fnGetRowElements(
                        settings, row, colIdx, colIdx === undefined ? undefined : row._aData
                    )
                    .data;
            }
            else {
                // Reading from data object, update the DOM
                var cells = row.anCells;
        
                if ( cells ) {
                    if ( colIdx !== undefined ) {
                        cellWrite( cells[colIdx], colIdx );
                    }
                    else {
                        for ( i=0, ien=cells.length ; i<ien ; i++ ) {
                            cellWrite( cells[i], i );
                        }
                    }
                }
            }
        
            // For both row and cell invalidation, the cached data for sorting and
            // filtering is nulled out
            row._aSortData = null;
            row._aFilterData = null;
        
            // Invalidate the type for a specific column (if given) or all columns since
            // the data might have changed
            var cols = settings.aoColumns;
            if ( colIdx !== undefined ) {
                cols[ colIdx ].sType = null;
            }
            else {
                for ( i=0, ien=cols.length ; i<ien ; i++ ) {
                    cols[i].sType = null;
                }
        
                // Update DataTables special `DT_*` attributes for the row
                _fnRowAttributes( settings, row );
            }
        }
        
        
        /**
         * Build a data source object from an HTML row, reading the contents of the
         * cells that are in the row.
         *
         * @param {object} settings DataTables settings object
         * @param {node|object} TR element from which to read data or existing row
         *   object from which to re-read the data from the cells
         * @param {int} [colIdx] Optional column index
         * @param {array|object} [d] Data source object. If `colIdx` is given then this
         *   parameter should also be given and will be used to write the data into.
         *   Only the column in question will be written
         * @returns {object} Object with two parameters: `data` the data read, in
         *   document order, and `cells` and array of nodes (they can be useful to the
         *   caller, so rather than needing a second traversal to get them, just return
         *   them from here).
         * @memberof DataTable#oApi
         */
        function _fnGetRowElements( settings, row, colIdx, d )
        {
            var
                tds = [],
                td = row.firstChild,
                name, col, o, i=0, contents,
                columns = settings.aoColumns,
                objectRead = settings._rowReadObject;
        
            // Allow the data object to be passed in, or construct
            d = d !== undefined ?
                d :
                objectRead ?
                    {} :
                    [];
        
            var attr = function ( str, td  ) {
                if ( typeof str === 'string' ) {
                    var idx = str.indexOf('@');
        
                    if ( idx !== -1 ) {
                        var attr = str.substring( idx+1 );
                        var setter = _fnSetObjectDataFn( str );
                        setter( d, td.getAttribute( attr ) );
                    }
                }
            };
        
            // Read data from a cell and store into the data object
            var cellProcess = function ( cell ) {
                if ( colIdx === undefined || colIdx === i ) {
                    col = columns[i];
                    contents = $.trim(cell.innerHTML);
        
                    if ( col && col._bAttrSrc ) {
                        var setter = _fnSetObjectDataFn( col.mData._ );
                        setter( d, contents );
        
                        attr( col.mData.sort, cell );
                        attr( col.mData.type, cell );
                        attr( col.mData.filter, cell );
                    }
                    else {
                        // Depending on the `data` option for the columns the data can
                        // be read to either an object or an array.
                        if ( objectRead ) {
                            if ( ! col._setter ) {
                                // Cache the setter function
                                col._setter = _fnSetObjectDataFn( col.mData );
                            }
                            col._setter( d, contents );
                        }
                        else {
                            d[i] = contents;
                        }
                    }
                }
        
                i++;
            };
        
            if ( td ) {
                // `tr` element was passed in
                while ( td ) {
                    name = td.nodeName.toUpperCase();
        
                    if ( name == "TD" || name == "TH" ) {
                        cellProcess( td );
                        tds.push( td );
                    }
        
                    td = td.nextSibling;
                }
            }
            else {
                // Existing row object passed in
                tds = row.anCells;
        
                for ( var j=0, jen=tds.length ; j<jen ; j++ ) {
                    cellProcess( tds[j] );
                }
            }
        
            // Read the ID from the DOM if present
            var rowNode = row.firstChild ? row : row.nTr;
        
            if ( rowNode ) {
                var id = rowNode.getAttribute( 'id' );
        
                if ( id ) {
                    _fnSetObjectDataFn( settings.rowId )( d, id );
                }
            }
        
            return {
                data: d,
                cells: tds
            };
        }
        /**
         * Create a new TR element (and it's TD children) for a row
         *  @param {object} oSettings dataTables settings object
         *  @param {int} iRow Row to consider
         *  @param {node} [nTrIn] TR element to add to the table - optional. If not given,
         *    DataTables will create a row automatically
         *  @param {array} [anTds] Array of TD|TH elements for the row - must be given
         *    if nTr is.
         *  @memberof DataTable#oApi
         */
        function _fnCreateTr ( oSettings, iRow, nTrIn, anTds )
        {
            var
                row = oSettings.aoData[iRow],
                rowData = row._aData,
                cells = [],
                nTr, nTd, oCol,
                i, iLen;
        
            if ( row.nTr === null )
            {
                nTr = nTrIn || document.createElement('tr');
        
                row.nTr = nTr;
                row.anCells = cells;
        
                /* Use a private property on the node to allow reserve mapping from the node
                 * to the aoData array for fast look up
                 */
                nTr._DT_RowIndex = iRow;
        
                /* Special parameters can be given by the data source to be used on the row */
                _fnRowAttributes( oSettings, row );
        
                /* Process each column */
                for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
                {
                    oCol = oSettings.aoColumns[i];
        
                    nTd = nTrIn ? anTds[i] : document.createElement( oCol.sCellType );
                    nTd._DT_CellIndex = {
                        row: iRow,
                        column: i
                    };
                    
                    cells.push( nTd );
        
                    // Need to create the HTML if new, or if a rendering function is defined
                    if ( (!nTrIn || oCol.mRender || oCol.mData !== i) &&
                         (!$.isPlainObject(oCol.mData) || oCol.mData._ !== i+'.display')
                    ) {
                        nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' );
                    }
        
                    /* Add user defined class */
                    if ( oCol.sClass )
                    {
                        nTd.className += ' '+oCol.sClass;
                    }
        
                    // Visibility - add or remove as required
                    if ( oCol.bVisible && ! nTrIn )
                    {
                        nTr.appendChild( nTd );
                    }
                    else if ( ! oCol.bVisible && nTrIn )
                    {
                        nTd.parentNode.removeChild( nTd );
                    }
        
                    if ( oCol.fnCreatedCell )
                    {
                        oCol.fnCreatedCell.call( oSettings.oInstance,
                            nTd, _fnGetCellData( oSettings, iRow, i ), rowData, iRow, i
                        );
                    }
                }
        
                _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow] );
            }
        
            // Remove once webkit bug 131819 and Chromium bug 365619 have been resolved
            // and deployed
            row.nTr.setAttribute( 'role', 'row' );
        }
        
        
        /**
         * Add attributes to a row based on the special `DT_*` parameters in a data
         * source object.
         *  @param {object} settings DataTables settings object
         *  @param {object} DataTables row object for the row to be modified
         *  @memberof DataTable#oApi
         */
        function _fnRowAttributes( settings, row )
        {
            var tr = row.nTr;
            var data = row._aData;
        
            if ( tr ) {
                var id = settings.rowIdFn( data );
        
                if ( id ) {
                    tr.id = id;
                }
        
                if ( data.DT_RowClass ) {
                    // Remove any classes added by DT_RowClass before
                    var a = data.DT_RowClass.split(' ');
                    row.__rowc = row.__rowc ?
                        _unique( row.__rowc.concat( a ) ) :
                        a;
        
                    $(tr)
                        .removeClass( row.__rowc.join(' ') )
                        .addClass( data.DT_RowClass );
                }
        
                if ( data.DT_RowAttr ) {
                    $(tr).attr( data.DT_RowAttr );
                }
        
                if ( data.DT_RowData ) {
                    $(tr).data( data.DT_RowData );
                }
            }
        }
        
        
        /**
         * Create the HTML header for the table
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnBuildHead( oSettings )
        {
            var i, ien, cell, row, column;
            var thead = oSettings.nTHead;
            var tfoot = oSettings.nTFoot;
            var createHeader = $('th, td', thead).length === 0;
            var classes = oSettings.oClasses;
            var columns = oSettings.aoColumns;
        
            if ( createHeader ) {
                row = $('<tr/>').appendTo( thead );
            }
        
            for ( i=0, ien=columns.length ; i<ien ; i++ ) {
                column = columns[i];
                cell = $( column.nTh ).addClass( column.sClass );
        
                if ( createHeader ) {
                    cell.appendTo( row );
                }
        
                // 1.11 move into sorting
                if ( oSettings.oFeatures.bSort ) {
                    cell.addClass( column.sSortingClass );
        
                    if ( column.bSortable !== false ) {
                        cell
                            .attr( 'tabindex', oSettings.iTabIndex )
                            .attr( 'aria-controls', oSettings.sTableId );
        
                        _fnSortAttachListener( oSettings, column.nTh, i );
                    }
                }
        
                if ( column.sTitle != cell[0].innerHTML ) {
                    cell.html( column.sTitle );
                }
        
                _fnRenderer( oSettings, 'header' )(
                    oSettings, cell, column, classes
                );
            }
        
            if ( createHeader ) {
                _fnDetectHeader( oSettings.aoHeader, thead );
            }
            
            /* ARIA role for the rows */
             $(thead).find('>tr').attr('role', 'row');
        
            /* Deal with the footer - add classes if required */
            $(thead).find('>tr>th, >tr>td').addClass( classes.sHeaderTH );
            $(tfoot).find('>tr>th, >tr>td').addClass( classes.sFooterTH );
        
            // Cache the footer cells. Note that we only take the cells from the first
            // row in the footer. If there is more than one row the user wants to
            // interact with, they need to use the table().foot() method. Note also this
            // allows cells to be used for multiple columns using colspan
            if ( tfoot !== null ) {
                var cells = oSettings.aoFooter[0];
        
                for ( i=0, ien=cells.length ; i<ien ; i++ ) {
                    column = columns[i];
                    column.nTf = cells[i].cell;
        
                    if ( column.sClass ) {
                        $(column.nTf).addClass( column.sClass );
                    }
                }
            }
        }
        
        
        /**
         * Draw the header (or footer) element based on the column visibility states. The
         * methodology here is to use the layout array from _fnDetectHeader, modified for
         * the instantaneous column visibility, to construct the new layout. The grid is
         * traversed over cell at a time in a rows x columns grid fashion, although each
         * cell insert can cover multiple elements in the grid - which is tracks using the
         * aApplied array. Cell inserts in the grid will only occur where there isn't
         * already a cell in that position.
         *  @param {object} oSettings dataTables settings object
         *  @param array {objects} aoSource Layout array from _fnDetectHeader
         *  @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
         *  @memberof DataTable#oApi
         */
        function _fnDrawHead( oSettings, aoSource, bIncludeHidden )
        {
            var i, iLen, j, jLen, k, kLen, n, nLocalTr;
            var aoLocal = [];
            var aApplied = [];
            var iColumns = oSettings.aoColumns.length;
            var iRowspan, iColspan;
        
            if ( ! aoSource )
            {
                return;
            }
        
            if (  bIncludeHidden === undefined )
            {
                bIncludeHidden = false;
            }
        
            /* Make a copy of the master layout array, but without the visible columns in it */
            for ( i=0, iLen=aoSource.length ; i<iLen ; i++ )
            {
                aoLocal[i] = aoSource[i].slice();
                aoLocal[i].nTr = aoSource[i].nTr;
        
                /* Remove any columns which are currently hidden */
                for ( j=iColumns-1 ; j>=0 ; j-- )
                {
                    if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden )
                    {
                        aoLocal[i].splice( j, 1 );
                    }
                }
        
                /* Prep the applied array - it needs an element for each row */
                aApplied.push( [] );
            }
        
            for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ )
            {
                nLocalTr = aoLocal[i].nTr;
        
                /* All cells are going to be replaced, so empty out the row */
                if ( nLocalTr )
                {
                    while( (n = nLocalTr.firstChild) )
                    {
                        nLocalTr.removeChild( n );
                    }
                }
        
                for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ )
                {
                    iRowspan = 1;
                    iColspan = 1;
        
                    /* Check to see if there is already a cell (row/colspan) covering our target
                     * insert point. If there is, then there is nothing to do.
                     */
                    if ( aApplied[i][j] === undefined )
                    {
                        nLocalTr.appendChild( aoLocal[i][j].cell );
                        aApplied[i][j] = 1;
        
                        /* Expand the cell to cover as many rows as needed */
                        while ( aoLocal[i+iRowspan] !== undefined &&
                                aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell )
                        {
                            aApplied[i+iRowspan][j] = 1;
                            iRowspan++;
                        }
        
                        /* Expand the cell to cover as many columns as needed */
                        while ( aoLocal[i][j+iColspan] !== undefined &&
                                aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell )
                        {
                            /* Must update the applied array over the rows for the columns */
                            for ( k=0 ; k<iRowspan ; k++ )
                            {
                                aApplied[i+k][j+iColspan] = 1;
                            }
                            iColspan++;
                        }
        
                        /* Do the actual expansion in the DOM */
                        $(aoLocal[i][j].cell)
                            .attr('rowspan', iRowspan)
                            .attr('colspan', iColspan);
                    }
                }
            }
        }
        
        
        /**
         * Insert the required TR nodes into the table for display
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnDraw( oSettings )
        {
            /* Provide a pre-callback function which can be used to cancel the draw is false is returned */
            var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] );
            if ( $.inArray( false, aPreDraw ) !== -1 )
            {
                _fnProcessingDisplay( oSettings, false );
                return;
            }
        
            var i, iLen, n;
            var anRows = [];
            var iRowCount = 0;
            var asStripeClasses = oSettings.asStripeClasses;
            var iStripes = asStripeClasses.length;
            var iOpenRows = oSettings.aoOpenRows.length;
            var oLang = oSettings.oLanguage;
            var iInitDisplayStart = oSettings.iInitDisplayStart;
            var bServerSide = _fnDataSource( oSettings ) == 'ssp';
            var aiDisplay = oSettings.aiDisplay;
        
            oSettings.bDrawing = true;
        
            /* Check and see if we have an initial draw position from state saving */
            if ( iInitDisplayStart !== undefined && iInitDisplayStart !== -1 )
            {
                oSettings._iDisplayStart = bServerSide ?
                    iInitDisplayStart :
                    iInitDisplayStart >= oSettings.fnRecordsDisplay() ?
                        0 :
                        iInitDisplayStart;
        
                oSettings.iInitDisplayStart = -1;
            }
        
            var iDisplayStart = oSettings._iDisplayStart;
            var iDisplayEnd = oSettings.fnDisplayEnd();
        
            /* Server-side processing draw intercept */
            if ( oSettings.bDeferLoading )
            {
                oSettings.bDeferLoading = false;
                oSettings.iDraw++;
                _fnProcessingDisplay( oSettings, false );
            }
            else if ( !bServerSide )
            {
                oSettings.iDraw++;
            }
            else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) )
            {
                return;
            }
        
            if ( aiDisplay.length !== 0 )
            {
                var iStart = bServerSide ? 0 : iDisplayStart;
                var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd;
        
                for ( var j=iStart ; j<iEnd ; j++ )
                {
                    var iDataIndex = aiDisplay[j];
                    var aoData = oSettings.aoData[ iDataIndex ];
                    if ( aoData.nTr === null )
                    {
                        _fnCreateTr( oSettings, iDataIndex );
                    }
        
                    var nRow = aoData.nTr;
        
                    /* Remove the old striping classes and then add the new one */
                    if ( iStripes !== 0 )
                    {
                        var sStripe = asStripeClasses[ iRowCount % iStripes ];
                        if ( aoData._sRowStripe != sStripe )
                        {
                            $(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe );
                            aoData._sRowStripe = sStripe;
                        }
                    }
        
                    // Row callback functions - might want to manipulate the row
                    // iRowCount and j are not currently documented. Are they at all
                    // useful?
                    _fnCallbackFire( oSettings, 'aoRowCallback', null,
                        [nRow, aoData._aData, iRowCount, j] );
        
                    anRows.push( nRow );
                    iRowCount++;
                }
            }
            else
            {
                /* Table is empty - create a row with an empty message in it */
                var sZero = oLang.sZeroRecords;
                if ( oSettings.iDraw == 1 &&  _fnDataSource( oSettings ) == 'ajax' )
                {
                    sZero = oLang.sLoadingRecords;
                }
                else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 )
                {
                    sZero = oLang.sEmptyTable;
                }
        
                anRows[ 0 ] = $( '<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' } )
                    .append( $('<td />', {
                        'valign':  'top',
                        'colSpan': _fnVisbleColumns( oSettings ),
                        'class':   oSettings.oClasses.sRowEmpty
                    } ).html( sZero ) )[0];
            }
        
            /* Header and footer callbacks */
            _fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0],
                _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
        
            _fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0],
                _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
        
            var body = $(oSettings.nTBody);
        
            body.children().detach();
            body.append( $(anRows) );
        
            /* Call all required callback functions for the end of a draw */
            _fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] );
        
            /* Draw is complete, sorting and filtering must be as well */
            oSettings.bSorted = false;
            oSettings.bFiltered = false;
            oSettings.bDrawing = false;
        }
        
        
        /**
         * Redraw the table - taking account of the various features which are enabled
         *  @param {object} oSettings dataTables settings object
         *  @param {boolean} [holdPosition] Keep the current paging position. By default
         *    the paging is reset to the first page
         *  @memberof DataTable#oApi
         */
        function _fnReDraw( settings, holdPosition )
        {
            var
                features = settings.oFeatures,
                sort     = features.bSort,
                filter   = features.bFilter;
        
            if ( sort ) {
                _fnSort( settings );
            }
        
            if ( filter ) {
                _fnFilterComplete( settings, settings.oPreviousSearch );
            }
            else {
                // No filtering, so we want to just use the display master
                settings.aiDisplay = settings.aiDisplayMaster.slice();
            }
        
            if ( holdPosition !== true ) {
                settings._iDisplayStart = 0;
            }
        
            // Let any modules know about the draw hold position state (used by
            // scrolling internally)
            settings._drawHold = holdPosition;
        
            _fnDraw( settings );
        
            settings._drawHold = false;
        }
        
        
        /**
         * Add the options to the page HTML for the table
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnAddOptionsHtml ( oSettings )
        {
            var classes = oSettings.oClasses;
            var table = $(oSettings.nTable);
            var holding = $('<div/>').insertBefore( table ); // Holding element for speed
            var features = oSettings.oFeatures;
        
            // All DataTables are wrapped in a div
            var insert = $('<div/>', {
                id:      oSettings.sTableId+'_wrapper',
                'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' '+classes.sNoFooter)
            } );
        
            oSettings.nHolding = holding[0];
            oSettings.nTableWrapper = insert[0];
            oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
        
            /* Loop over the user set positioning and place the elements as needed */
            var aDom = oSettings.sDom.split('');
            var featureNode, cOption, nNewNode, cNext, sAttr, j;
            for ( var i=0 ; i<aDom.length ; i++ )
            {
                featureNode = null;
                cOption = aDom[i];
        
                if ( cOption == '<' )
                {
                    /* New container div */
                    nNewNode = $('<div/>')[0];
        
                    /* Check to see if we should append an id and/or a class name to the container */
                    cNext = aDom[i+1];
                    if ( cNext == "'" || cNext == '"' )
                    {
                        sAttr = "";
                        j = 2;
                        while ( aDom[i+j] != cNext )
                        {
                            sAttr += aDom[i+j];
                            j++;
                        }
        
                        /* Replace jQuery UI constants @todo depreciated */
                        if ( sAttr == "H" )
                        {
                            sAttr = classes.sJUIHeader;
                        }
                        else if ( sAttr == "F" )
                        {
                            sAttr = classes.sJUIFooter;
                        }
        
                        /* The attribute can be in the format of "#id.class", "#id" or "class" This logic
                         * breaks the string into parts and applies them as needed
                         */
                        if ( sAttr.indexOf('.') != -1 )
                        {
                            var aSplit = sAttr.split('.');
                            nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1);
                            nNewNode.className = aSplit[1];
                        }
                        else if ( sAttr.charAt(0) == "#" )
                        {
                            nNewNode.id = sAttr.substr(1, sAttr.length-1);
                        }
                        else
                        {
                            nNewNode.className = sAttr;
                        }
        
                        i += j; /* Move along the position array */
                    }
        
                    insert.append( nNewNode );
                    insert = $(nNewNode);
                }
                else if ( cOption == '>' )
                {
                    /* End container div */
                    insert = insert.parent();
                }
                // @todo Move options into their own plugins?
                else if ( cOption == 'l' && features.bPaginate && features.bLengthChange )
                {
                    /* Length */
                    featureNode = _fnFeatureHtmlLength( oSettings );
                }
                else if ( cOption == 'f' && features.bFilter )
                {
                    /* Filter */
                    featureNode = _fnFeatureHtmlFilter( oSettings );
                }
                else if ( cOption == 'r' && features.bProcessing )
                {
                    /* pRocessing */
                    featureNode = _fnFeatureHtmlProcessing( oSettings );
                }
                else if ( cOption == 't' )
                {
                    /* Table */
                    featureNode = _fnFeatureHtmlTable( oSettings );
                }
                else if ( cOption ==  'i' && features.bInfo )
                {
                    /* Info */
                    featureNode = _fnFeatureHtmlInfo( oSettings );
                }
                else if ( cOption == 'p' && features.bPaginate )
                {
                    /* Pagination */
                    featureNode = _fnFeatureHtmlPaginate( oSettings );
                }
                else if ( DataTable.ext.feature.length !== 0 )
                {
                    /* Plug-in features */
                    var aoFeatures = DataTable.ext.feature;
                    for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ )
                    {
                        if ( cOption == aoFeatures[k].cFeature )
                        {
                            featureNode = aoFeatures[k].fnInit( oSettings );
                            break;
                        }
                    }
                }
        
                /* Add to the 2D features array */
                if ( featureNode )
                {
                    var aanFeatures = oSettings.aanFeatures;
        
                    if ( ! aanFeatures[cOption] )
                    {
                        aanFeatures[cOption] = [];
                    }
        
                    aanFeatures[cOption].push( featureNode );
                    insert.append( featureNode );
                }
            }
        
            /* Built our DOM structure - replace the holding div with what we want */
            holding.replaceWith( insert );
            oSettings.nHolding = null;
        }
        
        
        /**
         * Use the DOM source to create up an array of header cells. The idea here is to
         * create a layout grid (array) of rows x columns, which contains a reference
         * to the cell that that point in the grid (regardless of col/rowspan), such that
         * any column / row could be removed and the new grid constructed
         *  @param array {object} aLayout Array to store the calculated layout in
         *  @param {node} nThead The header/footer element for the table
         *  @memberof DataTable#oApi
         */
        function _fnDetectHeader ( aLayout, nThead )
        {
            var nTrs = $(nThead).children('tr');
            var nTr, nCell;
            var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
            var bUnique;
            var fnShiftCol = function ( a, i, j ) {
                var k = a[i];
                        while ( k[j] ) {
                    j++;
                }
                return j;
            };
        
            aLayout.splice( 0, aLayout.length );
        
            /* We know how many rows there are in the layout - so prep it */
            for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
            {
                aLayout.push( [] );
            }
        
            /* Calculate a layout array */
            for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
            {
                nTr = nTrs[i];
                iColumn = 0;
        
                /* For every cell in the row... */
                nCell = nTr.firstChild;
                while ( nCell ) {
                    if ( nCell.nodeName.toUpperCase() == "TD" ||
                         nCell.nodeName.toUpperCase() == "TH" )
                    {
                        /* Get the col and rowspan attributes from the DOM and sanitise them */
                        iColspan = nCell.getAttribute('colspan') * 1;
                        iRowspan = nCell.getAttribute('rowspan') * 1;
                        iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan;
                        iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan;
        
                        /* There might be colspan cells already in this row, so shift our target
                         * accordingly
                         */
                        iColShifted = fnShiftCol( aLayout, i, iColumn );
        
                        /* Cache calculation for unique columns */
                        bUnique = iColspan === 1 ? true : false;
        
                        /* If there is col / rowspan, copy the information into the layout grid */
                        for ( l=0 ; l<iColspan ; l++ )
                        {
                            for ( k=0 ; k<iRowspan ; k++ )
                            {
                                aLayout[i+k][iColShifted+l] = {
                                    "cell": nCell,
                                    "unique": bUnique
                                };
                                aLayout[i+k].nTr = nTr;
                            }
                        }
                    }
                    nCell = nCell.nextSibling;
                }
            }
        }
        
        
        /**
         * Get an array of unique th elements, one for each column
         *  @param {object} oSettings dataTables settings object
         *  @param {node} nHeader automatically detect the layout from this node - optional
         *  @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
         *  @returns array {node} aReturn list of unique th's
         *  @memberof DataTable#oApi
         */
        function _fnGetUniqueThs ( oSettings, nHeader, aLayout )
        {
            var aReturn = [];
            if ( !aLayout )
            {
                aLayout = oSettings.aoHeader;
                if ( nHeader )
                {
                    aLayout = [];
                    _fnDetectHeader( aLayout, nHeader );
                }
            }
        
            for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ )
            {
                for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ )
                {
                    if ( aLayout[i][j].unique &&
                         (!aReturn[j] || !oSettings.bSortCellsTop) )
                    {
                        aReturn[j] = aLayout[i][j].cell;
                    }
                }
            }
        
            return aReturn;
        }
        
        /**
         * Create an Ajax call based on the table's settings, taking into account that
         * parameters can have multiple forms, and backwards compatibility.
         *
         * @param {object} oSettings dataTables settings object
         * @param {array} data Data to send to the server, required by
         *     DataTables - may be augmented by developer callbacks
         * @param {function} fn Callback function to run when data is obtained
         */
        function _fnBuildAjax( oSettings, data, fn )
        {
            // Compatibility with 1.9-, allow fnServerData and event to manipulate
            _fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] );
        
            // Convert to object based for 1.10+ if using the old array scheme which can
            // come from server-side processing or serverParams
            if ( data && $.isArray(data) ) {
                var tmp = {};
                var rbracket = /(.*?)\[\]$/;
        
                $.each( data, function (key, val) {
                    var match = val.name.match(rbracket);
        
                    if ( match ) {
                        // Support for arrays
                        var name = match[0];
        
                        if ( ! tmp[ name ] ) {
                            tmp[ name ] = [];
                        }
                        tmp[ name ].push( val.value );
                    }
                    else {
                        tmp[val.name] = val.value;
                    }
                } );
                data = tmp;
            }
        
            var ajaxData;
            var ajax = oSettings.ajax;
            var instance = oSettings.oInstance;
            var callback = function ( json ) {
                _fnCallbackFire( oSettings, null, 'xhr', [oSettings, json, oSettings.jqXHR] );
                fn( json );
            };
        
            if ( $.isPlainObject( ajax ) && ajax.data )
            {
                ajaxData = ajax.data;
        
                var newData = $.isFunction( ajaxData ) ?
                    ajaxData( data, oSettings ) :  // fn can manipulate data or return
                    ajaxData;                      // an object object or array to merge
        
                // If the function returned something, use that alone
                data = $.isFunction( ajaxData ) && newData ?
                    newData :
                    $.extend( true, data, newData );
        
                // Remove the data property as we've resolved it already and don't want
                // jQuery to do it again (it is restored at the end of the function)
                delete ajax.data;
            }
        
            var baseAjax = {
                "data": data,
                "success": function (json) {
                    var error = json.error || json.sError;
                    if ( error ) {
                        _fnLog( oSettings, 0, error );
                    }
        
                    oSettings.json = json;
                    callback( json );
                },
                "dataType": "json",
                "cache": false,
                "type": oSettings.sServerMethod,
                "error": function (xhr, error, thrown) {
                    var ret = _fnCallbackFire( oSettings, null, 'xhr', [oSettings, null, oSettings.jqXHR] );
        
                    if ( $.inArray( true, ret ) === -1 ) {
                        if ( error == "parsererror" ) {
                            _fnLog( oSettings, 0, 'Invalid JSON response', 1 );
                        }
                        else if ( xhr.readyState === 4 ) {
                            _fnLog( oSettings, 0, 'Ajax error', 7 );
                        }
                    }
        
                    _fnProcessingDisplay( oSettings, false );
                }
            };
        
            // Store the data submitted for the API
            oSettings.oAjaxData = data;
        
            // Allow plug-ins and external processes to modify the data
            _fnCallbackFire( oSettings, null, 'preXhr', [oSettings, data] );
        
            if ( oSettings.fnServerData )
            {
                // DataTables 1.9- compatibility
                oSettings.fnServerData.call( instance,
                    oSettings.sAjaxSource,
                    $.map( data, function (val, key) { // Need to convert back to 1.9 trad format
                        return { name: key, value: val };
                    } ),
                    callback,
                    oSettings
                );
            }
            else if ( oSettings.sAjaxSource || typeof ajax === 'string' )
            {
                // DataTables 1.9- compatibility
                oSettings.jqXHR = $.ajax( $.extend( baseAjax, {
                    url: ajax || oSettings.sAjaxSource
                } ) );
            }
            else if ( $.isFunction( ajax ) )
            {
                // Is a function - let the caller define what needs to be done
                oSettings.jqXHR = ajax.call( instance, data, callback, oSettings );
            }
            else
            {
                // Object to extend the base settings
                oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) );
        
                // Restore for next time around
                ajax.data = ajaxData;
            }
        }
        
        
        /**
         * Update the table using an Ajax call
         *  @param {object} settings dataTables settings object
         *  @returns {boolean} Block the table drawing or not
         *  @memberof DataTable#oApi
         */
        function _fnAjaxUpdate( settings )
        {
            if ( settings.bAjaxDataGet ) {
                settings.iDraw++;
                _fnProcessingDisplay( settings, true );
        
                _fnBuildAjax(
                    settings,
                    _fnAjaxParameters( settings ),
                    function(json) {
                        _fnAjaxUpdateDraw( settings, json );
                    }
                );
        
                return false;
            }
            return true;
        }
        
        
        /**
         * Build up the parameters in an object needed for a server-side processing
         * request. Note that this is basically done twice, is different ways - a modern
         * method which is used by default in DataTables 1.10 which uses objects and
         * arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if
         * the sAjaxSource option is used in the initialisation, or the legacyAjax
         * option is set.
         *  @param {object} oSettings dataTables settings object
         *  @returns {bool} block the table drawing or not
         *  @memberof DataTable#oApi
         */
        function _fnAjaxParameters( settings )
        {
            var
                columns = settings.aoColumns,
                columnCount = columns.length,
                features = settings.oFeatures,
                preSearch = settings.oPreviousSearch,
                preColSearch = settings.aoPreSearchCols,
                i, data = [], dataProp, column, columnSearch,
                sort = _fnSortFlatten( settings ),
                displayStart = settings._iDisplayStart,
                displayLength = features.bPaginate !== false ?
                    settings._iDisplayLength :
                    -1;
        
            var param = function ( name, value ) {
                data.push( { 'name': name, 'value': value } );
            };
        
            // DataTables 1.9- compatible method
            param( 'sEcho',          settings.iDraw );
            param( 'iColumns',       columnCount );
            param( 'sColumns',       _pluck( columns, 'sName' ).join(',') );
            param( 'iDisplayStart',  displayStart );
            param( 'iDisplayLength', displayLength );
        
            // DataTables 1.10+ method
            var d = {
                draw:    settings.iDraw,
                columns: [],
                order:   [],
                start:   displayStart,
                length:  displayLength,
                search:  {
                    value: preSearch.sSearch,
                    regex: preSearch.bRegex
                }
            };
        
            for ( i=0 ; i<columnCount ; i++ ) {
                column = columns[i];
                columnSearch = preColSearch[i];
                dataProp = typeof column.mData=="function" ? 'function' : column.mData ;
        
                d.columns.push( {
                    data:       dataProp,
                    name:       column.sName,
                    searchable: column.bSearchable,
                    orderable:  column.bSortable,
                    search:     {
                        value: columnSearch.sSearch,
                        regex: columnSearch.bRegex
                    }
                } );
        
                param( "mDataProp_"+i, dataProp );
        
                if ( features.bFilter ) {
                    param( 'sSearch_'+i,     columnSearch.sSearch );
                    param( 'bRegex_'+i,      columnSearch.bRegex );
                    param( 'bSearchable_'+i, column.bSearchable );
                }
        
                if ( features.bSort ) {
                    param( 'bSortable_'+i, column.bSortable );
                }
            }
        
            if ( features.bFilter ) {
                param( 'sSearch', preSearch.sSearch );
                param( 'bRegex', preSearch.bRegex );
            }
        
            if ( features.bSort ) {
                $.each( sort, function ( i, val ) {
                    d.order.push( { column: val.col, dir: val.dir } );
        
                    param( 'iSortCol_'+i, val.col );
                    param( 'sSortDir_'+i, val.dir );
                } );
        
                param( 'iSortingCols', sort.length );
            }
        
            // If the legacy.ajax parameter is null, then we automatically decide which
            // form to use, based on sAjaxSource
            var legacy = DataTable.ext.legacy.ajax;
            if ( legacy === null ) {
                return settings.sAjaxSource ? data : d;
            }
        
            // Otherwise, if legacy has been specified then we use that to decide on the
            // form
            return legacy ? data : d;
        }
        
        
        /**
         * Data the data from the server (nuking the old) and redraw the table
         *  @param {object} oSettings dataTables settings object
         *  @param {object} json json data return from the server.
         *  @param {string} json.sEcho Tracking flag for DataTables to match requests
         *  @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
         *  @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
         *  @param {array} json.aaData The data to display on this page
         *  @param {string} [json.sColumns] Column ordering (sName, comma separated)
         *  @memberof DataTable#oApi
         */
        function _fnAjaxUpdateDraw ( settings, json )
        {
            // v1.10 uses camelCase variables, while 1.9 uses Hungarian notation.
            // Support both
            var compat = function ( old, modern ) {
                return json[old] !== undefined ? json[old] : json[modern];
            };
        
            var data = _fnAjaxDataSrc( settings, json );
            var draw            = compat( 'sEcho',                'draw' );
            var recordsTotal    = compat( 'iTotalRecords',        'recordsTotal' );
            var recordsFiltered = compat( 'iTotalDisplayRecords', 'recordsFiltered' );
        
            if ( draw ) {
                // Protect against out of sequence returns
                if ( draw*1 < settings.iDraw ) {
                    return;
                }
                settings.iDraw = draw * 1;
            }
        
            _fnClearTable( settings );
            settings._iRecordsTotal   = parseInt(recordsTotal, 10);
            settings._iRecordsDisplay = parseInt(recordsFiltered, 10);
        
            for ( var i=0, ien=data.length ; i<ien ; i++ ) {
                _fnAddData( settings, data[i] );
            }
            settings.aiDisplay = settings.aiDisplayMaster.slice();
        
            settings.bAjaxDataGet = false;
            _fnDraw( settings );
        
            if ( ! settings._bInitComplete ) {
                _fnInitComplete( settings, json );
            }
        
            settings.bAjaxDataGet = true;
            _fnProcessingDisplay( settings, false );
        }
        
        
        /**
         * Get the data from the JSON data source to use for drawing a table. Using
         * `_fnGetObjectDataFn` allows the data to be sourced from a property of the
         * source object, or from a processing function.
         *  @param {object} oSettings dataTables settings object
         *  @param  {object} json Data source object / array from the server
         *  @return {array} Array of data to use
         */
        function _fnAjaxDataSrc ( oSettings, json )
        {
            var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ?
                oSettings.ajax.dataSrc :
                oSettings.sAjaxDataProp; // Compatibility with 1.9-.
        
            // Compatibility with 1.9-. In order to read from aaData, check if the
            // default has been changed, if not, check for aaData
            if ( dataSrc === 'data' ) {
                return json.aaData || json[dataSrc];
            }
        
            return dataSrc !== "" ?
                _fnGetObjectDataFn( dataSrc )( json ) :
                json;
        }
        
        /**
         * Generate the node required for filtering text
         *  @returns {node} Filter control element
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnFeatureHtmlFilter ( settings )
        {
            var classes = settings.oClasses;
            var tableId = settings.sTableId;
            var language = settings.oLanguage;
            var previousSearch = settings.oPreviousSearch;
            var features = settings.aanFeatures;
            var input = '<input type="search" class="'+classes.sFilterInput+'"/>';
        
            var str = language.sSearch;
            str = str.match(/_INPUT_/) ?
                str.replace('_INPUT_', input) :
                str+input;
        
            var filter = $('<div/>', {
                    'id': ! features.f ? tableId+'_filter' : null,
                    'class': classes.sFilter
                } )
                .append( $('<label/>' ).append( str ) );
        
            var searchFn = function() {
                /* Update all other filter input elements for the new display */
                var n = features.f;
                var val = !this.value ? "" : this.value; // mental IE8 fix :-(
        
                /* Now do the filter */
                if ( val != previousSearch.sSearch ) {
                    _fnFilterComplete( settings, {
                        "sSearch": val,
                        "bRegex": previousSearch.bRegex,
                        "bSmart": previousSearch.bSmart ,
                        "bCaseInsensitive": previousSearch.bCaseInsensitive
                    } );
        
                    // Need to redraw, without resorting
                    settings._iDisplayStart = 0;
                    _fnDraw( settings );
                }
            };
        
            var searchDelay = settings.searchDelay !== null ?
                settings.searchDelay :
                _fnDataSource( settings ) === 'ssp' ?
                    400 :
                    0;
        
            var jqFilter = $('input', filter)
                .val( previousSearch.sSearch )
                .attr( 'placeholder', language.sSearchPlaceholder )
                .bind(
                    'keyup.DT search.DT input.DT paste.DT cut.DT',
                    searchDelay ?
                        _fnThrottle( searchFn, searchDelay ) :
                        searchFn
                )
                .bind( 'keypress.DT', function(e) {
                    /* Prevent form submission */
                    if ( e.keyCode == 13 ) {
                        return false;
                    }
                } )
                .attr('aria-controls', tableId);
        
            // Update the input elements whenever the table is filtered
            $(settings.nTable).on( 'search.dt.DT', function ( ev, s ) {
                if ( settings === s ) {
                    // IE9 throws an 'unknown error' if document.activeElement is used
                    // inside an iframe or frame...
                    try {
                        if ( jqFilter[0] !== document.activeElement ) {
                            jqFilter.val( previousSearch.sSearch );
                        }
                    }
                    catch ( e ) {}
                }
            } );
        
            return filter[0];
        }
        
        
        /**
         * Filter the table using both the global filter and column based filtering
         *  @param {object} oSettings dataTables settings object
         *  @param {object} oSearch search information
         *  @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
         *  @memberof DataTable#oApi
         */
        function _fnFilterComplete ( oSettings, oInput, iForce )
        {
            var oPrevSearch = oSettings.oPreviousSearch;
            var aoPrevSearch = oSettings.aoPreSearchCols;
            var fnSaveFilter = function ( oFilter ) {
                /* Save the filtering values */
                oPrevSearch.sSearch = oFilter.sSearch;
                oPrevSearch.bRegex = oFilter.bRegex;
                oPrevSearch.bSmart = oFilter.bSmart;
                oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
            };
            var fnRegex = function ( o ) {
                // Backwards compatibility with the bEscapeRegex option
                return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex;
            };
        
            // Resolve any column types that are unknown due to addition or invalidation
            // @todo As per sort - can this be moved into an event handler?
            _fnColumnTypes( oSettings );
        
            /* In server-side processing all filtering is done by the server, so no point hanging around here */
            if ( _fnDataSource( oSettings ) != 'ssp' )
            {
                /* Global filter */
                _fnFilter( oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive );
                fnSaveFilter( oInput );
        
                /* Now do the individual column filter */
                for ( var i=0 ; i<aoPrevSearch.length ; i++ )
                {
                    _fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]),
                        aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive );
                }
        
                /* Custom filtering */
                _fnFilterCustom( oSettings );
            }
            else
            {
                fnSaveFilter( oInput );
            }
        
            /* Tell the draw function we have been filtering */
            oSettings.bFiltered = true;
            _fnCallbackFire( oSettings, null, 'search', [oSettings] );
        }
        
        
        /**
         * Apply custom filtering functions
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnFilterCustom( settings )
        {
            var filters = DataTable.ext.search;
            var displayRows = settings.aiDisplay;
            var row, rowIdx;
        
            for ( var i=0, ien=filters.length ; i<ien ; i++ ) {
                var rows = [];
        
                // Loop over each row and see if it should be included
                for ( var j=0, jen=displayRows.length ; j<jen ; j++ ) {
                    rowIdx = displayRows[ j ];
                    row = settings.aoData[ rowIdx ];
        
                    if ( filters[i]( settings, row._aFilterData, rowIdx, row._aData, j ) ) {
                        rows.push( rowIdx );
                    }
                }
        
                // So the array reference doesn't break set the results into the
                // existing array
                displayRows.length = 0;
                $.merge( displayRows, rows );
            }
        }
        
        
        /**
         * Filter the table on a per-column basis
         *  @param {object} oSettings dataTables settings object
         *  @param {string} sInput string to filter on
         *  @param {int} iColumn column to filter
         *  @param {bool} bRegex treat search string as a regular expression or not
         *  @param {bool} bSmart use smart filtering or not
         *  @param {bool} bCaseInsensitive Do case insenstive matching or not
         *  @memberof DataTable#oApi
         */
        function _fnFilterColumn ( settings, searchStr, colIdx, regex, smart, caseInsensitive )
        {
            if ( searchStr === '' ) {
                return;
            }
        
            var data;
            var display = settings.aiDisplay;
            var rpSearch = _fnFilterCreateSearch( searchStr, regex, smart, caseInsensitive );
        
            for ( var i=display.length-1 ; i>=0 ; i-- ) {
                data = settings.aoData[ display[i] ]._aFilterData[ colIdx ];
        
                if ( ! rpSearch.test( data ) ) {
                    display.splice( i, 1 );
                }
            }
        }
        
        
        /**
         * Filter the data table based on user input and draw the table
         *  @param {object} settings dataTables settings object
         *  @param {string} input string to filter on
         *  @param {int} force optional - force a research of the master array (1) or not (undefined or 0)
         *  @param {bool} regex treat as a regular expression or not
         *  @param {bool} smart perform smart filtering or not
         *  @param {bool} caseInsensitive Do case insenstive matching or not
         *  @memberof DataTable#oApi
         */
        function _fnFilter( settings, input, force, regex, smart, caseInsensitive )
        {
            var rpSearch = _fnFilterCreateSearch( input, regex, smart, caseInsensitive );
            var prevSearch = settings.oPreviousSearch.sSearch;
            var displayMaster = settings.aiDisplayMaster;
            var display, invalidated, i;
        
            // Need to take account of custom filtering functions - always filter
            if ( DataTable.ext.search.length !== 0 ) {
                force = true;
            }
        
            // Check if any of the rows were invalidated
            invalidated = _fnFilterData( settings );
        
            // If the input is blank - we just want the full data set
            if ( input.length <= 0 ) {
                settings.aiDisplay = displayMaster.slice();
            }
            else {
                // New search - start from the master array
                if ( invalidated ||
                     force ||
                     prevSearch.length > input.length ||
                     input.indexOf(prevSearch) !== 0 ||
                     settings.bSorted // On resort, the display master needs to be
                                      // re-filtered since indexes will have changed
                ) {
                    settings.aiDisplay = displayMaster.slice();
                }
        
                // Search the display array
                display = settings.aiDisplay;
        
                for ( i=display.length-1 ; i>=0 ; i-- ) {
                    if ( ! rpSearch.test( settings.aoData[ display[i] ]._sFilterRow ) ) {
                        display.splice( i, 1 );
                    }
                }
            }
        }
        
        
        /**
         * Build a regular expression object suitable for searching a table
         *  @param {string} sSearch string to search for
         *  @param {bool} bRegex treat as a regular expression or not
         *  @param {bool} bSmart perform smart filtering or not
         *  @param {bool} bCaseInsensitive Do case insensitive matching or not
         *  @returns {RegExp} constructed object
         *  @memberof DataTable#oApi
         */
        function _fnFilterCreateSearch( search, regex, smart, caseInsensitive )
        {
            search = regex ?
                search :
                _fnEscapeRegex( search );
            
            if ( smart ) {
                /* For smart filtering we want to allow the search to work regardless of
                 * word order. We also want double quoted text to be preserved, so word
                 * order is important - a la google. So this is what we want to
                 * generate:
                 * 
                 * ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$
                 */
                var a = $.map( search.match( /"[^"]+"|[^ ]+/g ) || [''], function ( word ) {
                    if ( word.charAt(0) === '"' ) {
                        var m = word.match( /^"(.*)"$/ );
                        word = m ? m[1] : word;
                    }
        
                    return word.replace('"', '');
                } );
        
                search = '^(?=.*?'+a.join( ')(?=.*?' )+').*$';
            }
        
            return new RegExp( search, caseInsensitive ? 'i' : '' );
        }
        
        
        /**
         * Escape a string such that it can be used in a regular expression
         *  @param {string} sVal string to escape
         *  @returns {string} escaped string
         *  @memberof DataTable#oApi
         */
        var _fnEscapeRegex = DataTable.util.escapeRegex;
        
        var __filter_div = $('<div>')[0];
        var __filter_div_textContent = __filter_div.textContent !== undefined;
        
        // Update the filtering data for each row if needed (by invalidation or first run)
        function _fnFilterData ( settings )
        {
            var columns = settings.aoColumns;
            var column;
            var i, j, ien, jen, filterData, cellData, row;
            var fomatters = DataTable.ext.type.search;
            var wasInvalidated = false;
        
            for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
                row = settings.aoData[i];
        
                if ( ! row._aFilterData ) {
                    filterData = [];
        
                    for ( j=0, jen=columns.length ; j<jen ; j++ ) {
                        column = columns[j];
        
                        if ( column.bSearchable ) {
                            cellData = _fnGetCellData( settings, i, j, 'filter' );
        
                            if ( fomatters[ column.sType ] ) {
                                cellData = fomatters[ column.sType ]( cellData );
                            }
        
                            // Search in DataTables 1.10 is string based. In 1.11 this
                            // should be altered to also allow strict type checking.
                            if ( cellData === null ) {
                                cellData = '';
                            }
        
                            if ( typeof cellData !== 'string' && cellData.toString ) {
                                cellData = cellData.toString();
                            }
                        }
                        else {
                            cellData = '';
                        }
        
                        // If it looks like there is an HTML entity in the string,
                        // attempt to decode it so sorting works as expected. Note that
                        // we could use a single line of jQuery to do this, but the DOM
                        // method used here is much faster http://jsperf.com/html-decode
                        if ( cellData.indexOf && cellData.indexOf('&') !== -1 ) {
                            __filter_div.innerHTML = cellData;
                            cellData = __filter_div_textContent ?
                                __filter_div.textContent :
                                __filter_div.innerText;
                        }
        
                        if ( cellData.replace ) {
                            cellData = cellData.replace(/[\r\n]/g, '');
                        }
        
                        filterData.push( cellData );
                    }
        
                    row._aFilterData = filterData;
                    row._sFilterRow = filterData.join('  ');
                    wasInvalidated = true;
                }
            }
        
            return wasInvalidated;
        }
        
        
        /**
         * Convert from the internal Hungarian notation to camelCase for external
         * interaction
         *  @param {object} obj Object to convert
         *  @returns {object} Inverted object
         *  @memberof DataTable#oApi
         */
        function _fnSearchToCamel ( obj )
        {
            return {
                search:          obj.sSearch,
                smart:           obj.bSmart,
                regex:           obj.bRegex,
                caseInsensitive: obj.bCaseInsensitive
            };
        }
        
        
        
        /**
         * Convert from camelCase notation to the internal Hungarian. We could use the
         * Hungarian convert function here, but this is cleaner
         *  @param {object} obj Object to convert
         *  @returns {object} Inverted object
         *  @memberof DataTable#oApi
         */
        function _fnSearchToHung ( obj )
        {
            return {
                sSearch:          obj.search,
                bSmart:           obj.smart,
                bRegex:           obj.regex,
                bCaseInsensitive: obj.caseInsensitive
            };
        }
        
        /**
         * Generate the node required for the info display
         *  @param {object} oSettings dataTables settings object
         *  @returns {node} Information element
         *  @memberof DataTable#oApi
         */
        function _fnFeatureHtmlInfo ( settings )
        {
            var
                tid = settings.sTableId,
                nodes = settings.aanFeatures.i,
                n = $('<div/>', {
                    'class': settings.oClasses.sInfo,
                    'id': ! nodes ? tid+'_info' : null
                } );
        
            if ( ! nodes ) {
                // Update display on each draw
                settings.aoDrawCallback.push( {
                    "fn": _fnUpdateInfo,
                    "sName": "information"
                } );
        
                n
                    .attr( 'role', 'status' )
                    .attr( 'aria-live', 'polite' );
        
                // Table is described by our info div
                $(settings.nTable).attr( 'aria-describedby', tid+'_info' );
            }
        
            return n[0];
        }
        
        
        /**
         * Update the information elements in the display
         *  @param {object} settings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnUpdateInfo ( settings )
        {
            /* Show information about the table */
            var nodes = settings.aanFeatures.i;
            if ( nodes.length === 0 ) {
                return;
            }
        
            var
                lang  = settings.oLanguage,
                start = settings._iDisplayStart+1,
                end   = settings.fnDisplayEnd(),
                max   = settings.fnRecordsTotal(),
                total = settings.fnRecordsDisplay(),
                out   = total ?
                    lang.sInfo :
                    lang.sInfoEmpty;
        
            if ( total !== max ) {
                /* Record set after filtering */
                out += ' ' + lang.sInfoFiltered;
            }
        
            // Convert the macros
            out += lang.sInfoPostFix;
            out = _fnInfoMacros( settings, out );
        
            var callback = lang.fnInfoCallback;
            if ( callback !== null ) {
                out = callback.call( settings.oInstance,
                    settings, start, end, max, total, out
                );
            }
        
            $(nodes).html( out );
        }
        
        
        function _fnInfoMacros ( settings, str )
        {
            // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
            // internally
            var
                formatter  = settings.fnFormatNumber,
                start      = settings._iDisplayStart+1,
                len        = settings._iDisplayLength,
                vis        = settings.fnRecordsDisplay(),
                all        = len === -1;
        
            return str.
                replace(/_START_/g, formatter.call( settings, start ) ).
                replace(/_END_/g,   formatter.call( settings, settings.fnDisplayEnd() ) ).
                replace(/_MAX_/g,   formatter.call( settings, settings.fnRecordsTotal() ) ).
                replace(/_TOTAL_/g, formatter.call( settings, vis ) ).
                replace(/_PAGE_/g,  formatter.call( settings, all ? 1 : Math.ceil( start / len ) ) ).
                replace(/_PAGES_/g, formatter.call( settings, all ? 1 : Math.ceil( vis / len ) ) );
        }
        
        
        
        /**
         * Draw the table for the first time, adding all required features
         *  @param {object} settings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnInitialise ( settings )
        {
            var i, iLen, iAjaxStart=settings.iInitDisplayStart;
            var columns = settings.aoColumns, column;
            var features = settings.oFeatures;
            var deferLoading = settings.bDeferLoading; // value modified by the draw
        
            /* Ensure that the table data is fully initialised */
            if ( ! settings.bInitialised ) {
                setTimeout( function(){ _fnInitialise( settings ); }, 200 );
                return;
            }
        
            /* Show the display HTML options */
            _fnAddOptionsHtml( settings );
        
            /* Build and draw the header / footer for the table */
            _fnBuildHead( settings );
            _fnDrawHead( settings, settings.aoHeader );
            _fnDrawHead( settings, settings.aoFooter );
        
            /* Okay to show that something is going on now */
            _fnProcessingDisplay( settings, true );
        
            /* Calculate sizes for columns */
            if ( features.bAutoWidth ) {
                _fnCalculateColumnWidths( settings );
            }
        
            for ( i=0, iLen=columns.length ; i<iLen ; i++ ) {
                column = columns[i];
        
                if ( column.sWidth ) {
                    column.nTh.style.width = _fnStringToCss( column.sWidth );
                }
            }
        
            _fnCallbackFire( settings, null, 'preInit', [settings] );
        
            // If there is default sorting required - let's do it. The sort function
            // will do the drawing for us. Otherwise we draw the table regardless of the
            // Ajax source - this allows the table to look initialised for Ajax sourcing
            // data (show 'loading' message possibly)
            _fnReDraw( settings );
        
            // Server-side processing init complete is done by _fnAjaxUpdateDraw
            var dataSrc = _fnDataSource( settings );
            if ( dataSrc != 'ssp' || deferLoading ) {
                // if there is an ajax source load the data
                if ( dataSrc == 'ajax' ) {
                    _fnBuildAjax( settings, [], function(json) {
                        var aData = _fnAjaxDataSrc( settings, json );
        
                        // Got the data - add it to the table
                        for ( i=0 ; i<aData.length ; i++ ) {
                            _fnAddData( settings, aData[i] );
                        }
        
                        // Reset the init display for cookie saving. We've already done
                        // a filter, and therefore cleared it before. So we need to make
                        // it appear 'fresh'
                        settings.iInitDisplayStart = iAjaxStart;
        
                        _fnReDraw( settings );
        
                        _fnProcessingDisplay( settings, false );
                        _fnInitComplete( settings, json );
                    }, settings );
                }
                else {
                    _fnProcessingDisplay( settings, false );
                    _fnInitComplete( settings );
                }
            }
        }
        
        
        /**
         * Draw the table for the first time, adding all required features
         *  @param {object} oSettings dataTables settings object
         *  @param {object} [json] JSON from the server that completed the table, if using Ajax source
         *    with client-side processing (optional)
         *  @memberof DataTable#oApi
         */
        function _fnInitComplete ( settings, json )
        {
            settings._bInitComplete = true;
        
            // When data was added after the initialisation (data or Ajax) we need to
            // calculate the column sizing
            if ( json || settings.oInit.aaData ) {
                _fnAdjustColumnSizing( settings );
            }
        
            _fnCallbackFire( settings, null, 'plugin-init', [settings, json] );
            _fnCallbackFire( settings, 'aoInitComplete', 'init', [settings, json] );
        }
        
        
        function _fnLengthChange ( settings, val )
        {
            var len = parseInt( val, 10 );
            settings._iDisplayLength = len;
        
            _fnLengthOverflow( settings );
        
            // Fire length change event
            _fnCallbackFire( settings, null, 'length', [settings, len] );
        }
        
        
        /**
         * Generate the node required for user display length changing
         *  @param {object} settings dataTables settings object
         *  @returns {node} Display length feature node
         *  @memberof DataTable#oApi
         */
        function _fnFeatureHtmlLength ( settings )
        {
            var
                classes  = settings.oClasses,
                tableId  = settings.sTableId,
                menu     = settings.aLengthMenu,
                d2       = $.isArray( menu[0] ),
                lengths  = d2 ? menu[0] : menu,
                language = d2 ? menu[1] : menu;
        
            var select = $('<select/>', {
                'name':          tableId+'_length',
                'aria-controls': tableId,
                'class':         classes.sLengthSelect
            } );
        
            for ( var i=0, ien=lengths.length ; i<ien ; i++ ) {
                select[0][ i ] = new Option( language[i], lengths[i] );
            }
        
            var div = $('<div><label/></div>').addClass( classes.sLength );
            if ( ! settings.aanFeatures.l ) {
                div[0].id = tableId+'_length';
            }
        
            div.children().append(
                settings.oLanguage.sLengthMenu.replace( '_MENU_', select[0].outerHTML )
            );
        
            // Can't use `select` variable as user might provide their own and the
            // reference is broken by the use of outerHTML
            $('select', div)
                .val( settings._iDisplayLength )
                .bind( 'change.DT', function(e) {
                    _fnLengthChange( settings, $(this).val() );
                    _fnDraw( settings );
                } );
        
            // Update node value whenever anything changes the table's length
            $(settings.nTable).bind( 'length.dt.DT', function (e, s, len) {
                if ( settings === s ) {
                    $('select', div).val( len );
                }
            } );
        
            return div[0];
        }
        
        
        
        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * Note that most of the paging logic is done in
         * DataTable.ext.pager
         */
        
        /**
         * Generate the node required for default pagination
         *  @param {object} oSettings dataTables settings object
         *  @returns {node} Pagination feature node
         *  @memberof DataTable#oApi
         */
        function _fnFeatureHtmlPaginate ( settings )
        {
            var
                type   = settings.sPaginationType,
                plugin = DataTable.ext.pager[ type ],
                modern = typeof plugin === 'function',
                redraw = function( settings ) {
                    _fnDraw( settings );
                },
                node = $('<div/>').addClass( settings.oClasses.sPaging + type )[0],
                features = settings.aanFeatures;
        
            if ( ! modern ) {
                plugin.fnInit( settings, node, redraw );
            }
        
            /* Add a draw callback for the pagination on first instance, to update the paging display */
            if ( ! features.p )
            {
                node.id = settings.sTableId+'_paginate';
        
                settings.aoDrawCallback.push( {
                    "fn": function( settings ) {
                        if ( modern ) {
                            var
                                start      = settings._iDisplayStart,
                                len        = settings._iDisplayLength,
                                visRecords = settings.fnRecordsDisplay(),
                                all        = len === -1,
                                page = all ? 0 : Math.ceil( start / len ),
                                pages = all ? 1 : Math.ceil( visRecords / len ),
                                buttons = plugin(page, pages),
                                i, ien;
        
                            for ( i=0, ien=features.p.length ; i<ien ; i++ ) {
                                _fnRenderer( settings, 'pageButton' )(
                                    settings, features.p[i], i, buttons, page, pages
                                );
                            }
                        }
                        else {
                            plugin.fnUpdate( settings, redraw );
                        }
                    },
                    "sName": "pagination"
                } );
            }
        
            return node;
        }
        
        
        /**
         * Alter the display settings to change the page
         *  @param {object} settings DataTables settings object
         *  @param {string|int} action Paging action to take: "first", "previous",
         *    "next" or "last" or page number to jump to (integer)
         *  @param [bool] redraw Automatically draw the update or not
         *  @returns {bool} true page has changed, false - no change
         *  @memberof DataTable#oApi
         */
        function _fnPageChange ( settings, action, redraw )
        {
            var
                start     = settings._iDisplayStart,
                len       = settings._iDisplayLength,
                records   = settings.fnRecordsDisplay();
        
            if ( records === 0 || len === -1 )
            {
                start = 0;
            }
            else if ( typeof action === "number" )
            {
                start = action * len;
        
                if ( start > records )
                {
                    start = 0;
                }
            }
            else if ( action == "first" )
            {
                start = 0;
            }
            else if ( action == "previous" )
            {
                start = len >= 0 ?
                    start - len :
                    0;
        
                if ( start < 0 )
                {
                  start = 0;
                }
            }
            else if ( action == "next" )
            {
                if ( start + len < records )
                {
                    start += len;
                }
            }
            else if ( action == "last" )
            {
                start = Math.floor( (records-1) / len) * len;
            }
            else
            {
                _fnLog( settings, 0, "Unknown paging action: "+action, 5 );
            }
        
            var changed = settings._iDisplayStart !== start;
            settings._iDisplayStart = start;
        
            if ( changed ) {
                _fnCallbackFire( settings, null, 'page', [settings] );
        
                if ( redraw ) {
                    _fnDraw( settings );
                }
            }
        
            return changed;
        }
        
        
        
        /**
         * Generate the node required for the processing node
         *  @param {object} settings dataTables settings object
         *  @returns {node} Processing element
         *  @memberof DataTable#oApi
         */
        function _fnFeatureHtmlProcessing ( settings )
        {
            return $('<div/>', {
                    'id': ! settings.aanFeatures.r ? settings.sTableId+'_processing' : null,
                    'class': settings.oClasses.sProcessing
                } )
                .html( settings.oLanguage.sProcessing )
                .insertBefore( settings.nTable )[0];
        }
        
        
        /**
         * Display or hide the processing indicator
         *  @param {object} settings dataTables settings object
         *  @param {bool} show Show the processing indicator (true) or not (false)
         *  @memberof DataTable#oApi
         */
        function _fnProcessingDisplay ( settings, show )
        {
            if ( settings.oFeatures.bProcessing ) {
                $(settings.aanFeatures.r).css( 'display', show ? 'block' : 'none' );
            }
        
            _fnCallbackFire( settings, null, 'processing', [settings, show] );
        }
        
        /**
         * Add any control elements for the table - specifically scrolling
         *  @param {object} settings dataTables settings object
         *  @returns {node} Node to add to the DOM
         *  @memberof DataTable#oApi
         */
        function _fnFeatureHtmlTable ( settings )
        {
            var table = $(settings.nTable);
        
            // Add the ARIA grid role to the table
            table.attr( 'role', 'grid' );
        
            // Scrolling from here on in
            var scroll = settings.oScroll;
        
            if ( scroll.sX === '' && scroll.sY === '' ) {
                return settings.nTable;
            }
        
            var scrollX = scroll.sX;
            var scrollY = scroll.sY;
            var classes = settings.oClasses;
            var caption = table.children('caption');
            var captionSide = caption.length ? caption[0]._captionSide : null;
            var headerClone = $( table[0].cloneNode(false) );
            var footerClone = $( table[0].cloneNode(false) );
            var footer = table.children('tfoot');
            var _div = '<div/>';
            var size = function ( s ) {
                return !s ? null : _fnStringToCss( s );
            };
        
            if ( ! footer.length ) {
                footer = null;
            }
        
            /*
             * The HTML structure that we want to generate in this function is:
             *  div - scroller
             *    div - scroll head
             *      div - scroll head inner
             *        table - scroll head table
             *          thead - thead
             *    div - scroll body
             *      table - table (master table)
             *        thead - thead clone for sizing
             *        tbody - tbody
             *    div - scroll foot
             *      div - scroll foot inner
             *        table - scroll foot table
             *          tfoot - tfoot
             */
            var scroller = $( _div, { 'class': classes.sScrollWrapper } )
                .append(
                    $(_div, { 'class': classes.sScrollHead } )
                        .css( {
                            overflow: 'hidden',
                            position: 'relative',
                            border: 0,
                            width: scrollX ? size(scrollX) : '100%'
                        } )
                        .append(
                            $(_div, { 'class': classes.sScrollHeadInner } )
                                .css( {
                                    'box-sizing': 'content-box',
                                    width: scroll.sXInner || '100%'
                                } )
                                .append(
                                    headerClone
                                        .removeAttr('id')
                                        .css( 'margin-left', 0 )
                                        .append( captionSide === 'top' ? caption : null )
                                        .append(
                                            table.children('thead')
                                        )
                                )
                        )
                )
                .append(
                    $(_div, { 'class': classes.sScrollBody } )
                        .css( {
                            position: 'relative',
                            overflow: 'auto',
                            width: size( scrollX )
                        } )
                        .append( table )
                );
        
            if ( footer ) {
                scroller.append(
                    $(_div, { 'class': classes.sScrollFoot } )
                        .css( {
                            overflow: 'hidden',
                            border: 0,
                            width: scrollX ? size(scrollX) : '100%'
                        } )
                        .append(
                            $(_div, { 'class': classes.sScrollFootInner } )
                                .append(
                                    footerClone
                                        .removeAttr('id')
                                        .css( 'margin-left', 0 )
                                        .append( captionSide === 'bottom' ? caption : null )
                                        .append(
                                            table.children('tfoot')
                                        )
                                )
                        )
                );
            }
        
            var children = scroller.children();
            var scrollHead = children[0];
            var scrollBody = children[1];
            var scrollFoot = footer ? children[2] : null;
        
            // When the body is scrolled, then we also want to scroll the headers
            if ( scrollX ) {
                $(scrollBody).on( 'scroll.DT', function (e) {
                    var scrollLeft = this.scrollLeft;
        
                    scrollHead.scrollLeft = scrollLeft;
        
                    if ( footer ) {
                        scrollFoot.scrollLeft = scrollLeft;
                    }
                } );
            }
        
            $(scrollBody).css(
                scrollY && scroll.bCollapse ? 'max-height' : 'height', 
                scrollY
            );
        
            settings.nScrollHead = scrollHead;
            settings.nScrollBody = scrollBody;
            settings.nScrollFoot = scrollFoot;
        
            // On redraw - align columns
            settings.aoDrawCallback.push( {
                "fn": _fnScrollDraw,
                "sName": "scrolling"
            } );
        
            return scroller[0];
        }
        
        
        
        /**
         * Update the header, footer and body tables for resizing - i.e. column
         * alignment.
         *
         * Welcome to the most horrible function DataTables. The process that this
         * function follows is basically:
         *   1. Re-create the table inside the scrolling div
         *   2. Take live measurements from the DOM
         *   3. Apply the measurements to align the columns
         *   4. Clean up
         *
         *  @param {object} settings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnScrollDraw ( settings )
        {
            // Given that this is such a monster function, a lot of variables are use
            // to try and keep the minimised size as small as possible
            var
                scroll         = settings.oScroll,
                scrollX        = scroll.sX,
                scrollXInner   = scroll.sXInner,
                scrollY        = scroll.sY,
                barWidth       = scroll.iBarWidth,
                divHeader      = $(settings.nScrollHead),
                divHeaderStyle = divHeader[0].style,
                divHeaderInner = divHeader.children('div'),
                divHeaderInnerStyle = divHeaderInner[0].style,
                divHeaderTable = divHeaderInner.children('table'),
                divBodyEl      = settings.nScrollBody,
                divBody        = $(divBodyEl),
                divBodyStyle   = divBodyEl.style,
                divFooter      = $(settings.nScrollFoot),
                divFooterInner = divFooter.children('div'),
                divFooterTable = divFooterInner.children('table'),
                header         = $(settings.nTHead),
                table          = $(settings.nTable),
                tableEl        = table[0],
                tableStyle     = tableEl.style,
                footer         = settings.nTFoot ? $(settings.nTFoot) : null,
                browser        = settings.oBrowser,
                ie67           = browser.bScrollOversize,
                dtHeaderCells  = _pluck( settings.aoColumns, 'nTh' ),
                headerTrgEls, footerTrgEls,
                headerSrcEls, footerSrcEls,
                headerCopy, footerCopy,
                headerWidths=[], footerWidths=[],
                headerContent=[], footerContent=[],
                idx, correction, sanityWidth,
                zeroOut = function(nSizer) {
                    var style = nSizer.style;
                    style.paddingTop = "0";
                    style.paddingBottom = "0";
                    style.borderTopWidth = "0";
                    style.borderBottomWidth = "0";
                    style.height = 0;
                };
        
            // If the scrollbar visibility has changed from the last draw, we need to
            // adjust the column sizes as the table width will have changed to account
            // for the scrollbar
            var scrollBarVis = divBodyEl.scrollHeight > divBodyEl.clientHeight;
            
            if ( settings.scrollBarVis !== scrollBarVis && settings.scrollBarVis !== undefined ) {
                settings.scrollBarVis = scrollBarVis;
                _fnAdjustColumnSizing( settings );
                return; // adjust column sizing will call this function again
            }
            else {
                settings.scrollBarVis = scrollBarVis;
            }
        
            /*
             * 1. Re-create the table inside the scrolling div
             */
        
            // Remove the old minimised thead and tfoot elements in the inner table
            table.children('thead, tfoot').remove();
        
            if ( footer ) {
                footerCopy = footer.clone().prependTo( table );
                footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized
                footerSrcEls = footerCopy.find('tr');
            }
        
            // Clone the current header and footer elements and then place it into the inner table
            headerCopy = header.clone().prependTo( table );
            headerTrgEls = header.find('tr'); // original header is in its own table
            headerSrcEls = headerCopy.find('tr');
            headerCopy.find('th, td').removeAttr('tabindex');
        
        
            /*
             * 2. Take live measurements from the DOM - do not alter the DOM itself!
             */
        
            // Remove old sizing and apply the calculated column widths
            // Get the unique column headers in the newly created (cloned) header. We want to apply the
            // calculated sizes to this header
            if ( ! scrollX )
            {
                divBodyStyle.width = '100%';
                divHeader[0].style.width = '100%';
            }
        
            $.each( _fnGetUniqueThs( settings, headerCopy ), function ( i, el ) {
                idx = _fnVisibleToColumnIndex( settings, i );
                el.style.width = settings.aoColumns[idx].sWidth;
            } );
        
            if ( footer ) {
                _fnApplyToChildren( function(n) {
                    n.style.width = "";
                }, footerSrcEls );
            }
        
            // Size the table as a whole
            sanityWidth = table.outerWidth();
            if ( scrollX === "" ) {
                // No x scrolling
                tableStyle.width = "100%";
        
                // IE7 will make the width of the table when 100% include the scrollbar
                // - which is shouldn't. When there is a scrollbar we need to take this
                // into account.
                if ( ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight ||
                    divBody.css('overflow-y') == "scroll")
                ) {
                    tableStyle.width = _fnStringToCss( table.outerWidth() - barWidth);
                }
        
                // Recalculate the sanity width
                sanityWidth = table.outerWidth();
            }
            else if ( scrollXInner !== "" ) {
                // legacy x scroll inner has been given - use it
                tableStyle.width = _fnStringToCss(scrollXInner);
        
                // Recalculate the sanity width
                sanityWidth = table.outerWidth();
            }
        
            // Hidden header should have zero height, so remove padding and borders. Then
            // set the width based on the real headers
        
            // Apply all styles in one pass
            _fnApplyToChildren( zeroOut, headerSrcEls );
        
            // Read all widths in next pass
            _fnApplyToChildren( function(nSizer) {
                headerContent.push( nSizer.innerHTML );
                headerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
            }, headerSrcEls );
        
            // Apply all widths in final pass
            _fnApplyToChildren( function(nToSize, i) {
                // Only apply widths to the DataTables detected header cells - this
                // prevents complex headers from having contradictory sizes applied
                if ( $.inArray( nToSize, dtHeaderCells ) !== -1 ) {
                    nToSize.style.width = headerWidths[i];
                }
            }, headerTrgEls );
        
            $(headerSrcEls).height(0);
        
            /* Same again with the footer if we have one */
            if ( footer )
            {
                _fnApplyToChildren( zeroOut, footerSrcEls );
        
                _fnApplyToChildren( function(nSizer) {
                    footerContent.push( nSizer.innerHTML );
                    footerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
                }, footerSrcEls );
        
                _fnApplyToChildren( function(nToSize, i) {
                    nToSize.style.width = footerWidths[i];
                }, footerTrgEls );
        
                $(footerSrcEls).height(0);
            }
        
        
            /*
             * 3. Apply the measurements
             */
        
            // "Hide" the header and footer that we used for the sizing. We need to keep
            // the content of the cell so that the width applied to the header and body
            // both match, but we want to hide it completely. We want to also fix their
            // width to what they currently are
            _fnApplyToChildren( function(nSizer, i) {
                nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+headerContent[i]+'</div>';
                nSizer.style.width = headerWidths[i];
            }, headerSrcEls );
        
            if ( footer )
            {
                _fnApplyToChildren( function(nSizer, i) {
                    nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+footerContent[i]+'</div>';
                    nSizer.style.width = footerWidths[i];
                }, footerSrcEls );
            }
        
            // Sanity check that the table is of a sensible width. If not then we are going to get
            // misalignment - try to prevent this by not allowing the table to shrink below its min width
            if ( table.outerWidth() < sanityWidth )
            {
                // The min width depends upon if we have a vertical scrollbar visible or not */
                correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight ||
                    divBody.css('overflow-y') == "scroll")) ?
                        sanityWidth+barWidth :
                        sanityWidth;
        
                // IE6/7 are a law unto themselves...
                if ( ie67 && (divBodyEl.scrollHeight >
                    divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")
                ) {
                    tableStyle.width = _fnStringToCss( correction-barWidth );
                }
        
                // And give the user a warning that we've stopped the table getting too small
                if ( scrollX === "" || scrollXInner !== "" ) {
                    _fnLog( settings, 1, 'Possible column misalignment', 6 );
                }
            }
            else
            {
                correction = '100%';
            }
        
            // Apply to the container elements
            divBodyStyle.width = _fnStringToCss( correction );
            divHeaderStyle.width = _fnStringToCss( correction );
        
            if ( footer ) {
                settings.nScrollFoot.style.width = _fnStringToCss( correction );
            }
        
        
            /*
             * 4. Clean up
             */
            if ( ! scrollY ) {
                /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
                 * the scrollbar height from the visible display, rather than adding it on. We need to
                 * set the height in order to sort this. Don't want to do it in any other browsers.
                 */
                if ( ie67 ) {
                    divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+barWidth );
                }
            }
        
            /* Finally set the width's of the header and footer tables */
            var iOuterWidth = table.outerWidth();
            divHeaderTable[0].style.width = _fnStringToCss( iOuterWidth );
            divHeaderInnerStyle.width = _fnStringToCss( iOuterWidth );
        
            // Figure out if there are scrollbar present - if so then we need a the header and footer to
            // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
            var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll";
            var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' );
            divHeaderInnerStyle[ padding ] = bScrolling ? barWidth+"px" : "0px";
        
            if ( footer ) {
                divFooterTable[0].style.width = _fnStringToCss( iOuterWidth );
                divFooterInner[0].style.width = _fnStringToCss( iOuterWidth );
                divFooterInner[0].style[padding] = bScrolling ? barWidth+"px" : "0px";
            }
        
            // Correct DOM ordering for colgroup - comes before the thead
            table.children('colgroup').insertBefore( table.children('thead') );
        
            /* Adjust the position of the header in case we loose the y-scrollbar */
            divBody.scroll();
        
            // If sorting or filtering has occurred, jump the scrolling back to the top
            // only if we aren't holding the position
            if ( (settings.bSorted || settings.bFiltered) && ! settings._drawHold ) {
                divBodyEl.scrollTop = 0;
            }
        }
        
        
        
        /**
         * Apply a given function to the display child nodes of an element array (typically
         * TD children of TR rows
         *  @param {function} fn Method to apply to the objects
         *  @param array {nodes} an1 List of elements to look through for display children
         *  @param array {nodes} an2 Another list (identical structure to the first) - optional
         *  @memberof DataTable#oApi
         */
        function _fnApplyToChildren( fn, an1, an2 )
        {
            var index=0, i=0, iLen=an1.length;
            var nNode1, nNode2;
        
            while ( i < iLen ) {
                nNode1 = an1[i].firstChild;
                nNode2 = an2 ? an2[i].firstChild : null;
        
                while ( nNode1 ) {
                    if ( nNode1.nodeType === 1 ) {
                        if ( an2 ) {
                            fn( nNode1, nNode2, index );
                        }
                        else {
                            fn( nNode1, index );
                        }
        
                        index++;
                    }
        
                    nNode1 = nNode1.nextSibling;
                    nNode2 = an2 ? nNode2.nextSibling : null;
                }
        
                i++;
            }
        }
        
        
        
        var __re_html_remove = /<.*?>/g;
        
        
        /**
         * Calculate the width of columns for the table
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnCalculateColumnWidths ( oSettings )
        {
            var
                table = oSettings.nTable,
                columns = oSettings.aoColumns,
                scroll = oSettings.oScroll,
                scrollY = scroll.sY,
                scrollX = scroll.sX,
                scrollXInner = scroll.sXInner,
                columnCount = columns.length,
                visibleColumns = _fnGetColumns( oSettings, 'bVisible' ),
                headerCells = $('th', oSettings.nTHead),
                tableWidthAttr = table.getAttribute('width'), // from DOM element
                tableContainer = table.parentNode,
                userInputs = false,
                i, column, columnIdx, width, outerWidth,
                browser = oSettings.oBrowser,
                ie67 = browser.bScrollOversize;
        
            var styleWidth = table.style.width;
            if ( styleWidth && styleWidth.indexOf('%') !== -1 ) {
                tableWidthAttr = styleWidth;
            }
        
            /* Convert any user input sizes into pixel sizes */
            for ( i=0 ; i<visibleColumns.length ; i++ ) {
                column = columns[ visibleColumns[i] ];
        
                if ( column.sWidth !== null ) {
                    column.sWidth = _fnConvertToWidth( column.sWidthOrig, tableContainer );
        
                    userInputs = true;
                }
            }
        
            /* If the number of columns in the DOM equals the number that we have to
             * process in DataTables, then we can use the offsets that are created by
             * the web- browser. No custom sizes can be set in order for this to happen,
             * nor scrolling used
             */
            if ( ie67 || ! userInputs && ! scrollX && ! scrollY &&
                 columnCount == _fnVisbleColumns( oSettings ) &&
                 columnCount == headerCells.length
            ) {
                for ( i=0 ; i<columnCount ; i++ ) {
                    var colIdx = _fnVisibleToColumnIndex( oSettings, i );
        
                    if ( colIdx !== null ) {
                        columns[ colIdx ].sWidth = _fnStringToCss( headerCells.eq(i).width() );
                    }
                }
            }
            else
            {
                // Otherwise construct a single row, worst case, table with the widest
                // node in the data, assign any user defined widths, then insert it into
                // the DOM and allow the browser to do all the hard work of calculating
                // table widths
                var tmpTable = $(table).clone() // don't use cloneNode - IE8 will remove events on the main table
                    .css( 'visibility', 'hidden' )
                    .removeAttr( 'id' );
        
                // Clean up the table body
                tmpTable.find('tbody tr').remove();
                var tr = $('<tr/>').appendTo( tmpTable.find('tbody') );
        
                // Clone the table header and footer - we can't use the header / footer
                // from the cloned table, since if scrolling is active, the table's
                // real header and footer are contained in different table tags
                tmpTable.find('thead, tfoot').remove();
                tmpTable
                    .append( $(oSettings.nTHead).clone() )
                    .append( $(oSettings.nTFoot).clone() );
        
                // Remove any assigned widths from the footer (from scrolling)
                tmpTable.find('tfoot th, tfoot td').css('width', '');
        
                // Apply custom sizing to the cloned header
                headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] );
        
                for ( i=0 ; i<visibleColumns.length ; i++ ) {
                    column = columns[ visibleColumns[i] ];
        
                    headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
                        _fnStringToCss( column.sWidthOrig ) :
                        '';
        
                    // For scrollX we need to force the column width otherwise the
                    // browser will collapse it. If this width is smaller than the
                    // width the column requires, then it will have no effect
                    if ( column.sWidthOrig && scrollX ) {
                        $( headerCells[i] ).append( $('<div/>').css( {
                            width: column.sWidthOrig,
                            margin: 0,
                            padding: 0,
                            border: 0,
                            height: 1
                        } ) );
                    }
                }
        
                // Find the widest cell for each column and put it into the table
                if ( oSettings.aoData.length ) {
                    for ( i=0 ; i<visibleColumns.length ; i++ ) {
                        columnIdx = visibleColumns[i];
                        column = columns[ columnIdx ];
        
                        $( _fnGetWidestNode( oSettings, columnIdx ) )
                            .clone( false )
                            .append( column.sContentPadding )
                            .appendTo( tr );
                    }
                }
        
                // Tidy the temporary table - remove name attributes so there aren't
                // duplicated in the dom (radio elements for example)
                $('[name]', tmpTable).removeAttr('name');
        
                // Table has been built, attach to the document so we can work with it.
                // A holding element is used, positioned at the top of the container
                // with minimal height, so it has no effect on if the container scrolls
                // or not. Otherwise it might trigger scrolling when it actually isn't
                // needed
                var holder = $('<div/>').css( scrollX || scrollY ?
                        {
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            height: 1,
                            right: 0,
                            overflow: 'hidden'
                        } :
                        {}
                    )
                    .append( tmpTable )
                    .appendTo( tableContainer );
        
                // When scrolling (X or Y) we want to set the width of the table as 
                // appropriate. However, when not scrolling leave the table width as it
                // is. This results in slightly different, but I think correct behaviour
                if ( scrollX && scrollXInner ) {
                    tmpTable.width( scrollXInner );
                }
                else if ( scrollX ) {
                    tmpTable.css( 'width', 'auto' );
                    tmpTable.removeAttr('width');
        
                    // If there is no width attribute or style, then allow the table to
                    // collapse
                    if ( tmpTable.width() < tableContainer.clientWidth && tableWidthAttr ) {
                        tmpTable.width( tableContainer.clientWidth );
                    }
                }
                else if ( scrollY ) {
                    tmpTable.width( tableContainer.clientWidth );
                }
                else if ( tableWidthAttr ) {
                    tmpTable.width( tableWidthAttr );
                }
        
                // Get the width of each column in the constructed table - we need to
                // know the inner width (so it can be assigned to the other table's
                // cells) and the outer width so we can calculate the full width of the
                // table. This is safe since DataTables requires a unique cell for each
                // column, but if ever a header can span multiple columns, this will
                // need to be modified.
                var total = 0;
                for ( i=0 ; i<visibleColumns.length ; i++ ) {
                    var cell = $(headerCells[i]);
                    var border = cell.outerWidth() - cell.width();
        
                    // Use getBounding... where possible (not IE8-) because it can give
                    // sub-pixel accuracy, which we then want to round up!
                    var bounding = browser.bBounding ?
                        Math.ceil( headerCells[i].getBoundingClientRect().width ) :
                        cell.outerWidth();
        
                    // Total is tracked to remove any sub-pixel errors as the outerWidth
                    // of the table might not equal the total given here (IE!).
                    total += bounding;
        
                    // Width for each column to use
                    columns[ visibleColumns[i] ].sWidth = _fnStringToCss( bounding - border );
                }
        
                table.style.width = _fnStringToCss( total );
        
                // Finished with the table - ditch it
                holder.remove();
            }
        
            // If there is a width attr, we want to attach an event listener which
            // allows the table sizing to automatically adjust when the window is
            // resized. Use the width attr rather than CSS, since we can't know if the
            // CSS is a relative value or absolute - DOM read is always px.
            if ( tableWidthAttr ) {
                table.style.width = _fnStringToCss( tableWidthAttr );
            }
        
            if ( (tableWidthAttr || scrollX) && ! oSettings._reszEvt ) {
                var bindResize = function () {
                    $(window).bind('resize.DT-'+oSettings.sInstance, _fnThrottle( function () {
                        _fnAdjustColumnSizing( oSettings );
                    } ) );
                };
        
                // IE6/7 will crash if we bind a resize event handler on page load.
                // To be removed in 1.11 which drops IE6/7 support
                if ( ie67 ) {
                    setTimeout( bindResize, 1000 );
                }
                else {
                    bindResize();
                }
        
                oSettings._reszEvt = true;
            }
        }
        
        
        /**
         * Throttle the calls to a function. Arguments and context are maintained for
         * the throttled function
         *  @param {function} fn Function to be called
         *  @param {int} [freq=200] call frequency in mS
         *  @returns {function} wrapped function
         *  @memberof DataTable#oApi
         */
        var _fnThrottle = DataTable.util.throttle;
        
        
        /**
         * Convert a CSS unit width to pixels (e.g. 2em)
         *  @param {string} width width to be converted
         *  @param {node} parent parent to get the with for (required for relative widths) - optional
         *  @returns {int} width in pixels
         *  @memberof DataTable#oApi
         */
        function _fnConvertToWidth ( width, parent )
        {
            if ( ! width ) {
                return 0;
            }
        
            var n = $('<div/>')
                .css( 'width', _fnStringToCss( width ) )
                .appendTo( parent || document.body );
        
            var val = n[0].offsetWidth;
            n.remove();
        
            return val;
        }
        
        
        /**
         * Get the widest node
         *  @param {object} settings dataTables settings object
         *  @param {int} colIdx column of interest
         *  @returns {node} widest table node
         *  @memberof DataTable#oApi
         */
        function _fnGetWidestNode( settings, colIdx )
        {
            var idx = _fnGetMaxLenString( settings, colIdx );
            if ( idx < 0 ) {
                return null;
            }
        
            var data = settings.aoData[ idx ];
            return ! data.nTr ? // Might not have been created when deferred rendering
                $('<td/>').html( _fnGetCellData( settings, idx, colIdx, 'display' ) )[0] :
                data.anCells[ colIdx ];
        }
        
        
        /**
         * Get the maximum strlen for each data column
         *  @param {object} settings dataTables settings object
         *  @param {int} colIdx column of interest
         *  @returns {string} max string length for each column
         *  @memberof DataTable#oApi
         */
        function _fnGetMaxLenString( settings, colIdx )
        {
            var s, max=-1, maxIdx = -1;
        
            for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
                s = _fnGetCellData( settings, i, colIdx, 'display' )+'';
                s = s.replace( __re_html_remove, '' );
                s = s.replace( /&nbsp;/g, ' ' );
        
                if ( s.length > max ) {
                    max = s.length;
                    maxIdx = i;
                }
            }
        
            return maxIdx;
        }
        
        
        /**
         * Append a CSS unit (only if required) to a string
         *  @param {string} value to css-ify
         *  @returns {string} value with css unit
         *  @memberof DataTable#oApi
         */
        function _fnStringToCss( s )
        {
            if ( s === null ) {
                return '0px';
            }
        
            if ( typeof s == 'number' ) {
                return s < 0 ?
                    '0px' :
                    s+'px';
            }
        
            // Check it has a unit character already
            return s.match(/\d$/) ?
                s+'px' :
                s;
        }
        
        
        
        function _fnSortFlatten ( settings )
        {
            var
                i, iLen, k, kLen,
                aSort = [],
                aiOrig = [],
                aoColumns = settings.aoColumns,
                aDataSort, iCol, sType, srcCol,
                fixed = settings.aaSortingFixed,
                fixedObj = $.isPlainObject( fixed ),
                nestedSort = [],
                add = function ( a ) {
                    if ( a.length && ! $.isArray( a[0] ) ) {
                        // 1D array
                        nestedSort.push( a );
                    }
                    else {
                        // 2D array
                        $.merge( nestedSort, a );
                    }
                };
        
            // Build the sort array, with pre-fix and post-fix options if they have been
            // specified
            if ( $.isArray( fixed ) ) {
                add( fixed );
            }
        
            if ( fixedObj && fixed.pre ) {
                add( fixed.pre );
            }
        
            add( settings.aaSorting );
        
            if (fixedObj && fixed.post ) {
                add( fixed.post );
            }
        
            for ( i=0 ; i<nestedSort.length ; i++ )
            {
                srcCol = nestedSort[i][0];
                aDataSort = aoColumns[ srcCol ].aDataSort;
        
                for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ )
                {
                    iCol = aDataSort[k];
                    sType = aoColumns[ iCol ].sType || 'string';
        
                    if ( nestedSort[i]._idx === undefined ) {
                        nestedSort[i]._idx = $.inArray( nestedSort[i][1], aoColumns[iCol].asSorting );
                    }
        
                    aSort.push( {
                        src:       srcCol,
                        col:       iCol,
                        dir:       nestedSort[i][1],
                        index:     nestedSort[i]._idx,
                        type:      sType,
                        formatter: DataTable.ext.type.order[ sType+"-pre" ]
                    } );
                }
            }
        
            return aSort;
        }
        
        /**
         * Change the order of the table
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         *  @todo This really needs split up!
         */
        function _fnSort ( oSettings )
        {
            var
                i, ien, iLen, j, jLen, k, kLen,
                sDataType, nTh,
                aiOrig = [],
                oExtSort = DataTable.ext.type.order,
                aoData = oSettings.aoData,
                aoColumns = oSettings.aoColumns,
                aDataSort, data, iCol, sType, oSort,
                formatters = 0,
                sortCol,
                displayMaster = oSettings.aiDisplayMaster,
                aSort;
        
            // Resolve any column types that are unknown due to addition or invalidation
            // @todo Can this be moved into a 'data-ready' handler which is called when
            //   data is going to be used in the table?
            _fnColumnTypes( oSettings );
        
            aSort = _fnSortFlatten( oSettings );
        
            for ( i=0, ien=aSort.length ; i<ien ; i++ ) {
                sortCol = aSort[i];
        
                // Track if we can use the fast sort algorithm
                if ( sortCol.formatter ) {
                    formatters++;
                }
        
                // Load the data needed for the sort, for each cell
                _fnSortData( oSettings, sortCol.col );
            }
        
            /* No sorting required if server-side or no sorting array */
            if ( _fnDataSource( oSettings ) != 'ssp' && aSort.length !== 0 )
            {
                // Create a value - key array of the current row positions such that we can use their
                // current position during the sort, if values match, in order to perform stable sorting
                for ( i=0, iLen=displayMaster.length ; i<iLen ; i++ ) {
                    aiOrig[ displayMaster[i] ] = i;
                }
        
                /* Do the sort - here we want multi-column sorting based on a given data source (column)
                 * and sorting function (from oSort) in a certain direction. It's reasonably complex to
                 * follow on it's own, but this is what we want (example two column sorting):
                 *  fnLocalSorting = function(a,b){
                 *    var iTest;
                 *    iTest = oSort['string-asc']('data11', 'data12');
                 *      if (iTest !== 0)
                 *        return iTest;
                 *    iTest = oSort['numeric-desc']('data21', 'data22');
                 *    if (iTest !== 0)
                 *      return iTest;
                 *    return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
                 *  }
                 * Basically we have a test for each sorting column, if the data in that column is equal,
                 * test the next column. If all columns match, then we use a numeric sort on the row
                 * positions in the original data array to provide a stable sort.
                 *
                 * Note - I know it seems excessive to have two sorting methods, but the first is around
                 * 15% faster, so the second is only maintained for backwards compatibility with sorting
                 * methods which do not have a pre-sort formatting function.
                 */
                if ( formatters === aSort.length ) {
                    // All sort types have formatting functions
                    displayMaster.sort( function ( a, b ) {
                        var
                            x, y, k, test, sort,
                            len=aSort.length,
                            dataA = aoData[a]._aSortData,
                            dataB = aoData[b]._aSortData;
        
                        for ( k=0 ; k<len ; k++ ) {
                            sort = aSort[k];
        
                            x = dataA[ sort.col ];
                            y = dataB[ sort.col ];
        
                            test = x<y ? -1 : x>y ? 1 : 0;
                            if ( test !== 0 ) {
                                return sort.dir === 'asc' ? test : -test;
                            }
                        }
        
                        x = aiOrig[a];
                        y = aiOrig[b];
                        return x<y ? -1 : x>y ? 1 : 0;
                    } );
                }
                else {
                    // Depreciated - remove in 1.11 (providing a plug-in option)
                    // Not all sort types have formatting methods, so we have to call their sorting
                    // methods.
                    displayMaster.sort( function ( a, b ) {
                        var
                            x, y, k, l, test, sort, fn,
                            len=aSort.length,
                            dataA = aoData[a]._aSortData,
                            dataB = aoData[b]._aSortData;
        
                        for ( k=0 ; k<len ; k++ ) {
                            sort = aSort[k];
        
                            x = dataA[ sort.col ];
                            y = dataB[ sort.col ];
        
                            fn = oExtSort[ sort.type+"-"+sort.dir ] || oExtSort[ "string-"+sort.dir ];
                            test = fn( x, y );
                            if ( test !== 0 ) {
                                return test;
                            }
                        }
        
                        x = aiOrig[a];
                        y = aiOrig[b];
                        return x<y ? -1 : x>y ? 1 : 0;
                    } );
                }
            }
        
            /* Tell the draw function that we have sorted the data */
            oSettings.bSorted = true;
        }
        
        
        function _fnSortAria ( settings )
        {
            var label;
            var nextSort;
            var columns = settings.aoColumns;
            var aSort = _fnSortFlatten( settings );
            var oAria = settings.oLanguage.oAria;
        
            // ARIA attributes - need to loop all columns, to update all (removing old
            // attributes as needed)
            for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
            {
                var col = columns[i];
                var asSorting = col.asSorting;
                var sTitle = col.sTitle.replace( /<.*?>/g, "" );
                var th = col.nTh;
        
                // IE7 is throwing an error when setting these properties with jQuery's
                // attr() and removeAttr() methods...
                th.removeAttribute('aria-sort');
        
                /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
                if ( col.bSortable ) {
                    if ( aSort.length > 0 && aSort[0].col == i ) {
                        th.setAttribute('aria-sort', aSort[0].dir=="asc" ? "ascending" : "descending" );
                        nextSort = asSorting[ aSort[0].index+1 ] || asSorting[0];
                    }
                    else {
                        nextSort = asSorting[0];
                    }
        
                    label = sTitle + ( nextSort === "asc" ?
                        oAria.sSortAscending :
                        oAria.sSortDescending
                    );
                }
                else {
                    label = sTitle;
                }
        
                th.setAttribute('aria-label', label);
            }
        }
        
        
        /**
         * Function to run on user sort request
         *  @param {object} settings dataTables settings object
         *  @param {node} attachTo node to attach the handler to
         *  @param {int} colIdx column sorting index
         *  @param {boolean} [append=false] Append the requested sort to the existing
         *    sort if true (i.e. multi-column sort)
         *  @param {function} [callback] callback function
         *  @memberof DataTable#oApi
         */
        function _fnSortListener ( settings, colIdx, append, callback )
        {
            var col = settings.aoColumns[ colIdx ];
            var sorting = settings.aaSorting;
            var asSorting = col.asSorting;
            var nextSortIdx;
            var next = function ( a, overflow ) {
                var idx = a._idx;
                if ( idx === undefined ) {
                    idx = $.inArray( a[1], asSorting );
                }
        
                return idx+1 < asSorting.length ?
                    idx+1 :
                    overflow ?
                        null :
                        0;
            };
        
            // Convert to 2D array if needed
            if ( typeof sorting[0] === 'number' ) {
                sorting = settings.aaSorting = [ sorting ];
            }
        
            // If appending the sort then we are multi-column sorting
            if ( append && settings.oFeatures.bSortMulti ) {
                // Are we already doing some kind of sort on this column?
                var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') );
        
                if ( sortIdx !== -1 ) {
                    // Yes, modify the sort
                    nextSortIdx = next( sorting[sortIdx], true );
        
                    if ( nextSortIdx === null && sorting.length === 1 ) {
                        nextSortIdx = 0; // can't remove sorting completely
                    }
        
                    if ( nextSortIdx === null ) {
                        sorting.splice( sortIdx, 1 );
                    }
                    else {
                        sorting[sortIdx][1] = asSorting[ nextSortIdx ];
                        sorting[sortIdx]._idx = nextSortIdx;
                    }
                }
                else {
                    // No sort on this column yet
                    sorting.push( [ colIdx, asSorting[0], 0 ] );
                    sorting[sorting.length-1]._idx = 0;
                }
            }
            else if ( sorting.length && sorting[0][0] == colIdx ) {
                // Single column - already sorting on this column, modify the sort
                nextSortIdx = next( sorting[0] );
        
                sorting.length = 1;
                sorting[0][1] = asSorting[ nextSortIdx ];
                sorting[0]._idx = nextSortIdx;
            }
            else {
                // Single column - sort only on this column
                sorting.length = 0;
                sorting.push( [ colIdx, asSorting[0] ] );
                sorting[0]._idx = 0;
            }
        
            // Run the sort by calling a full redraw
            _fnReDraw( settings );
        
            // callback used for async user interaction
            if ( typeof callback == 'function' ) {
                callback( settings );
            }
        }
        
        
        /**
         * Attach a sort handler (click) to a node
         *  @param {object} settings dataTables settings object
         *  @param {node} attachTo node to attach the handler to
         *  @param {int} colIdx column sorting index
         *  @param {function} [callback] callback function
         *  @memberof DataTable#oApi
         */
        function _fnSortAttachListener ( settings, attachTo, colIdx, callback )
        {
            var col = settings.aoColumns[ colIdx ];
        
            _fnBindAction( attachTo, {}, function (e) {
                /* If the column is not sortable - don't to anything */
                if ( col.bSortable === false ) {
                    return;
                }
        
                // If processing is enabled use a timeout to allow the processing
                // display to be shown - otherwise to it synchronously
                if ( settings.oFeatures.bProcessing ) {
                    _fnProcessingDisplay( settings, true );
        
                    setTimeout( function() {
                        _fnSortListener( settings, colIdx, e.shiftKey, callback );
        
                        // In server-side processing, the draw callback will remove the
                        // processing display
                        if ( _fnDataSource( settings ) !== 'ssp' ) {
                            _fnProcessingDisplay( settings, false );
                        }
                    }, 0 );
                }
                else {
                    _fnSortListener( settings, colIdx, e.shiftKey, callback );
                }
            } );
        }
        
        
        /**
         * Set the sorting classes on table's body, Note: it is safe to call this function
         * when bSort and bSortClasses are false
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnSortingClasses( settings )
        {
            var oldSort = settings.aLastSort;
            var sortClass = settings.oClasses.sSortColumn;
            var sort = _fnSortFlatten( settings );
            var features = settings.oFeatures;
            var i, ien, colIdx;
        
            if ( features.bSort && features.bSortClasses ) {
                // Remove old sorting classes
                for ( i=0, ien=oldSort.length ; i<ien ; i++ ) {
                    colIdx = oldSort[i].src;
        
                    // Remove column sorting
                    $( _pluck( settings.aoData, 'anCells', colIdx ) )
                        .removeClass( sortClass + (i<2 ? i+1 : 3) );
                }
        
                // Add new column sorting
                for ( i=0, ien=sort.length ; i<ien ; i++ ) {
                    colIdx = sort[i].src;
        
                    $( _pluck( settings.aoData, 'anCells', colIdx ) )
                        .addClass( sortClass + (i<2 ? i+1 : 3) );
                }
            }
        
            settings.aLastSort = sort;
        }
        
        
        // Get the data to sort a column, be it from cache, fresh (populating the
        // cache), or from a sort formatter
        function _fnSortData( settings, idx )
        {
            // Custom sorting function - provided by the sort data type
            var column = settings.aoColumns[ idx ];
            var customSort = DataTable.ext.order[ column.sSortDataType ];
            var customData;
        
            if ( customSort ) {
                customData = customSort.call( settings.oInstance, settings, idx,
                    _fnColumnIndexToVisible( settings, idx )
                );
            }
        
            // Use / populate cache
            var row, cellData;
            var formatter = DataTable.ext.type.order[ column.sType+"-pre" ];
        
            for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
                row = settings.aoData[i];
        
                if ( ! row._aSortData ) {
                    row._aSortData = [];
                }
        
                if ( ! row._aSortData[idx] || customSort ) {
                    cellData = customSort ?
                        customData[i] : // If there was a custom sort function, use data from there
                        _fnGetCellData( settings, i, idx, 'sort' );
        
                    row._aSortData[ idx ] = formatter ?
                        formatter( cellData ) :
                        cellData;
                }
            }
        }
        
        
        
        /**
         * Save the state of a table
         *  @param {object} oSettings dataTables settings object
         *  @memberof DataTable#oApi
         */
        function _fnSaveState ( settings )
        {
            if ( !settings.oFeatures.bStateSave || settings.bDestroying )
            {
                return;
            }
        
            /* Store the interesting variables */
            var state = {
                time:    +new Date(),
                start:   settings._iDisplayStart,
                length:  settings._iDisplayLength,
                order:   $.extend( true, [], settings.aaSorting ),
                search:  _fnSearchToCamel( settings.oPreviousSearch ),
                columns: $.map( settings.aoColumns, function ( col, i ) {
                    return {
                        visible: col.bVisible,
                        search: _fnSearchToCamel( settings.aoPreSearchCols[i] )
                    };
                } )
            };
        
            _fnCallbackFire( settings, "aoStateSaveParams", 'stateSaveParams', [settings, state] );
        
            settings.oSavedState = state;
            settings.fnStateSaveCallback.call( settings.oInstance, settings, state );
        }
        
        
        /**
         * Attempt to load a saved table state
         *  @param {object} oSettings dataTables settings object
         *  @param {object} oInit DataTables init object so we can override settings
         *  @memberof DataTable#oApi
         */
        function _fnLoadState ( settings, oInit )
        {
            var i, ien;
            var columns = settings.aoColumns;
        
            if ( ! settings.oFeatures.bStateSave ) {
                return;
            }
        
            var state = settings.fnStateLoadCallback.call( settings.oInstance, settings );
            if ( ! state || ! state.time ) {
                return;
            }
        
            /* Allow custom and plug-in manipulation functions to alter the saved data set and
             * cancelling of loading by returning false
             */
            var abStateLoad = _fnCallbackFire( settings, 'aoStateLoadParams', 'stateLoadParams', [settings, state] );
            if ( $.inArray( false, abStateLoad ) !== -1 ) {
                return;
            }
        
            /* Reject old data */
            var duration = settings.iStateDuration;
            if ( duration > 0 && state.time < +new Date() - (duration*1000) ) {
                return;
            }
        
            // Number of columns have changed - all bets are off, no restore of settings
            if ( columns.length !== state.columns.length ) {
                return;
            }
        
            // Store the saved state so it might be accessed at any time
            settings.oLoadedState = $.extend( true, {}, state );
        
            // Restore key features - todo - for 1.11 this needs to be done by
            // subscribed events
            if ( state.start !== undefined ) {
                settings._iDisplayStart    = state.start;
                settings.iInitDisplayStart = state.start;
            }
            if ( state.length !== undefined ) {
                settings._iDisplayLength   = state.length;
            }
        
            // Order
            if ( state.order !== undefined ) {
                settings.aaSorting = [];
                $.each( state.order, function ( i, col ) {
                    settings.aaSorting.push( col[0] >= columns.length ?
                        [ 0, col[1] ] :
                        col
                    );
                } );
            }
        
            // Search
            if ( state.search !== undefined ) {
                $.extend( settings.oPreviousSearch, _fnSearchToHung( state.search ) );
            }
        
            // Columns
            for ( i=0, ien=state.columns.length ; i<ien ; i++ ) {
                var col = state.columns[i];
        
                // Visibility
                if ( col.visible !== undefined ) {
                    columns[i].bVisible = col.visible;
                }
        
                // Search
                if ( col.search !== undefined ) {
                    $.extend( settings.aoPreSearchCols[i], _fnSearchToHung( col.search ) );
                }
            }
        
            _fnCallbackFire( settings, 'aoStateLoaded', 'stateLoaded', [settings, state] );
        }
        
        
        /**
         * Return the settings object for a particular table
         *  @param {node} table table we are using as a dataTable
         *  @returns {object} Settings object - or null if not found
         *  @memberof DataTable#oApi
         */
        function _fnSettingsFromNode ( table )
        {
            var settings = DataTable.settings;
            var idx = $.inArray( table, _pluck( settings, 'nTable' ) );
        
            return idx !== -1 ?
                settings[ idx ] :
                null;
        }
        
        
        /**
         * Log an error message
         *  @param {object} settings dataTables settings object
         *  @param {int} level log error messages, or display them to the user
         *  @param {string} msg error message
         *  @param {int} tn Technical note id to get more information about the error.
         *  @memberof DataTable#oApi
         */
        function _fnLog( settings, level, msg, tn )
        {
            msg = 'DataTables warning: '+
                (settings ? 'table id='+settings.sTableId+' - ' : '')+msg;
        
            if ( tn ) {
                msg += '. For more information about this error, please see '+
                'http://datatables.net/tn/'+tn;
            }
        
            if ( ! level  ) {
                // Backwards compatibility pre 1.10
                var ext = DataTable.ext;
                var type = ext.sErrMode || ext.errMode;
        
                if ( settings ) {
                    _fnCallbackFire( settings, null, 'error', [ settings, tn, msg ] );
                }
        
                if ( type == 'alert' ) {
                    alert( msg );
                }
                else if ( type == 'throw' ) {
                    throw new Error(msg);
                }
                else if ( typeof type == 'function' ) {
                    type( settings, tn, msg );
                }
            }
            else if ( window.console && console.log ) {
                console.log( msg );
            }
        }
        
        
        /**
         * See if a property is defined on one object, if so assign it to the other object
         *  @param {object} ret target object
         *  @param {object} src source object
         *  @param {string} name property
         *  @param {string} [mappedName] name to map too - optional, name used if not given
         *  @memberof DataTable#oApi
         */
        function _fnMap( ret, src, name, mappedName )
        {
            if ( $.isArray( name ) ) {
                $.each( name, function (i, val) {
                    if ( $.isArray( val ) ) {
                        _fnMap( ret, src, val[0], val[1] );
                    }
                    else {
                        _fnMap( ret, src, val );
                    }
                } );
        
                return;
            }
        
            if ( mappedName === undefined ) {
                mappedName = name;
            }
        
            if ( src[name] !== undefined ) {
                ret[mappedName] = src[name];
            }
        }
        
        
        /**
         * Extend objects - very similar to jQuery.extend, but deep copy objects, and
         * shallow copy arrays. The reason we need to do this, is that we don't want to
         * deep copy array init values (such as aaSorting) since the dev wouldn't be
         * able to override them, but we do want to deep copy arrays.
         *  @param {object} out Object to extend
         *  @param {object} extender Object from which the properties will be applied to
         *      out
         *  @param {boolean} breakRefs If true, then arrays will be sliced to take an
         *      independent copy with the exception of the `data` or `aaData` parameters
         *      if they are present. This is so you can pass in a collection to
         *      DataTables and have that used as your data source without breaking the
         *      references
         *  @returns {object} out Reference, just for convenience - out === the return.
         *  @memberof DataTable#oApi
         *  @todo This doesn't take account of arrays inside the deep copied objects.
         */
        function _fnExtend( out, extender, breakRefs )
        {
            var val;
        
            for ( var prop in extender ) {
                if ( extender.hasOwnProperty(prop) ) {
                    val = extender[prop];
        
                    if ( $.isPlainObject( val ) ) {
                        if ( ! $.isPlainObject( out[prop] ) ) {
                            out[prop] = {};
                        }
                        $.extend( true, out[prop], val );
                    }
                    else if ( breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val) ) {
                        out[prop] = val.slice();
                    }
                    else {
                        out[prop] = val;
                    }
                }
            }
        
            return out;
        }
        
        
        /**
         * Bind an event handers to allow a click or return key to activate the callback.
         * This is good for accessibility since a return on the keyboard will have the
         * same effect as a click, if the element has focus.
         *  @param {element} n Element to bind the action to
         *  @param {object} oData Data object to pass to the triggered function
         *  @param {function} fn Callback function for when the event is triggered
         *  @memberof DataTable#oApi
         */
        function _fnBindAction( n, oData, fn )
        {
            $(n)
                .bind( 'click.DT', oData, function (e) {
                        n.blur(); // Remove focus outline for mouse users
                        fn(e);
                    } )
                .bind( 'keypress.DT', oData, function (e){
                        if ( e.which === 13 ) {
                            e.preventDefault();
                            fn(e);
                        }
                    } )
                .bind( 'selectstart.DT', function () {
                        /* Take the brutal approach to cancelling text selection */
                        return false;
                    } );
        }
        
        
        /**
         * Register a callback function. Easily allows a callback function to be added to
         * an array store of callback functions that can then all be called together.
         *  @param {object} oSettings dataTables settings object
         *  @param {string} sStore Name of the array storage for the callbacks in oSettings
         *  @param {function} fn Function to be called back
         *  @param {string} sName Identifying name for the callback (i.e. a label)
         *  @memberof DataTable#oApi
         */
        function _fnCallbackReg( oSettings, sStore, fn, sName )
        {
            if ( fn )
            {
                oSettings[sStore].push( {
                    "fn": fn,
                    "sName": sName
                } );
            }
        }
        
        
        /**
         * Fire callback functions and trigger events. Note that the loop over the
         * callback array store is done backwards! Further note that you do not want to
         * fire off triggers in time sensitive applications (for example cell creation)
         * as its slow.
         *  @param {object} settings dataTables settings object
         *  @param {string} callbackArr Name of the array storage for the callbacks in
         *      oSettings
         *  @param {string} eventName Name of the jQuery custom event to trigger. If
         *      null no trigger is fired
         *  @param {array} args Array of arguments to pass to the callback function /
         *      trigger
         *  @memberof DataTable#oApi
         */
        function _fnCallbackFire( settings, callbackArr, eventName, args )
        {
            var ret = [];
        
            if ( callbackArr ) {
                ret = $.map( settings[callbackArr].slice().reverse(), function (val, i) {
                    return val.fn.apply( settings.oInstance, args );
                } );
            }
        
            if ( eventName !== null ) {
                var e = $.Event( eventName+'.dt' );
        
                $(settings.nTable).trigger( e, args );
        
                ret.push( e.result );
            }
        
            return ret;
        }
        
        
        function _fnLengthOverflow ( settings )
        {
            var
                start = settings._iDisplayStart,
                end = settings.fnDisplayEnd(),
                len = settings._iDisplayLength;
        
            /* If we have space to show extra rows (backing up from the end point - then do so */
            if ( start >= end )
            {
                start = end - len;
            }
        
            // Keep the start record on the current page
            start -= (start % len);
        
            if ( len === -1 || start < 0 )
            {
                start = 0;
            }
        
            settings._iDisplayStart = start;
        }
        
        
        function _fnRenderer( settings, type )
        {
            var renderer = settings.renderer;
            var host = DataTable.ext.renderer[type];
        
            if ( $.isPlainObject( renderer ) && renderer[type] ) {
                // Specific renderer for this type. If available use it, otherwise use
                // the default.
                return host[renderer[type]] || host._;
            }
            else if ( typeof renderer === 'string' ) {
                // Common renderer - if there is one available for this type use it,
                // otherwise use the default
                return host[renderer] || host._;
            }
        
            // Use the default
            return host._;
        }
        
        
        /**
         * Detect the data source being used for the table. Used to simplify the code
         * a little (ajax) and to make it compress a little smaller.
         *
         *  @param {object} settings dataTables settings object
         *  @returns {string} Data source
         *  @memberof DataTable#oApi
         */
        function _fnDataSource ( settings )
        {
            if ( settings.oFeatures.bServerSide ) {
                return 'ssp';
            }
            else if ( settings.ajax || settings.sAjaxSource ) {
                return 'ajax';
            }
            return 'dom';
        }
        
    
        
        
        /**
         * Computed structure of the DataTables API, defined by the options passed to
         * `DataTable.Api.register()` when building the API.
         *
         * The structure is built in order to speed creation and extension of the Api
         * objects since the extensions are effectively pre-parsed.
         *
         * The array is an array of objects with the following structure, where this
         * base array represents the Api prototype base:
         *
         *     [
         *       {
         *         name:      'data'                -- string   - Property name
         *         val:       function () {},       -- function - Api method (or undefined if just an object
         *         methodExt: [ ... ],              -- array    - Array of Api object definitions to extend the method result
         *         propExt:   [ ... ]               -- array    - Array of Api object definitions to extend the property
         *       },
         *       {
         *         name:     'row'
         *         val:       {},
         *         methodExt: [ ... ],
         *         propExt:   [
         *           {
         *             name:      'data'
         *             val:       function () {},
         *             methodExt: [ ... ],
         *             propExt:   [ ... ]
         *           },
         *           ...
         *         ]
         *       }
         *     ]
         *
         * @type {Array}
         * @ignore
         */
        var __apiStruct = [];
        
        
        /**
         * `Array.prototype` reference.
         *
         * @type object
         * @ignore
         */
        var __arrayProto = Array.prototype;
        
        
        /**
         * Abstraction for `context` parameter of the `Api` constructor to allow it to
         * take several different forms for ease of use.
         *
         * Each of the input parameter types will be converted to a DataTables settings
         * object where possible.
         *
         * @param  {string|node|jQuery|object} mixed DataTable identifier. Can be one
         *   of:
         *
         *   * `string` - jQuery selector. Any DataTables' matching the given selector
         *     with be found and used.
         *   * `node` - `TABLE` node which has already been formed into a DataTable.
         *   * `jQuery` - A jQuery object of `TABLE` nodes.
         *   * `object` - DataTables settings object
         *   * `DataTables.Api` - API instance
         * @return {array|null} Matching DataTables settings objects. `null` or
         *   `undefined` is returned if no matching DataTable is found.
         * @ignore
         */
        var _toSettings = function ( mixed )
        {
            var idx, jq;
            var settings = DataTable.settings;
            var tables = $.map( settings, function (el, i) {
                return el.nTable;
            } );
        
            if ( ! mixed ) {
                return [];
            }
            else if ( mixed.nTable && mixed.oApi ) {
                // DataTables settings object
                return [ mixed ];
            }
            else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) {
                // Table node
                idx = $.inArray( mixed, tables );
                return idx !== -1 ? [ settings[idx] ] : null;
            }
            else if ( mixed && typeof mixed.settings === 'function' ) {
                return mixed.settings().toArray();
            }
            else if ( typeof mixed === 'string' ) {
                // jQuery selector
                jq = $(mixed);
            }
            else if ( mixed instanceof $ ) {
                // jQuery object (also DataTables instance)
                jq = mixed;
            }
        
            if ( jq ) {
                return jq.map( function(i) {
                    idx = $.inArray( this, tables );
                    return idx !== -1 ? settings[idx] : null;
                } ).toArray();
            }
        };
        
        
        /**
         * DataTables API class - used to control and interface with  one or more
         * DataTables enhanced tables.
         *
         * The API class is heavily based on jQuery, presenting a chainable interface
         * that you can use to interact with tables. Each instance of the API class has
         * a "context" - i.e. the tables that it will operate on. This could be a single
         * table, all tables on a page or a sub-set thereof.
         *
         * Additionally the API is designed to allow you to easily work with the data in
         * the tables, retrieving and manipulating it as required. This is done by
         * presenting the API class as an array like interface. The contents of the
         * array depend upon the actions requested by each method (for example
         * `rows().nodes()` will return an array of nodes, while `rows().data()` will
         * return an array of objects or arrays depending upon your table's
         * configuration). The API object has a number of array like methods (`push`,
         * `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`,
         * `unique` etc) to assist your working with the data held in a table.
         *
         * Most methods (those which return an Api instance) are chainable, which means
         * the return from a method call also has all of the methods available that the
         * top level object had. For example, these two calls are equivalent:
         *
         *     // Not chained
         *     api.row.add( {...} );
         *     api.draw();
         *
         *     // Chained
         *     api.row.add( {...} ).draw();
         *
         * @class DataTable.Api
         * @param {array|object|string|jQuery} context DataTable identifier. This is
         *   used to define which DataTables enhanced tables this API will operate on.
         *   Can be one of:
         *
         *   * `string` - jQuery selector. Any DataTables' matching the given selector
         *     with be found and used.
         *   * `node` - `TABLE` node which has already been formed into a DataTable.
         *   * `jQuery` - A jQuery object of `TABLE` nodes.
         *   * `object` - DataTables settings object
         * @param {array} [data] Data to initialise the Api instance with.
         *
         * @example
         *   // Direct initialisation during DataTables construction
         *   var api = $('#example').DataTable();
         *
         * @example
         *   // Initialisation using a DataTables jQuery object
         *   var api = $('#example').dataTable().api();
         *
         * @example
         *   // Initialisation as a constructor
         *   var api = new $.fn.DataTable.Api( 'table.dataTable' );
         */
        _Api = function ( context, data )
        {
            if ( ! (this instanceof _Api) ) {
                return new _Api( context, data );
            }
        
            var settings = [];
            var ctxSettings = function ( o ) {
                var a = _toSettings( o );
                if ( a ) {
                    settings = settings.concat( a );
                }
            };
        
            if ( $.isArray( context ) ) {
                for ( var i=0, ien=context.length ; i<ien ; i++ ) {
                    ctxSettings( context[i] );
                }
            }
            else {
                ctxSettings( context );
            }
        
            // Remove duplicates
            this.context = _unique( settings );
        
            // Initial data
            if ( data ) {
                $.merge( this, data );
            }
        
            // selector
            this.selector = {
                rows: null,
                cols: null,
                opts: null
            };
        
            _Api.extend( this, this, __apiStruct );
        };
        
        DataTable.Api = _Api;
        
        // Don't destroy the existing prototype, just extend it. Required for jQuery 2's
        // isPlainObject.
        $.extend( _Api.prototype, {
            any: function ()
            {
                return this.count() !== 0;
            },
        
        
            concat:  __arrayProto.concat,
        
        
            context: [], // array of table settings objects
        
        
            count: function ()
            {
                return this.flatten().length;
            },
        
        
            each: function ( fn )
            {
                for ( var i=0, ien=this.length ; i<ien; i++ ) {
                    fn.call( this, this[i], i, this );
                }
        
                return this;
            },
        
        
            eq: function ( idx )
            {
                var ctx = this.context;
        
                return ctx.length > idx ?
                    new _Api( ctx[idx], this[idx] ) :
                    null;
            },
        
        
            filter: function ( fn )
            {
                var a = [];
        
                if ( __arrayProto.filter ) {
                    a = __arrayProto.filter.call( this, fn, this );
                }
                else {
                    // Compatibility for browsers without EMCA-252-5 (JS 1.6)
                    for ( var i=0, ien=this.length ; i<ien ; i++ ) {
                        if ( fn.call( this, this[i], i, this ) ) {
                            a.push( this[i] );
                        }
                    }
                }
        
                return new _Api( this.context, a );
            },
        
        
            flatten: function ()
            {
                var a = [];
                return new _Api( this.context, a.concat.apply( a, this.toArray() ) );
            },
        
        
            join:    __arrayProto.join,
        
        
            indexOf: __arrayProto.indexOf || function (obj, start)
            {
                for ( var i=(start || 0), ien=this.length ; i<ien ; i++ ) {
                    if ( this[i] === obj ) {
                        return i;
                    }
                }
                return -1;
            },
        
            iterator: function ( flatten, type, fn, alwaysNew ) {
                var
                    a = [], ret,
                    i, ien, j, jen,
                    context = this.context,
                    rows, items, item,
                    selector = this.selector;
        
                // Argument shifting
                if ( typeof flatten === 'string' ) {
                    alwaysNew = fn;
                    fn = type;
                    type = flatten;
                    flatten = false;
                }
        
                for ( i=0, ien=context.length ; i<ien ; i++ ) {
                    var apiInst = new _Api( context[i] );
        
                    if ( type === 'table' ) {
                        ret = fn.call( apiInst, context[i], i );
        
                        if ( ret !== undefined ) {
                            a.push( ret );
                        }
                    }
                    else if ( type === 'columns' || type === 'rows' ) {
                        // this has same length as context - one entry for each table
                        ret = fn.call( apiInst, context[i], this[i], i );
        
                        if ( ret !== undefined ) {
                            a.push( ret );
                        }
                    }
                    else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) {
                        // columns and rows share the same structure.
                        // 'this' is an array of column indexes for each context
                        items = this[i];
        
                        if ( type === 'column-rows' ) {
                            rows = _selector_row_indexes( context[i], selector.opts );
                        }
        
                        for ( j=0, jen=items.length ; j<jen ; j++ ) {
                            item = items[j];
        
                            if ( type === 'cell' ) {
                                ret = fn.call( apiInst, context[i], item.row, item.column, i, j );
                            }
                            else {
                                ret = fn.call( apiInst, context[i], item, i, j, rows );
                            }
        
                            if ( ret !== undefined ) {
                                a.push( ret );
                            }
                        }
                    }
                }
        
                if ( a.length || alwaysNew ) {
                    var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a );
                    var apiSelector = api.selector;
                    apiSelector.rows = selector.rows;
                    apiSelector.cols = selector.cols;
                    apiSelector.opts = selector.opts;
                    return api;
                }
                return this;
            },
        
        
            lastIndexOf: __arrayProto.lastIndexOf || function (obj, start)
            {
                // Bit cheeky...
                return this.indexOf.apply( this.toArray.reverse(), arguments );
            },
        
        
            length:  0,
        
        
            map: function ( fn )
            {
                var a = [];
        
                if ( __arrayProto.map ) {
                    a = __arrayProto.map.call( this, fn, this );
                }
                else {
                    // Compatibility for browsers without EMCA-252-5 (JS 1.6)
                    for ( var i=0, ien=this.length ; i<ien ; i++ ) {
                        a.push( fn.call( this, this[i], i ) );
                    }
                }
        
                return new _Api( this.context, a );
            },
        
        
            pluck: function ( prop )
            {
                return this.map( function ( el ) {
                    return el[ prop ];
                } );
            },
        
            pop:     __arrayProto.pop,
        
        
            push:    __arrayProto.push,
        
        
            // Does not return an API instance
            reduce: __arrayProto.reduce || function ( fn, init )
            {
                return _fnReduce( this, fn, init, 0, this.length, 1 );
            },
        
        
            reduceRight: __arrayProto.reduceRight || function ( fn, init )
            {
                return _fnReduce( this, fn, init, this.length-1, -1, -1 );
            },
        
        
            reverse: __arrayProto.reverse,
        
        
            // Object with rows, columns and opts
            selector: null,
        
        
            shift:   __arrayProto.shift,
        
        
            sort:    __arrayProto.sort, // ? name - order?
        
        
            splice:  __arrayProto.splice,
        
        
            toArray: function ()
            {
                return __arrayProto.slice.call( this );
            },
        
        
            to$: function ()
            {
                return $( this );
            },
        
        
            toJQuery: function ()
            {
                return $( this );
            },
        
        
            unique: function ()
            {
                return new _Api( this.context, _unique(this) );
            },
        
        
            unshift: __arrayProto.unshift
        } );
        
        
        _Api.extend = function ( scope, obj, ext )
        {
            // Only extend API instances and static properties of the API
            if ( ! ext.length || ! obj || ( ! (obj instanceof _Api) && ! obj.__dt_wrapper ) ) {
                return;
            }
        
            var
                i, ien,
                j, jen,
                struct, inner,
                methodScoping = function ( scope, fn, struc ) {
                    return function () {
                        var ret = fn.apply( scope, arguments );
        
                        // Method extension
                        _Api.extend( ret, ret, struc.methodExt );
                        return ret;
                    };
                };
        
            for ( i=0, ien=ext.length ; i<ien ; i++ ) {
                struct = ext[i];
        
                // Value
                obj[ struct.name ] = typeof struct.val === 'function' ?
                    methodScoping( scope, struct.val, struct ) :
                    $.isPlainObject( struct.val ) ?
                        {} :
                        struct.val;
        
                obj[ struct.name ].__dt_wrapper = true;
        
                // Property extension
                _Api.extend( scope, obj[ struct.name ], struct.propExt );
            }
        };
        
        
        // @todo - Is there need for an augment function?
        // _Api.augment = function ( inst, name )
        // {
        // 	// Find src object in the structure from the name
        // 	var parts = name.split('.');
        
        // 	_Api.extend( inst, obj );
        // };
        
        
        //     [
        //       {
        //         name:      'data'                -- string   - Property name
        //         val:       function () {},       -- function - Api method (or undefined if just an object
        //         methodExt: [ ... ],              -- array    - Array of Api object definitions to extend the method result
        //         propExt:   [ ... ]               -- array    - Array of Api object definitions to extend the property
        //       },
        //       {
        //         name:     'row'
        //         val:       {},
        //         methodExt: [ ... ],
        //         propExt:   [
        //           {
        //             name:      'data'
        //             val:       function () {},
        //             methodExt: [ ... ],
        //             propExt:   [ ... ]
        //           },
        //           ...
        //         ]
        //       }
        //     ]
        
        _Api.register = _api_register = function ( name, val )
        {
            if ( $.isArray( name ) ) {
                for ( var j=0, jen=name.length ; j<jen ; j++ ) {
                    _Api.register( name[j], val );
                }
                return;
            }
        
            var
                i, ien,
                heir = name.split('.'),
                struct = __apiStruct,
                key, method;
        
            var find = function ( src, name ) {
                for ( var i=0, ien=src.length ; i<ien ; i++ ) {
                    if ( src[i].name === name ) {
                        return src[i];
                    }
                }
                return null;
            };
        
            for ( i=0, ien=heir.length ; i<ien ; i++ ) {
                method = heir[i].indexOf('()') !== -1;
                key = method ?
                    heir[i].replace('()', '') :
                    heir[i];
        
                var src = find( struct, key );
                if ( ! src ) {
                    src = {
                        name:      key,
                        val:       {},
                        methodExt: [],
                        propExt:   []
                    };
                    struct.push( src );
                }
        
                if ( i === ien-1 ) {
                    src.val = val;
                }
                else {
                    struct = method ?
                        src.methodExt :
                        src.propExt;
                }
            }
        };
        
        
        _Api.registerPlural = _api_registerPlural = function ( pluralName, singularName, val ) {
            _Api.register( pluralName, val );
        
            _Api.register( singularName, function () {
                var ret = val.apply( this, arguments );
        
                if ( ret === this ) {
                    // Returned item is the API instance that was passed in, return it
                    return this;
                }
                else if ( ret instanceof _Api ) {
                    // New API instance returned, want the value from the first item
                    // in the returned array for the singular result.
                    return ret.length ?
                        $.isArray( ret[0] ) ?
                            new _Api( ret.context, ret[0] ) : // Array results are 'enhanced'
                            ret[0] :
                        undefined;
                }
        
                // Non-API return - just fire it back
                return ret;
            } );
        };
        
        
        /**
         * Selector for HTML tables. Apply the given selector to the give array of
         * DataTables settings objects.
         *
         * @param {string|integer} [selector] jQuery selector string or integer
         * @param  {array} Array of DataTables settings objects to be filtered
         * @return {array}
         * @ignore
         */
        var __table_selector = function ( selector, a )
        {
            // Integer is used to pick out a table by index
            if ( typeof selector === 'number' ) {
                return [ a[ selector ] ];
            }
        
            // Perform a jQuery selector on the table nodes
            var nodes = $.map( a, function (el, i) {
                return el.nTable;
            } );
        
            return $(nodes)
                .filter( selector )
                .map( function (i) {
                    // Need to translate back from the table node to the settings
                    var idx = $.inArray( this, nodes );
                    return a[ idx ];
                } )
                .toArray();
        };
        
        
        
        /**
         * Context selector for the API's context (i.e. the tables the API instance
         * refers to.
         *
         * @name    DataTable.Api#tables
         * @param {string|integer} [selector] Selector to pick which tables the iterator
         *   should operate on. If not given, all tables in the current context are
         *   used. This can be given as a jQuery selector (for example `':gt(0)'`) to
         *   select multiple tables or as an integer to select a single table.
         * @returns {DataTable.Api} Returns a new API instance if a selector is given.
         */
        _api_register( 'tables()', function ( selector ) {
            // A new instance is created if there was a selector specified
            return selector ?
                new _Api( __table_selector( selector, this.context ) ) :
                this;
        } );
        
        
        _api_register( 'table()', function ( selector ) {
            var tables = this.tables( selector );
            var ctx = tables.context;
        
            // Truncate to the first matched table
            return ctx.length ?
                new _Api( ctx[0] ) :
                tables;
        } );
        
        
        _api_registerPlural( 'tables().nodes()', 'table().node()' , function () {
            return this.iterator( 'table', function ( ctx ) {
                return ctx.nTable;
            }, 1 );
        } );
        
        
        _api_registerPlural( 'tables().body()', 'table().body()' , function () {
            return this.iterator( 'table', function ( ctx ) {
                return ctx.nTBody;
            }, 1 );
        } );
        
        
        _api_registerPlural( 'tables().header()', 'table().header()' , function () {
            return this.iterator( 'table', function ( ctx ) {
                return ctx.nTHead;
            }, 1 );
        } );
        
        
        _api_registerPlural( 'tables().footer()', 'table().footer()' , function () {
            return this.iterator( 'table', function ( ctx ) {
                return ctx.nTFoot;
            }, 1 );
        } );
        
        
        _api_registerPlural( 'tables().containers()', 'table().container()' , function () {
            return this.iterator( 'table', function ( ctx ) {
                return ctx.nTableWrapper;
            }, 1 );
        } );
        
        
        
        /**
         * Redraw the tables in the current context.
         */
        _api_register( 'draw()', function ( paging ) {
            return this.iterator( 'table', function ( settings ) {
                if ( paging === 'page' ) {
                    _fnDraw( settings );
                }
                else {
                    if ( typeof paging === 'string' ) {
                        paging = paging === 'full-hold' ?
                            false :
                            true;
                    }
        
                    _fnReDraw( settings, paging===false );
                }
            } );
        } );
        
        
        
        /**
         * Get the current page index.
         *
         * @return {integer} Current page index (zero based)
         *//**
         * Set the current page.
         *
         * Note that if you attempt to show a page which does not exist, DataTables will
         * not throw an error, but rather reset the paging.
         *
         * @param {integer|string} action The paging action to take. This can be one of:
         *  * `integer` - The page index to jump to
         *  * `string` - An action to take:
         *    * `first` - Jump to first page.
         *    * `next` - Jump to the next page
         *    * `previous` - Jump to previous page
         *    * `last` - Jump to the last page.
         * @returns {DataTables.Api} this
         */
        _api_register( 'page()', function ( action ) {
            if ( action === undefined ) {
                return this.page.info().page; // not an expensive call
            }
        
            // else, have an action to take on all tables
            return this.iterator( 'table', function ( settings ) {
                _fnPageChange( settings, action );
            } );
        } );
        
        
        /**
         * Paging information for the first table in the current context.
         *
         * If you require paging information for another table, use the `table()` method
         * with a suitable selector.
         *
         * @return {object} Object with the following properties set:
         *  * `page` - Current page index (zero based - i.e. the first page is `0`)
         *  * `pages` - Total number of pages
         *  * `start` - Display index for the first record shown on the current page
         *  * `end` - Display index for the last record shown on the current page
         *  * `length` - Display length (number of records). Note that generally `start
         *    + length = end`, but this is not always true, for example if there are
         *    only 2 records to show on the final page, with a length of 10.
         *  * `recordsTotal` - Full data set length
         *  * `recordsDisplay` - Data set length once the current filtering criterion
         *    are applied.
         */
        _api_register( 'page.info()', function ( action ) {
            if ( this.context.length === 0 ) {
                return undefined;
            }
        
            var
                settings   = this.context[0],
                start      = settings._iDisplayStart,
                len        = settings.oFeatures.bPaginate ? settings._iDisplayLength : -1,
                visRecords = settings.fnRecordsDisplay(),
                all        = len === -1;
        
            return {
                "page":           all ? 0 : Math.floor( start / len ),
                "pages":          all ? 1 : Math.ceil( visRecords / len ),
                "start":          start,
                "end":            settings.fnDisplayEnd(),
                "length":         len,
                "recordsTotal":   settings.fnRecordsTotal(),
                "recordsDisplay": visRecords,
                "serverSide":     _fnDataSource( settings ) === 'ssp'
            };
        } );
        
        
        /**
         * Get the current page length.
         *
         * @return {integer} Current page length. Note `-1` indicates that all records
         *   are to be shown.
         *//**
         * Set the current page length.
         *
         * @param {integer} Page length to set. Use `-1` to show all records.
         * @returns {DataTables.Api} this
         */
        _api_register( 'page.len()', function ( len ) {
            // Note that we can't call this function 'length()' because `length`
            // is a Javascript property of functions which defines how many arguments
            // the function expects.
            if ( len === undefined ) {
                return this.context.length !== 0 ?
                    this.context[0]._iDisplayLength :
                    undefined;
            }
        
            // else, set the page length
            return this.iterator( 'table', function ( settings ) {
                _fnLengthChange( settings, len );
            } );
        } );
        
        
        
        var __reload = function ( settings, holdPosition, callback ) {
            // Use the draw event to trigger a callback
            if ( callback ) {
                var api = new _Api( settings );
        
                api.one( 'draw', function () {
                    callback( api.ajax.json() );
                } );
            }
        
            if ( _fnDataSource( settings ) == 'ssp' ) {
                _fnReDraw( settings, holdPosition );
            }
            else {
                _fnProcessingDisplay( settings, true );
        
                // Cancel an existing request
                var xhr = settings.jqXHR;
                if ( xhr && xhr.readyState !== 4 ) {
                    xhr.abort();
                }
        
                // Trigger xhr
                _fnBuildAjax( settings, [], function( json ) {
                    _fnClearTable( settings );
        
                    var data = _fnAjaxDataSrc( settings, json );
                    for ( var i=0, ien=data.length ; i<ien ; i++ ) {
                        _fnAddData( settings, data[i] );
                    }
        
                    _fnReDraw( settings, holdPosition );
                    _fnProcessingDisplay( settings, false );
                } );
            }
        };
        
        
        /**
         * Get the JSON response from the last Ajax request that DataTables made to the
         * server. Note that this returns the JSON from the first table in the current
         * context.
         *
         * @return {object} JSON received from the server.
         */
        _api_register( 'ajax.json()', function () {
            var ctx = this.context;
        
            if ( ctx.length > 0 ) {
                return ctx[0].json;
            }
        
            // else return undefined;
        } );
        
        
        /**
         * Get the data submitted in the last Ajax request
         */
        _api_register( 'ajax.params()', function () {
            var ctx = this.context;
        
            if ( ctx.length > 0 ) {
                return ctx[0].oAjaxData;
            }
        
            // else return undefined;
        } );
        
        
        /**
         * Reload tables from the Ajax data source. Note that this function will
         * automatically re-draw the table when the remote data has been loaded.
         *
         * @param {boolean} [reset=true] Reset (default) or hold the current paging
         *   position. A full re-sort and re-filter is performed when this method is
         *   called, which is why the pagination reset is the default action.
         * @returns {DataTables.Api} this
         */
        _api_register( 'ajax.reload()', function ( callback, resetPaging ) {
            return this.iterator( 'table', function (settings) {
                __reload( settings, resetPaging===false, callback );
            } );
        } );
        
        
        /**
         * Get the current Ajax URL. Note that this returns the URL from the first
         * table in the current context.
         *
         * @return {string} Current Ajax source URL
         *//**
         * Set the Ajax URL. Note that this will set the URL for all tables in the
         * current context.
         *
         * @param {string} url URL to set.
         * @returns {DataTables.Api} this
         */
        _api_register( 'ajax.url()', function ( url ) {
            var ctx = this.context;
        
            if ( url === undefined ) {
                // get
                if ( ctx.length === 0 ) {
                    return undefined;
                }
                ctx = ctx[0];
        
                return ctx.ajax ?
                    $.isPlainObject( ctx.ajax ) ?
                        ctx.ajax.url :
                        ctx.ajax :
                    ctx.sAjaxSource;
            }
        
            // set
            return this.iterator( 'table', function ( settings ) {
                if ( $.isPlainObject( settings.ajax ) ) {
                    settings.ajax.url = url;
                }
                else {
                    settings.ajax = url;
                }
                // No need to consider sAjaxSource here since DataTables gives priority
                // to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any
                // value of `sAjaxSource` redundant.
            } );
        } );
        
        
        /**
         * Load data from the newly set Ajax URL. Note that this method is only
         * available when `ajax.url()` is used to set a URL. Additionally, this method
         * has the same effect as calling `ajax.reload()` but is provided for
         * convenience when setting a new URL. Like `ajax.reload()` it will
         * automatically redraw the table once the remote data has been loaded.
         *
         * @returns {DataTables.Api} this
         */
        _api_register( 'ajax.url().load()', function ( callback, resetPaging ) {
            // Same as a reload, but makes sense to present it for easy access after a
            // url change
            return this.iterator( 'table', function ( ctx ) {
                __reload( ctx, resetPaging===false, callback );
            } );
        } );
        
        
        
        
        var _selector_run = function ( type, selector, selectFn, settings, opts )
        {
            var
                out = [], res,
                a, i, ien, j, jen,
                selectorType = typeof selector;
        
            // Can't just check for isArray here, as an API or jQuery instance might be
            // given with their array like look
            if ( ! selector || selectorType === 'string' || selectorType === 'function' || selector.length === undefined ) {
                selector = [ selector ];
            }
        
            for ( i=0, ien=selector.length ; i<ien ; i++ ) {
                a = selector[i] && selector[i].split ?
                    selector[i].split(',') :
                    [ selector[i] ];
        
                for ( j=0, jen=a.length ; j<jen ; j++ ) {
                    res = selectFn( typeof a[j] === 'string' ? $.trim(a[j]) : a[j] );
        
                    if ( res && res.length ) {
                        out = out.concat( res );
                    }
                }
            }
        
            // selector extensions
            var ext = _ext.selector[ type ];
            if ( ext.length ) {
                for ( i=0, ien=ext.length ; i<ien ; i++ ) {
                    out = ext[i]( settings, opts, out );
                }
            }
        
            return _unique( out );
        };
        
        
        var _selector_opts = function ( opts )
        {
            if ( ! opts ) {
                opts = {};
            }
        
            // Backwards compatibility for 1.9- which used the terminology filter rather
            // than search
            if ( opts.filter && opts.search === undefined ) {
                opts.search = opts.filter;
            }
        
            return $.extend( {
                search: 'none',
                order: 'current',
                page: 'all'
            }, opts );
        };
        
        
        var _selector_first = function ( inst )
        {
            // Reduce the API instance to the first item found
            for ( var i=0, ien=inst.length ; i<ien ; i++ ) {
                if ( inst[i].length > 0 ) {
                    // Assign the first element to the first item in the instance
                    // and truncate the instance and context
                    inst[0] = inst[i];
                    inst[0].length = 1;
                    inst.length = 1;
                    inst.context = [ inst.context[i] ];
        
                    return inst;
                }
            }
        
            // Not found - return an empty instance
            inst.length = 0;
            return inst;
        };
        
        
        var _selector_row_indexes = function ( settings, opts )
        {
            var
                i, ien, tmp, a=[],
                displayFiltered = settings.aiDisplay,
                displayMaster = settings.aiDisplayMaster;
        
            var
                search = opts.search,  // none, applied, removed
                order  = opts.order,   // applied, current, index (original - compatibility with 1.9)
                page   = opts.page;    // all, current
        
            if ( _fnDataSource( settings ) == 'ssp' ) {
                // In server-side processing mode, most options are irrelevant since
                // rows not shown don't exist and the index order is the applied order
                // Removed is a special case - for consistency just return an empty
                // array
                return search === 'removed' ?
                    [] :
                    _range( 0, displayMaster.length );
            }
            else if ( page == 'current' ) {
                // Current page implies that order=current and fitler=applied, since it is
                // fairly senseless otherwise, regardless of what order and search actually
                // are
                for ( i=settings._iDisplayStart, ien=settings.fnDisplayEnd() ; i<ien ; i++ ) {
                    a.push( displayFiltered[i] );
                }
            }
            else if ( order == 'current' || order == 'applied' ) {
                a = search == 'none' ?
                    displayMaster.slice() :                      // no search
                    search == 'applied' ?
                        displayFiltered.slice() :                // applied search
                        $.map( displayMaster, function (el, i) { // removed search
                            return $.inArray( el, displayFiltered ) === -1 ? el : null;
                        } );
            }
            else if ( order == 'index' || order == 'original' ) {
                for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
                    if ( search == 'none' ) {
                        a.push( i );
                    }
                    else { // applied | removed
                        tmp = $.inArray( i, displayFiltered );
        
                        if ((tmp === -1 && search == 'removed') ||
                            (tmp >= 0   && search == 'applied') )
                        {
                            a.push( i );
                        }
                    }
                }
            }
        
            return a;
        };
        
        
        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * Rows
         *
         * {}          - no selector - use all available rows
         * {integer}   - row aoData index
         * {node}      - TR node
         * {string}    - jQuery selector to apply to the TR elements
         * {array}     - jQuery array of nodes, or simply an array of TR nodes
         *
         */
        
        
        var __row_selector = function ( settings, selector, opts )
        {
            var run = function ( sel ) {
                var selInt = _intVal( sel );
                var i, ien;
        
                // Short cut - selector is a number and no options provided (default is
                // all records, so no need to check if the index is in there, since it
                // must be - dev error if the index doesn't exist).
                if ( selInt !== null && ! opts ) {
                    return [ selInt ];
                }
        
                var rows = _selector_row_indexes( settings, opts );
        
                if ( selInt !== null && $.inArray( selInt, rows ) !== -1 ) {
                    // Selector - integer
                    return [ selInt ];
                }
                else if ( ! sel ) {
                    // Selector - none
                    return rows;
                }
        
                // Selector - function
                if ( typeof sel === 'function' ) {
                    return $.map( rows, function (idx) {
                        var row = settings.aoData[ idx ];
                        return sel( idx, row._aData, row.nTr ) ? idx : null;
                    } );
                }
        
                // Get nodes in the order from the `rows` array with null values removed
                var nodes = _removeEmpty(
                    _pluck_order( settings.aoData, rows, 'nTr' )
                );
        
                // Selector - node
                if ( sel.nodeName ) {
                    if ( sel._DT_RowIndex !== undefined ) {
                        return [ sel._DT_RowIndex ]; // Property added by DT for fast lookup
                    }
                    else if ( sel._DT_CellIndex ) {
                        return [ sel._DT_CellIndex.row ];
                    }
                    else {
                        var host = $(sel).closest('*[data-dt-row]');
                        return host.length ?
                            [ host.data('dt-row') ] :
                            [];
                    }
                }
        
                // ID selector. Want to always be able to select rows by id, regardless
                // of if the tr element has been created or not, so can't rely upon
                // jQuery here - hence a custom implementation. This does not match
                // Sizzle's fast selector or HTML4 - in HTML5 the ID can be anything,
                // but to select it using a CSS selector engine (like Sizzle or
                // querySelect) it would need to need to be escaped for some characters.
                // DataTables simplifies this for row selectors since you can select
                // only a row. A # indicates an id any anything that follows is the id -
                // unescaped.
                if ( typeof sel === 'string' && sel.charAt(0) === '#' ) {
                    // get row index from id
                    var rowObj = settings.aIds[ sel.replace( /^#/, '' ) ];
                    if ( rowObj !== undefined ) {
                        return [ rowObj.idx ];
                    }
        
                    // need to fall through to jQuery in case there is DOM id that
                    // matches
                }
        
                // Selector - jQuery selector string, array of nodes or jQuery object/
                // As jQuery's .filter() allows jQuery objects to be passed in filter,
                // it also allows arrays, so this will cope with all three options
                return $(nodes)
                    .filter( sel )
                    .map( function () {
                        return this._DT_RowIndex;
                    } )
                    .toArray();
            };
        
            return _selector_run( 'row', selector, run, settings, opts );
        };
        
        
        _api_register( 'rows()', function ( selector, opts ) {
            // argument shifting
            if ( selector === undefined ) {
                selector = '';
            }
            else if ( $.isPlainObject( selector ) ) {
                opts = selector;
                selector = '';
            }
        
            opts = _selector_opts( opts );
        
            var inst = this.iterator( 'table', function ( settings ) {
                return __row_selector( settings, selector, opts );
            }, 1 );
        
            // Want argument shifting here and in __row_selector?
            inst.selector.rows = selector;
            inst.selector.opts = opts;
        
            return inst;
        } );
        
        _api_register( 'rows().nodes()', function () {
            return this.iterator( 'row', function ( settings, row ) {
                return settings.aoData[ row ].nTr || undefined;
            }, 1 );
        } );
        
        _api_register( 'rows().data()', function () {
            return this.iterator( true, 'rows', function ( settings, rows ) {
                return _pluck_order( settings.aoData, rows, '_aData' );
            }, 1 );
        } );
        
        _api_registerPlural( 'rows().cache()', 'row().cache()', function ( type ) {
            return this.iterator( 'row', function ( settings, row ) {
                var r = settings.aoData[ row ];
                return type === 'search' ? r._aFilterData : r._aSortData;
            }, 1 );
        } );
        
        _api_registerPlural( 'rows().invalidate()', 'row().invalidate()', function ( src ) {
            return this.iterator( 'row', function ( settings, row ) {
                _fnInvalidate( settings, row, src );
            } );
        } );
        
        _api_registerPlural( 'rows().indexes()', 'row().index()', function () {
            return this.iterator( 'row', function ( settings, row ) {
                return row;
            }, 1 );
        } );
        
        _api_registerPlural( 'rows().ids()', 'row().id()', function ( hash ) {
            var a = [];
            var context = this.context;
        
            // `iterator` will drop undefined values, but in this case we want them
            for ( var i=0, ien=context.length ; i<ien ; i++ ) {
                for ( var j=0, jen=this[i].length ; j<jen ; j++ ) {
                    var id = context[i].rowIdFn( context[i].aoData[ this[i][j] ]._aData );
                    a.push( (hash === true ? '#' : '' )+ id );
                }
            }
        
            return new _Api( context, a );
        } );
        
        _api_registerPlural( 'rows().remove()', 'row().remove()', function () {
            var that = this;
        
            this.iterator( 'row', function ( settings, row, thatIdx ) {
                var data = settings.aoData;
                var rowData = data[ row ];
                var i, ien, j, jen;
                var loopRow, loopCells;
        
                data.splice( row, 1 );
        
                // Update the cached indexes
                for ( i=0, ien=data.length ; i<ien ; i++ ) {
                    loopRow = data[i];
                    loopCells = loopRow.anCells;
        
                    // Rows
                    if ( loopRow.nTr !== null ) {
                        loopRow.nTr._DT_RowIndex = i;
                    }
        
                    // Cells
                    if ( loopCells !== null ) {
                        for ( j=0, jen=loopCells.length ; j<jen ; j++ ) {
                            loopCells[j]._DT_CellIndex.row = i;
                        }
                    }
                }
        
                // Delete from the display arrays
                _fnDeleteIndex( settings.aiDisplayMaster, row );
                _fnDeleteIndex( settings.aiDisplay, row );
                _fnDeleteIndex( that[ thatIdx ], row, false ); // maintain local indexes
        
                // Check for an 'overflow' they case for displaying the table
                _fnLengthOverflow( settings );
        
                // Remove the row's ID reference if there is one
                var id = settings.rowIdFn( rowData._aData );
                if ( id !== undefined ) {
                    delete settings.aIds[ id ];
                }
            } );
        
            this.iterator( 'table', function ( settings ) {
                for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
                    settings.aoData[i].idx = i;
                }
            } );
        
            return this;
        } );
        
        
        _api_register( 'rows.add()', function ( rows ) {
            var newRows = this.iterator( 'table', function ( settings ) {
                    var row, i, ien;
                    var out = [];
        
                    for ( i=0, ien=rows.length ; i<ien ; i++ ) {
                        row = rows[i];
        
                        if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
                            out.push( _fnAddTr( settings, row )[0] );
                        }
                        else {
                            out.push( _fnAddData( settings, row ) );
                        }
                    }
        
                    return out;
                }, 1 );
        
            // Return an Api.rows() extended instance, so rows().nodes() etc can be used
            var modRows = this.rows( -1 );
            modRows.pop();
            $.merge( modRows, newRows );
        
            return modRows;
        } );
        
        
        
        
        
        /**
         *
         */
        _api_register( 'row()', function ( selector, opts ) {
            return _selector_first( this.rows( selector, opts ) );
        } );
        
        
        _api_register( 'row().data()', function ( data ) {
            var ctx = this.context;
        
            if ( data === undefined ) {
                // Get
                return ctx.length && this.length ?
                    ctx[0].aoData[ this[0] ]._aData :
                    undefined;
            }
        
            // Set
            ctx[0].aoData[ this[0] ]._aData = data;
        
            // Automatically invalidate
            _fnInvalidate( ctx[0], this[0], 'data' );
        
            return this;
        } );
        
        
        _api_register( 'row().node()', function () {
            var ctx = this.context;
        
            return ctx.length && this.length ?
                ctx[0].aoData[ this[0] ].nTr || null :
                null;
        } );
        
        
        _api_register( 'row.add()', function ( row ) {
            // Allow a jQuery object to be passed in - only a single row is added from
            // it though - the first element in the set
            if ( row instanceof $ && row.length ) {
                row = row[0];
            }
        
            var rows = this.iterator( 'table', function ( settings ) {
                if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
                    return _fnAddTr( settings, row )[0];
                }
                return _fnAddData( settings, row );
            } );
        
            // Return an Api.rows() extended instance, with the newly added row selected
            return this.row( rows[0] );
        } );
        
        
        
        var __details_add = function ( ctx, row, data, klass )
        {
            // Convert to array of TR elements
            var rows = [];
            var addRow = function ( r, k ) {
                // Recursion to allow for arrays of jQuery objects
                if ( $.isArray( r ) || r instanceof $ ) {
                    for ( var i=0, ien=r.length ; i<ien ; i++ ) {
                        addRow( r[i], k );
                    }
                    return;
                }
        
                // If we get a TR element, then just add it directly - up to the dev
                // to add the correct number of columns etc
                if ( r.nodeName && r.nodeName.toLowerCase() === 'tr' ) {
                    rows.push( r );
                }
                else {
                    // Otherwise create a row with a wrapper
                    var created = $('<tr><td/></tr>').addClass( k );
                    $('td', created)
                        .addClass( k )
                        .html( r )
                        [0].colSpan = _fnVisbleColumns( ctx );
        
                    rows.push( created[0] );
                }
            };
        
            addRow( data, klass );
        
            if ( row._details ) {
                row._details.remove();
            }
        
            row._details = $(rows);
        
            // If the children were already shown, that state should be retained
            if ( row._detailsShow ) {
                row._details.insertAfter( row.nTr );
            }
        };
        
        
        var __details_remove = function ( api, idx )
        {
            var ctx = api.context;
        
            if ( ctx.length ) {
                var row = ctx[0].aoData[ idx !== undefined ? idx : api[0] ];
        
                if ( row && row._details ) {
                    row._details.remove();
        
                    row._detailsShow = undefined;
                    row._details = undefined;
                }
            }
        };
        
        
        var __details_display = function ( api, show ) {
            var ctx = api.context;
        
            if ( ctx.length && api.length ) {
                var row = ctx[0].aoData[ api[0] ];
        
                if ( row._details ) {
                    row._detailsShow = show;
        
                    if ( show ) {
                        row._details.insertAfter( row.nTr );
                    }
                    else {
                        row._details.detach();
                    }
        
                    __details_events( ctx[0] );
                }
            }
        };
        
        
        var __details_events = function ( settings )
        {
            var api = new _Api( settings );
            var namespace = '.dt.DT_details';
            var drawEvent = 'draw'+namespace;
            var colvisEvent = 'column-visibility'+namespace;
            var destroyEvent = 'destroy'+namespace;
            var data = settings.aoData;
        
            api.off( drawEvent +' '+ colvisEvent +' '+ destroyEvent );
        
            if ( _pluck( data, '_details' ).length > 0 ) {
                // On each draw, insert the required elements into the document
                api.on( drawEvent, function ( e, ctx ) {
                    if ( settings !== ctx ) {
                        return;
                    }
        
                    api.rows( {page:'current'} ).eq(0).each( function (idx) {
                        // Internal data grab
                        var row = data[ idx ];
        
                        if ( row._detailsShow ) {
                            row._details.insertAfter( row.nTr );
                        }
                    } );
                } );
        
                // Column visibility change - update the colspan
                api.on( colvisEvent, function ( e, ctx, idx, vis ) {
                    if ( settings !== ctx ) {
                        return;
                    }
        
                    // Update the colspan for the details rows (note, only if it already has
                    // a colspan)
                    var row, visible = _fnVisbleColumns( ctx );
        
                    for ( var i=0, ien=data.length ; i<ien ; i++ ) {
                        row = data[i];
        
                        if ( row._details ) {
                            row._details.children('td[colspan]').attr('colspan', visible );
                        }
                    }
                } );
        
                // Table destroyed - nuke any child rows
                api.on( destroyEvent, function ( e, ctx ) {
                    if ( settings !== ctx ) {
                        return;
                    }
        
                    for ( var i=0, ien=data.length ; i<ien ; i++ ) {
                        if ( data[i]._details ) {
                            __details_remove( api, i );
                        }
                    }
                } );
            }
        };
        
        // Strings for the method names to help minification
        var _emp = '';
        var _child_obj = _emp+'row().child';
        var _child_mth = _child_obj+'()';
        
        // data can be:
        //  tr
        //  string
        //  jQuery or array of any of the above
        _api_register( _child_mth, function ( data, klass ) {
            var ctx = this.context;
        
            if ( data === undefined ) {
                // get
                return ctx.length && this.length ?
                    ctx[0].aoData[ this[0] ]._details :
                    undefined;
            }
            else if ( data === true ) {
                // show
                this.child.show();
            }
            else if ( data === false ) {
                // remove
                __details_remove( this );
            }
            else if ( ctx.length && this.length ) {
                // set
                __details_add( ctx[0], ctx[0].aoData[ this[0] ], data, klass );
            }
        
            return this;
        } );
        
        
        _api_register( [
            _child_obj+'.show()',
            _child_mth+'.show()' // only when `child()` was called with parameters (without
        ], function ( show ) {   // it returns an object and this method is not executed)
            __details_display( this, true );
            return this;
        } );
        
        
        _api_register( [
            _child_obj+'.hide()',
            _child_mth+'.hide()' // only when `child()` was called with parameters (without
        ], function () {         // it returns an object and this method is not executed)
            __details_display( this, false );
            return this;
        } );
        
        
        _api_register( [
            _child_obj+'.remove()',
            _child_mth+'.remove()' // only when `child()` was called with parameters (without
        ], function () {           // it returns an object and this method is not executed)
            __details_remove( this );
            return this;
        } );
        
        
        _api_register( _child_obj+'.isShown()', function () {
            var ctx = this.context;
        
            if ( ctx.length && this.length ) {
                // _detailsShown as false or undefined will fall through to return false
                return ctx[0].aoData[ this[0] ]._detailsShow || false;
            }
            return false;
        } );
        
        
        
        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * Columns
         *
         * {integer}           - column index (>=0 count from left, <0 count from right)
         * "{integer}:visIdx"  - visible column index (i.e. translate to column index)  (>=0 count from left, <0 count from right)
         * "{integer}:visible" - alias for {integer}:visIdx  (>=0 count from left, <0 count from right)
         * "{string}:name"     - column name
         * "{string}"          - jQuery selector on column header nodes
         *
         */
        
        // can be an array of these items, comma separated list, or an array of comma
        // separated lists
        
        var __re_column_selector = /^(.+):(name|visIdx|visible)$/;
        
        
        // r1 and r2 are redundant - but it means that the parameters match for the
        // iterator callback in columns().data()
        var __columnData = function ( settings, column, r1, r2, rows ) {
            var a = [];
            for ( var row=0, ien=rows.length ; row<ien ; row++ ) {
                a.push( _fnGetCellData( settings, rows[row], column ) );
            }
            return a;
        };
        
        
        var __column_selector = function ( settings, selector, opts )
        {
            var
                columns = settings.aoColumns,
                names = _pluck( columns, 'sName' ),
                nodes = _pluck( columns, 'nTh' );
        
            var run = function ( s ) {
                var selInt = _intVal( s );
        
                // Selector - all
                if ( s === '' ) {
                    return _range( columns.length );
                }
        
                // Selector - index
                if ( selInt !== null ) {
                    return [ selInt >= 0 ?
                        selInt : // Count from left
                        columns.length + selInt // Count from right (+ because its a negative value)
                    ];
                }
        
                // Selector = function
                if ( typeof s === 'function' ) {
                    var rows = _selector_row_indexes( settings, opts );
        
                    return $.map( columns, function (col, idx) {
                        return s(
                                idx,
                                __columnData( settings, idx, 0, 0, rows ),
                                nodes[ idx ]
                            ) ? idx : null;
                    } );
                }
        
                // jQuery or string selector
                var match = typeof s === 'string' ?
                    s.match( __re_column_selector ) :
                    '';
        
                if ( match ) {
                    switch( match[2] ) {
                        case 'visIdx':
                        case 'visible':
                            var idx = parseInt( match[1], 10 );
                            // Visible index given, convert to column index
                            if ( idx < 0 ) {
                                // Counting from the right
                                var visColumns = $.map( columns, function (col,i) {
                                    return col.bVisible ? i : null;
                                } );
                                return [ visColumns[ visColumns.length + idx ] ];
                            }
                            // Counting from the left
                            return [ _fnVisibleToColumnIndex( settings, idx ) ];
        
                        case 'name':
                            // match by name. `names` is column index complete and in order
                            return $.map( names, function (name, i) {
                                return name === match[1] ? i : null;
                            } );
        
                        default:
                            return [];
                    }
                }
        
                // Cell in the table body
                if ( s.nodeName && s._DT_CellIndex ) {
                    return [ s._DT_CellIndex.column ];
                }
        
                // jQuery selector on the TH elements for the columns
                var jqResult = $( nodes )
                    .filter( s )
                    .map( function () {
                        return $.inArray( this, nodes ); // `nodes` is column index complete and in order
                    } )
                    .toArray();
        
                if ( jqResult.length || ! s.nodeName ) {
                    return jqResult;
                }
        
                // Otherwise a node which might have a `dt-column` data attribute, or be
                // a child or such an element
                var host = $(s).closest('*[data-dt-column]');
                return host.length ?
                    [ host.data('dt-column') ] :
                    [];
            };
        
            return _selector_run( 'column', selector, run, settings, opts );
        };
        
        
        var __setColumnVis = function ( settings, column, vis ) {
            var
                cols = settings.aoColumns,
                col  = cols[ column ],
                data = settings.aoData,
                row, cells, i, ien, tr;
        
            // Get
            if ( vis === undefined ) {
                return col.bVisible;
            }
        
            // Set
            // No change
            if ( col.bVisible === vis ) {
                return;
            }
        
            if ( vis ) {
                // Insert column
                // Need to decide if we should use appendChild or insertBefore
                var insertBefore = $.inArray( true, _pluck(cols, 'bVisible'), column+1 );
        
                for ( i=0, ien=data.length ; i<ien ; i++ ) {
                    tr = data[i].nTr;
                    cells = data[i].anCells;
        
                    if ( tr ) {
                        // insertBefore can act like appendChild if 2nd arg is null
                        tr.insertBefore( cells[ column ], cells[ insertBefore ] || null );
                    }
                }
            }
            else {
                // Remove column
                $( _pluck( settings.aoData, 'anCells', column ) ).detach();
            }
        
            // Common actions
            col.bVisible = vis;
            _fnDrawHead( settings, settings.aoHeader );
            _fnDrawHead( settings, settings.aoFooter );
        
            _fnSaveState( settings );
        };
        
        
        _api_register( 'columns()', function ( selector, opts ) {
            // argument shifting
            if ( selector === undefined ) {
                selector = '';
            }
            else if ( $.isPlainObject( selector ) ) {
                opts = selector;
                selector = '';
            }
        
            opts = _selector_opts( opts );
        
            var inst = this.iterator( 'table', function ( settings ) {
                return __column_selector( settings, selector, opts );
            }, 1 );
        
            // Want argument shifting here and in _row_selector?
            inst.selector.cols = selector;
            inst.selector.opts = opts;
        
            return inst;
        } );
        
        _api_registerPlural( 'columns().header()', 'column().header()', function ( selector, opts ) {
            return this.iterator( 'column', function ( settings, column ) {
                return settings.aoColumns[column].nTh;
            }, 1 );
        } );
        
        _api_registerPlural( 'columns().footer()', 'column().footer()', function ( selector, opts ) {
            return this.iterator( 'column', function ( settings, column ) {
                return settings.aoColumns[column].nTf;
            }, 1 );
        } );
        
        _api_registerPlural( 'columns().data()', 'column().data()', function () {
            return this.iterator( 'column-rows', __columnData, 1 );
        } );
        
        _api_registerPlural( 'columns().dataSrc()', 'column().dataSrc()', function () {
            return this.iterator( 'column', function ( settings, column ) {
                return settings.aoColumns[column].mData;
            }, 1 );
        } );
        
        _api_registerPlural( 'columns().cache()', 'column().cache()', function ( type ) {
            return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
                return _pluck_order( settings.aoData, rows,
                    type === 'search' ? '_aFilterData' : '_aSortData', column
                );
            }, 1 );
        } );
        
        _api_registerPlural( 'columns().nodes()', 'column().nodes()', function () {
            return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
                return _pluck_order( settings.aoData, rows, 'anCells', column ) ;
            }, 1 );
        } );
        
        _api_registerPlural( 'columns().visible()', 'column().visible()', function ( vis, calc ) {
            var ret = this.iterator( 'column', function ( settings, column ) {
                if ( vis === undefined ) {
                    return settings.aoColumns[ column ].bVisible;
                } // else
                __setColumnVis( settings, column, vis );
            } );
        
            // Group the column visibility changes
            if ( vis !== undefined ) {
                // Second loop once the first is done for events
                this.iterator( 'column', function ( settings, column ) {
                    _fnCallbackFire( settings, null, 'column-visibility', [settings, column, vis, calc] );
                } );
        
                if ( calc === undefined || calc ) {
                    this.columns.adjust();
                }
            }
        
            return ret;
        } );
        
        _api_registerPlural( 'columns().indexes()', 'column().index()', function ( type ) {
            return this.iterator( 'column', function ( settings, column ) {
                return type === 'visible' ?
                    _fnColumnIndexToVisible( settings, column ) :
                    column;
            }, 1 );
        } );
        
        _api_register( 'columns.adjust()', function () {
            return this.iterator( 'table', function ( settings ) {
                _fnAdjustColumnSizing( settings );
            }, 1 );
        } );
        
        _api_register( 'column.index()', function ( type, idx ) {
            if ( this.context.length !== 0 ) {
                var ctx = this.context[0];
        
                if ( type === 'fromVisible' || type === 'toData' ) {
                    return _fnVisibleToColumnIndex( ctx, idx );
                }
                else if ( type === 'fromData' || type === 'toVisible' ) {
                    return _fnColumnIndexToVisible( ctx, idx );
                }
            }
        } );
        
        _api_register( 'column()', function ( selector, opts ) {
            return _selector_first( this.columns( selector, opts ) );
        } );
        
        
        
        var __cell_selector = function ( settings, selector, opts )
        {
            var data = settings.aoData;
            var rows = _selector_row_indexes( settings, opts );
            var cells = _removeEmpty( _pluck_order( data, rows, 'anCells' ) );
            var allCells = $( [].concat.apply([], cells) );
            var row;
            var columns = settings.aoColumns.length;
            var a, i, ien, j, o, host;
        
            var run = function ( s ) {
                var fnSelector = typeof s === 'function';
        
                if ( s === null || s === undefined || fnSelector ) {
                    // All cells and function selectors
                    a = [];
        
                    for ( i=0, ien=rows.length ; i<ien ; i++ ) {
                        row = rows[i];
        
                        for ( j=0 ; j<columns ; j++ ) {
                            o = {
                                row: row,
                                column: j
                            };
        
                            if ( fnSelector ) {
                                // Selector - function
                                host = data[ row ];
        
                                if ( s( o, _fnGetCellData(settings, row, j), host.anCells ? host.anCells[j] : null ) ) {
                                    a.push( o );
                                }
                            }
                            else {
                                // Selector - all
                                a.push( o );
                            }
                        }
                    }
        
                    return a;
                }
                
                // Selector - index
                if ( $.isPlainObject( s ) ) {
                    return [s];
                }
        
                // Selector - jQuery filtered cells
                var jqResult = allCells
                    .filter( s )
                    .map( function (i, el) {
                        return { // use a new object, in case someone changes the values
                            row:    el._DT_CellIndex.row,
                            column: el._DT_CellIndex.column
                         };
                    } )
                    .toArray();
        
                if ( jqResult.length || ! s.nodeName ) {
                    return jqResult;
                }
        
                // Otherwise the selector is a node, and there is one last option - the
                // element might be a child of an element which has dt-row and dt-column
                // data attributes
                host = $(s).closest('*[data-dt-row]');
                return host.length ?
                    [ {
                        row: host.data('dt-row'),
                        column: host.data('dt-column')
                    } ] :
                    [];
            };
        
            return _selector_run( 'cell', selector, run, settings, opts );
        };
        
        
        
        
        _api_register( 'cells()', function ( rowSelector, columnSelector, opts ) {
            // Argument shifting
            if ( $.isPlainObject( rowSelector ) ) {
                // Indexes
                if ( rowSelector.row === undefined ) {
                    // Selector options in first parameter
                    opts = rowSelector;
                    rowSelector = null;
                }
                else {
                    // Cell index objects in first parameter
                    opts = columnSelector;
                    columnSelector = null;
                }
            }
            if ( $.isPlainObject( columnSelector ) ) {
                opts = columnSelector;
                columnSelector = null;
            }
        
            // Cell selector
            if ( columnSelector === null || columnSelector === undefined ) {
                return this.iterator( 'table', function ( settings ) {
                    return __cell_selector( settings, rowSelector, _selector_opts( opts ) );
                } );
            }
        
            // Row + column selector
            var columns = this.columns( columnSelector, opts );
            var rows = this.rows( rowSelector, opts );
            var a, i, ien, j, jen;
        
            var cells = this.iterator( 'table', function ( settings, idx ) {
                a = [];
        
                for ( i=0, ien=rows[idx].length ; i<ien ; i++ ) {
                    for ( j=0, jen=columns[idx].length ; j<jen ; j++ ) {
                        a.push( {
                            row:    rows[idx][i],
                            column: columns[idx][j]
                        } );
                    }
                }
        
                return a;
            }, 1 );
        
            $.extend( cells.selector, {
                cols: columnSelector,
                rows: rowSelector,
                opts: opts
            } );
        
            return cells;
        } );
        
        
        _api_registerPlural( 'cells().nodes()', 'cell().node()', function () {
            return this.iterator( 'cell', function ( settings, row, column ) {
                var data = settings.aoData[ row ];
        
                return data && data.anCells ?
                    data.anCells[ column ] :
                    undefined;
            }, 1 );
        } );
        
        
        _api_register( 'cells().data()', function () {
            return this.iterator( 'cell', function ( settings, row, column ) {
                return _fnGetCellData( settings, row, column );
            }, 1 );
        } );
        
        
        _api_registerPlural( 'cells().cache()', 'cell().cache()', function ( type ) {
            type = type === 'search' ? '_aFilterData' : '_aSortData';
        
            return this.iterator( 'cell', function ( settings, row, column ) {
                return settings.aoData[ row ][ type ][ column ];
            }, 1 );
        } );
        
        
        _api_registerPlural( 'cells().render()', 'cell().render()', function ( type ) {
            return this.iterator( 'cell', function ( settings, row, column ) {
                return _fnGetCellData( settings, row, column, type );
            }, 1 );
        } );
        
        
        _api_registerPlural( 'cells().indexes()', 'cell().index()', function () {
            return this.iterator( 'cell', function ( settings, row, column ) {
                return {
                    row: row,
                    column: column,
                    columnVisible: _fnColumnIndexToVisible( settings, column )
                };
            }, 1 );
        } );
        
        
        _api_registerPlural( 'cells().invalidate()', 'cell().invalidate()', function ( src ) {
            return this.iterator( 'cell', function ( settings, row, column ) {
                _fnInvalidate( settings, row, src, column );
            } );
        } );
        
        
        
        _api_register( 'cell()', function ( rowSelector, columnSelector, opts ) {
            return _selector_first( this.cells( rowSelector, columnSelector, opts ) );
        } );
        
        
        _api_register( 'cell().data()', function ( data ) {
            var ctx = this.context;
            var cell = this[0];
        
            if ( data === undefined ) {
                // Get
                return ctx.length && cell.length ?
                    _fnGetCellData( ctx[0], cell[0].row, cell[0].column ) :
                    undefined;
            }
        
            // Set
            _fnSetCellData( ctx[0], cell[0].row, cell[0].column, data );
            _fnInvalidate( ctx[0], cell[0].row, 'data', cell[0].column );
        
            return this;
        } );
        
        
        
        /**
         * Get current ordering (sorting) that has been applied to the table.
         *
         * @returns {array} 2D array containing the sorting information for the first
         *   table in the current context. Each element in the parent array represents
         *   a column being sorted upon (i.e. multi-sorting with two columns would have
         *   2 inner arrays). The inner arrays may have 2 or 3 elements. The first is
         *   the column index that the sorting condition applies to, the second is the
         *   direction of the sort (`desc` or `asc`) and, optionally, the third is the
         *   index of the sorting order from the `column.sorting` initialisation array.
         *//**
         * Set the ordering for the table.
         *
         * @param {integer} order Column index to sort upon.
         * @param {string} direction Direction of the sort to be applied (`asc` or `desc`)
         * @returns {DataTables.Api} this
         *//**
         * Set the ordering for the table.
         *
         * @param {array} order 1D array of sorting information to be applied.
         * @param {array} [...] Optional additional sorting conditions
         * @returns {DataTables.Api} this
         *//**
         * Set the ordering for the table.
         *
         * @param {array} order 2D array of sorting information to be applied.
         * @returns {DataTables.Api} this
         */
        _api_register( 'order()', function ( order, dir ) {
            var ctx = this.context;
        
            if ( order === undefined ) {
                // get
                return ctx.length !== 0 ?
                    ctx[0].aaSorting :
                    undefined;
            }
        
            // set
            if ( typeof order === 'number' ) {
                // Simple column / direction passed in
                order = [ [ order, dir ] ];
            }
            else if ( order.length && ! $.isArray( order[0] ) ) {
                // Arguments passed in (list of 1D arrays)
                order = Array.prototype.slice.call( arguments );
            }
            // otherwise a 2D array was passed in
        
            return this.iterator( 'table', function ( settings ) {
                settings.aaSorting = order.slice();
            } );
        } );
        
        
        /**
         * Attach a sort listener to an element for a given column
         *
         * @param {node|jQuery|string} node Identifier for the element(s) to attach the
         *   listener to. This can take the form of a single DOM node, a jQuery
         *   collection of nodes or a jQuery selector which will identify the node(s).
         * @param {integer} column the column that a click on this node will sort on
         * @param {function} [callback] callback function when sort is run
         * @returns {DataTables.Api} this
         */
        _api_register( 'order.listener()', function ( node, column, callback ) {
            return this.iterator( 'table', function ( settings ) {
                _fnSortAttachListener( settings, node, column, callback );
            } );
        } );
        
        
        _api_register( 'order.fixed()', function ( set ) {
            if ( ! set ) {
                var ctx = this.context;
                var fixed = ctx.length ?
                    ctx[0].aaSortingFixed :
                    undefined;
        
                return $.isArray( fixed ) ?
                    { pre: fixed } :
                    fixed;
            }
        
            return this.iterator( 'table', function ( settings ) {
                settings.aaSortingFixed = $.extend( true, {}, set );
            } );
        } );
        
        
        // Order by the selected column(s)
        _api_register( [
            'columns().order()',
            'column().order()'
        ], function ( dir ) {
            var that = this;
        
            return this.iterator( 'table', function ( settings, i ) {
                var sort = [];
        
                $.each( that[i], function (j, col) {
                    sort.push( [ col, dir ] );
                } );
        
                settings.aaSorting = sort;
            } );
        } );
        
        
        
        _api_register( 'search()', function ( input, regex, smart, caseInsen ) {
            var ctx = this.context;
        
            if ( input === undefined ) {
                // get
                return ctx.length !== 0 ?
                    ctx[0].oPreviousSearch.sSearch :
                    undefined;
            }
        
            // set
            return this.iterator( 'table', function ( settings ) {
                if ( ! settings.oFeatures.bFilter ) {
                    return;
                }
        
                _fnFilterComplete( settings, $.extend( {}, settings.oPreviousSearch, {
                    "sSearch": input+"",
                    "bRegex":  regex === null ? false : regex,
                    "bSmart":  smart === null ? true  : smart,
                    "bCaseInsensitive": caseInsen === null ? true : caseInsen
                } ), 1 );
            } );
        } );
        
        
        _api_registerPlural(
            'columns().search()',
            'column().search()',
            function ( input, regex, smart, caseInsen ) {
                return this.iterator( 'column', function ( settings, column ) {
                    var preSearch = settings.aoPreSearchCols;
        
                    if ( input === undefined ) {
                        // get
                        return preSearch[ column ].sSearch;
                    }
        
                    // set
                    if ( ! settings.oFeatures.bFilter ) {
                        return;
                    }
        
                    $.extend( preSearch[ column ], {
                        "sSearch": input+"",
                        "bRegex":  regex === null ? false : regex,
                        "bSmart":  smart === null ? true  : smart,
                        "bCaseInsensitive": caseInsen === null ? true : caseInsen
                    } );
        
                    _fnFilterComplete( settings, settings.oPreviousSearch, 1 );
                } );
            }
        );
        
        /*
         * State API methods
         */
        
        _api_register( 'state()', function () {
            return this.context.length ?
                this.context[0].oSavedState :
                null;
        } );
        
        
        _api_register( 'state.clear()', function () {
            return this.iterator( 'table', function ( settings ) {
                // Save an empty object
                settings.fnStateSaveCallback.call( settings.oInstance, settings, {} );
            } );
        } );
        
        
        _api_register( 'state.loaded()', function () {
            return this.context.length ?
                this.context[0].oLoadedState :
                null;
        } );
        
        
        _api_register( 'state.save()', function () {
            return this.iterator( 'table', function ( settings ) {
                _fnSaveState( settings );
            } );
        } );
        
        
        
        /**
         * Provide a common method for plug-ins to check the version of DataTables being
         * used, in order to ensure compatibility.
         *
         *  @param {string} version Version string to check for, in the format "X.Y.Z".
         *    Note that the formats "X" and "X.Y" are also acceptable.
         *  @returns {boolean} true if this version of DataTables is greater or equal to
         *    the required version, or false if this version of DataTales is not
         *    suitable
         *  @static
         *  @dtopt API-Static
         *
         *  @example
         *    alert( $.fn.dataTable.versionCheck( '1.9.0' ) );
         */
        DataTable.versionCheck = DataTable.fnVersionCheck = function( version )
        {
            var aThis = DataTable.version.split('.');
            var aThat = version.split('.');
            var iThis, iThat;
        
            for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) {
                iThis = parseInt( aThis[i], 10 ) || 0;
                iThat = parseInt( aThat[i], 10 ) || 0;
        
                // Parts are the same, keep comparing
                if (iThis === iThat) {
                    continue;
                }
        
                // Parts are different, return immediately
                return iThis > iThat;
            }
        
            return true;
        };
        
        
        /**
         * Check if a `<table>` node is a DataTable table already or not.
         *
         *  @param {node|jquery|string} table Table node, jQuery object or jQuery
         *      selector for the table to test. Note that if more than more than one
         *      table is passed on, only the first will be checked
         *  @returns {boolean} true the table given is a DataTable, or false otherwise
         *  @static
         *  @dtopt API-Static
         *
         *  @example
         *    if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
         *      $('#example').dataTable();
         *    }
         */
        DataTable.isDataTable = DataTable.fnIsDataTable = function ( table )
        {
            var t = $(table).get(0);
            var is = false;
        
            $.each( DataTable.settings, function (i, o) {
                var head = o.nScrollHead ? $('table', o.nScrollHead)[0] : null;
                var foot = o.nScrollFoot ? $('table', o.nScrollFoot)[0] : null;
        
                if ( o.nTable === t || head === t || foot === t ) {
                    is = true;
                }
            } );
        
            return is;
        };
        
        
        /**
         * Get all DataTable tables that have been initialised - optionally you can
         * select to get only currently visible tables.
         *
         *  @param {boolean} [visible=false] Flag to indicate if you want all (default)
         *    or visible tables only.
         *  @returns {array} Array of `table` nodes (not DataTable instances) which are
         *    DataTables
         *  @static
         *  @dtopt API-Static
         *
         *  @example
         *    $.each( $.fn.dataTable.tables(true), function () {
         *      $(table).DataTable().columns.adjust();
         *    } );
         */
        DataTable.tables = DataTable.fnTables = function ( visible )
        {
            var api = false;
        
            if ( $.isPlainObject( visible ) ) {
                api = visible.api;
                visible = visible.visible;
            }
        
            var a = $.map( DataTable.settings, function (o) {
                if ( !visible || (visible && $(o.nTable).is(':visible')) ) {
                    return o.nTable;
                }
            } );
        
            return api ?
                new _Api( a ) :
                a;
        };
        
        
        /**
         * Convert from camel case parameters to Hungarian notation. This is made public
         * for the extensions to provide the same ability as DataTables core to accept
         * either the 1.9 style Hungarian notation, or the 1.10+ style camelCase
         * parameters.
         *
         *  @param {object} src The model object which holds all parameters that can be
         *    mapped.
         *  @param {object} user The object to convert from camel case to Hungarian.
         *  @param {boolean} force When set to `true`, properties which already have a
         *    Hungarian value in the `user` object will be overwritten. Otherwise they
         *    won't be.
         */
        DataTable.camelToHungarian = _fnCamelToHungarian;
        
        
        
        /**
         *
         */
        _api_register( '$()', function ( selector, opts ) {
            var
                rows   = this.rows( opts ).nodes(), // Get all rows
                jqRows = $(rows);
        
            return $( [].concat(
                jqRows.filter( selector ).toArray(),
                jqRows.find( selector ).toArray()
            ) );
        } );
        
        
        // jQuery functions to operate on the tables
        $.each( [ 'on', 'one', 'off' ], function (i, key) {
            _api_register( key+'()', function ( /* event, handler */ ) {
                var args = Array.prototype.slice.call(arguments);
        
                // Add the `dt` namespace automatically if it isn't already present
                if ( ! args[0].match(/\.dt\b/) ) {
                    args[0] += '.dt';
                }
        
                var inst = $( this.tables().nodes() );
                inst[key].apply( inst, args );
                return this;
            } );
        } );
        
        
        _api_register( 'clear()', function () {
            return this.iterator( 'table', function ( settings ) {
                _fnClearTable( settings );
            } );
        } );
        
        
        _api_register( 'settings()', function () {
            return new _Api( this.context, this.context );
        } );
        
        
        _api_register( 'init()', function () {
            var ctx = this.context;
            return ctx.length ? ctx[0].oInit : null;
        } );
        
        
        _api_register( 'data()', function () {
            return this.iterator( 'table', function ( settings ) {
                return _pluck( settings.aoData, '_aData' );
            } ).flatten();
        } );
        
        
        _api_register( 'destroy()', function ( remove ) {
            remove = remove || false;
        
            return this.iterator( 'table', function ( settings ) {
                var orig      = settings.nTableWrapper.parentNode;
                var classes   = settings.oClasses;
                var table     = settings.nTable;
                var tbody     = settings.nTBody;
                var thead     = settings.nTHead;
                var tfoot     = settings.nTFoot;
                var jqTable   = $(table);
                var jqTbody   = $(tbody);
                var jqWrapper = $(settings.nTableWrapper);
                var rows      = $.map( settings.aoData, function (r) { return r.nTr; } );
                var i, ien;
        
                // Flag to note that the table is currently being destroyed - no action
                // should be taken
                settings.bDestroying = true;
        
                // Fire off the destroy callbacks for plug-ins etc
                _fnCallbackFire( settings, "aoDestroyCallback", "destroy", [settings] );
        
                // If not being removed from the document, make all columns visible
                if ( ! remove ) {
                    new _Api( settings ).columns().visible( true );
                }
        
                // Blitz all `DT` namespaced events (these are internal events, the
                // lowercase, `dt` events are user subscribed and they are responsible
                // for removing them
                jqWrapper.unbind('.DT').find(':not(tbody *)').unbind('.DT');
                $(window).unbind('.DT-'+settings.sInstance);
        
                // When scrolling we had to break the table up - restore it
                if ( table != thead.parentNode ) {
                    jqTable.children('thead').detach();
                    jqTable.append( thead );
                }
        
                if ( tfoot && table != tfoot.parentNode ) {
                    jqTable.children('tfoot').detach();
                    jqTable.append( tfoot );
                }
        
                settings.aaSorting = [];
                settings.aaSortingFixed = [];
                _fnSortingClasses( settings );
        
                $( rows ).removeClass( settings.asStripeClasses.join(' ') );
        
                $('th, td', thead).removeClass( classes.sSortable+' '+
                    classes.sSortableAsc+' '+classes.sSortableDesc+' '+classes.sSortableNone
                );
        
                if ( settings.bJUI ) {
                    $('th span.'+classes.sSortIcon+ ', td span.'+classes.sSortIcon, thead).detach();
                    $('th, td', thead).each( function () {
                        var wrapper = $('div.'+classes.sSortJUIWrapper, this);
                        $(this).append( wrapper.contents() );
                        wrapper.detach();
                    } );
                }
        
                // Add the TR elements back into the table in their original order
                jqTbody.children().detach();
                jqTbody.append( rows );
        
                // Remove the DataTables generated nodes, events and classes
                var removedMethod = remove ? 'remove' : 'detach';
                jqTable[ removedMethod ]();
                jqWrapper[ removedMethod ]();
        
                // If we need to reattach the table to the document
                if ( ! remove && orig ) {
                    // insertBefore acts like appendChild if !arg[1]
                    orig.insertBefore( table, settings.nTableReinsertBefore );
        
                    // Restore the width of the original table - was read from the style property,
                    // so we can restore directly to that
                    jqTable
                        .css( 'width', settings.sDestroyWidth )
                        .removeClass( classes.sTable );
        
                    // If the were originally stripe classes - then we add them back here.
                    // Note this is not fool proof (for example if not all rows had stripe
                    // classes - but it's a good effort without getting carried away
                    ien = settings.asDestroyStripes.length;
        
                    if ( ien ) {
                        jqTbody.children().each( function (i) {
                            $(this).addClass( settings.asDestroyStripes[i % ien] );
                        } );
                    }
                }
        
                /* Remove the settings object from the settings array */
                var idx = $.inArray( settings, DataTable.settings );
                if ( idx !== -1 ) {
                    DataTable.settings.splice( idx, 1 );
                }
            } );
        } );
        
        
        // Add the `every()` method for rows, columns and cells in a compact form
        $.each( [ 'column', 'row', 'cell' ], function ( i, type ) {
            _api_register( type+'s().every()', function ( fn ) {
                var opts = this.selector.opts;
                var api = this;
        
                return this.iterator( type, function ( settings, arg1, arg2, arg3, arg4 ) {
                    // Rows and columns:
                    //  arg1 - index
                    //  arg2 - table counter
                    //  arg3 - loop counter
                    //  arg4 - undefined
                    // Cells:
                    //  arg1 - row index
                    //  arg2 - column index
                    //  arg3 - table counter
                    //  arg4 - loop counter
                    fn.call(
                        api[ type ](
                            arg1,
                            type==='cell' ? arg2 : opts,
                            type==='cell' ? opts : undefined
                        ),
                        arg1, arg2, arg3, arg4
                    );
                } );
            } );
        } );
        
        
        // i18n method for extensions to be able to use the language object from the
        // DataTable
        _api_register( 'i18n()', function ( token, def, plural ) {
            var ctx = this.context[0];
            var resolved = _fnGetObjectDataFn( token )( ctx.oLanguage );
        
            if ( resolved === undefined ) {
                resolved = def;
            }
        
            if ( plural !== undefined && $.isPlainObject( resolved ) ) {
                resolved = resolved[ plural ] !== undefined ?
                    resolved[ plural ] :
                    resolved._;
            }
        
            return resolved.replace( '%d', plural ); // nb: plural might be undefined,
        } );
        /**
         * Version string for plug-ins to check compatibility. Allowed format is
         * `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used
         * only for non-release builds. See http://semver.org/ for more information.
         *  @member
         *  @type string
         *  @default Version number
         */
        DataTable.version = "1.10.12";
    
        /**
         * Private data store, containing all of the settings objects that are
         * created for the tables on a given page.
         *
         * Note that the `DataTable.settings` object is aliased to
         * `jQuery.fn.dataTableExt` through which it may be accessed and
         * manipulated, or `jQuery.fn.dataTable.settings`.
         *  @member
         *  @type array
         *  @default []
         *  @private
         */
        DataTable.settings = [];
    
        /**
         * Object models container, for the various models that DataTables has
         * available to it. These models define the objects that are used to hold
         * the active state and configuration of the table.
         *  @namespace
         */
        DataTable.models = {};
        
        
        
        /**
         * Template object for the way in which DataTables holds information about
         * search information for the global filter and individual column filters.
         *  @namespace
         */
        DataTable.models.oSearch = {
            /**
             * Flag to indicate if the filtering should be case insensitive or not
             *  @type boolean
             *  @default true
             */
            "bCaseInsensitive": true,
        
            /**
             * Applied search term
             *  @type string
             *  @default <i>Empty string</i>
             */
            "sSearch": "",
        
            /**
             * Flag to indicate if the search term should be interpreted as a
             * regular expression (true) or not (false) and therefore and special
             * regex characters escaped.
             *  @type boolean
             *  @default false
             */
            "bRegex": false,
        
            /**
             * Flag to indicate if DataTables is to use its smart filtering or not.
             *  @type boolean
             *  @default true
             */
            "bSmart": true
        };
        
        
        
        
        /**
         * Template object for the way in which DataTables holds information about
         * each individual row. This is the object format used for the settings
         * aoData array.
         *  @namespace
         */
        DataTable.models.oRow = {
            /**
             * TR element for the row
             *  @type node
             *  @default null
             */
            "nTr": null,
        
            /**
             * Array of TD elements for each row. This is null until the row has been
             * created.
             *  @type array nodes
             *  @default []
             */
            "anCells": null,
        
            /**
             * Data object from the original data source for the row. This is either
             * an array if using the traditional form of DataTables, or an object if
             * using mData options. The exact type will depend on the passed in
             * data from the data source, or will be an array if using DOM a data
             * source.
             *  @type array|object
             *  @default []
             */
            "_aData": [],
        
            /**
             * Sorting data cache - this array is ostensibly the same length as the
             * number of columns (although each index is generated only as it is
             * needed), and holds the data that is used for sorting each column in the
             * row. We do this cache generation at the start of the sort in order that
             * the formatting of the sort data need be done only once for each cell
             * per sort. This array should not be read from or written to by anything
             * other than the master sorting methods.
             *  @type array
             *  @default null
             *  @private
             */
            "_aSortData": null,
        
            /**
             * Per cell filtering data cache. As per the sort data cache, used to
             * increase the performance of the filtering in DataTables
             *  @type array
             *  @default null
             *  @private
             */
            "_aFilterData": null,
        
            /**
             * Filtering data cache. This is the same as the cell filtering cache, but
             * in this case a string rather than an array. This is easily computed with
             * a join on `_aFilterData`, but is provided as a cache so the join isn't
             * needed on every search (memory traded for performance)
             *  @type array
             *  @default null
             *  @private
             */
            "_sFilterRow": null,
        
            /**
             * Cache of the class name that DataTables has applied to the row, so we
             * can quickly look at this variable rather than needing to do a DOM check
             * on className for the nTr property.
             *  @type string
             *  @default <i>Empty string</i>
             *  @private
             */
            "_sRowStripe": "",
        
            /**
             * Denote if the original data source was from the DOM, or the data source
             * object. This is used for invalidating data, so DataTables can
             * automatically read data from the original source, unless uninstructed
             * otherwise.
             *  @type string
             *  @default null
             *  @private
             */
            "src": null,
        
            /**
             * Index in the aoData array. This saves an indexOf lookup when we have the
             * object, but want to know the index
             *  @type integer
             *  @default -1
             *  @private
             */
            "idx": -1
        };
        
        
        /**
         * Template object for the column information object in DataTables. This object
         * is held in the settings aoColumns array and contains all the information that
         * DataTables needs about each individual column.
         *
         * Note that this object is related to {@link DataTable.defaults.column}
         * but this one is the internal data store for DataTables's cache of columns.
         * It should NOT be manipulated outside of DataTables. Any configuration should
         * be done through the initialisation options.
         *  @namespace
         */
        DataTable.models.oColumn = {
            /**
             * Column index. This could be worked out on-the-fly with $.inArray, but it
             * is faster to just hold it as a variable
             *  @type integer
             *  @default null
             */
            "idx": null,
        
            /**
             * A list of the columns that sorting should occur on when this column
             * is sorted. That this property is an array allows multi-column sorting
             * to be defined for a column (for example first name / last name columns
             * would benefit from this). The values are integers pointing to the
             * columns to be sorted on (typically it will be a single integer pointing
             * at itself, but that doesn't need to be the case).
             *  @type array
             */
            "aDataSort": null,
        
            /**
             * Define the sorting directions that are applied to the column, in sequence
             * as the column is repeatedly sorted upon - i.e. the first value is used
             * as the sorting direction when the column if first sorted (clicked on).
             * Sort it again (click again) and it will move on to the next index.
             * Repeat until loop.
             *  @type array
             */
            "asSorting": null,
        
            /**
             * Flag to indicate if the column is searchable, and thus should be included
             * in the filtering or not.
             *  @type boolean
             */
            "bSearchable": null,
        
            /**
             * Flag to indicate if the column is sortable or not.
             *  @type boolean
             */
            "bSortable": null,
        
            /**
             * Flag to indicate if the column is currently visible in the table or not
             *  @type boolean
             */
            "bVisible": null,
        
            /**
             * Store for manual type assignment using the `column.type` option. This
             * is held in store so we can manipulate the column's `sType` property.
             *  @type string
             *  @default null
             *  @private
             */
            "_sManualType": null,
        
            /**
             * Flag to indicate if HTML5 data attributes should be used as the data
             * source for filtering or sorting. True is either are.
             *  @type boolean
             *  @default false
             *  @private
             */
            "_bAttrSrc": false,
        
            /**
             * Developer definable function that is called whenever a cell is created (Ajax source,
             * etc) or processed for input (DOM source). This can be used as a compliment to mRender
             * allowing you to modify the DOM element (add background colour for example) when the
             * element is available.
             *  @type function
             *  @param {element} nTd The TD node that has been created
             *  @param {*} sData The Data for the cell
             *  @param {array|object} oData The data for the whole row
             *  @param {int} iRow The row index for the aoData data store
             *  @default null
             */
            "fnCreatedCell": null,
        
            /**
             * Function to get data from a cell in a column. You should <b>never</b>
             * access data directly through _aData internally in DataTables - always use
             * the method attached to this property. It allows mData to function as
             * required. This function is automatically assigned by the column
             * initialisation method
             *  @type function
             *  @param {array|object} oData The data array/object for the array
             *    (i.e. aoData[]._aData)
             *  @param {string} sSpecific The specific data type you want to get -
             *    'display', 'type' 'filter' 'sort'
             *  @returns {*} The data for the cell from the given row's data
             *  @default null
             */
            "fnGetData": null,
        
            /**
             * Function to set data for a cell in the column. You should <b>never</b>
             * set the data directly to _aData internally in DataTables - always use
             * this method. It allows mData to function as required. This function
             * is automatically assigned by the column initialisation method
             *  @type function
             *  @param {array|object} oData The data array/object for the array
             *    (i.e. aoData[]._aData)
             *  @param {*} sValue Value to set
             *  @default null
             */
            "fnSetData": null,
        
            /**
             * Property to read the value for the cells in the column from the data
             * source array / object. If null, then the default content is used, if a
             * function is given then the return from the function is used.
             *  @type function|int|string|null
             *  @default null
             */
            "mData": null,
        
            /**
             * Partner property to mData which is used (only when defined) to get
             * the data - i.e. it is basically the same as mData, but without the
             * 'set' option, and also the data fed to it is the result from mData.
             * This is the rendering method to match the data method of mData.
             *  @type function|int|string|null
             *  @default null
             */
            "mRender": null,
        
            /**
             * Unique header TH/TD element for this column - this is what the sorting
             * listener is attached to (if sorting is enabled.)
             *  @type node
             *  @default null
             */
            "nTh": null,
        
            /**
             * Unique footer TH/TD element for this column (if there is one). Not used
             * in DataTables as such, but can be used for plug-ins to reference the
             * footer for each column.
             *  @type node
             *  @default null
             */
            "nTf": null,
        
            /**
             * The class to apply to all TD elements in the table's TBODY for the column
             *  @type string
             *  @default null
             */
            "sClass": null,
        
            /**
             * When DataTables calculates the column widths to assign to each column,
             * it finds the longest string in each column and then constructs a
             * temporary table and reads the widths from that. The problem with this
             * is that "mmm" is much wider then "iiii", but the latter is a longer
             * string - thus the calculation can go wrong (doing it properly and putting
             * it into an DOM object and measuring that is horribly(!) slow). Thus as
             * a "work around" we provide this option. It will append its value to the
             * text that is found to be the longest string for the column - i.e. padding.
             *  @type string
             */
            "sContentPadding": null,
        
            /**
             * Allows a default value to be given for a column's data, and will be used
             * whenever a null data source is encountered (this can be because mData
             * is set to null, or because the data source itself is null).
             *  @type string
             *  @default null
             */
            "sDefaultContent": null,
        
            /**
             * Name for the column, allowing reference to the column by name as well as
             * by index (needs a lookup to work by name).
             *  @type string
             */
            "sName": null,
        
            /**
             * Custom sorting data type - defines which of the available plug-ins in
             * afnSortData the custom sorting will use - if any is defined.
             *  @type string
             *  @default std
             */
            "sSortDataType": 'std',
        
            /**
             * Class to be applied to the header element when sorting on this column
             *  @type string
             *  @default null
             */
            "sSortingClass": null,
        
            /**
             * Class to be applied to the header element when sorting on this column -
             * when jQuery UI theming is used.
             *  @type string
             *  @default null
             */
            "sSortingClassJUI": null,
        
            /**
             * Title of the column - what is seen in the TH element (nTh).
             *  @type string
             */
            "sTitle": null,
        
            /**
             * Column sorting and filtering type
             *  @type string
             *  @default null
             */
            "sType": null,
        
            /**
             * Width of the column
             *  @type string
             *  @default null
             */
            "sWidth": null,
        
            /**
             * Width of the column when it was first "encountered"
             *  @type string
             *  @default null
             */
            "sWidthOrig": null
        };
        
        
        /*
         * Developer note: The properties of the object below are given in Hungarian
         * notation, that was used as the interface for DataTables prior to v1.10, however
         * from v1.10 onwards the primary interface is camel case. In order to avoid
         * breaking backwards compatibility utterly with this change, the Hungarian
         * version is still, internally the primary interface, but is is not documented
         * - hence the @name tags in each doc comment. This allows a Javascript function
         * to create a map from Hungarian notation to camel case (going the other direction
         * would require each property to be listed, which would at around 3K to the size
         * of DataTables, while this method is about a 0.5K hit.
         *
         * Ultimately this does pave the way for Hungarian notation to be dropped
         * completely, but that is a massive amount of work and will break current
         * installs (therefore is on-hold until v2).
         */
        
        /**
         * Initialisation options that can be given to DataTables at initialisation
         * time.
         *  @namespace
         */
        DataTable.defaults = {
            /**
             * An array of data to use for the table, passed in at initialisation which
             * will be used in preference to any data which is already in the DOM. This is
             * particularly useful for constructing tables purely in Javascript, for
             * example with a custom Ajax call.
             *  @type array
             *  @default null
             *
             *  @dtopt Option
             *  @name DataTable.defaults.data
             *
             *  @example
             *    // Using a 2D array data source
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "data": [
             *          ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
             *          ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
             *        ],
             *        "columns": [
             *          { "title": "Engine" },
             *          { "title": "Browser" },
             *          { "title": "Platform" },
             *          { "title": "Version" },
             *          { "title": "Grade" }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using an array of objects as a data source (`data`)
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "data": [
             *          {
             *            "engine":   "Trident",
             *            "browser":  "Internet Explorer 4.0",
             *            "platform": "Win 95+",
             *            "version":  4,
             *            "grade":    "X"
             *          },
             *          {
             *            "engine":   "Trident",
             *            "browser":  "Internet Explorer 5.0",
             *            "platform": "Win 95+",
             *            "version":  5,
             *            "grade":    "C"
             *          }
             *        ],
             *        "columns": [
             *          { "title": "Engine",   "data": "engine" },
             *          { "title": "Browser",  "data": "browser" },
             *          { "title": "Platform", "data": "platform" },
             *          { "title": "Version",  "data": "version" },
             *          { "title": "Grade",    "data": "grade" }
             *        ]
             *      } );
             *    } );
             */
            "aaData": null,
        
        
            /**
             * If ordering is enabled, then DataTables will perform a first pass sort on
             * initialisation. You can define which column(s) the sort is performed
             * upon, and the sorting direction, with this variable. The `sorting` array
             * should contain an array for each column to be sorted initially containing
             * the column's index and a direction string ('asc' or 'desc').
             *  @type array
             *  @default [[0,'asc']]
             *
             *  @dtopt Option
             *  @name DataTable.defaults.order
             *
             *  @example
             *    // Sort by 3rd column first, and then 4th column
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "order": [[2,'asc'], [3,'desc']]
             *      } );
             *    } );
             *
             *    // No initial sorting
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "order": []
             *      } );
             *    } );
             */
            "aaSorting": [[0,'asc']],
        
        
            /**
             * This parameter is basically identical to the `sorting` parameter, but
             * cannot be overridden by user interaction with the table. What this means
             * is that you could have a column (visible or hidden) which the sorting
             * will always be forced on first - any sorting after that (from the user)
             * will then be performed as required. This can be useful for grouping rows
             * together.
             *  @type array
             *  @default null
             *
             *  @dtopt Option
             *  @name DataTable.defaults.orderFixed
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "orderFixed": [[0,'asc']]
             *      } );
             *    } )
             */
            "aaSortingFixed": [],
        
        
            /**
             * DataTables can be instructed to load data to display in the table from a
             * Ajax source. This option defines how that Ajax call is made and where to.
             *
             * The `ajax` property has three different modes of operation, depending on
             * how it is defined. These are:
             *
             * * `string` - Set the URL from where the data should be loaded from.
             * * `object` - Define properties for `jQuery.ajax`.
             * * `function` - Custom data get function
             *
             * `string`
             * --------
             *
             * As a string, the `ajax` property simply defines the URL from which
             * DataTables will load data.
             *
             * `object`
             * --------
             *
             * As an object, the parameters in the object are passed to
             * [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control
             * of the Ajax request. DataTables has a number of default parameters which
             * you can override using this option. Please refer to the jQuery
             * documentation for a full description of the options available, although
             * the following parameters provide additional options in DataTables or
             * require special consideration:
             *
             * * `data` - As with jQuery, `data` can be provided as an object, but it
             *   can also be used as a function to manipulate the data DataTables sends
             *   to the server. The function takes a single parameter, an object of
             *   parameters with the values that DataTables has readied for sending. An
             *   object may be returned which will be merged into the DataTables
             *   defaults, or you can add the items to the object that was passed in and
             *   not return anything from the function. This supersedes `fnServerParams`
             *   from DataTables 1.9-.
             *
             * * `dataSrc` - By default DataTables will look for the property `data` (or
             *   `aaData` for compatibility with DataTables 1.9-) when obtaining data
             *   from an Ajax source or for server-side processing - this parameter
             *   allows that property to be changed. You can use Javascript dotted
             *   object notation to get a data source for multiple levels of nesting, or
             *   it my be used as a function. As a function it takes a single parameter,
             *   the JSON returned from the server, which can be manipulated as
             *   required, with the returned value being that used by DataTables as the
             *   data source for the table. This supersedes `sAjaxDataProp` from
             *   DataTables 1.9-.
             *
             * * `success` - Should not be overridden it is used internally in
             *   DataTables. To manipulate / transform the data returned by the server
             *   use `ajax.dataSrc`, or use `ajax` as a function (see below).
             *
             * `function`
             * ----------
             *
             * As a function, making the Ajax call is left up to yourself allowing
             * complete control of the Ajax request. Indeed, if desired, a method other
             * than Ajax could be used to obtain the required data, such as Web storage
             * or an AIR database.
             *
             * The function is given four parameters and no return is required. The
             * parameters are:
             *
             * 1. _object_ - Data to send to the server
             * 2. _function_ - Callback function that must be executed when the required
             *    data has been obtained. That data should be passed into the callback
             *    as the only parameter
             * 3. _object_ - DataTables settings object for the table
             *
             * Note that this supersedes `fnServerData` from DataTables 1.9-.
             *
             *  @type string|object|function
             *  @default null
             *
             *  @dtopt Option
             *  @name DataTable.defaults.ajax
             *  @since 1.10.0
             *
             * @example
             *   // Get JSON data from a file via Ajax.
             *   // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default).
             *   $('#example').dataTable( {
             *     "ajax": "data.json"
             *   } );
             *
             * @example
             *   // Get JSON data from a file via Ajax, using `dataSrc` to change
             *   // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`)
             *   $('#example').dataTable( {
             *     "ajax": {
             *       "url": "data.json",
             *       "dataSrc": "tableData"
             *     }
             *   } );
             *
             * @example
             *   // Get JSON data from a file via Ajax, using `dataSrc` to read data
             *   // from a plain array rather than an array in an object
             *   $('#example').dataTable( {
             *     "ajax": {
             *       "url": "data.json",
             *       "dataSrc": ""
             *     }
             *   } );
             *
             * @example
             *   // Manipulate the data returned from the server - add a link to data
             *   // (note this can, should, be done using `render` for the column - this
             *   // is just a simple example of how the data can be manipulated).
             *   $('#example').dataTable( {
             *     "ajax": {
             *       "url": "data.json",
             *       "dataSrc": function ( json ) {
             *         for ( var i=0, ien=json.length ; i<ien ; i++ ) {
             *           json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>';
             *         }
             *         return json;
             *       }
             *     }
             *   } );
             *
             * @example
             *   // Add data to the request
             *   $('#example').dataTable( {
             *     "ajax": {
             *       "url": "data.json",
             *       "data": function ( d ) {
             *         return {
             *           "extra_search": $('#extra').val()
             *         };
             *       }
             *     }
             *   } );
             *
             * @example
             *   // Send request as POST
             *   $('#example').dataTable( {
             *     "ajax": {
             *       "url": "data.json",
             *       "type": "POST"
             *     }
             *   } );
             *
             * @example
             *   // Get the data from localStorage (could interface with a form for
             *   // adding, editing and removing rows).
             *   $('#example').dataTable( {
             *     "ajax": function (data, callback, settings) {
             *       callback(
             *         JSON.parse( localStorage.getItem('dataTablesData') )
             *       );
             *     }
             *   } );
             */
            "ajax": null,
        
        
            /**
             * This parameter allows you to readily specify the entries in the length drop
             * down menu that DataTables shows when pagination is enabled. It can be
             * either a 1D array of options which will be used for both the displayed
             * option and the value, or a 2D array which will use the array in the first
             * position as the value, and the array in the second position as the
             * displayed options (useful for language strings such as 'All').
             *
             * Note that the `pageLength` property will be automatically set to the
             * first value given in this array, unless `pageLength` is also provided.
             *  @type array
             *  @default [ 10, 25, 50, 100 ]
             *
             *  @dtopt Option
             *  @name DataTable.defaults.lengthMenu
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
             *      } );
             *    } );
             */
            "aLengthMenu": [ 10, 25, 50, 100 ],
        
        
            /**
             * The `columns` option in the initialisation parameter allows you to define
             * details about the way individual columns behave. For a full list of
             * column options that can be set, please see
             * {@link DataTable.defaults.column}. Note that if you use `columns` to
             * define your columns, you must have an entry in the array for every single
             * column that you have in your table (these can be null if you don't which
             * to specify any options).
             *  @member
             *
             *  @name DataTable.defaults.column
             */
            "aoColumns": null,
        
            /**
             * Very similar to `columns`, `columnDefs` allows you to target a specific
             * column, multiple columns, or all columns, using the `targets` property of
             * each object in the array. This allows great flexibility when creating
             * tables, as the `columnDefs` arrays can be of any length, targeting the
             * columns you specifically want. `columnDefs` may use any of the column
             * options available: {@link DataTable.defaults.column}, but it _must_
             * have `targets` defined in each object in the array. Values in the `targets`
             * array may be:
             *   <ul>
             *     <li>a string - class name will be matched on the TH for the column</li>
             *     <li>0 or a positive integer - column index counting from the left</li>
             *     <li>a negative integer - column index counting from the right</li>
             *     <li>the string "_all" - all columns (i.e. assign a default)</li>
             *   </ul>
             *  @member
             *
             *  @name DataTable.defaults.columnDefs
             */
            "aoColumnDefs": null,
        
        
            /**
             * Basically the same as `search`, this parameter defines the individual column
             * filtering state at initialisation time. The array must be of the same size
             * as the number of columns, and each element be an object with the parameters
             * `search` and `escapeRegex` (the latter is optional). 'null' is also
             * accepted and the default will be used.
             *  @type array
             *  @default []
             *
             *  @dtopt Option
             *  @name DataTable.defaults.searchCols
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "searchCols": [
             *          null,
             *          { "search": "My filter" },
             *          null,
             *          { "search": "^[0-9]", "escapeRegex": false }
             *        ]
             *      } );
             *    } )
             */
            "aoSearchCols": [],
        
        
            /**
             * An array of CSS classes that should be applied to displayed rows. This
             * array may be of any length, and DataTables will apply each class
             * sequentially, looping when required.
             *  @type array
             *  @default null <i>Will take the values determined by the `oClasses.stripe*`
             *    options</i>
             *
             *  @dtopt Option
             *  @name DataTable.defaults.stripeClasses
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stripeClasses": [ 'strip1', 'strip2', 'strip3' ]
             *      } );
             *    } )
             */
            "asStripeClasses": null,
        
        
            /**
             * Enable or disable automatic column width calculation. This can be disabled
             * as an optimisation (it takes some time to calculate the widths) if the
             * tables widths are passed in using `columns`.
             *  @type boolean
             *  @default true
             *
             *  @dtopt Features
             *  @name DataTable.defaults.autoWidth
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "autoWidth": false
             *      } );
             *    } );
             */
            "bAutoWidth": true,
        
        
            /**
             * Deferred rendering can provide DataTables with a huge speed boost when you
             * are using an Ajax or JS data source for the table. This option, when set to
             * true, will cause DataTables to defer the creation of the table elements for
             * each row until they are needed for a draw - saving a significant amount of
             * time.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Features
             *  @name DataTable.defaults.deferRender
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "ajax": "sources/arrays.txt",
             *        "deferRender": true
             *      } );
             *    } );
             */
            "bDeferRender": false,
        
        
            /**
             * Replace a DataTable which matches the given selector and replace it with
             * one which has the properties of the new initialisation object passed. If no
             * table matches the selector, then the new DataTable will be constructed as
             * per normal.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Options
             *  @name DataTable.defaults.destroy
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "srollY": "200px",
             *        "paginate": false
             *      } );
             *
             *      // Some time later....
             *      $('#example').dataTable( {
             *        "filter": false,
             *        "destroy": true
             *      } );
             *    } );
             */
            "bDestroy": false,
        
        
            /**
             * Enable or disable filtering of data. Filtering in DataTables is "smart" in
             * that it allows the end user to input multiple words (space separated) and
             * will match a row containing those words, even if not in the order that was
             * specified (this allow matching across multiple columns). Note that if you
             * wish to use filtering in DataTables this must remain 'true' - to remove the
             * default filtering input box and retain filtering abilities, please use
             * {@link DataTable.defaults.dom}.
             *  @type boolean
             *  @default true
             *
             *  @dtopt Features
             *  @name DataTable.defaults.searching
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "searching": false
             *      } );
             *    } );
             */
            "bFilter": true,
        
        
            /**
             * Enable or disable the table information display. This shows information
             * about the data that is currently visible on the page, including information
             * about filtered data if that action is being performed.
             *  @type boolean
             *  @default true
             *
             *  @dtopt Features
             *  @name DataTable.defaults.info
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "info": false
             *      } );
             *    } );
             */
            "bInfo": true,
        
        
            /**
             * Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some
             * slightly different and additional mark-up from what DataTables has
             * traditionally used).
             *  @type boolean
             *  @default false
             *
             *  @dtopt Features
             *  @name DataTable.defaults.jQueryUI
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "jQueryUI": true
             *      } );
             *    } );
             */
            "bJQueryUI": false,
        
        
            /**
             * Allows the end user to select the size of a formatted page from a select
             * menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`).
             *  @type boolean
             *  @default true
             *
             *  @dtopt Features
             *  @name DataTable.defaults.lengthChange
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "lengthChange": false
             *      } );
             *    } );
             */
            "bLengthChange": true,
        
        
            /**
             * Enable or disable pagination.
             *  @type boolean
             *  @default true
             *
             *  @dtopt Features
             *  @name DataTable.defaults.paging
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "paging": false
             *      } );
             *    } );
             */
            "bPaginate": true,
        
        
            /**
             * Enable or disable the display of a 'processing' indicator when the table is
             * being processed (e.g. a sort). This is particularly useful for tables with
             * large amounts of data where it can take a noticeable amount of time to sort
             * the entries.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Features
             *  @name DataTable.defaults.processing
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "processing": true
             *      } );
             *    } );
             */
            "bProcessing": false,
        
        
            /**
             * Retrieve the DataTables object for the given selector. Note that if the
             * table has already been initialised, this parameter will cause DataTables
             * to simply return the object that has already been set up - it will not take
             * account of any changes you might have made to the initialisation object
             * passed to DataTables (setting this parameter to true is an acknowledgement
             * that you understand this). `destroy` can be used to reinitialise a table if
             * you need.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Options
             *  @name DataTable.defaults.retrieve
             *
             *  @example
             *    $(document).ready( function() {
             *      initTable();
             *      tableActions();
             *    } );
             *
             *    function initTable ()
             *    {
             *      return $('#example').dataTable( {
             *        "scrollY": "200px",
             *        "paginate": false,
             *        "retrieve": true
             *      } );
             *    }
             *
             *    function tableActions ()
             *    {
             *      var table = initTable();
             *      // perform API operations with oTable
             *    }
             */
            "bRetrieve": false,
        
        
            /**
             * When vertical (y) scrolling is enabled, DataTables will force the height of
             * the table's viewport to the given height at all times (useful for layout).
             * However, this can look odd when filtering data down to a small data set,
             * and the footer is left "floating" further down. This parameter (when
             * enabled) will cause DataTables to collapse the table's viewport down when
             * the result set will fit within the given Y height.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Options
             *  @name DataTable.defaults.scrollCollapse
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "scrollY": "200",
             *        "scrollCollapse": true
             *      } );
             *    } );
             */
            "bScrollCollapse": false,
        
        
            /**
             * Configure DataTables to use server-side processing. Note that the
             * `ajax` parameter must also be given in order to give DataTables a
             * source to obtain the required data for each draw.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Features
             *  @dtopt Server-side
             *  @name DataTable.defaults.serverSide
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "serverSide": true,
             *        "ajax": "xhr.php"
             *      } );
             *    } );
             */
            "bServerSide": false,
        
        
            /**
             * Enable or disable sorting of columns. Sorting of individual columns can be
             * disabled by the `sortable` option for each column.
             *  @type boolean
             *  @default true
             *
             *  @dtopt Features
             *  @name DataTable.defaults.ordering
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "ordering": false
             *      } );
             *    } );
             */
            "bSort": true,
        
        
            /**
             * Enable or display DataTables' ability to sort multiple columns at the
             * same time (activated by shift-click by the user).
             *  @type boolean
             *  @default true
             *
             *  @dtopt Options
             *  @name DataTable.defaults.orderMulti
             *
             *  @example
             *    // Disable multiple column sorting ability
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "orderMulti": false
             *      } );
             *    } );
             */
            "bSortMulti": true,
        
        
            /**
             * Allows control over whether DataTables should use the top (true) unique
             * cell that is found for a single column, or the bottom (false - default).
             * This is useful when using complex headers.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Options
             *  @name DataTable.defaults.orderCellsTop
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "orderCellsTop": true
             *      } );
             *    } );
             */
            "bSortCellsTop": false,
        
        
            /**
             * Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and
             * `sorting\_3` to the columns which are currently being sorted on. This is
             * presented as a feature switch as it can increase processing time (while
             * classes are removed and added) so for large data sets you might want to
             * turn this off.
             *  @type boolean
             *  @default true
             *
             *  @dtopt Features
             *  @name DataTable.defaults.orderClasses
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "orderClasses": false
             *      } );
             *    } );
             */
            "bSortClasses": true,
        
        
            /**
             * Enable or disable state saving. When enabled HTML5 `localStorage` will be
             * used to save table display information such as pagination information,
             * display length, filtering and sorting. As such when the end user reloads
             * the page the display display will match what thy had previously set up.
             *
             * Due to the use of `localStorage` the default state saving is not supported
             * in IE6 or 7. If state saving is required in those browsers, use
             * `stateSaveCallback` to provide a storage solution such as cookies.
             *  @type boolean
             *  @default false
             *
             *  @dtopt Features
             *  @name DataTable.defaults.stateSave
             *
             *  @example
             *    $(document).ready( function () {
             *      $('#example').dataTable( {
             *        "stateSave": true
             *      } );
             *    } );
             */
            "bStateSave": false,
        
        
            /**
             * This function is called when a TR element is created (and all TD child
             * elements have been inserted), or registered if using a DOM source, allowing
             * manipulation of the TR element (adding classes etc).
             *  @type function
             *  @param {node} row "TR" element for the current row
             *  @param {array} data Raw data array for this row
             *  @param {int} dataIndex The index of this row in the internal aoData array
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.createdRow
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "createdRow": function( row, data, dataIndex ) {
             *          // Bold the grade for all 'A' grade browsers
             *          if ( data[4] == "A" )
             *          {
             *            $('td:eq(4)', row).html( '<b>A</b>' );
             *          }
             *        }
             *      } );
             *    } );
             */
            "fnCreatedRow": null,
        
        
            /**
             * This function is called on every 'draw' event, and allows you to
             * dynamically modify any aspect you want about the created DOM.
             *  @type function
             *  @param {object} settings DataTables settings object
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.drawCallback
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "drawCallback": function( settings ) {
             *          alert( 'DataTables has redrawn the table' );
             *        }
             *      } );
             *    } );
             */
            "fnDrawCallback": null,
        
        
            /**
             * Identical to fnHeaderCallback() but for the table footer this function
             * allows you to modify the table footer on every 'draw' event.
             *  @type function
             *  @param {node} foot "TR" element for the footer
             *  @param {array} data Full table data (as derived from the original HTML)
             *  @param {int} start Index for the current display starting point in the
             *    display array
             *  @param {int} end Index for the current display ending point in the
             *    display array
             *  @param {array int} display Index array to translate the visual position
             *    to the full data array
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.footerCallback
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "footerCallback": function( tfoot, data, start, end, display ) {
             *          tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start;
             *        }
             *      } );
             *    } )
             */
            "fnFooterCallback": null,
        
        
            /**
             * When rendering large numbers in the information element for the table
             * (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers
             * to have a comma separator for the 'thousands' units (e.g. 1 million is
             * rendered as "1,000,000") to help readability for the end user. This
             * function will override the default method DataTables uses.
             *  @type function
             *  @member
             *  @param {int} toFormat number to be formatted
             *  @returns {string} formatted string for DataTables to show the number
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.formatNumber
             *
             *  @example
             *    // Format a number using a single quote for the separator (note that
             *    // this can also be done with the language.thousands option)
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "formatNumber": function ( toFormat ) {
             *          return toFormat.toString().replace(
             *            /\B(?=(\d{3})+(?!\d))/g, "'"
             *          );
             *        };
             *      } );
             *    } );
             */
            "fnFormatNumber": function ( toFormat ) {
                return toFormat.toString().replace(
                    /\B(?=(\d{3})+(?!\d))/g,
                    this.oLanguage.sThousands
                );
            },
        
        
            /**
             * This function is called on every 'draw' event, and allows you to
             * dynamically modify the header row. This can be used to calculate and
             * display useful information about the table.
             *  @type function
             *  @param {node} head "TR" element for the header
             *  @param {array} data Full table data (as derived from the original HTML)
             *  @param {int} start Index for the current display starting point in the
             *    display array
             *  @param {int} end Index for the current display ending point in the
             *    display array
             *  @param {array int} display Index array to translate the visual position
             *    to the full data array
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.headerCallback
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "fheaderCallback": function( head, data, start, end, display ) {
             *          head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records";
             *        }
             *      } );
             *    } )
             */
            "fnHeaderCallback": null,
        
        
            /**
             * The information element can be used to convey information about the current
             * state of the table. Although the internationalisation options presented by
             * DataTables are quite capable of dealing with most customisations, there may
             * be times where you wish to customise the string further. This callback
             * allows you to do exactly that.
             *  @type function
             *  @param {object} oSettings DataTables settings object
             *  @param {int} start Starting position in data for the draw
             *  @param {int} end End position in data for the draw
             *  @param {int} max Total number of rows in the table (regardless of
             *    filtering)
             *  @param {int} total Total number of rows in the data set, after filtering
             *  @param {string} pre The string that DataTables has formatted using it's
             *    own rules
             *  @returns {string} The string to be displayed in the information element.
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.infoCallback
             *
             *  @example
             *    $('#example').dataTable( {
             *      "infoCallback": function( settings, start, end, max, total, pre ) {
             *        return start +" to "+ end;
             *      }
             *    } );
             */
            "fnInfoCallback": null,
        
        
            /**
             * Called when the table has been initialised. Normally DataTables will
             * initialise sequentially and there will be no need for this function,
             * however, this does not hold true when using external language information
             * since that is obtained using an async XHR call.
             *  @type function
             *  @param {object} settings DataTables settings object
             *  @param {object} json The JSON object request from the server - only
             *    present if client-side Ajax sourced data is used
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.initComplete
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "initComplete": function(settings, json) {
             *          alert( 'DataTables has finished its initialisation.' );
             *        }
             *      } );
             *    } )
             */
            "fnInitComplete": null,
        
        
            /**
             * Called at the very start of each table draw and can be used to cancel the
             * draw by returning false, any other return (including undefined) results in
             * the full draw occurring).
             *  @type function
             *  @param {object} settings DataTables settings object
             *  @returns {boolean} False will cancel the draw, anything else (including no
             *    return) will allow it to complete.
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.preDrawCallback
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "preDrawCallback": function( settings ) {
             *          if ( $('#test').val() == 1 ) {
             *            return false;
             *          }
             *        }
             *      } );
             *    } );
             */
            "fnPreDrawCallback": null,
        
        
            /**
             * This function allows you to 'post process' each row after it have been
             * generated for each table draw, but before it is rendered on screen. This
             * function might be used for setting the row class name etc.
             *  @type function
             *  @param {node} row "TR" element for the current row
             *  @param {array} data Raw data array for this row
             *  @param {int} displayIndex The display index for the current table draw
             *  @param {int} displayIndexFull The index of the data in the full list of
             *    rows (after filtering)
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.rowCallback
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "rowCallback": function( row, data, displayIndex, displayIndexFull ) {
             *          // Bold the grade for all 'A' grade browsers
             *          if ( data[4] == "A" ) {
             *            $('td:eq(4)', row).html( '<b>A</b>' );
             *          }
             *        }
             *      } );
             *    } );
             */
            "fnRowCallback": null,
        
        
            /**
             * __Deprecated__ The functionality provided by this parameter has now been
             * superseded by that provided through `ajax`, which should be used instead.
             *
             * This parameter allows you to override the default function which obtains
             * the data from the server so something more suitable for your application.
             * For example you could use POST data, or pull information from a Gears or
             * AIR database.
             *  @type function
             *  @member
             *  @param {string} source HTTP source to obtain the data from (`ajax`)
             *  @param {array} data A key/value pair object containing the data to send
             *    to the server
             *  @param {function} callback to be called on completion of the data get
             *    process that will draw the data on the page.
             *  @param {object} settings DataTables settings object
             *
             *  @dtopt Callbacks
             *  @dtopt Server-side
             *  @name DataTable.defaults.serverData
             *
             *  @deprecated 1.10. Please use `ajax` for this functionality now.
             */
            "fnServerData": null,
        
        
            /**
             * __Deprecated__ The functionality provided by this parameter has now been
             * superseded by that provided through `ajax`, which should be used instead.
             *
             *  It is often useful to send extra data to the server when making an Ajax
             * request - for example custom filtering information, and this callback
             * function makes it trivial to send extra information to the server. The
             * passed in parameter is the data set that has been constructed by
             * DataTables, and you can add to this or modify it as you require.
             *  @type function
             *  @param {array} data Data array (array of objects which are name/value
             *    pairs) that has been constructed by DataTables and will be sent to the
             *    server. In the case of Ajax sourced data with server-side processing
             *    this will be an empty array, for server-side processing there will be a
             *    significant number of parameters!
             *  @returns {undefined} Ensure that you modify the data array passed in,
             *    as this is passed by reference.
             *
             *  @dtopt Callbacks
             *  @dtopt Server-side
             *  @name DataTable.defaults.serverParams
             *
             *  @deprecated 1.10. Please use `ajax` for this functionality now.
             */
            "fnServerParams": null,
        
        
            /**
             * Load the table state. With this function you can define from where, and how, the
             * state of a table is loaded. By default DataTables will load from `localStorage`
             * but you might wish to use a server-side database or cookies.
             *  @type function
             *  @member
             *  @param {object} settings DataTables settings object
             *  @return {object} The DataTables state object to be loaded
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.stateLoadCallback
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stateSave": true,
             *        "stateLoadCallback": function (settings) {
             *          var o;
             *
             *          // Send an Ajax request to the server to get the data. Note that
             *          // this is a synchronous request.
             *          $.ajax( {
             *            "url": "/state_load",
             *            "async": false,
             *            "dataType": "json",
             *            "success": function (json) {
             *              o = json;
             *            }
             *          } );
             *
             *          return o;
             *        }
             *      } );
             *    } );
             */
            "fnStateLoadCallback": function ( settings ) {
                try {
                    return JSON.parse(
                        (settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem(
                            'DataTables_'+settings.sInstance+'_'+location.pathname
                        )
                    );
                } catch (e) {}
            },
        
        
            /**
             * Callback which allows modification of the saved state prior to loading that state.
             * This callback is called when the table is loading state from the stored data, but
             * prior to the settings object being modified by the saved state. Note that for
             * plug-in authors, you should use the `stateLoadParams` event to load parameters for
             * a plug-in.
             *  @type function
             *  @param {object} settings DataTables settings object
             *  @param {object} data The state object that is to be loaded
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.stateLoadParams
             *
             *  @example
             *    // Remove a saved filter, so filtering is never loaded
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stateSave": true,
             *        "stateLoadParams": function (settings, data) {
             *          data.oSearch.sSearch = "";
             *        }
             *      } );
             *    } );
             *
             *  @example
             *    // Disallow state loading by returning false
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stateSave": true,
             *        "stateLoadParams": function (settings, data) {
             *          return false;
             *        }
             *      } );
             *    } );
             */
            "fnStateLoadParams": null,
        
        
            /**
             * Callback that is called when the state has been loaded from the state saving method
             * and the DataTables settings object has been modified as a result of the loaded state.
             *  @type function
             *  @param {object} settings DataTables settings object
             *  @param {object} data The state object that was loaded
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.stateLoaded
             *
             *  @example
             *    // Show an alert with the filtering value that was saved
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stateSave": true,
             *        "stateLoaded": function (settings, data) {
             *          alert( 'Saved filter was: '+data.oSearch.sSearch );
             *        }
             *      } );
             *    } );
             */
            "fnStateLoaded": null,
        
        
            /**
             * Save the table state. This function allows you to define where and how the state
             * information for the table is stored By default DataTables will use `localStorage`
             * but you might wish to use a server-side database or cookies.
             *  @type function
             *  @member
             *  @param {object} settings DataTables settings object
             *  @param {object} data The state object to be saved
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.stateSaveCallback
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stateSave": true,
             *        "stateSaveCallback": function (settings, data) {
             *          // Send an Ajax request to the server with the state object
             *          $.ajax( {
             *            "url": "/state_save",
             *            "data": data,
             *            "dataType": "json",
             *            "method": "POST"
             *            "success": function () {}
             *          } );
             *        }
             *      } );
             *    } );
             */
            "fnStateSaveCallback": function ( settings, data ) {
                try {
                    (settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem(
                        'DataTables_'+settings.sInstance+'_'+location.pathname,
                        JSON.stringify( data )
                    );
                } catch (e) {}
            },
        
        
            /**
             * Callback which allows modification of the state to be saved. Called when the table
             * has changed state a new state save is required. This method allows modification of
             * the state saving object prior to actually doing the save, including addition or
             * other state properties or modification. Note that for plug-in authors, you should
             * use the `stateSaveParams` event to save parameters for a plug-in.
             *  @type function
             *  @param {object} settings DataTables settings object
             *  @param {object} data The state object to be saved
             *
             *  @dtopt Callbacks
             *  @name DataTable.defaults.stateSaveParams
             *
             *  @example
             *    // Remove a saved filter, so filtering is never saved
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stateSave": true,
             *        "stateSaveParams": function (settings, data) {
             *          data.oSearch.sSearch = "";
             *        }
             *      } );
             *    } );
             */
            "fnStateSaveParams": null,
        
        
            /**
             * Duration for which the saved state information is considered valid. After this period
             * has elapsed the state will be returned to the default.
             * Value is given in seconds.
             *  @type int
             *  @default 7200 <i>(2 hours)</i>
             *
             *  @dtopt Options
             *  @name DataTable.defaults.stateDuration
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "stateDuration": 60*60*24; // 1 day
             *      } );
             *    } )
             */
            "iStateDuration": 7200,
        
        
            /**
             * When enabled DataTables will not make a request to the server for the first
             * page draw - rather it will use the data already on the page (no sorting etc
             * will be applied to it), thus saving on an XHR at load time. `deferLoading`
             * is used to indicate that deferred loading is required, but it is also used
             * to tell DataTables how many records there are in the full table (allowing
             * the information element and pagination to be displayed correctly). In the case
             * where a filtering is applied to the table on initial load, this can be
             * indicated by giving the parameter as an array, where the first element is
             * the number of records available after filtering and the second element is the
             * number of records without filtering (allowing the table information element
             * to be shown correctly).
             *  @type int | array
             *  @default null
             *
             *  @dtopt Options
             *  @name DataTable.defaults.deferLoading
             *
             *  @example
             *    // 57 records available in the table, no filtering applied
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "serverSide": true,
             *        "ajax": "scripts/server_processing.php",
             *        "deferLoading": 57
             *      } );
             *    } );
             *
             *  @example
             *    // 57 records after filtering, 100 without filtering (an initial filter applied)
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "serverSide": true,
             *        "ajax": "scripts/server_processing.php",
             *        "deferLoading": [ 57, 100 ],
             *        "search": {
             *          "search": "my_filter"
             *        }
             *      } );
             *    } );
             */
            "iDeferLoading": null,
        
        
            /**
             * Number of rows to display on a single page when using pagination. If
             * feature enabled (`lengthChange`) then the end user will be able to override
             * this to a custom setting using a pop-up menu.
             *  @type int
             *  @default 10
             *
             *  @dtopt Options
             *  @name DataTable.defaults.pageLength
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "pageLength": 50
             *      } );
             *    } )
             */
            "iDisplayLength": 10,
        
        
            /**
             * Define the starting point for data display when using DataTables with
             * pagination. Note that this parameter is the number of records, rather than
             * the page number, so if you have 10 records per page and want to start on
             * the third page, it should be "20".
             *  @type int
             *  @default 0
             *
             *  @dtopt Options
             *  @name DataTable.defaults.displayStart
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "displayStart": 20
             *      } );
             *    } )
             */
            "iDisplayStart": 0,
        
        
            /**
             * By default DataTables allows keyboard navigation of the table (sorting, paging,
             * and filtering) by adding a `tabindex` attribute to the required elements. This
             * allows you to tab through the controls and press the enter key to activate them.
             * The tabindex is default 0, meaning that the tab follows the flow of the document.
             * You can overrule this using this parameter if you wish. Use a value of -1 to
             * disable built-in keyboard navigation.
             *  @type int
             *  @default 0
             *
             *  @dtopt Options
             *  @name DataTable.defaults.tabIndex
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "tabIndex": 1
             *      } );
             *    } );
             */
            "iTabIndex": 0,
        
        
            /**
             * Classes that DataTables assigns to the various components and features
             * that it adds to the HTML table. This allows classes to be configured
             * during initialisation in addition to through the static
             * {@link DataTable.ext.oStdClasses} object).
             *  @namespace
             *  @name DataTable.defaults.classes
             */
            "oClasses": {},
        
        
            /**
             * All strings that DataTables uses in the user interface that it creates
             * are defined in this object, allowing you to modified them individually or
             * completely replace them all as required.
             *  @namespace
             *  @name DataTable.defaults.language
             */
            "oLanguage": {
                /**
                 * Strings that are used for WAI-ARIA labels and controls only (these are not
                 * actually visible on the page, but will be read by screenreaders, and thus
                 * must be internationalised as well).
                 *  @namespace
                 *  @name DataTable.defaults.language.aria
                 */
                "oAria": {
                    /**
                     * ARIA label that is added to the table headers when the column may be
                     * sorted ascending by activing the column (click or return when focused).
                     * Note that the column header is prefixed to this string.
                     *  @type string
                     *  @default : activate to sort column ascending
                     *
                     *  @dtopt Language
                     *  @name DataTable.defaults.language.aria.sortAscending
                     *
                     *  @example
                     *    $(document).ready( function() {
                     *      $('#example').dataTable( {
                     *        "language": {
                     *          "aria": {
                     *            "sortAscending": " - click/return to sort ascending"
                     *          }
                     *        }
                     *      } );
                     *    } );
                     */
                    "sSortAscending": ": activate to sort column ascending",
        
                    /**
                     * ARIA label that is added to the table headers when the column may be
                     * sorted descending by activing the column (click or return when focused).
                     * Note that the column header is prefixed to this string.
                     *  @type string
                     *  @default : activate to sort column ascending
                     *
                     *  @dtopt Language
                     *  @name DataTable.defaults.language.aria.sortDescending
                     *
                     *  @example
                     *    $(document).ready( function() {
                     *      $('#example').dataTable( {
                     *        "language": {
                     *          "aria": {
                     *            "sortDescending": " - click/return to sort descending"
                     *          }
                     *        }
                     *      } );
                     *    } );
                     */
                    "sSortDescending": ": activate to sort column descending"
                },
        
                /**
                 * Pagination string used by DataTables for the built-in pagination
                 * control types.
                 *  @namespace
                 *  @name DataTable.defaults.language.paginate
                 */
                "oPaginate": {
                    /**
                     * Text to use when using the 'full_numbers' type of pagination for the
                     * button to take the user to the first page.
                     *  @type string
                     *  @default First
                     *
                     *  @dtopt Language
                     *  @name DataTable.defaults.language.paginate.first
                     *
                     *  @example
                     *    $(document).ready( function() {
                     *      $('#example').dataTable( {
                     *        "language": {
                     *          "paginate": {
                     *            "first": "First page"
                     *          }
                     *        }
                     *      } );
                     *    } );
                     */
                    "sFirst": "First",
        
        
                    /**
                     * Text to use when using the 'full_numbers' type of pagination for the
                     * button to take the user to the last page.
                     *  @type string
                     *  @default Last
                     *
                     *  @dtopt Language
                     *  @name DataTable.defaults.language.paginate.last
                     *
                     *  @example
                     *    $(document).ready( function() {
                     *      $('#example').dataTable( {
                     *        "language": {
                     *          "paginate": {
                     *            "last": "Last page"
                     *          }
                     *        }
                     *      } );
                     *    } );
                     */
                    "sLast": "Last",
        
        
                    /**
                     * Text to use for the 'next' pagination button (to take the user to the
                     * next page).
                     *  @type string
                     *  @default Next
                     *
                     *  @dtopt Language
                     *  @name DataTable.defaults.language.paginate.next
                     *
                     *  @example
                     *    $(document).ready( function() {
                     *      $('#example').dataTable( {
                     *        "language": {
                     *          "paginate": {
                     *            "next": "Next page"
                     *          }
                     *        }
                     *      } );
                     *    } );
                     */
                    "sNext": "Next",
        
        
                    /**
                     * Text to use for the 'previous' pagination button (to take the user to
                     * the previous page).
                     *  @type string
                     *  @default Previous
                     *
                     *  @dtopt Language
                     *  @name DataTable.defaults.language.paginate.previous
                     *
                     *  @example
                     *    $(document).ready( function() {
                     *      $('#example').dataTable( {
                     *        "language": {
                     *          "paginate": {
                     *            "previous": "Previous page"
                     *          }
                     *        }
                     *      } );
                     *    } );
                     */
                    "sPrevious": "Previous"
                },
        
                /**
                 * This string is shown in preference to `zeroRecords` when the table is
                 * empty of data (regardless of filtering). Note that this is an optional
                 * parameter - if it is not given, the value of `zeroRecords` will be used
                 * instead (either the default or given value).
                 *  @type string
                 *  @default No data available in table
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.emptyTable
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "emptyTable": "No data available in table"
                 *        }
                 *      } );
                 *    } );
                 */
                "sEmptyTable": "No data available in table",
        
        
                /**
                 * This string gives information to the end user about the information
                 * that is current on display on the page. The following tokens can be
                 * used in the string and will be dynamically replaced as the table
                 * display updates. This tokens can be placed anywhere in the string, or
                 * removed as needed by the language requires:
                 *
                 * * `\_START\_` - Display index of the first record on the current page
                 * * `\_END\_` - Display index of the last record on the current page
                 * * `\_TOTAL\_` - Number of records in the table after filtering
                 * * `\_MAX\_` - Number of records in the table without filtering
                 * * `\_PAGE\_` - Current page number
                 * * `\_PAGES\_` - Total number of pages of data in the table
                 *
                 *  @type string
                 *  @default Showing _START_ to _END_ of _TOTAL_ entries
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.info
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "info": "Showing page _PAGE_ of _PAGES_"
                 *        }
                 *      } );
                 *    } );
                 */
                "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
        
        
                /**
                 * Display information string for when the table is empty. Typically the
                 * format of this string should match `info`.
                 *  @type string
                 *  @default Showing 0 to 0 of 0 entries
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.infoEmpty
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "infoEmpty": "No entries to show"
                 *        }
                 *      } );
                 *    } );
                 */
                "sInfoEmpty": "Showing 0 to 0 of 0 entries",
        
        
                /**
                 * When a user filters the information in a table, this string is appended
                 * to the information (`info`) to give an idea of how strong the filtering
                 * is. The variable _MAX_ is dynamically updated.
                 *  @type string
                 *  @default (filtered from _MAX_ total entries)
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.infoFiltered
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "infoFiltered": " - filtering from _MAX_ records"
                 *        }
                 *      } );
                 *    } );
                 */
                "sInfoFiltered": "(filtered from _MAX_ total entries)",
        
        
                /**
                 * If can be useful to append extra information to the info string at times,
                 * and this variable does exactly that. This information will be appended to
                 * the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are
                 * being used) at all times.
                 *  @type string
                 *  @default <i>Empty string</i>
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.infoPostFix
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "infoPostFix": "All records shown are derived from real information."
                 *        }
                 *      } );
                 *    } );
                 */
                "sInfoPostFix": "",
        
        
                /**
                 * This decimal place operator is a little different from the other
                 * language options since DataTables doesn't output floating point
                 * numbers, so it won't ever use this for display of a number. Rather,
                 * what this parameter does is modify the sort methods of the table so
                 * that numbers which are in a format which has a character other than
                 * a period (`.`) as a decimal place will be sorted numerically.
                 *
                 * Note that numbers with different decimal places cannot be shown in
                 * the same table and still be sortable, the table must be consistent.
                 * However, multiple different tables on the page can use different
                 * decimal place characters.
                 *  @type string
                 *  @default 
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.decimal
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "decimal": ","
                 *          "thousands": "."
                 *        }
                 *      } );
                 *    } );
                 */
                "sDecimal": "",
        
        
                /**
                 * DataTables has a build in number formatter (`formatNumber`) which is
                 * used to format large numbers that are used in the table information.
                 * By default a comma is used, but this can be trivially changed to any
                 * character you wish with this parameter.
                 *  @type string
                 *  @default ,
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.thousands
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "thousands": "'"
                 *        }
                 *      } );
                 *    } );
                 */
                "sThousands": ",",
        
        
                /**
                 * Detail the action that will be taken when the drop down menu for the
                 * pagination length option is changed. The '_MENU_' variable is replaced
                 * with a default select list of 10, 25, 50 and 100, and can be replaced
                 * with a custom select box if required.
                 *  @type string
                 *  @default Show _MENU_ entries
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.lengthMenu
                 *
                 *  @example
                 *    // Language change only
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "lengthMenu": "Display _MENU_ records"
                 *        }
                 *      } );
                 *    } );
                 *
                 *  @example
                 *    // Language and options change
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "lengthMenu": 'Display <select>'+
                 *            '<option value="10">10</option>'+
                 *            '<option value="20">20</option>'+
                 *            '<option value="30">30</option>'+
                 *            '<option value="40">40</option>'+
                 *            '<option value="50">50</option>'+
                 *            '<option value="-1">All</option>'+
                 *            '</select> records'
                 *        }
                 *      } );
                 *    } );
                 */
                "sLengthMenu": "Show _MENU_ entries",
        
        
                /**
                 * When using Ajax sourced data and during the first draw when DataTables is
                 * gathering the data, this message is shown in an empty row in the table to
                 * indicate to the end user the the data is being loaded. Note that this
                 * parameter is not used when loading data by server-side processing, just
                 * Ajax sourced data with client-side processing.
                 *  @type string
                 *  @default Loading...
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.loadingRecords
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "loadingRecords": "Please wait - loading..."
                 *        }
                 *      } );
                 *    } );
                 */
                "sLoadingRecords": "Loading...",
        
        
                /**
                 * Text which is displayed when the table is processing a user action
                 * (usually a sort command or similar).
                 *  @type string
                 *  @default Processing...
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.processing
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "processing": "DataTables is currently busy"
                 *        }
                 *      } );
                 *    } );
                 */
                "sProcessing": "Processing...",
        
        
                /**
                 * Details the actions that will be taken when the user types into the
                 * filtering input text box. The variable "_INPUT_", if used in the string,
                 * is replaced with the HTML text box for the filtering input allowing
                 * control over where it appears in the string. If "_INPUT_" is not given
                 * then the input box is appended to the string automatically.
                 *  @type string
                 *  @default Search:
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.search
                 *
                 *  @example
                 *    // Input text box will be appended at the end automatically
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "search": "Filter records:"
                 *        }
                 *      } );
                 *    } );
                 *
                 *  @example
                 *    // Specify where the filter should appear
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "search": "Apply filter _INPUT_ to table"
                 *        }
                 *      } );
                 *    } );
                 */
                "sSearch": "Search:",
        
        
                /**
                 * Assign a `placeholder` attribute to the search `input` element
                 *  @type string
                 *  @default 
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.searchPlaceholder
                 */
                "sSearchPlaceholder": "",
        
        
                /**
                 * All of the language information can be stored in a file on the
                 * server-side, which DataTables will look up if this parameter is passed.
                 * It must store the URL of the language file, which is in a JSON format,
                 * and the object has the same properties as the oLanguage object in the
                 * initialiser object (i.e. the above parameters). Please refer to one of
                 * the example language files to see how this works in action.
                 *  @type string
                 *  @default <i>Empty string - i.e. disabled</i>
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.url
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "url": "http://www.sprymedia.co.uk/dataTables/lang.txt"
                 *        }
                 *      } );
                 *    } );
                 */
                "sUrl": "",
        
        
                /**
                 * Text shown inside the table records when the is no information to be
                 * displayed after filtering. `emptyTable` is shown when there is simply no
                 * information in the table at all (regardless of filtering).
                 *  @type string
                 *  @default No matching records found
                 *
                 *  @dtopt Language
                 *  @name DataTable.defaults.language.zeroRecords
                 *
                 *  @example
                 *    $(document).ready( function() {
                 *      $('#example').dataTable( {
                 *        "language": {
                 *          "zeroRecords": "No records to display"
                 *        }
                 *      } );
                 *    } );
                 */
                "sZeroRecords": "No matching records found"
            },
        
        
            /**
             * This parameter allows you to have define the global filtering state at
             * initialisation time. As an object the `search` parameter must be
             * defined, but all other parameters are optional. When `regex` is true,
             * the search string will be treated as a regular expression, when false
             * (default) it will be treated as a straight string. When `smart`
             * DataTables will use it's smart filtering methods (to word match at
             * any point in the data), when false this will not be done.
             *  @namespace
             *  @extends DataTable.models.oSearch
             *
             *  @dtopt Options
             *  @name DataTable.defaults.search
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "search": {"search": "Initial search"}
             *      } );
             *    } )
             */
            "oSearch": $.extend( {}, DataTable.models.oSearch ),
        
        
            /**
             * __Deprecated__ The functionality provided by this parameter has now been
             * superseded by that provided through `ajax`, which should be used instead.
             *
             * By default DataTables will look for the property `data` (or `aaData` for
             * compatibility with DataTables 1.9-) when obtaining data from an Ajax
             * source or for server-side processing - this parameter allows that
             * property to be changed. You can use Javascript dotted object notation to
             * get a data source for multiple levels of nesting.
             *  @type string
             *  @default data
             *
             *  @dtopt Options
             *  @dtopt Server-side
             *  @name DataTable.defaults.ajaxDataProp
             *
             *  @deprecated 1.10. Please use `ajax` for this functionality now.
             */
            "sAjaxDataProp": "data",
        
        
            /**
             * __Deprecated__ The functionality provided by this parameter has now been
             * superseded by that provided through `ajax`, which should be used instead.
             *
             * You can instruct DataTables to load data from an external
             * source using this parameter (use aData if you want to pass data in you
             * already have). Simply provide a url a JSON object can be obtained from.
             *  @type string
             *  @default null
             *
             *  @dtopt Options
             *  @dtopt Server-side
             *  @name DataTable.defaults.ajaxSource
             *
             *  @deprecated 1.10. Please use `ajax` for this functionality now.
             */
            "sAjaxSource": null,
        
        
            /**
             * This initialisation variable allows you to specify exactly where in the
             * DOM you want DataTables to inject the various controls it adds to the page
             * (for example you might want the pagination controls at the top of the
             * table). DIV elements (with or without a custom class) can also be added to
             * aid styling. The follow syntax is used:
             *   <ul>
             *     <li>The following options are allowed:
             *       <ul>
             *         <li>'l' - Length changing</li>
             *         <li>'f' - Filtering input</li>
             *         <li>'t' - The table!</li>
             *         <li>'i' - Information</li>
             *         <li>'p' - Pagination</li>
             *         <li>'r' - pRocessing</li>
             *       </ul>
             *     </li>
             *     <li>The following constants are allowed:
             *       <ul>
             *         <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li>
             *         <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li>
             *       </ul>
             *     </li>
             *     <li>The following syntax is expected:
             *       <ul>
             *         <li>'&lt;' and '&gt;' - div elements</li>
             *         <li>'&lt;"class" and '&gt;' - div with a class</li>
             *         <li>'&lt;"#id" and '&gt;' - div with an ID</li>
             *       </ul>
             *     </li>
             *     <li>Examples:
             *       <ul>
             *         <li>'&lt;"wrapper"flipt&gt;'</li>
             *         <li>'&lt;lf&lt;t&gt;ip&gt;'</li>
             *       </ul>
             *     </li>
             *   </ul>
             *  @type string
             *  @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b>
             *    <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i>
             *
             *  @dtopt Options
             *  @name DataTable.defaults.dom
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "dom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;'
             *      } );
             *    } );
             */
            "sDom": "lfrtip",
        
        
            /**
             * Search delay option. This will throttle full table searches that use the
             * DataTables provided search input element (it does not effect calls to
             * `dt-api search()`, providing a delay before the search is made.
             *  @type integer
             *  @default 0
             *
             *  @dtopt Options
             *  @name DataTable.defaults.searchDelay
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "searchDelay": 200
             *      } );
             *    } )
             */
            "searchDelay": null,
        
        
            /**
             * DataTables features four different built-in options for the buttons to
             * display for pagination control:
             *
             * * `simple` - 'Previous' and 'Next' buttons only
             * * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers
             * * `full` - 'First', 'Previous', 'Next' and 'Last' buttons
             * * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus
             *   page numbers
             *  
             * Further methods can be added using {@link DataTable.ext.oPagination}.
             *  @type string
             *  @default simple_numbers
             *
             *  @dtopt Options
             *  @name DataTable.defaults.pagingType
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "pagingType": "full_numbers"
             *      } );
             *    } )
             */
            "sPaginationType": "simple_numbers",
        
        
            /**
             * Enable horizontal scrolling. When a table is too wide to fit into a
             * certain layout, or you have a large number of columns in the table, you
             * can enable x-scrolling to show the table in a viewport, which can be
             * scrolled. This property can be `true` which will allow the table to
             * scroll horizontally when needed, or any CSS unit, or a number (in which
             * case it will be treated as a pixel measurement). Setting as simply `true`
             * is recommended.
             *  @type boolean|string
             *  @default <i>blank string - i.e. disabled</i>
             *
             *  @dtopt Features
             *  @name DataTable.defaults.scrollX
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "scrollX": true,
             *        "scrollCollapse": true
             *      } );
             *    } );
             */
            "sScrollX": "",
        
        
            /**
             * This property can be used to force a DataTable to use more width than it
             * might otherwise do when x-scrolling is enabled. For example if you have a
             * table which requires to be well spaced, this parameter is useful for
             * "over-sizing" the table, and thus forcing scrolling. This property can by
             * any CSS unit, or a number (in which case it will be treated as a pixel
             * measurement).
             *  @type string
             *  @default <i>blank string - i.e. disabled</i>
             *
             *  @dtopt Options
             *  @name DataTable.defaults.scrollXInner
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "scrollX": "100%",
             *        "scrollXInner": "110%"
             *      } );
             *    } );
             */
            "sScrollXInner": "",
        
        
            /**
             * Enable vertical scrolling. Vertical scrolling will constrain the DataTable
             * to the given height, and enable scrolling for any data which overflows the
             * current viewport. This can be used as an alternative to paging to display
             * a lot of data in a small area (although paging and scrolling can both be
             * enabled at the same time). This property can be any CSS unit, or a number
             * (in which case it will be treated as a pixel measurement).
             *  @type string
             *  @default <i>blank string - i.e. disabled</i>
             *
             *  @dtopt Features
             *  @name DataTable.defaults.scrollY
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "scrollY": "200px",
             *        "paginate": false
             *      } );
             *    } );
             */
            "sScrollY": "",
        
        
            /**
             * __Deprecated__ The functionality provided by this parameter has now been
             * superseded by that provided through `ajax`, which should be used instead.
             *
             * Set the HTTP method that is used to make the Ajax call for server-side
             * processing or Ajax sourced data.
             *  @type string
             *  @default GET
             *
             *  @dtopt Options
             *  @dtopt Server-side
             *  @name DataTable.defaults.serverMethod
             *
             *  @deprecated 1.10. Please use `ajax` for this functionality now.
             */
            "sServerMethod": "GET",
        
        
            /**
             * DataTables makes use of renderers when displaying HTML elements for
             * a table. These renderers can be added or modified by plug-ins to
             * generate suitable mark-up for a site. For example the Bootstrap
             * integration plug-in for DataTables uses a paging button renderer to
             * display pagination buttons in the mark-up required by Bootstrap.
             *
             * For further information about the renderers available see
             * DataTable.ext.renderer
             *  @type string|object
             *  @default null
             *
             *  @name DataTable.defaults.renderer
             *
             */
            "renderer": null,
        
        
            /**
             * Set the data property name that DataTables should use to get a row's id
             * to set as the `id` property in the node.
             *  @type string
             *  @default DT_RowId
             *
             *  @name DataTable.defaults.rowId
             */
            "rowId": "DT_RowId"
        };
        
        _fnHungarianMap( DataTable.defaults );
        
        
        
        /*
         * Developer note - See note in model.defaults.js about the use of Hungarian
         * notation and camel case.
         */
        
        /**
         * Column options that can be given to DataTables at initialisation time.
         *  @namespace
         */
        DataTable.defaults.column = {
            /**
             * Define which column(s) an order will occur on for this column. This
             * allows a column's ordering to take multiple columns into account when
             * doing a sort or use the data from a different column. For example first
             * name / last name columns make sense to do a multi-column sort over the
             * two columns.
             *  @type array|int
             *  @default null <i>Takes the value of the column index automatically</i>
             *
             *  @name DataTable.defaults.column.orderData
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "orderData": [ 0, 1 ], "targets": [ 0 ] },
             *          { "orderData": [ 1, 0 ], "targets": [ 1 ] },
             *          { "orderData": 2, "targets": [ 2 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "orderData": [ 0, 1 ] },
             *          { "orderData": [ 1, 0 ] },
             *          { "orderData": 2 },
             *          null,
             *          null
             *        ]
             *      } );
             *    } );
             */
            "aDataSort": null,
            "iDataSort": -1,
        
        
            /**
             * You can control the default ordering direction, and even alter the
             * behaviour of the sort handler (i.e. only allow ascending ordering etc)
             * using this parameter.
             *  @type array
             *  @default [ 'asc', 'desc' ]
             *
             *  @name DataTable.defaults.column.orderSequence
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "orderSequence": [ "asc" ], "targets": [ 1 ] },
             *          { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] },
             *          { "orderSequence": [ "desc" ], "targets": [ 3 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          null,
             *          { "orderSequence": [ "asc" ] },
             *          { "orderSequence": [ "desc", "asc", "asc" ] },
             *          { "orderSequence": [ "desc" ] },
             *          null
             *        ]
             *      } );
             *    } );
             */
            "asSorting": [ 'asc', 'desc' ],
        
        
            /**
             * Enable or disable filtering on the data in this column.
             *  @type boolean
             *  @default true
             *
             *  @name DataTable.defaults.column.searchable
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "searchable": false, "targets": [ 0 ] }
             *        ] } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "searchable": false },
             *          null,
             *          null,
             *          null,
             *          null
             *        ] } );
             *    } );
             */
            "bSearchable": true,
        
        
            /**
             * Enable or disable ordering on this column.
             *  @type boolean
             *  @default true
             *
             *  @name DataTable.defaults.column.orderable
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "orderable": false, "targets": [ 0 ] }
             *        ] } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "orderable": false },
             *          null,
             *          null,
             *          null,
             *          null
             *        ] } );
             *    } );
             */
            "bSortable": true,
        
        
            /**
             * Enable or disable the display of this column.
             *  @type boolean
             *  @default true
             *
             *  @name DataTable.defaults.column.visible
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "visible": false, "targets": [ 0 ] }
             *        ] } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "visible": false },
             *          null,
             *          null,
             *          null,
             *          null
             *        ] } );
             *    } );
             */
            "bVisible": true,
        
        
            /**
             * Developer definable function that is called whenever a cell is created (Ajax source,
             * etc) or processed for input (DOM source). This can be used as a compliment to mRender
             * allowing you to modify the DOM element (add background colour for example) when the
             * element is available.
             *  @type function
             *  @param {element} td The TD node that has been created
             *  @param {*} cellData The Data for the cell
             *  @param {array|object} rowData The data for the whole row
             *  @param {int} row The row index for the aoData data store
             *  @param {int} col The column index for aoColumns
             *
             *  @name DataTable.defaults.column.createdCell
             *  @dtopt Columns
             *
             *  @example
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [3],
             *          "createdCell": function (td, cellData, rowData, row, col) {
             *            if ( cellData == "1.7" ) {
             *              $(td).css('color', 'blue')
             *            }
             *          }
             *        } ]
             *      });
             *    } );
             */
            "fnCreatedCell": null,
        
        
            /**
             * This parameter has been replaced by `data` in DataTables to ensure naming
             * consistency. `dataProp` can still be used, as there is backwards
             * compatibility in DataTables for this option, but it is strongly
             * recommended that you use `data` in preference to `dataProp`.
             *  @name DataTable.defaults.column.dataProp
             */
        
        
            /**
             * This property can be used to read data from any data source property,
             * including deeply nested objects / properties. `data` can be given in a
             * number of different ways which effect its behaviour:
             *
             * * `integer` - treated as an array index for the data source. This is the
             *   default that DataTables uses (incrementally increased for each column).
             * * `string` - read an object property from the data source. There are
             *   three 'special' options that can be used in the string to alter how
             *   DataTables reads the data from the source object:
             *    * `.` - Dotted Javascript notation. Just as you use a `.` in
             *      Javascript to read from nested objects, so to can the options
             *      specified in `data`. For example: `browser.version` or
             *      `browser.name`. If your object parameter name contains a period, use
             *      `\\` to escape it - i.e. `first\\.name`.
             *    * `[]` - Array notation. DataTables can automatically combine data
             *      from and array source, joining the data with the characters provided
             *      between the two brackets. For example: `name[, ]` would provide a
             *      comma-space separated list from the source array. If no characters
             *      are provided between the brackets, the original array source is
             *      returned.
             *    * `()` - Function notation. Adding `()` to the end of a parameter will
             *      execute a function of the name given. For example: `browser()` for a
             *      simple function on the data source, `browser.version()` for a
             *      function in a nested property or even `browser().version` to get an
             *      object property if the function called returns an object. Note that
             *      function notation is recommended for use in `render` rather than
             *      `data` as it is much simpler to use as a renderer.
             * * `null` - use the original data source for the row rather than plucking
             *   data directly from it. This action has effects on two other
             *   initialisation options:
             *    * `defaultContent` - When null is given as the `data` option and
             *      `defaultContent` is specified for the column, the value defined by
             *      `defaultContent` will be used for the cell.
             *    * `render` - When null is used for the `data` option and the `render`
             *      option is specified for the column, the whole data source for the
             *      row is used for the renderer.
             * * `function` - the function given will be executed whenever DataTables
             *   needs to set or get the data for a cell in the column. The function
             *   takes three parameters:
             *    * Parameters:
             *      * `{array|object}` The data source for the row
             *      * `{string}` The type call data requested - this will be 'set' when
             *        setting data or 'filter', 'display', 'type', 'sort' or undefined
             *        when gathering data. Note that when `undefined` is given for the
             *        type DataTables expects to get the raw data for the object back<
             *      * `{*}` Data to set when the second parameter is 'set'.
             *    * Return:
             *      * The return value from the function is not required when 'set' is
             *        the type of call, but otherwise the return is what will be used
             *        for the data requested.
             *
             * Note that `data` is a getter and setter option. If you just require
             * formatting of data for output, you will likely want to use `render` which
             * is simply a getter and thus simpler to use.
             *
             * Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The
             * name change reflects the flexibility of this property and is consistent
             * with the naming of mRender. If 'mDataProp' is given, then it will still
             * be used by DataTables, as it automatically maps the old name to the new
             * if required.
             *
             *  @type string|int|function|null
             *  @default null <i>Use automatically calculated column index</i>
             *
             *  @name DataTable.defaults.column.data
             *  @dtopt Columns
             *
             *  @example
             *    // Read table data from objects
             *    // JSON structure for each row:
             *    //   {
             *    //      "engine": {value},
             *    //      "browser": {value},
             *    //      "platform": {value},
             *    //      "version": {value},
             *    //      "grade": {value}
             *    //   }
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "ajaxSource": "sources/objects.txt",
             *        "columns": [
             *          { "data": "engine" },
             *          { "data": "browser" },
             *          { "data": "platform" },
             *          { "data": "version" },
             *          { "data": "grade" }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Read information from deeply nested objects
             *    // JSON structure for each row:
             *    //   {
             *    //      "engine": {value},
             *    //      "browser": {value},
             *    //      "platform": {
             *    //         "inner": {value}
             *    //      },
             *    //      "details": [
             *    //         {value}, {value}
             *    //      ]
             *    //   }
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "ajaxSource": "sources/deep.txt",
             *        "columns": [
             *          { "data": "engine" },
             *          { "data": "browser" },
             *          { "data": "platform.inner" },
             *          { "data": "platform.details.0" },
             *          { "data": "platform.details.1" }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `data` as a function to provide different information for
             *    // sorting, filtering and display. In this case, currency (price)
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [ 0 ],
             *          "data": function ( source, type, val ) {
             *            if (type === 'set') {
             *              source.price = val;
             *              // Store the computed dislay and filter values for efficiency
             *              source.price_display = val=="" ? "" : "$"+numberFormat(val);
             *              source.price_filter  = val=="" ? "" : "$"+numberFormat(val)+" "+val;
             *              return;
             *            }
             *            else if (type === 'display') {
             *              return source.price_display;
             *            }
             *            else if (type === 'filter') {
             *              return source.price_filter;
             *            }
             *            // 'sort', 'type' and undefined all just use the integer
             *            return source.price;
             *          }
             *        } ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using default content
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [ 0 ],
             *          "data": null,
             *          "defaultContent": "Click to edit"
             *        } ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using array notation - outputting a list from an array
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [ 0 ],
             *          "data": "name[, ]"
             *        } ]
             *      } );
             *    } );
             *
             */
            "mData": null,
        
        
            /**
             * This property is the rendering partner to `data` and it is suggested that
             * when you want to manipulate data for display (including filtering,
             * sorting etc) without altering the underlying data for the table, use this
             * property. `render` can be considered to be the the read only companion to
             * `data` which is read / write (then as such more complex). Like `data`
             * this option can be given in a number of different ways to effect its
             * behaviour:
             *
             * * `integer` - treated as an array index for the data source. This is the
             *   default that DataTables uses (incrementally increased for each column).
             * * `string` - read an object property from the data source. There are
             *   three 'special' options that can be used in the string to alter how
             *   DataTables reads the data from the source object:
             *    * `.` - Dotted Javascript notation. Just as you use a `.` in
             *      Javascript to read from nested objects, so to can the options
             *      specified in `data`. For example: `browser.version` or
             *      `browser.name`. If your object parameter name contains a period, use
             *      `\\` to escape it - i.e. `first\\.name`.
             *    * `[]` - Array notation. DataTables can automatically combine data
             *      from and array source, joining the data with the characters provided
             *      between the two brackets. For example: `name[, ]` would provide a
             *      comma-space separated list from the source array. If no characters
             *      are provided between the brackets, the original array source is
             *      returned.
             *    * `()` - Function notation. Adding `()` to the end of a parameter will
             *      execute a function of the name given. For example: `browser()` for a
             *      simple function on the data source, `browser.version()` for a
             *      function in a nested property or even `browser().version` to get an
             *      object property if the function called returns an object.
             * * `object` - use different data for the different data types requested by
             *   DataTables ('filter', 'display', 'type' or 'sort'). The property names
             *   of the object is the data type the property refers to and the value can
             *   defined using an integer, string or function using the same rules as
             *   `render` normally does. Note that an `_` option _must_ be specified.
             *   This is the default value to use if you haven't specified a value for
             *   the data type requested by DataTables.
             * * `function` - the function given will be executed whenever DataTables
             *   needs to set or get the data for a cell in the column. The function
             *   takes three parameters:
             *    * Parameters:
             *      * {array|object} The data source for the row (based on `data`)
             *      * {string} The type call data requested - this will be 'filter',
             *        'display', 'type' or 'sort'.
             *      * {array|object} The full data source for the row (not based on
             *        `data`)
             *    * Return:
             *      * The return value from the function is what will be used for the
             *        data requested.
             *
             *  @type string|int|function|object|null
             *  @default null Use the data source value.
             *
             *  @name DataTable.defaults.column.render
             *  @dtopt Columns
             *
             *  @example
             *    // Create a comma separated list from an array of objects
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "ajaxSource": "sources/deep.txt",
             *        "columns": [
             *          { "data": "engine" },
             *          { "data": "browser" },
             *          {
             *            "data": "platform",
             *            "render": "[, ].name"
             *          }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Execute a function to obtain data
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [ 0 ],
             *          "data": null, // Use the full data source object for the renderer's source
             *          "render": "browserName()"
             *        } ]
             *      } );
             *    } );
             *
             *  @example
             *    // As an object, extracting different data for the different types
             *    // This would be used with a data source such as:
             *    //   { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" }
             *    // Here the `phone` integer is used for sorting and type detection, while `phone_filter`
             *    // (which has both forms) is used for filtering for if a user inputs either format, while
             *    // the formatted phone number is the one that is shown in the table.
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [ 0 ],
             *          "data": null, // Use the full data source object for the renderer's source
             *          "render": {
             *            "_": "phone",
             *            "filter": "phone_filter",
             *            "display": "phone_display"
             *          }
             *        } ]
             *      } );
             *    } );
             *
             *  @example
             *    // Use as a function to create a link from the data source
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [ 0 ],
             *          "data": "download_link",
             *          "render": function ( data, type, full ) {
             *            return '<a href="'+data+'">Download</a>';
             *          }
             *        } ]
             *      } );
             *    } );
             */
            "mRender": null,
        
        
            /**
             * Change the cell type created for the column - either TD cells or TH cells. This
             * can be useful as TH cells have semantic meaning in the table body, allowing them
             * to act as a header for a row (you may wish to add scope='row' to the TH elements).
             *  @type string
             *  @default td
             *
             *  @name DataTable.defaults.column.cellType
             *  @dtopt Columns
             *
             *  @example
             *    // Make the first column use TH cells
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [ {
             *          "targets": [ 0 ],
             *          "cellType": "th"
             *        } ]
             *      } );
             *    } );
             */
            "sCellType": "td",
        
        
            /**
             * Class to give to each cell in this column.
             *  @type string
             *  @default <i>Empty string</i>
             *
             *  @name DataTable.defaults.column.class
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "class": "my_class", "targets": [ 0 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "class": "my_class" },
             *          null,
             *          null,
             *          null,
             *          null
             *        ]
             *      } );
             *    } );
             */
            "sClass": "",
        
            /**
             * When DataTables calculates the column widths to assign to each column,
             * it finds the longest string in each column and then constructs a
             * temporary table and reads the widths from that. The problem with this
             * is that "mmm" is much wider then "iiii", but the latter is a longer
             * string - thus the calculation can go wrong (doing it properly and putting
             * it into an DOM object and measuring that is horribly(!) slow). Thus as
             * a "work around" we provide this option. It will append its value to the
             * text that is found to be the longest string for the column - i.e. padding.
             * Generally you shouldn't need this!
             *  @type string
             *  @default <i>Empty string<i>
             *
             *  @name DataTable.defaults.column.contentPadding
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          null,
             *          null,
             *          null,
             *          {
             *            "contentPadding": "mmm"
             *          }
             *        ]
             *      } );
             *    } );
             */
            "sContentPadding": "",
        
        
            /**
             * Allows a default value to be given for a column's data, and will be used
             * whenever a null data source is encountered (this can be because `data`
             * is set to null, or because the data source itself is null).
             *  @type string
             *  @default null
             *
             *  @name DataTable.defaults.column.defaultContent
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          {
             *            "data": null,
             *            "defaultContent": "Edit",
             *            "targets": [ -1 ]
             *          }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          null,
             *          null,
             *          null,
             *          {
             *            "data": null,
             *            "defaultContent": "Edit"
             *          }
             *        ]
             *      } );
             *    } );
             */
            "sDefaultContent": null,
        
        
            /**
             * This parameter is only used in DataTables' server-side processing. It can
             * be exceptionally useful to know what columns are being displayed on the
             * client side, and to map these to database fields. When defined, the names
             * also allow DataTables to reorder information from the server if it comes
             * back in an unexpected order (i.e. if you switch your columns around on the
             * client-side, your server-side code does not also need updating).
             *  @type string
             *  @default <i>Empty string</i>
             *
             *  @name DataTable.defaults.column.name
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "name": "engine", "targets": [ 0 ] },
             *          { "name": "browser", "targets": [ 1 ] },
             *          { "name": "platform", "targets": [ 2 ] },
             *          { "name": "version", "targets": [ 3 ] },
             *          { "name": "grade", "targets": [ 4 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "name": "engine" },
             *          { "name": "browser" },
             *          { "name": "platform" },
             *          { "name": "version" },
             *          { "name": "grade" }
             *        ]
             *      } );
             *    } );
             */
            "sName": "",
        
        
            /**
             * Defines a data source type for the ordering which can be used to read
             * real-time information from the table (updating the internally cached
             * version) prior to ordering. This allows ordering to occur on user
             * editable elements such as form inputs.
             *  @type string
             *  @default std
             *
             *  @name DataTable.defaults.column.orderDataType
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "orderDataType": "dom-text", "targets": [ 2, 3 ] },
             *          { "type": "numeric", "targets": [ 3 ] },
             *          { "orderDataType": "dom-select", "targets": [ 4 ] },
             *          { "orderDataType": "dom-checkbox", "targets": [ 5 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          null,
             *          null,
             *          { "orderDataType": "dom-text" },
             *          { "orderDataType": "dom-text", "type": "numeric" },
             *          { "orderDataType": "dom-select" },
             *          { "orderDataType": "dom-checkbox" }
             *        ]
             *      } );
             *    } );
             */
            "sSortDataType": "std",
        
        
            /**
             * The title of this column.
             *  @type string
             *  @default null <i>Derived from the 'TH' value for this column in the
             *    original HTML table.</i>
             *
             *  @name DataTable.defaults.column.title
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "title": "My column title", "targets": [ 0 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "title": "My column title" },
             *          null,
             *          null,
             *          null,
             *          null
             *        ]
             *      } );
             *    } );
             */
            "sTitle": null,
        
        
            /**
             * The type allows you to specify how the data for this column will be
             * ordered. Four types (string, numeric, date and html (which will strip
             * HTML tags before ordering)) are currently available. Note that only date
             * formats understood by Javascript's Date() object will be accepted as type
             * date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string',
             * 'numeric', 'date' or 'html' (by default). Further types can be adding
             * through plug-ins.
             *  @type string
             *  @default null <i>Auto-detected from raw data</i>
             *
             *  @name DataTable.defaults.column.type
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "type": "html", "targets": [ 0 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "type": "html" },
             *          null,
             *          null,
             *          null,
             *          null
             *        ]
             *      } );
             *    } );
             */
            "sType": null,
        
        
            /**
             * Defining the width of the column, this parameter may take any CSS value
             * (3em, 20px etc). DataTables applies 'smart' widths to columns which have not
             * been given a specific width through this interface ensuring that the table
             * remains readable.
             *  @type string
             *  @default null <i>Automatic</i>
             *
             *  @name DataTable.defaults.column.width
             *  @dtopt Columns
             *
             *  @example
             *    // Using `columnDefs`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columnDefs": [
             *          { "width": "20%", "targets": [ 0 ] }
             *        ]
             *      } );
             *    } );
             *
             *  @example
             *    // Using `columns`
             *    $(document).ready( function() {
             *      $('#example').dataTable( {
             *        "columns": [
             *          { "width": "20%" },
             *          null,
             *          null,
             *          null,
             *          null
             *        ]
             *      } );
             *    } );
             */
            "sWidth": null
        };
        
        _fnHungarianMap( DataTable.defaults.column );
        
        
        
        /**
         * DataTables settings object - this holds all the information needed for a
         * given table, including configuration, data and current application of the
         * table options. DataTables does not have a single instance for each DataTable
         * with the settings attached to that instance, but rather instances of the
         * DataTable "class" are created on-the-fly as needed (typically by a
         * $().dataTable() call) and the settings object is then applied to that
         * instance.
         *
         * Note that this object is related to {@link DataTable.defaults} but this
         * one is the internal data store for DataTables's cache of columns. It should
         * NOT be manipulated outside of DataTables. Any configuration should be done
         * through the initialisation options.
         *  @namespace
         *  @todo Really should attach the settings object to individual instances so we
         *    don't need to create new instances on each $().dataTable() call (if the
         *    table already exists). It would also save passing oSettings around and
         *    into every single function. However, this is a very significant
         *    architecture change for DataTables and will almost certainly break
         *    backwards compatibility with older installations. This is something that
         *    will be done in 2.0.
         */
        DataTable.models.oSettings = {
            /**
             * Primary features of DataTables and their enablement state.
             *  @namespace
             */
            "oFeatures": {
        
                /**
                 * Flag to say if DataTables should automatically try to calculate the
                 * optimum table and columns widths (true) or not (false).
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bAutoWidth": null,
        
                /**
                 * Delay the creation of TR and TD elements until they are actually
                 * needed by a driven page draw. This can give a significant speed
                 * increase for Ajax source and Javascript source data, but makes no
                 * difference at all fro DOM and server-side processing tables.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bDeferRender": null,
        
                /**
                 * Enable filtering on the table or not. Note that if this is disabled
                 * then there is no filtering at all on the table, including fnFilter.
                 * To just remove the filtering input use sDom and remove the 'f' option.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bFilter": null,
        
                /**
                 * Table information element (the 'Showing x of y records' div) enable
                 * flag.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bInfo": null,
        
                /**
                 * Present a user control allowing the end user to change the page size
                 * when pagination is enabled.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bLengthChange": null,
        
                /**
                 * Pagination enabled or not. Note that if this is disabled then length
                 * changing must also be disabled.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bPaginate": null,
        
                /**
                 * Processing indicator enable flag whenever DataTables is enacting a
                 * user request - typically an Ajax request for server-side processing.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bProcessing": null,
        
                /**
                 * Server-side processing enabled flag - when enabled DataTables will
                 * get all data from the server for every draw - there is no filtering,
                 * sorting or paging done on the client-side.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bServerSide": null,
        
                /**
                 * Sorting enablement flag.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bSort": null,
        
                /**
                 * Multi-column sorting
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bSortMulti": null,
        
                /**
                 * Apply a class to the columns which are being sorted to provide a
                 * visual highlight or not. This can slow things down when enabled since
                 * there is a lot of DOM interaction.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bSortClasses": null,
        
                /**
                 * State saving enablement flag.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bStateSave": null
            },
        
        
            /**
             * Scrolling settings for a table.
             *  @namespace
             */
            "oScroll": {
                /**
                 * When the table is shorter in height than sScrollY, collapse the
                 * table container down to the height of the table (when true).
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type boolean
                 */
                "bCollapse": null,
        
                /**
                 * Width of the scrollbar for the web-browser's platform. Calculated
                 * during table initialisation.
                 *  @type int
                 *  @default 0
                 */
                "iBarWidth": 0,
        
                /**
                 * Viewport width for horizontal scrolling. Horizontal scrolling is
                 * disabled if an empty string.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type string
                 */
                "sX": null,
        
                /**
                 * Width to expand the table to when using x-scrolling. Typically you
                 * should not need to use this.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type string
                 *  @deprecated
                 */
                "sXInner": null,
        
                /**
                 * Viewport height for vertical scrolling. Vertical scrolling is disabled
                 * if an empty string.
                 * Note that this parameter will be set by the initialisation routine. To
                 * set a default use {@link DataTable.defaults}.
                 *  @type string
                 */
                "sY": null
            },
        
            /**
             * Language information for the table.
             *  @namespace
             *  @extends DataTable.defaults.oLanguage
             */
            "oLanguage": {
                /**
                 * Information callback function. See
                 * {@link DataTable.defaults.fnInfoCallback}
                 *  @type function
                 *  @default null
                 */
                "fnInfoCallback": null
            },
        
            /**
             * Browser support parameters
             *  @namespace
             */
            "oBrowser": {
                /**
                 * Indicate if the browser incorrectly calculates width:100% inside a
                 * scrolling element (IE6/7)
                 *  @type boolean
                 *  @default false
                 */
                "bScrollOversize": false,
        
                /**
                 * Determine if the vertical scrollbar is on the right or left of the
                 * scrolling container - needed for rtl language layout, although not
                 * all browsers move the scrollbar (Safari).
                 *  @type boolean
                 *  @default false
                 */
                "bScrollbarLeft": false,
        
                /**
                 * Flag for if `getBoundingClientRect` is fully supported or not
                 *  @type boolean
                 *  @default false
                 */
                "bBounding": false,
        
                /**
                 * Browser scrollbar width
                 *  @type integer
                 *  @default 0
                 */
                "barWidth": 0
            },
        
        
            "ajax": null,
        
        
            /**
             * Array referencing the nodes which are used for the features. The
             * parameters of this object match what is allowed by sDom - i.e.
             *   <ul>
             *     <li>'l' - Length changing</li>
             *     <li>'f' - Filtering input</li>
             *     <li>'t' - The table!</li>
             *     <li>'i' - Information</li>
             *     <li>'p' - Pagination</li>
             *     <li>'r' - pRocessing</li>
             *   </ul>
             *  @type array
             *  @default []
             */
            "aanFeatures": [],
        
            /**
             * Store data information - see {@link DataTable.models.oRow} for detailed
             * information.
             *  @type array
             *  @default []
             */
            "aoData": [],
        
            /**
             * Array of indexes which are in the current display (after filtering etc)
             *  @type array
             *  @default []
             */
            "aiDisplay": [],
        
            /**
             * Array of indexes for display - no filtering
             *  @type array
             *  @default []
             */
            "aiDisplayMaster": [],
        
            /**
             * Map of row ids to data indexes
             *  @type object
             *  @default {}
             */
            "aIds": {},
        
            /**
             * Store information about each column that is in use
             *  @type array
             *  @default []
             */
            "aoColumns": [],
        
            /**
             * Store information about the table's header
             *  @type array
             *  @default []
             */
            "aoHeader": [],
        
            /**
             * Store information about the table's footer
             *  @type array
             *  @default []
             */
            "aoFooter": [],
        
            /**
             * Store the applied global search information in case we want to force a
             * research or compare the old search to a new one.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @namespace
             *  @extends DataTable.models.oSearch
             */
            "oPreviousSearch": {},
        
            /**
             * Store the applied search for each column - see
             * {@link DataTable.models.oSearch} for the format that is used for the
             * filtering information for each column.
             *  @type array
             *  @default []
             */
            "aoPreSearchCols": [],
        
            /**
             * Sorting that is applied to the table. Note that the inner arrays are
             * used in the following manner:
             * <ul>
             *   <li>Index 0 - column number</li>
             *   <li>Index 1 - current sorting direction</li>
             * </ul>
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type array
             *  @todo These inner arrays should really be objects
             */
            "aaSorting": null,
        
            /**
             * Sorting that is always applied to the table (i.e. prefixed in front of
             * aaSorting).
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type array
             *  @default []
             */
            "aaSortingFixed": [],
        
            /**
             * Classes to use for the striping of a table.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type array
             *  @default []
             */
            "asStripeClasses": null,
        
            /**
             * If restoring a table - we should restore its striping classes as well
             *  @type array
             *  @default []
             */
            "asDestroyStripes": [],
        
            /**
             * If restoring a table - we should restore its width
             *  @type int
             *  @default 0
             */
            "sDestroyWidth": 0,
        
            /**
             * Callback functions array for every time a row is inserted (i.e. on a draw).
             *  @type array
             *  @default []
             */
            "aoRowCallback": [],
        
            /**
             * Callback functions for the header on each draw.
             *  @type array
             *  @default []
             */
            "aoHeaderCallback": [],
        
            /**
             * Callback function for the footer on each draw.
             *  @type array
             *  @default []
             */
            "aoFooterCallback": [],
        
            /**
             * Array of callback functions for draw callback functions
             *  @type array
             *  @default []
             */
            "aoDrawCallback": [],
        
            /**
             * Array of callback functions for row created function
             *  @type array
             *  @default []
             */
            "aoRowCreatedCallback": [],
        
            /**
             * Callback functions for just before the table is redrawn. A return of
             * false will be used to cancel the draw.
             *  @type array
             *  @default []
             */
            "aoPreDrawCallback": [],
        
            /**
             * Callback functions for when the table has been initialised.
             *  @type array
             *  @default []
             */
            "aoInitComplete": [],
        
        
            /**
             * Callbacks for modifying the settings to be stored for state saving, prior to
             * saving state.
             *  @type array
             *  @default []
             */
            "aoStateSaveParams": [],
        
            /**
             * Callbacks for modifying the settings that have been stored for state saving
             * prior to using the stored values to restore the state.
             *  @type array
             *  @default []
             */
            "aoStateLoadParams": [],
        
            /**
             * Callbacks for operating on the settings object once the saved state has been
             * loaded
             *  @type array
             *  @default []
             */
            "aoStateLoaded": [],
        
            /**
             * Cache the table ID for quick access
             *  @type string
             *  @default <i>Empty string</i>
             */
            "sTableId": "",
        
            /**
             * The TABLE node for the main table
             *  @type node
             *  @default null
             */
            "nTable": null,
        
            /**
             * Permanent ref to the thead element
             *  @type node
             *  @default null
             */
            "nTHead": null,
        
            /**
             * Permanent ref to the tfoot element - if it exists
             *  @type node
             *  @default null
             */
            "nTFoot": null,
        
            /**
             * Permanent ref to the tbody element
             *  @type node
             *  @default null
             */
            "nTBody": null,
        
            /**
             * Cache the wrapper node (contains all DataTables controlled elements)
             *  @type node
             *  @default null
             */
            "nTableWrapper": null,
        
            /**
             * Indicate if when using server-side processing the loading of data
             * should be deferred until the second draw.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type boolean
             *  @default false
             */
            "bDeferLoading": false,
        
            /**
             * Indicate if all required information has been read in
             *  @type boolean
             *  @default false
             */
            "bInitialised": false,
        
            /**
             * Information about open rows. Each object in the array has the parameters
             * 'nTr' and 'nParent'
             *  @type array
             *  @default []
             */
            "aoOpenRows": [],
        
            /**
             * Dictate the positioning of DataTables' control elements - see
             * {@link DataTable.model.oInit.sDom}.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type string
             *  @default null
             */
            "sDom": null,
        
            /**
             * Search delay (in mS)
             *  @type integer
             *  @default null
             */
            "searchDelay": null,
        
            /**
             * Which type of pagination should be used.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type string
             *  @default two_button
             */
            "sPaginationType": "two_button",
        
            /**
             * The state duration (for `stateSave`) in seconds.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type int
             *  @default 0
             */
            "iStateDuration": 0,
        
            /**
             * Array of callback functions for state saving. Each array element is an
             * object with the following parameters:
             *   <ul>
             *     <li>function:fn - function to call. Takes two parameters, oSettings
             *       and the JSON string to save that has been thus far created. Returns
             *       a JSON string to be inserted into a json object
             *       (i.e. '"param": [ 0, 1, 2]')</li>
             *     <li>string:sName - name of callback</li>
             *   </ul>
             *  @type array
             *  @default []
             */
            "aoStateSave": [],
        
            /**
             * Array of callback functions for state loading. Each array element is an
             * object with the following parameters:
             *   <ul>
             *     <li>function:fn - function to call. Takes two parameters, oSettings
             *       and the object stored. May return false to cancel state loading</li>
             *     <li>string:sName - name of callback</li>
             *   </ul>
             *  @type array
             *  @default []
             */
            "aoStateLoad": [],
        
            /**
             * State that was saved. Useful for back reference
             *  @type object
             *  @default null
             */
            "oSavedState": null,
        
            /**
             * State that was loaded. Useful for back reference
             *  @type object
             *  @default null
             */
            "oLoadedState": null,
        
            /**
             * Source url for AJAX data for the table.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type string
             *  @default null
             */
            "sAjaxSource": null,
        
            /**
             * Property from a given object from which to read the table data from. This
             * can be an empty string (when not server-side processing), in which case
             * it is  assumed an an array is given directly.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type string
             */
            "sAjaxDataProp": null,
        
            /**
             * Note if draw should be blocked while getting data
             *  @type boolean
             *  @default true
             */
            "bAjaxDataGet": true,
        
            /**
             * The last jQuery XHR object that was used for server-side data gathering.
             * This can be used for working with the XHR information in one of the
             * callbacks
             *  @type object
             *  @default null
             */
            "jqXHR": null,
        
            /**
             * JSON returned from the server in the last Ajax request
             *  @type object
             *  @default undefined
             */
            "json": undefined,
        
            /**
             * Data submitted as part of the last Ajax request
             *  @type object
             *  @default undefined
             */
            "oAjaxData": undefined,
        
            /**
             * Function to get the server-side data.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type function
             */
            "fnServerData": null,
        
            /**
             * Functions which are called prior to sending an Ajax request so extra
             * parameters can easily be sent to the server
             *  @type array
             *  @default []
             */
            "aoServerParams": [],
        
            /**
             * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
             * required).
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type string
             */
            "sServerMethod": null,
        
            /**
             * Format numbers for display.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type function
             */
            "fnFormatNumber": null,
        
            /**
             * List of options that can be used for the user selectable length menu.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type array
             *  @default []
             */
            "aLengthMenu": null,
        
            /**
             * Counter for the draws that the table does. Also used as a tracker for
             * server-side processing
             *  @type int
             *  @default 0
             */
            "iDraw": 0,
        
            /**
             * Indicate if a redraw is being done - useful for Ajax
             *  @type boolean
             *  @default false
             */
            "bDrawing": false,
        
            /**
             * Draw index (iDraw) of the last error when parsing the returned data
             *  @type int
             *  @default -1
             */
            "iDrawError": -1,
        
            /**
             * Paging display length
             *  @type int
             *  @default 10
             */
            "_iDisplayLength": 10,
        
            /**
             * Paging start point - aiDisplay index
             *  @type int
             *  @default 0
             */
            "_iDisplayStart": 0,
        
            /**
             * Server-side processing - number of records in the result set
             * (i.e. before filtering), Use fnRecordsTotal rather than
             * this property to get the value of the number of records, regardless of
             * the server-side processing setting.
             *  @type int
             *  @default 0
             *  @private
             */
            "_iRecordsTotal": 0,
        
            /**
             * Server-side processing - number of records in the current display set
             * (i.e. after filtering). Use fnRecordsDisplay rather than
             * this property to get the value of the number of records, regardless of
             * the server-side processing setting.
             *  @type boolean
             *  @default 0
             *  @private
             */
            "_iRecordsDisplay": 0,
        
            /**
             * Flag to indicate if jQuery UI marking and classes should be used.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type boolean
             */
            "bJUI": null,
        
            /**
             * The classes to use for the table
             *  @type object
             *  @default {}
             */
            "oClasses": {},
        
            /**
             * Flag attached to the settings object so you can check in the draw
             * callback if filtering has been done in the draw. Deprecated in favour of
             * events.
             *  @type boolean
             *  @default false
             *  @deprecated
             */
            "bFiltered": false,
        
            /**
             * Flag attached to the settings object so you can check in the draw
             * callback if sorting has been done in the draw. Deprecated in favour of
             * events.
             *  @type boolean
             *  @default false
             *  @deprecated
             */
            "bSorted": false,
        
            /**
             * Indicate that if multiple rows are in the header and there is more than
             * one unique cell per column, if the top one (true) or bottom one (false)
             * should be used for sorting / title by DataTables.
             * Note that this parameter will be set by the initialisation routine. To
             * set a default use {@link DataTable.defaults}.
             *  @type boolean
             */
            "bSortCellsTop": null,
        
            /**
             * Initialisation object that is used for the table
             *  @type object
             *  @default null
             */
            "oInit": null,
        
            /**
             * Destroy callback functions - for plug-ins to attach themselves to the
             * destroy so they can clean up markup and events.
             *  @type array
             *  @default []
             */
            "aoDestroyCallback": [],
        
        
            /**
             * Get the number of records in the current record set, before filtering
             *  @type function
             */
            "fnRecordsTotal": function ()
            {
                return _fnDataSource( this ) == 'ssp' ?
                    this._iRecordsTotal * 1 :
                    this.aiDisplayMaster.length;
            },
        
            /**
             * Get the number of records in the current record set, after filtering
             *  @type function
             */
            "fnRecordsDisplay": function ()
            {
                return _fnDataSource( this ) == 'ssp' ?
                    this._iRecordsDisplay * 1 :
                    this.aiDisplay.length;
            },
        
            /**
             * Get the display end point - aiDisplay index
             *  @type function
             */
            "fnDisplayEnd": function ()
            {
                var
                    len      = this._iDisplayLength,
                    start    = this._iDisplayStart,
                    calc     = start + len,
                    records  = this.aiDisplay.length,
                    features = this.oFeatures,
                    paginate = features.bPaginate;
        
                if ( features.bServerSide ) {
                    return paginate === false || len === -1 ?
                        start + records :
                        Math.min( start+len, this._iRecordsDisplay );
                }
                else {
                    return ! paginate || calc>records || len===-1 ?
                        records :
                        calc;
                }
            },
        
            /**
             * The DataTables object for this table
             *  @type object
             *  @default null
             */
            "oInstance": null,
        
            /**
             * Unique identifier for each instance of the DataTables object. If there
             * is an ID on the table node, then it takes that value, otherwise an
             * incrementing internal counter is used.
             *  @type string
             *  @default null
             */
            "sInstance": null,
        
            /**
             * tabindex attribute value that is added to DataTables control elements, allowing
             * keyboard navigation of the table and its controls.
             */
            "iTabIndex": 0,
        
            /**
             * DIV container for the footer scrolling table if scrolling
             */
            "nScrollHead": null,
        
            /**
             * DIV container for the footer scrolling table if scrolling
             */
            "nScrollFoot": null,
        
            /**
             * Last applied sort
             *  @type array
             *  @default []
             */
            "aLastSort": [],
        
            /**
             * Stored plug-in instances
             *  @type object
             *  @default {}
             */
            "oPlugins": {},
        
            /**
             * Function used to get a row's id from the row's data
             *  @type function
             *  @default null
             */
            "rowIdFn": null,
        
            /**
             * Data location where to store a row's id
             *  @type string
             *  @default null
             */
            "rowId": null
        };
    
        /**
         * Extension object for DataTables that is used to provide all extension
         * options.
         *
         * Note that the `DataTable.ext` object is available through
         * `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is
         * also aliased to `jQuery.fn.dataTableExt` for historic reasons.
         *  @namespace
         *  @extends DataTable.models.ext
         */
        
        
        /**
         * DataTables extensions
         * 
         * This namespace acts as a collection area for plug-ins that can be used to
         * extend DataTables capabilities. Indeed many of the build in methods
         * use this method to provide their own capabilities (sorting methods for
         * example).
         *
         * Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy
         * reasons
         *
         *  @namespace
         */
        DataTable.ext = _ext = {
            /**
             * Buttons. For use with the Buttons extension for DataTables. This is
             * defined here so other extensions can define buttons regardless of load
             * order. It is _not_ used by DataTables core.
             *
             *  @type object
             *  @default {}
             */
            buttons: {},
        
        
            /**
             * Element class names
             *
             *  @type object
             *  @default {}
             */
            classes: {},
        
        
            /**
             * DataTables build type (expanded by the download builder)
             *
             *  @type string
             */
            builder: "-source-",
        
        
            /**
             * Error reporting.
             * 
             * How should DataTables report an error. Can take the value 'alert',
             * 'throw', 'none' or a function.
             *
             *  @type string|function
             *  @default alert
             */
            errMode: "alert",
        
        
            /**
             * Feature plug-ins.
             * 
             * This is an array of objects which describe the feature plug-ins that are
             * available to DataTables. These feature plug-ins are then available for
             * use through the `dom` initialisation option.
             * 
             * Each feature plug-in is described by an object which must have the
             * following properties:
             * 
             * * `fnInit` - function that is used to initialise the plug-in,
             * * `cFeature` - a character so the feature can be enabled by the `dom`
             *   instillation option. This is case sensitive.
             *
             * The `fnInit` function has the following input parameters:
             *
             * 1. `{object}` DataTables settings object: see
             *    {@link DataTable.models.oSettings}
             *
             * And the following return is expected:
             * 
             * * {node|null} The element which contains your feature. Note that the
             *   return may also be void if your plug-in does not require to inject any
             *   DOM elements into DataTables control (`dom`) - for example this might
             *   be useful when developing a plug-in which allows table control via
             *   keyboard entry
             *
             *  @type array
             *
             *  @example
             *    $.fn.dataTable.ext.features.push( {
             *      "fnInit": function( oSettings ) {
             *        return new TableTools( { "oDTSettings": oSettings } );
             *      },
             *      "cFeature": "T"
             *    } );
             */
            feature: [],
        
        
            /**
             * Row searching.
             * 
             * This method of searching is complimentary to the default type based
             * searching, and a lot more comprehensive as it allows you complete control
             * over the searching logic. Each element in this array is a function
             * (parameters described below) that is called for every row in the table,
             * and your logic decides if it should be included in the searching data set
             * or not.
             *
             * Searching functions have the following input parameters:
             *
             * 1. `{object}` DataTables settings object: see
             *    {@link DataTable.models.oSettings}
             * 2. `{array|object}` Data for the row to be processed (same as the
             *    original format that was passed in as the data source, or an array
             *    from a DOM data source
             * 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which
             *    can be useful to retrieve the `TR` element if you need DOM interaction.
             *
             * And the following return is expected:
             *
             * * {boolean} Include the row in the searched result set (true) or not
             *   (false)
             *
             * Note that as with the main search ability in DataTables, technically this
             * is "filtering", since it is subtractive. However, for consistency in
             * naming we call it searching here.
             *
             *  @type array
             *  @default []
             *
             *  @example
             *    // The following example shows custom search being applied to the
             *    // fourth column (i.e. the data[3] index) based on two input values
             *    // from the end-user, matching the data in a certain range.
             *    $.fn.dataTable.ext.search.push(
             *      function( settings, data, dataIndex ) {
             *        var min = document.getElementById('min').value * 1;
             *        var max = document.getElementById('max').value * 1;
             *        var version = data[3] == "-" ? 0 : data[3]*1;
             *
             *        if ( min == "" && max == "" ) {
             *          return true;
             *        }
             *        else if ( min == "" && version < max ) {
             *          return true;
             *        }
             *        else if ( min < version && "" == max ) {
             *          return true;
             *        }
             *        else if ( min < version && version < max ) {
             *          return true;
             *        }
             *        return false;
             *      }
             *    );
             */
            search: [],
        
        
            /**
             * Selector extensions
             *
             * The `selector` option can be used to extend the options available for the
             * selector modifier options (`selector-modifier` object data type) that
             * each of the three built in selector types offer (row, column and cell +
             * their plural counterparts). For example the Select extension uses this
             * mechanism to provide an option to select only rows, columns and cells
             * that have been marked as selected by the end user (`{selected: true}`),
             * which can be used in conjunction with the existing built in selector
             * options.
             *
             * Each property is an array to which functions can be pushed. The functions
             * take three attributes:
             *
             * * Settings object for the host table
             * * Options object (`selector-modifier` object type)
             * * Array of selected item indexes
             *
             * The return is an array of the resulting item indexes after the custom
             * selector has been applied.
             *
             *  @type object
             */
            selector: {
                cell: [],
                column: [],
                row: []
            },
        
        
            /**
             * Internal functions, exposed for used in plug-ins.
             * 
             * Please note that you should not need to use the internal methods for
             * anything other than a plug-in (and even then, try to avoid if possible).
             * The internal function may change between releases.
             *
             *  @type object
             *  @default {}
             */
            internal: {},
        
        
            /**
             * Legacy configuration options. Enable and disable legacy options that
             * are available in DataTables.
             *
             *  @type object
             */
            legacy: {
                /**
                 * Enable / disable DataTables 1.9 compatible server-side processing
                 * requests
                 *
                 *  @type boolean
                 *  @default null
                 */
                ajax: null
            },
        
        
            /**
             * Pagination plug-in methods.
             * 
             * Each entry in this object is a function and defines which buttons should
             * be shown by the pagination rendering method that is used for the table:
             * {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the
             * buttons are displayed in the document, while the functions here tell it
             * what buttons to display. This is done by returning an array of button
             * descriptions (what each button will do).
             *
             * Pagination types (the four built in options and any additional plug-in
             * options defined here) can be used through the `paginationType`
             * initialisation parameter.
             *
             * The functions defined take two parameters:
             *
             * 1. `{int} page` The current page index
             * 2. `{int} pages` The number of pages in the table
             *
             * Each function is expected to return an array where each element of the
             * array can be one of:
             *
             * * `first` - Jump to first page when activated
             * * `last` - Jump to last page when activated
             * * `previous` - Show previous page when activated
             * * `next` - Show next page when activated
             * * `{int}` - Show page of the index given
             * * `{array}` - A nested array containing the above elements to add a
             *   containing 'DIV' element (might be useful for styling).
             *
             * Note that DataTables v1.9- used this object slightly differently whereby
             * an object with two functions would be defined for each plug-in. That
             * ability is still supported by DataTables 1.10+ to provide backwards
             * compatibility, but this option of use is now decremented and no longer
             * documented in DataTables 1.10+.
             *
             *  @type object
             *  @default {}
             *
             *  @example
             *    // Show previous, next and current page buttons only
             *    $.fn.dataTableExt.oPagination.current = function ( page, pages ) {
             *      return [ 'previous', page, 'next' ];
             *    };
             */
            pager: {},
        
        
            renderer: {
                pageButton: {},
                header: {}
            },
        
        
            /**
             * Ordering plug-ins - custom data source
             * 
             * The extension options for ordering of data available here is complimentary
             * to the default type based ordering that DataTables typically uses. It
             * allows much greater control over the the data that is being used to
             * order a column, but is necessarily therefore more complex.
             * 
             * This type of ordering is useful if you want to do ordering based on data
             * live from the DOM (for example the contents of an 'input' element) rather
             * than just the static string that DataTables knows of.
             * 
             * The way these plug-ins work is that you create an array of the values you
             * wish to be ordering for the column in question and then return that
             * array. The data in the array much be in the index order of the rows in
             * the table (not the currently ordering order!). Which order data gathering
             * function is run here depends on the `dt-init columns.orderDataType`
             * parameter that is used for the column (if any).
             *
             * The functions defined take two parameters:
             *
             * 1. `{object}` DataTables settings object: see
             *    {@link DataTable.models.oSettings}
             * 2. `{int}` Target column index
             *
             * Each function is expected to return an array:
             *
             * * `{array}` Data for the column to be ordering upon
             *
             *  @type array
             *
             *  @example
             *    // Ordering using `input` node values
             *    $.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
             *    {
             *      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
             *        return $('input', td).val();
             *      } );
             *    }
             */
            order: {},
        
        
            /**
             * Type based plug-ins.
             *
             * Each column in DataTables has a type assigned to it, either by automatic
             * detection or by direct assignment using the `type` option for the column.
             * The type of a column will effect how it is ordering and search (plug-ins
             * can also make use of the column type if required).
             *
             * @namespace
             */
            type: {
                /**
                 * Type detection functions.
                 *
                 * The functions defined in this object are used to automatically detect
                 * a column's type, making initialisation of DataTables super easy, even
                 * when complex data is in the table.
                 *
                 * The functions defined take two parameters:
                 *
                 *  1. `{*}` Data from the column cell to be analysed
                 *  2. `{settings}` DataTables settings object. This can be used to
                 *     perform context specific type detection - for example detection
                 *     based on language settings such as using a comma for a decimal
                 *     place. Generally speaking the options from the settings will not
                 *     be required
                 *
                 * Each function is expected to return:
                 *
                 * * `{string|null}` Data type detected, or null if unknown (and thus
                 *   pass it on to the other type detection functions.
                 *
                 *  @type array
                 *
                 *  @example
                 *    // Currency type detection plug-in:
                 *    $.fn.dataTable.ext.type.detect.push(
                 *      function ( data, settings ) {
                 *        // Check the numeric part
                 *        if ( ! $.isNumeric( data.substring(1) ) ) {
                 *          return null;
                 *        }
                 *
                 *        // Check prefixed by currency
                 *        if ( data.charAt(0) == '$' || data.charAt(0) == '&pound;' ) {
                 *          return 'currency';
                 *        }
                 *        return null;
                 *      }
                 *    );
                 */
                detect: [],
        
        
                /**
                 * Type based search formatting.
                 *
                 * The type based searching functions can be used to pre-format the
                 * data to be search on. For example, it can be used to strip HTML
                 * tags or to de-format telephone numbers for numeric only searching.
                 *
                 * Note that is a search is not defined for a column of a given type,
                 * no search formatting will be performed.
                 * 
                 * Pre-processing of searching data plug-ins - When you assign the sType
                 * for a column (or have it automatically detected for you by DataTables
                 * or a type detection plug-in), you will typically be using this for
                 * custom sorting, but it can also be used to provide custom searching
                 * by allowing you to pre-processing the data and returning the data in
                 * the format that should be searched upon. This is done by adding
                 * functions this object with a parameter name which matches the sType
                 * for that target column. This is the corollary of <i>afnSortData</i>
                 * for searching data.
                 *
                 * The functions defined take a single parameter:
                 *
                 *  1. `{*}` Data from the column cell to be prepared for searching
                 *
                 * Each function is expected to return:
                 *
                 * * `{string|null}` Formatted string that will be used for the searching.
                 *
                 *  @type object
                 *  @default {}
                 *
                 *  @example
                 *    $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
                 *      return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
                 *    }
                 */
                search: {},
        
        
                /**
                 * Type based ordering.
                 *
                 * The column type tells DataTables what ordering to apply to the table
                 * when a column is sorted upon. The order for each type that is defined,
                 * is defined by the functions available in this object.
                 *
                 * Each ordering option can be described by three properties added to
                 * this object:
                 *
                 * * `{type}-pre` - Pre-formatting function
                 * * `{type}-asc` - Ascending order function
                 * * `{type}-desc` - Descending order function
                 *
                 * All three can be used together, only `{type}-pre` or only
                 * `{type}-asc` and `{type}-desc` together. It is generally recommended
                 * that only `{type}-pre` is used, as this provides the optimal
                 * implementation in terms of speed, although the others are provided
                 * for compatibility with existing Javascript sort functions.
                 *
                 * `{type}-pre`: Functions defined take a single parameter:
                 *
                 *  1. `{*}` Data from the column cell to be prepared for ordering
                 *
                 * And return:
                 *
                 * * `{*}` Data to be sorted upon
                 *
                 * `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort
                 * functions, taking two parameters:
                 *
                 *  1. `{*}` Data to compare to the second parameter
                 *  2. `{*}` Data to compare to the first parameter
                 *
                 * And returning:
                 *
                 * * `{*}` Ordering match: <0 if first parameter should be sorted lower
                 *   than the second parameter, ===0 if the two parameters are equal and
                 *   >0 if the first parameter should be sorted height than the second
                 *   parameter.
                 * 
                 *  @type object
                 *  @default {}
                 *
                 *  @example
                 *    // Numeric ordering of formatted numbers with a pre-formatter
                 *    $.extend( $.fn.dataTable.ext.type.order, {
                 *      "string-pre": function(x) {
                 *        a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
                 *        return parseFloat( a );
                 *      }
                 *    } );
                 *
                 *  @example
                 *    // Case-sensitive string ordering, with no pre-formatting method
                 *    $.extend( $.fn.dataTable.ext.order, {
                 *      "string-case-asc": function(x,y) {
                 *        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
                 *      },
                 *      "string-case-desc": function(x,y) {
                 *        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
                 *      }
                 *    } );
                 */
                order: {}
            },
        
            /**
             * Unique DataTables instance counter
             *
             * @type int
             * @private
             */
            _unique: 0,
        
        
            //
            // Depreciated
            // The following properties are retained for backwards compatiblity only.
            // The should not be used in new projects and will be removed in a future
            // version
            //
        
            /**
             * Version check function.
             *  @type function
             *  @depreciated Since 1.10
             */
            fnVersionCheck: DataTable.fnVersionCheck,
        
        
            /**
             * Index for what 'this' index API functions should use
             *  @type int
             *  @deprecated Since v1.10
             */
            iApiIndex: 0,
        
        
            /**
             * jQuery UI class container
             *  @type object
             *  @deprecated Since v1.10
             */
            oJUIClasses: {},
        
        
            /**
             * Software version
             *  @type string
             *  @deprecated Since v1.10
             */
            sVersion: DataTable.version
        };
        
        
        //
        // Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts
        //
        $.extend( _ext, {
            afnFiltering: _ext.search,
            aTypes:       _ext.type.detect,
            ofnSearch:    _ext.type.search,
            oSort:        _ext.type.order,
            afnSortData:  _ext.order,
            aoFeatures:   _ext.feature,
            oApi:         _ext.internal,
            oStdClasses:  _ext.classes,
            oPagination:  _ext.pager
        } );
        
        
        $.extend( DataTable.ext.classes, {
            "sTable": "dataTable",
            "sNoFooter": "no-footer",
        
            /* Paging buttons */
            "sPageButton": "paginate_button",
            "sPageButtonActive": "current",
            "sPageButtonDisabled": "disabled",
        
            /* Striping classes */
            "sStripeOdd": "odd",
            "sStripeEven": "even",
        
            /* Empty row */
            "sRowEmpty": "dataTables_empty",
        
            /* Features */
            "sWrapper": "dataTables_wrapper",
            "sFilter": "dataTables_filter",
            "sInfo": "dataTables_info",
            "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
            "sLength": "dataTables_length",
            "sProcessing": "dataTables_processing",
        
            /* Sorting */
            "sSortAsc": "sorting_asc",
            "sSortDesc": "sorting_desc",
            "sSortable": "sorting", /* Sortable in both directions */
            "sSortableAsc": "sorting_asc_disabled",
            "sSortableDesc": "sorting_desc_disabled",
            "sSortableNone": "sorting_disabled",
            "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */
        
            /* Filtering */
            "sFilterInput": "",
        
            /* Page length */
            "sLengthSelect": "",
        
            /* Scrolling */
            "sScrollWrapper": "dataTables_scroll",
            "sScrollHead": "dataTables_scrollHead",
            "sScrollHeadInner": "dataTables_scrollHeadInner",
            "sScrollBody": "dataTables_scrollBody",
            "sScrollFoot": "dataTables_scrollFoot",
            "sScrollFootInner": "dataTables_scrollFootInner",
        
            /* Misc */
            "sHeaderTH": "",
            "sFooterTH": "",
        
            // Deprecated
            "sSortJUIAsc": "",
            "sSortJUIDesc": "",
            "sSortJUI": "",
            "sSortJUIAscAllowed": "",
            "sSortJUIDescAllowed": "",
            "sSortJUIWrapper": "",
            "sSortIcon": "",
            "sJUIHeader": "",
            "sJUIFooter": ""
        } );
        
        
        (function() {
        
        // Reused strings for better compression. Closure compiler appears to have a
        // weird edge case where it is trying to expand strings rather than use the
        // variable version. This results in about 200 bytes being added, for very
        // little preference benefit since it this run on script load only.
        var _empty = '';
        _empty = '';
        
        var _stateDefault = _empty + 'ui-state-default';
        var _sortIcon     = _empty + 'css_right ui-icon ui-icon-';
        var _headerFooter = _empty + 'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix';
        
        $.extend( DataTable.ext.oJUIClasses, DataTable.ext.classes, {
            /* Full numbers paging buttons */
            "sPageButton":         "fg-button ui-button "+_stateDefault,
            "sPageButtonActive":   "ui-state-disabled",
            "sPageButtonDisabled": "ui-state-disabled",
        
            /* Features */
            "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+
                "ui-buttonset-multi paging_", /* Note that the type is postfixed */
        
            /* Sorting */
            "sSortAsc":            _stateDefault+" sorting_asc",
            "sSortDesc":           _stateDefault+" sorting_desc",
            "sSortable":           _stateDefault+" sorting",
            "sSortableAsc":        _stateDefault+" sorting_asc_disabled",
            "sSortableDesc":       _stateDefault+" sorting_desc_disabled",
            "sSortableNone":       _stateDefault+" sorting_disabled",
            "sSortJUIAsc":         _sortIcon+"triangle-1-n",
            "sSortJUIDesc":        _sortIcon+"triangle-1-s",
            "sSortJUI":            _sortIcon+"carat-2-n-s",
            "sSortJUIAscAllowed":  _sortIcon+"carat-1-n",
            "sSortJUIDescAllowed": _sortIcon+"carat-1-s",
            "sSortJUIWrapper":     "DataTables_sort_wrapper",
            "sSortIcon":           "DataTables_sort_icon",
        
            /* Scrolling */
            "sScrollHead": "dataTables_scrollHead "+_stateDefault,
            "sScrollFoot": "dataTables_scrollFoot "+_stateDefault,
        
            /* Misc */
            "sHeaderTH":  _stateDefault,
            "sFooterTH":  _stateDefault,
            "sJUIHeader": _headerFooter+" ui-corner-tl ui-corner-tr",
            "sJUIFooter": _headerFooter+" ui-corner-bl ui-corner-br"
        } );
        
        }());
        
        
        
        var extPagination = DataTable.ext.pager;
        
        function _numbers ( page, pages ) {
            var
                numbers = [],
                buttons = extPagination.numbers_length,
                half = Math.floor( buttons / 2 ),
                i = 1;
        
            if ( pages <= buttons ) {
                numbers = _range( 0, pages );
            }
            else if ( page <= half ) {
                numbers = _range( 0, buttons-2 );
                numbers.push( 'ellipsis' );
                numbers.push( pages-1 );
            }
            else if ( page >= pages - 1 - half ) {
                numbers = _range( pages-(buttons-2), pages );
                numbers.splice( 0, 0, 'ellipsis' ); // no unshift in ie6
                numbers.splice( 0, 0, 0 );
            }
            else {
                numbers = _range( page-half+2, page+half-1 );
                numbers.push( 'ellipsis' );
                numbers.push( pages-1 );
                numbers.splice( 0, 0, 'ellipsis' );
                numbers.splice( 0, 0, 0 );
            }
        
            numbers.DT_el = 'span';
            return numbers;
        }
        
        
        $.extend( extPagination, {
            simple: function ( page, pages ) {
                return [ 'previous', 'next' ];
            },
        
            full: function ( page, pages ) {
                return [  'first', 'previous', 'next', 'last' ];
            },
        
            numbers: function ( page, pages ) {
                return [ _numbers(page, pages) ];
            },
        
            simple_numbers: function ( page, pages ) {
                return [ 'previous', _numbers(page, pages), 'next' ];
            },
        
            full_numbers: function ( page, pages ) {
                return [ 'first', 'previous', _numbers(page, pages), 'next', 'last' ];
            },
        
            // For testing and plug-ins to use
            _numbers: _numbers,
        
            // Number of number buttons (including ellipsis) to show. _Must be odd!_
            numbers_length: 7
        } );
        
        
        $.extend( true, DataTable.ext.renderer, {
            pageButton: {
                _: function ( settings, host, idx, buttons, page, pages ) {
                    var classes = settings.oClasses;
                    var lang = settings.oLanguage.oPaginate;
                    var aria = settings.oLanguage.oAria.paginate || {};
                    var btnDisplay, btnClass, counter=0;
        
                    var attach = function( container, buttons ) {
                        var i, ien, node, button;
                        var clickHandler = function ( e ) {
                            _fnPageChange( settings, e.data.action, true );
                        };
        
                        for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
                            button = buttons[i];
        
                            if ( $.isArray( button ) ) {
                                var inner = $( '<'+(button.DT_el || 'div')+'/>' )
                                    .appendTo( container );
                                attach( inner, button );
                            }
                            else {
                                btnDisplay = null;
                                btnClass = '';
        
                                switch ( button ) {
                                    case 'ellipsis':
                                        container.append('<span class="ellipsis">&#x2026;</span>');
                                        break;
        
                                    case 'first':
                                        btnDisplay = lang.sFirst;
                                        btnClass = button + (page > 0 ?
                                            '' : ' '+classes.sPageButtonDisabled);
                                        break;
        
                                    case 'previous':
                                        btnDisplay = lang.sPrevious;
                                        btnClass = button + (page > 0 ?
                                            '' : ' '+classes.sPageButtonDisabled);
                                        break;
        
                                    case 'next':
                                        btnDisplay = lang.sNext;
                                        btnClass = button + (page < pages-1 ?
                                            '' : ' '+classes.sPageButtonDisabled);
                                        break;
        
                                    case 'last':
                                        btnDisplay = lang.sLast;
                                        btnClass = button + (page < pages-1 ?
                                            '' : ' '+classes.sPageButtonDisabled);
                                        break;
        
                                    default:
                                        btnDisplay = button + 1;
                                        btnClass = page === button ?
                                            classes.sPageButtonActive : '';
                                        break;
                                }
        
                                if ( btnDisplay !== null ) {
                                    node = $('<a>', {
                                            'class': classes.sPageButton+' '+btnClass,
                                            'aria-controls': settings.sTableId,
                                            'aria-label': aria[ button ],
                                            'data-dt-idx': counter,
                                            'tabindex': settings.iTabIndex,
                                            'id': idx === 0 && typeof button === 'string' ?
                                                settings.sTableId +'_'+ button :
                                                null
                                        } )
                                        .html( btnDisplay )
                                        .appendTo( container );
        
                                    _fnBindAction(
                                        node, {action: button}, clickHandler
                                    );
        
                                    counter++;
                                }
                            }
                        }
                    };
        
                    // IE9 throws an 'unknown error' if document.activeElement is used
                    // inside an iframe or frame. Try / catch the error. Not good for
                    // accessibility, but neither are frames.
                    var activeEl;
        
                    try {
                        // Because this approach is destroying and recreating the paging
                        // elements, focus is lost on the select button which is bad for
                        // accessibility. So we want to restore focus once the draw has
                        // completed
                        activeEl = $(host).find(document.activeElement).data('dt-idx');
                    }
                    catch (e) {}
        
                    attach( $(host).empty(), buttons );
        
                    if ( activeEl ) {
                        $(host).find( '[data-dt-idx='+activeEl+']' ).focus();
                    }
                }
            }
        } );
        
        
        
        // Built in type detection. See model.ext.aTypes for information about
        // what is required from this methods.
        $.extend( DataTable.ext.type.detect, [
            // Plain numbers - first since V8 detects some plain numbers as dates
            // e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...).
            function ( d, settings )
            {
                var decimal = settings.oLanguage.sDecimal;
                return _isNumber( d, decimal ) ? 'num'+decimal : null;
            },
        
            // Dates (only those recognised by the browser's Date.parse)
            function ( d, settings )
            {
                // V8 will remove any unknown characters at the start and end of the
                // expression, leading to false matches such as `$245.12` or `10%` being
                // a valid date. See forum thread 18941 for detail.
                if ( d && !(d instanceof Date) && ( ! _re_date_start.test(d) || ! _re_date_end.test(d) ) ) {
                    return null;
                }
                var parsed = Date.parse(d);
                return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null;
            },
        
            // Formatted numbers
            function ( d, settings )
            {
                var decimal = settings.oLanguage.sDecimal;
                return _isNumber( d, decimal, true ) ? 'num-fmt'+decimal : null;
            },
        
            // HTML numeric
            function ( d, settings )
            {
                var decimal = settings.oLanguage.sDecimal;
                return _htmlNumeric( d, decimal ) ? 'html-num'+decimal : null;
            },
        
            // HTML numeric, formatted
            function ( d, settings )
            {
                var decimal = settings.oLanguage.sDecimal;
                return _htmlNumeric( d, decimal, true ) ? 'html-num-fmt'+decimal : null;
            },
        
            // HTML (this is strict checking - there must be html)
            function ( d, settings )
            {
                return _empty( d ) || (typeof d === 'string' && d.indexOf('<') !== -1) ?
                    'html' : null;
            }
        ] );
        
        
        
        // Filter formatting functions. See model.ext.ofnSearch for information about
        // what is required from these methods.
        // 
        // Note that additional search methods are added for the html numbers and
        // html formatted numbers by `_addNumericSort()` when we know what the decimal
        // place is
        
        
        $.extend( DataTable.ext.type.search, {
            html: function ( data ) {
                return _empty(data) ?
                    data :
                    typeof data === 'string' ?
                        data
                            .replace( _re_new_lines, " " )
                            .replace( _re_html, "" ) :
                        '';
            },
        
            string: function ( data ) {
                return _empty(data) ?
                    data :
                    typeof data === 'string' ?
                        data.replace( _re_new_lines, " " ) :
                        data;
            }
        } );
        
        
        
        var __numericReplace = function ( d, decimalPlace, re1, re2 ) {
            if ( d !== 0 && (!d || d === '-') ) {
                return -Infinity;
            }
        
            // If a decimal place other than `.` is used, it needs to be given to the
            // function so we can detect it and replace with a `.` which is the only
            // decimal place Javascript recognises - it is not locale aware.
            if ( decimalPlace ) {
                d = _numToDecimal( d, decimalPlace );
            }
        
            if ( d.replace ) {
                if ( re1 ) {
                    d = d.replace( re1, '' );
                }
        
                if ( re2 ) {
                    d = d.replace( re2, '' );
                }
            }
        
            return d * 1;
        };
        
        
        // Add the numeric 'deformatting' functions for sorting and search. This is done
        // in a function to provide an easy ability for the language options to add
        // additional methods if a non-period decimal place is used.
        function _addNumericSort ( decimalPlace ) {
            $.each(
                {
                    // Plain numbers
                    "num": function ( d ) {
                        return __numericReplace( d, decimalPlace );
                    },
        
                    // Formatted numbers
                    "num-fmt": function ( d ) {
                        return __numericReplace( d, decimalPlace, _re_formatted_numeric );
                    },
        
                    // HTML numeric
                    "html-num": function ( d ) {
                        return __numericReplace( d, decimalPlace, _re_html );
                    },
        
                    // HTML numeric, formatted
                    "html-num-fmt": function ( d ) {
                        return __numericReplace( d, decimalPlace, _re_html, _re_formatted_numeric );
                    }
                },
                function ( key, fn ) {
                    // Add the ordering method
                    _ext.type.order[ key+decimalPlace+'-pre' ] = fn;
        
                    // For HTML types add a search formatter that will strip the HTML
                    if ( key.match(/^html\-/) ) {
                        _ext.type.search[ key+decimalPlace ] = _ext.type.search.html;
                    }
                }
            );
        }
        
        
        // Default sort methods
        $.extend( _ext.type.order, {
            // Dates
            "date-pre": function ( d ) {
                return Date.parse( d ) || 0;
            },
        
            // html
            "html-pre": function ( a ) {
                return _empty(a) ?
                    '' :
                    a.replace ?
                        a.replace( /<.*?>/g, "" ).toLowerCase() :
                        a+'';
            },
        
            // string
            "string-pre": function ( a ) {
                // This is a little complex, but faster than always calling toString,
                // http://jsperf.com/tostring-v-check
                return _empty(a) ?
                    '' :
                    typeof a === 'string' ?
                        a.toLowerCase() :
                        ! a.toString ?
                            '' :
                            a.toString();
            },
        
            // string-asc and -desc are retained only for compatibility with the old
            // sort methods
            "string-asc": function ( x, y ) {
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            },
        
            "string-desc": function ( x, y ) {
                return ((x < y) ? 1 : ((x > y) ? -1 : 0));
            }
        } );
        
        
        // Numeric sorting types - order doesn't matter here
        _addNumericSort( '' );
        
        
        $.extend( true, DataTable.ext.renderer, {
            header: {
                _: function ( settings, cell, column, classes ) {
                    // No additional mark-up required
                    // Attach a sort listener to update on sort - note that using the
                    // `DT` namespace will allow the event to be removed automatically
                    // on destroy, while the `dt` namespaced event is the one we are
                    // listening for
                    $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
                        if ( settings !== ctx ) { // need to check this this is the host
                            return;               // table, not a nested one
                        }
        
                        var colIdx = column.idx;
        
                        cell
                            .removeClass(
                                column.sSortingClass +' '+
                                classes.sSortAsc +' '+
                                classes.sSortDesc
                            )
                            .addClass( columns[ colIdx ] == 'asc' ?
                                classes.sSortAsc : columns[ colIdx ] == 'desc' ?
                                    classes.sSortDesc :
                                    column.sSortingClass
                            );
                    } );
                },
        
                jqueryui: function ( settings, cell, column, classes ) {
                    $('<div/>')
                        .addClass( classes.sSortJUIWrapper )
                        .append( cell.contents() )
                        .append( $('<span/>')
                            .addClass( classes.sSortIcon+' '+column.sSortingClassJUI )
                        )
                        .appendTo( cell );
        
                    // Attach a sort listener to update on sort
                    $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
                        if ( settings !== ctx ) {
                            return;
                        }
        
                        var colIdx = column.idx;
        
                        cell
                            .removeClass( classes.sSortAsc +" "+classes.sSortDesc )
                            .addClass( columns[ colIdx ] == 'asc' ?
                                classes.sSortAsc : columns[ colIdx ] == 'desc' ?
                                    classes.sSortDesc :
                                    column.sSortingClass
                            );
        
                        cell
                            .find( 'span.'+classes.sSortIcon )
                            .removeClass(
                                classes.sSortJUIAsc +" "+
                                classes.sSortJUIDesc +" "+
                                classes.sSortJUI +" "+
                                classes.sSortJUIAscAllowed +" "+
                                classes.sSortJUIDescAllowed
                            )
                            .addClass( columns[ colIdx ] == 'asc' ?
                                classes.sSortJUIAsc : columns[ colIdx ] == 'desc' ?
                                    classes.sSortJUIDesc :
                                    column.sSortingClassJUI
                            );
                    } );
                }
            }
        } );
        
        /*
         * Public helper functions. These aren't used internally by DataTables, or
         * called by any of the options passed into DataTables, but they can be used
         * externally by developers working with DataTables. They are helper functions
         * to make working with DataTables a little bit easier.
         */
        
        var __htmlEscapeEntities = function ( d ) {
            return typeof d === 'string' ?
                d.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') :
                d;
        };
        
        /**
         * Helpers for `columns.render`.
         *
         * The options defined here can be used with the `columns.render` initialisation
         * option to provide a display renderer. The following functions are defined:
         *
         * * `number` - Will format numeric data (defined by `columns.data`) for
         *   display, retaining the original unformatted data for sorting and filtering.
         *   It takes 5 parameters:
         *   * `string` - Thousands grouping separator
         *   * `string` - Decimal point indicator
         *   * `integer` - Number of decimal points to show
         *   * `string` (optional) - Prefix.
         *   * `string` (optional) - Postfix (/suffix).
         * * `text` - Escape HTML to help prevent XSS attacks. It has no optional
         *   parameters.
         *
         * @example
         *   // Column definition using the number renderer
         *   {
         *     data: "salary",
         *     render: $.fn.dataTable.render.number( '\'', '.', 0, '$' )
         *   }
         *
         * @namespace
         */
        DataTable.render = {
            number: function ( thousands, decimal, precision, prefix, postfix ) {
                return {
                    display: function ( d ) {
                        if ( typeof d !== 'number' && typeof d !== 'string' ) {
                            return d;
                        }
        
                        var negative = d < 0 ? '-' : '';
                        var flo = parseFloat( d );
        
                        // If NaN then there isn't much formatting that we can do - just
                        // return immediately, escaping any HTML (this was supposed to
                        // be a number after all)
                        if ( isNaN( flo ) ) {
                            return __htmlEscapeEntities( d );
                        }
        
                        d = Math.abs( flo );
        
                        var intPart = parseInt( d, 10 );
                        var floatPart = precision ?
                            decimal+(d - intPart).toFixed( precision ).substring( 2 ):
                            '';
        
                        return negative + (prefix||'') +
                            intPart.toString().replace(
                                /\B(?=(\d{3})+(?!\d))/g, thousands
                            ) +
                            floatPart +
                            (postfix||'');
                    }
                };
            },
        
            text: function () {
                return {
                    display: __htmlEscapeEntities
                };
            }
        };
        
        
        /*
         * This is really a good bit rubbish this method of exposing the internal methods
         * publicly... - To be fixed in 2.0 using methods on the prototype
         */
        
        
        /**
         * Create a wrapper function for exporting an internal functions to an external API.
         *  @param {string} fn API function name
         *  @returns {function} wrapped function
         *  @memberof DataTable#internal
         */
        function _fnExternApiFunc (fn)
        {
            return function() {
                var args = [_fnSettingsFromNode( this[DataTable.ext.iApiIndex] )].concat(
                    Array.prototype.slice.call(arguments)
                );
                return DataTable.ext.internal[fn].apply( this, args );
            };
        }
        
        
        /**
         * Reference to internal functions for use by plug-in developers. Note that
         * these methods are references to internal functions and are considered to be
         * private. If you use these methods, be aware that they are liable to change
         * between versions.
         *  @namespace
         */
        $.extend( DataTable.ext.internal, {
            _fnExternApiFunc: _fnExternApiFunc,
            _fnBuildAjax: _fnBuildAjax,
            _fnAjaxUpdate: _fnAjaxUpdate,
            _fnAjaxParameters: _fnAjaxParameters,
            _fnAjaxUpdateDraw: _fnAjaxUpdateDraw,
            _fnAjaxDataSrc: _fnAjaxDataSrc,
            _fnAddColumn: _fnAddColumn,
            _fnColumnOptions: _fnColumnOptions,
            _fnAdjustColumnSizing: _fnAdjustColumnSizing,
            _fnVisibleToColumnIndex: _fnVisibleToColumnIndex,
            _fnColumnIndexToVisible: _fnColumnIndexToVisible,
            _fnVisbleColumns: _fnVisbleColumns,
            _fnGetColumns: _fnGetColumns,
            _fnColumnTypes: _fnColumnTypes,
            _fnApplyColumnDefs: _fnApplyColumnDefs,
            _fnHungarianMap: _fnHungarianMap,
            _fnCamelToHungarian: _fnCamelToHungarian,
            _fnLanguageCompat: _fnLanguageCompat,
            _fnBrowserDetect: _fnBrowserDetect,
            _fnAddData: _fnAddData,
            _fnAddTr: _fnAddTr,
            _fnNodeToDataIndex: _fnNodeToDataIndex,
            _fnNodeToColumnIndex: _fnNodeToColumnIndex,
            _fnGetCellData: _fnGetCellData,
            _fnSetCellData: _fnSetCellData,
            _fnSplitObjNotation: _fnSplitObjNotation,
            _fnGetObjectDataFn: _fnGetObjectDataFn,
            _fnSetObjectDataFn: _fnSetObjectDataFn,
            _fnGetDataMaster: _fnGetDataMaster,
            _fnClearTable: _fnClearTable,
            _fnDeleteIndex: _fnDeleteIndex,
            _fnInvalidate: _fnInvalidate,
            _fnGetRowElements: _fnGetRowElements,
            _fnCreateTr: _fnCreateTr,
            _fnBuildHead: _fnBuildHead,
            _fnDrawHead: _fnDrawHead,
            _fnDraw: _fnDraw,
            _fnReDraw: _fnReDraw,
            _fnAddOptionsHtml: _fnAddOptionsHtml,
            _fnDetectHeader: _fnDetectHeader,
            _fnGetUniqueThs: _fnGetUniqueThs,
            _fnFeatureHtmlFilter: _fnFeatureHtmlFilter,
            _fnFilterComplete: _fnFilterComplete,
            _fnFilterCustom: _fnFilterCustom,
            _fnFilterColumn: _fnFilterColumn,
            _fnFilter: _fnFilter,
            _fnFilterCreateSearch: _fnFilterCreateSearch,
            _fnEscapeRegex: _fnEscapeRegex,
            _fnFilterData: _fnFilterData,
            _fnFeatureHtmlInfo: _fnFeatureHtmlInfo,
            _fnUpdateInfo: _fnUpdateInfo,
            _fnInfoMacros: _fnInfoMacros,
            _fnInitialise: _fnInitialise,
            _fnInitComplete: _fnInitComplete,
            _fnLengthChange: _fnLengthChange,
            _fnFeatureHtmlLength: _fnFeatureHtmlLength,
            _fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate,
            _fnPageChange: _fnPageChange,
            _fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing,
            _fnProcessingDisplay: _fnProcessingDisplay,
            _fnFeatureHtmlTable: _fnFeatureHtmlTable,
            _fnScrollDraw: _fnScrollDraw,
            _fnApplyToChildren: _fnApplyToChildren,
            _fnCalculateColumnWidths: _fnCalculateColumnWidths,
            _fnThrottle: _fnThrottle,
            _fnConvertToWidth: _fnConvertToWidth,
            _fnGetWidestNode: _fnGetWidestNode,
            _fnGetMaxLenString: _fnGetMaxLenString,
            _fnStringToCss: _fnStringToCss,
            _fnSortFlatten: _fnSortFlatten,
            _fnSort: _fnSort,
            _fnSortAria: _fnSortAria,
            _fnSortListener: _fnSortListener,
            _fnSortAttachListener: _fnSortAttachListener,
            _fnSortingClasses: _fnSortingClasses,
            _fnSortData: _fnSortData,
            _fnSaveState: _fnSaveState,
            _fnLoadState: _fnLoadState,
            _fnSettingsFromNode: _fnSettingsFromNode,
            _fnLog: _fnLog,
            _fnMap: _fnMap,
            _fnBindAction: _fnBindAction,
            _fnCallbackReg: _fnCallbackReg,
            _fnCallbackFire: _fnCallbackFire,
            _fnLengthOverflow: _fnLengthOverflow,
            _fnRenderer: _fnRenderer,
            _fnDataSource: _fnDataSource,
            _fnRowAttributes: _fnRowAttributes,
            _fnCalculateEnd: function () {} // Used by a lot of plug-ins, but redundant
                                            // in 1.10, so this dead-end function is
                                            // added to prevent errors
        } );
        
    
        // jQuery access
        $.fn.dataTable = DataTable;
    
        // Provide access to the host jQuery object (circular reference)
        DataTable.$ = $;
    
        // Legacy aliases
        $.fn.dataTableSettings = DataTable.settings;
        $.fn.dataTableExt = DataTable.ext;
    
        // With a capital `D` we return a DataTables API instance rather than a
        // jQuery object
        $.fn.DataTable = function ( opts ) {
            return $(this).dataTable( opts ).api();
        };
    
        // All properties that are available to $.fn.dataTable should also be
        // available on $.fn.DataTable
        $.each( DataTable, function ( prop, val ) {
            $.fn.DataTable[ prop ] = val;
        } );
    
    
        // Information about events fired by DataTables - for documentation.
        /**
         * Draw event, fired whenever the table is redrawn on the page, at the same
         * point as fnDrawCallback. This may be useful for binding events or
         * performing calculations when the table is altered at all.
         *  @name DataTable#draw.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         */
    
        /**
         * Search event, fired when the searching applied to the table (using the
         * built-in global search, or column filters) is altered.
         *  @name DataTable#search.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         */
    
        /**
         * Page change event, fired when the paging of the table is altered.
         *  @name DataTable#page.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         */
    
        /**
         * Order event, fired when the ordering applied to the table is altered.
         *  @name DataTable#order.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         */
    
        /**
         * DataTables initialisation complete event, fired when the table is fully
         * drawn, including Ajax data loaded, if Ajax data is required.
         *  @name DataTable#init.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} oSettings DataTables settings object
         *  @param {object} json The JSON object request from the server - only
         *    present if client-side Ajax sourced data is used</li></ol>
         */
    
        /**
         * State save event, fired when the table has changed state a new state save
         * is required. This event allows modification of the state saving object
         * prior to actually doing the save, including addition or other state
         * properties (for plug-ins) or modification of a DataTables core property.
         *  @name DataTable#stateSaveParams.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} oSettings DataTables settings object
         *  @param {object} json The state information to be saved
         */
    
        /**
         * State load event, fired when the table is loading state from the stored
         * data, but prior to the settings object being modified by the saved state
         * - allowing modification of the saved state is required or loading of
         * state for a plug-in.
         *  @name DataTable#stateLoadParams.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} oSettings DataTables settings object
         *  @param {object} json The saved state information
         */
    
        /**
         * State loaded event, fired when state has been loaded from stored data and
         * the settings object has been modified by the loaded data.
         *  @name DataTable#stateLoaded.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} oSettings DataTables settings object
         *  @param {object} json The saved state information
         */
    
        /**
         * Processing event, fired when DataTables is doing some kind of processing
         * (be it, order, searcg or anything else). It can be used to indicate to
         * the end user that there is something happening, or that something has
         * finished.
         *  @name DataTable#processing.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} oSettings DataTables settings object
         *  @param {boolean} bShow Flag for if DataTables is doing processing or not
         */
    
        /**
         * Ajax (XHR) event, fired whenever an Ajax request is completed from a
         * request to made to the server for new data. This event is called before
         * DataTables processed the returned data, so it can also be used to pre-
         * process the data returned from the server, if needed.
         *
         * Note that this trigger is called in `fnServerData`, if you override
         * `fnServerData` and which to use this event, you need to trigger it in you
         * success function.
         *  @name DataTable#xhr.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         *  @param {object} json JSON returned from the server
         *
         *  @example
         *     // Use a custom property returned from the server in another DOM element
         *     $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
         *       $('#status').html( json.status );
         *     } );
         *
         *  @example
         *     // Pre-process the data returned from the server
         *     $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
         *       for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) {
         *         json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
         *       }
         *       // Note no return - manipulate the data directly in the JSON object.
         *     } );
         */
    
        /**
         * Destroy event, fired when the DataTable is destroyed by calling fnDestroy
         * or passing the bDestroy:true parameter in the initialisation object. This
         * can be used to remove bound events, added DOM nodes, etc.
         *  @name DataTable#destroy.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         */
    
        /**
         * Page length change event, fired when number of records to show on each
         * page (the length) is changed.
         *  @name DataTable#length.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         *  @param {integer} len New length
         */
    
        /**
         * Column sizing has changed.
         *  @name DataTable#column-sizing.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         */
    
        /**
         * Column visibility has changed.
         *  @name DataTable#column-visibility.dt
         *  @event
         *  @param {event} e jQuery event object
         *  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
         *  @param {int} column Column index
         *  @param {bool} vis `false` if column now hidden, or `true` if visible
         */
    
        return $.fn.dataTable;
    }));
    
    /*! DataTables Bootstrap 3 integration
     * Â©2011-2015 SpryMedia Ltd - datatables.net/license
     */
    
    /**
     * DataTables integration for Bootstrap 3. This requires Bootstrap 3 and
     * DataTables 1.10 or newer.
     *
     * This file sets the defaults and adds options to DataTables to style its
     * controls using Bootstrap. See http://datatables.net/manual/styling/bootstrap
     * for further information.
     */
    (function( factory ){
        if ( typeof define === 'function' && define.amd ) {
            // AMD
            define( ['jquery', 'datatables.net'], function ( $ ) {
                return factory( $, window, document );
            } );
        }
        else if ( typeof exports === 'object' ) {
            // CommonJS
            module.exports = function (root, $) {
                if ( ! root ) {
                    root = window;
                }
    
                if ( ! $ || ! $.fn.dataTable ) {
                    // Require DataTables, which attaches to jQuery, including
                    // jQuery if needed and have a $ property so we can access the
                    // jQuery object that is used
                    $ = require('datatables.net')(root, $).$;
                }
    
                return factory( $, root, root.document );
            };
        }
        else {
            // Browser
            factory( jQuery, window, document );
        }
    }(function( $, window, document, undefined ) {
    'use strict';
    var DataTable = $.fn.dataTable;
    
    
    /* Set the defaults for DataTables initialisation */
    $.extend( true, DataTable.defaults, {
        dom:
            "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        renderer: 'bootstrap'
    } );
    
    
    /* Default class modification */
    $.extend( DataTable.ext.classes, {
        sWrapper:      "dataTables_wrapper form-inline dt-bootstrap",
        sFilterInput:  "form-control input-sm",
        sLengthSelect: "form-control input-sm",
        sProcessing:   "dataTables_processing panel panel-default"
    } );
    
    
    /* Bootstrap paging button renderer */
    DataTable.ext.renderer.pageButton.bootstrap = function ( settings, host, idx, buttons, page, pages ) {
        var api     = new DataTable.Api( settings );
        var classes = settings.oClasses;
        var lang    = settings.oLanguage.oPaginate;
        var aria = settings.oLanguage.oAria.paginate || {};
        var btnDisplay, btnClass, counter=0;
    
        var attach = function( container, buttons ) {
            var i, ien, node, button;
            var clickHandler = function ( e ) {
                e.preventDefault();
                if ( !$(e.currentTarget).hasClass('disabled') && api.page() != e.data.action ) {
                    api.page( e.data.action ).draw( 'page' );
                }
            };
    
            for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
                button = buttons[i];
    
                if ( $.isArray( button ) ) {
                    attach( container, button );
                }
                else {
                    btnDisplay = '';
                    btnClass = '';
    
                    switch ( button ) {
                        case 'ellipsis':
                            btnDisplay = '&#x2026;';
                            btnClass = 'disabled';
                            break;
    
                        case 'first':
                            btnDisplay = lang.sFirst;
                            btnClass = button + (page > 0 ?
                                '' : ' disabled');
                            break;
    
                        case 'previous':
                            btnDisplay = lang.sPrevious;
                            btnClass = button + (page > 0 ?
                                '' : ' disabled');
                            break;
    
                        case 'next':
                            btnDisplay = lang.sNext;
                            btnClass = button + (page < pages-1 ?
                                '' : ' disabled');
                            break;
    
                        case 'last':
                            btnDisplay = lang.sLast;
                            btnClass = button + (page < pages-1 ?
                                '' : ' disabled');
                            break;
    
                        default:
                            btnDisplay = button + 1;
                            btnClass = page === button ?
                                'active' : '';
                            break;
                    }
    
                    if ( btnDisplay ) {
                        node = $('<li>', {
                                'class': classes.sPageButton+' '+btnClass,
                                'id': idx === 0 && typeof button === 'string' ?
                                    settings.sTableId +'_'+ button :
                                    null
                            } )
                            .append( $('<a>', {
                                    'href': '#',
                                    'aria-controls': settings.sTableId,
                                    'aria-label': aria[ button ],
                                    'data-dt-idx': counter,
                                    'tabindex': settings.iTabIndex
                                } )
                                .html( btnDisplay )
                            )
                            .appendTo( container );
    
                        settings.oApi._fnBindAction(
                            node, {action: button}, clickHandler
                        );
    
                        counter++;
                    }
                }
            }
        };
    
        // IE9 throws an 'unknown error' if document.activeElement is used
        // inside an iframe or frame. 
        var activeEl;
    
        try {
            // Because this approach is destroying and recreating the paging
            // elements, focus is lost on the select button which is bad for
            // accessibility. So we want to restore focus once the draw has
            // completed
            activeEl = $(host).find(document.activeElement).data('dt-idx');
        }
        catch (e) {}
    
        attach(
            $(host).empty().html('<ul class="pagination"/>').children('ul'),
            buttons
        );
    
        if ( activeEl ) {
            $(host).find( '[data-dt-idx='+activeEl+']' ).focus();
        }
    };
    
    
    return DataTable;
    }));
    /*! Responsive 2.1.0
     * 2014-2016 SpryMedia Ltd - datatables.net/license
     */
    
    /**
     * @summary     Responsive
     * @description Responsive tables plug-in for DataTables
     * @version     2.1.0
     * @file        dataTables.responsive.js
     * @author      SpryMedia Ltd (www.sprymedia.co.uk)
     * @contact     www.sprymedia.co.uk/contact
     * @copyright   Copyright 2014-2016 SpryMedia Ltd.
     *
     * This source file is free software, available under the following license:
     *   MIT license - http://datatables.net/license/mit
     *
     * This source file is distributed in the hope that it will be useful, but
     * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
     * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
     *
     * For details please refer to: http://www.datatables.net
     */
    (function( factory ){
        if ( typeof define === 'function' && define.amd ) {
            // AMD
            define( ['jquery', 'datatables.net'], function ( $ ) {
                return factory( $, window, document );
            } );
        }
        else if ( typeof exports === 'object' ) {
            // CommonJS
            module.exports = function (root, $) {
                if ( ! root ) {
                    root = window;
                }
    
                if ( ! $ || ! $.fn.dataTable ) {
                    $ = require('datatables.net')(root, $).$;
                }
    
                return factory( $, root, root.document );
            };
        }
        else {
            // Browser
            factory( jQuery, window, document );
        }
    }(function( $, window, document, undefined ) {
    'use strict';
    var DataTable = $.fn.dataTable;
    
    
    /**
     * Responsive is a plug-in for the DataTables library that makes use of
     * DataTables' ability to change the visibility of columns, changing the
     * visibility of columns so the displayed columns fit into the table container.
     * The end result is that complex tables will be dynamically adjusted to fit
     * into the viewport, be it on a desktop, tablet or mobile browser.
     *
     * Responsive for DataTables has two modes of operation, which can used
     * individually or combined:
     *
     * * Class name based control - columns assigned class names that match the
     *   breakpoint logic can be shown / hidden as required for each breakpoint.
     * * Automatic control - columns are automatically hidden when there is no
     *   room left to display them. Columns removed from the right.
     *
     * In additional to column visibility control, Responsive also has built into
     * options to use DataTables' child row display to show / hide the information
     * from the table that has been hidden. There are also two modes of operation
     * for this child row display:
     *
     * * Inline - when the control element that the user can use to show / hide
     *   child rows is displayed inside the first column of the table.
     * * Column - where a whole column is dedicated to be the show / hide control.
     *
     * Initialisation of Responsive is performed by:
     *
     * * Adding the class `responsive` or `dt-responsive` to the table. In this case
     *   Responsive will automatically be initialised with the default configuration
     *   options when the DataTable is created.
     * * Using the `responsive` option in the DataTables configuration options. This
     *   can also be used to specify the configuration options, or simply set to
     *   `true` to use the defaults.
     *
     *  @class
     *  @param {object} settings DataTables settings object for the host table
     *  @param {object} [opts] Configuration options
     *  @requires jQuery 1.7+
     *  @requires DataTables 1.10.3+
     *
     *  @example
     *      $('#example').DataTable( {
     *        responsive: true
     *      } );
     *    } );
     */
    var Responsive = function ( settings, opts ) {
        // Sanity check that we are using DataTables 1.10 or newer
        if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.3' ) ) {
            throw 'DataTables Responsive requires DataTables 1.10.3 or newer';
        }
    
        this.s = {
            dt: new DataTable.Api( settings ),
            columns: [],
            current: []
        };
    
        // Check if responsive has already been initialised on this table
        if ( this.s.dt.settings()[0].responsive ) {
            return;
        }
    
        // details is an object, but for simplicity the user can give it as a string
        // or a boolean
        if ( opts && typeof opts.details === 'string' ) {
            opts.details = { type: opts.details };
        }
        else if ( opts && opts.details === false ) {
            opts.details = { type: false };
        }
        else if ( opts && opts.details === true ) {
            opts.details = { type: 'inline' };
        }
    
        this.c = $.extend( true, {}, Responsive.defaults, DataTable.defaults.responsive, opts );
        settings.responsive = this;
        this._constructor();
    };
    
    $.extend( Responsive.prototype, {
        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * Constructor
         */
    
        /**
         * Initialise the Responsive instance
         *
         * @private
         */
        _constructor: function ()
        {
            var that = this;
            var dt = this.s.dt;
            var dtPrivateSettings = dt.settings()[0];
            var oldWindowWidth = $(window).width();
    
            dt.settings()[0]._responsive = this;
    
            // Use DataTables' throttle function to avoid processor thrashing on
            // resize
            $(window).on( 'resize.dtr orientationchange.dtr', DataTable.util.throttle( function () {
                // iOS has a bug whereby resize can fire when only scrolling
                // See: http://stackoverflow.com/questions/8898412
                var width = $(window).width();
    
                if ( width !== oldWindowWidth ) {
                    that._resize();
                    oldWindowWidth = width;
                }
            } ) );
    
            // DataTables doesn't currently trigger an event when a row is added, so
            // we need to hook into its private API to enforce the hidden rows when
            // new data is added
            dtPrivateSettings.oApi._fnCallbackReg( dtPrivateSettings, 'aoRowCreatedCallback', function (tr, data, idx) {
                if ( $.inArray( false, that.s.current ) !== -1 ) {
                    $('td, th', tr).each( function ( i ) {
                        var idx = dt.column.index( 'toData', i );
    
                        if ( that.s.current[idx] === false ) {
                            $(this).css('display', 'none');
                        }
                    } );
                }
            } );
    
            // Destroy event handler
            dt.on( 'destroy.dtr', function () {
                dt.off( '.dtr' );
                $( dt.table().body() ).off( '.dtr' );
                $(window).off( 'resize.dtr orientationchange.dtr' );
    
                // Restore the columns that we've hidden
                $.each( that.s.current, function ( i, val ) {
                    if ( val === false ) {
                        that._setColumnVis( i, true );
                    }
                } );
            } );
    
            // Reorder the breakpoints array here in case they have been added out
            // of order
            this.c.breakpoints.sort( function (a, b) {
                return a.width < b.width ? 1 :
                    a.width > b.width ? -1 : 0;
            } );
    
            this._classLogic();
            this._resizeAuto();
    
            // Details handler
            var details = this.c.details;
    
            if ( details.type !== false ) {
                that._detailsInit();
    
                // DataTables will trigger this event on every column it shows and
                // hides individually
                dt.on( 'column-visibility.dtr', function (e, ctx, col, vis) {
                    that._classLogic();
                    that._resizeAuto();
                    that._resize();
                } );
    
                // Redraw the details box on each draw which will happen if the data
                // has changed. This is used until DataTables implements a native
                // `updated` event for rows
                dt.on( 'draw.dtr', function () {
                    that._redrawChildren();
                } );
    
                $(dt.table().node()).addClass( 'dtr-'+details.type );
            }
    
            dt.on( 'column-reorder.dtr', function (e, settings, details) {
                that._classLogic();
                that._resizeAuto();
                that._resize();
            } );
    
            // Change in column sizes means we need to calc
            dt.on( 'column-sizing.dtr', function () {
                that._resizeAuto();
                that._resize();
            });
    
            dt.on( 'init.dtr', function (e, settings, details) {
                that._resizeAuto();
                that._resize();
    
                // If columns were hidden, then DataTables needs to adjust the
                // column sizing
                if ( $.inArray( false, that.s.current ) ) {
                    dt.columns.adjust();
                }
            } );
    
            // First pass - draw the table for the current viewport size
            this._resize();
        },
    
    
        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * Private methods
         */
    
        /**
         * Calculate the visibility for the columns in a table for a given
         * breakpoint. The result is pre-determined based on the class logic if
         * class names are used to control all columns, but the width of the table
         * is also used if there are columns which are to be automatically shown
         * and hidden.
         *
         * @param  {string} breakpoint Breakpoint name to use for the calculation
         * @return {array} Array of boolean values initiating the visibility of each
         *   column.
         *  @private
         */
        _columnsVisiblity: function ( breakpoint )
        {
            var dt = this.s.dt;
            var columns = this.s.columns;
            var i, ien;
    
            // Create an array that defines the column ordering based first on the
            // column's priority, and secondly the column index. This allows the
            // columns to be removed from the right if the priority matches
            var order = columns
                .map( function ( col, idx ) {
                    return {
                        columnIdx: idx,
                        priority: col.priority
                    };
                } )
                .sort( function ( a, b ) {
                    if ( a.priority !== b.priority ) {
                        return a.priority - b.priority;
                    }
                    return a.columnIdx - b.columnIdx;
                } );
    
            // Class logic - determine which columns are in this breakpoint based
            // on the classes. If no class control (i.e. `auto`) then `-` is used
            // to indicate this to the rest of the function
            var display = $.map( columns, function ( col ) {
                return col.auto && col.minWidth === null ?
                    false :
                    col.auto === true ?
                        '-' :
                        $.inArray( breakpoint, col.includeIn ) !== -1;
            } );
    
            // Auto column control - first pass: how much width is taken by the
            // ones that must be included from the non-auto columns
            var requiredWidth = 0;
            for ( i=0, ien=display.length ; i<ien ; i++ ) {
                if ( display[i] === true ) {
                    requiredWidth += columns[i].minWidth;
                }
            }
    
            // Second pass, use up any remaining width for other columns. For
            // scrolling tables we need to subtract the width of the scrollbar. It
            // may not be requires which makes this sub-optimal, but it would
            // require another full redraw to make complete use of those extra few
            // pixels
            var scrolling = dt.settings()[0].oScroll;
            var bar = scrolling.sY || scrolling.sX ? scrolling.iBarWidth : 0;
            var widthAvailable = dt.table().container().offsetWidth - bar;
            var usedWidth = widthAvailable - requiredWidth;
    
            // Control column needs to always be included. This makes it sub-
            // optimal in terms of using the available with, but to stop layout
            // thrashing or overflow. Also we need to account for the control column
            // width first so we know how much width is available for the other
            // columns, since the control column might not be the first one shown
            for ( i=0, ien=display.length ; i<ien ; i++ ) {
                if ( columns[i].control ) {
                    usedWidth -= columns[i].minWidth;
                }
            }
    
            // Allow columns to be shown (counting by priority and then right to
            // left) until we run out of room
            var empty = false;
            for ( i=0, ien=order.length ; i<ien ; i++ ) {
                var colIdx = order[i].columnIdx;
    
                if ( display[colIdx] === '-' && ! columns[colIdx].control && columns[colIdx].minWidth ) {
                    // Once we've found a column that won't fit we don't let any
                    // others display either, or columns might disappear in the
                    // middle of the table
                    if ( empty || usedWidth - columns[colIdx].minWidth < 0 ) {
                        empty = true;
                        display[colIdx] = false;
                    }
                    else {
                        display[colIdx] = true;
                    }
    
                    usedWidth -= columns[colIdx].minWidth;
                }
            }
    
            // Determine if the 'control' column should be shown (if there is one).
            // This is the case when there is a hidden column (that is not the
            // control column). The two loops look inefficient here, but they are
            // trivial and will fly through. We need to know the outcome from the
            // first , before the action in the second can be taken
            var showControl = false;
    
            for ( i=0, ien=columns.length ; i<ien ; i++ ) {
                if ( ! columns[i].control && ! columns[i].never && ! display[i] ) {
                    showControl = true;
                    break;
                }
            }
    
            for ( i=0, ien=columns.length ; i<ien ; i++ ) {
                if ( columns[i].control ) {
                    display[i] = showControl;
                }
            }
    
            // Finally we need to make sure that there is at least one column that
            // is visible
            if ( $.inArray( true, display ) === -1 ) {
                display[0] = true;
            }
    
            return display;
        },
    
    
        /**
         * Create the internal `columns` array with information about the columns
         * for the table. This includes determining which breakpoints the column
         * will appear in, based upon class names in the column, which makes up the
         * vast majority of this method.
         *
         * @private
         */
        _classLogic: function ()
        {
            var that = this;
            var calc = {};
            var breakpoints = this.c.breakpoints;
            var dt = this.s.dt;
            var columns = dt.columns().eq(0).map( function (i) {
                var column = this.column(i);
                var className = column.header().className;
                var priority = dt.settings()[0].aoColumns[i].responsivePriority;
    
                if ( priority === undefined ) {
                    var dataPriority = $(column.header()).data('priority');
    
                    priority = dataPriority !== undefined ?
                        dataPriority * 1 :
                        10000;
                }
    
                return {
                    className: className,
                    includeIn: [],
                    auto:      false,
                    control:   false,
                    never:     className.match(/\bnever\b/) ? true : false,
                    priority:  priority
                };
            } );
    
            // Simply add a breakpoint to `includeIn` array, ensuring that there are
            // no duplicates
            var add = function ( colIdx, name ) {
                var includeIn = columns[ colIdx ].includeIn;
    
                if ( $.inArray( name, includeIn ) === -1 ) {
                    includeIn.push( name );
                }
            };
    
            var column = function ( colIdx, name, operator, matched ) {
                var size, i, ien;
    
                if ( ! operator ) {
                    columns[ colIdx ].includeIn.push( name );
                }
                else if ( operator === 'max-' ) {
                    // Add this breakpoint and all smaller
                    size = that._find( name ).width;
    
                    for ( i=0, ien=breakpoints.length ; i<ien ; i++ ) {
                        if ( breakpoints[i].width <= size ) {
                            add( colIdx, breakpoints[i].name );
                        }
                    }
                }
                else if ( operator === 'min-' ) {
                    // Add this breakpoint and all larger
                    size = that._find( name ).width;
    
                    for ( i=0, ien=breakpoints.length ; i<ien ; i++ ) {
                        if ( breakpoints[i].width >= size ) {
                            add( colIdx, breakpoints[i].name );
                        }
                    }
                }
                else if ( operator === 'not-' ) {
                    // Add all but this breakpoint
                    for ( i=0, ien=breakpoints.length ; i<ien ; i++ ) {
                        if ( breakpoints[i].name.indexOf( matched ) === -1 ) {
                            add( colIdx, breakpoints[i].name );
                        }
                    }
                }
            };
    
            // Loop over each column and determine if it has a responsive control
            // class
            columns.each( function ( col, i ) {
                var classNames = col.className.split(' ');
                var hasClass = false;
    
                // Split the class name up so multiple rules can be applied if needed
                for ( var k=0, ken=classNames.length ; k<ken ; k++ ) {
                    var className = $.trim( classNames[k] );
    
                    if ( className === 'all' ) {
                        // Include in all
                        hasClass = true;
                        col.includeIn = $.map( breakpoints, function (a) {
                            return a.name;
                        } );
                        return;
                    }
                    else if ( className === 'none' || col.never ) {
                        // Include in none (default) and no auto
                        hasClass = true;
                        return;
                    }
                    else if ( className === 'control' ) {
                        // Special column that is only visible, when one of the other
                        // columns is hidden. This is used for the details control
                        hasClass = true;
                        col.control = true;
                        return;
                    }
    
                    $.each( breakpoints, function ( j, breakpoint ) {
                        // Does this column have a class that matches this breakpoint?
                        var brokenPoint = breakpoint.name.split('-');
                        var re = new RegExp( '(min\\-|max\\-|not\\-)?('+brokenPoint[0]+')(\\-[_a-zA-Z0-9])?' );
                        var match = className.match( re );
    
                        if ( match ) {
                            hasClass = true;
    
                            if ( match[2] === brokenPoint[0] && match[3] === '-'+brokenPoint[1] ) {
                                // Class name matches breakpoint name fully
                                column( i, breakpoint.name, match[1], match[2]+match[3] );
                            }
                            else if ( match[2] === brokenPoint[0] && ! match[3] ) {
                                // Class name matched primary breakpoint name with no qualifier
                                column( i, breakpoint.name, match[1], match[2] );
                            }
                        }
                    } );
                }
    
                // If there was no control class, then automatic sizing is used
                if ( ! hasClass ) {
                    col.auto = true;
                }
            } );
    
            this.s.columns = columns;
        },
    
    
        /**
         * Show the details for the child row
         *
         * @param  {DataTables.Api} row    API instance for the row
         * @param  {boolean}        update Update flag
         * @private
         */
        _detailsDisplay: function ( row, update )
        {
            var that = this;
            var dt = this.s.dt;
            var details = this.c.details;
    
            if ( details && details.type !== false ) {
                var res = details.display( row, update, function () {
                    return details.renderer(
                        dt, row[0], that._detailsObj(row[0])
                    );
                } );
    
                if ( res === true || res === false ) {
                    $(dt.table().node()).triggerHandler( 'responsive-display.dt', [dt, row, res, update] );
                }
            }
        },
    
    
        /**
         * Initialisation for the details handler
         *
         * @private
         */
        _detailsInit: function ()
        {
            var that    = this;
            var dt      = this.s.dt;
            var details = this.c.details;
    
            // The inline type always uses the first child as the target
            if ( details.type === 'inline' ) {
                details.target = 'td:first-child, th:first-child';
            }
    
            // Keyboard accessibility
            dt.on( 'draw.dtr', function () {
                that._tabIndexes();
            } );
            that._tabIndexes(); // Initial draw has already happened
    
            $( dt.table().body() ).on( 'keyup.dtr', 'td, th', function (e) {
                if ( e.keyCode === 13 && $(this).data('dtr-keyboard') ) {
                    $(this).click();
                }
            } );
    
            // type.target can be a string jQuery selector or a column index
            var target   = details.target;
            var selector = typeof target === 'string' ? target : 'td, th';
    
            // Click handler to show / hide the details rows when they are available
            $( dt.table().body() )
                .on( 'click.dtr mousedown.dtr mouseup.dtr', selector, function (e) {
                    // If the table is not collapsed (i.e. there is no hidden columns)
                    // then take no action
                    if ( ! $(dt.table().node()).hasClass('collapsed' ) ) {
                        return;
                    }
    
                    // Check that the row is actually a DataTable's controlled node
                    if ( ! dt.row( $(this).closest('tr') ).length ) {
                        return;
                    }
    
                    // For column index, we determine if we should act or not in the
                    // handler - otherwise it is already okay
                    if ( typeof target === 'number' ) {
                        var targetIdx = target < 0 ?
                            dt.columns().eq(0).length + target :
                            target;
    
                        if ( dt.cell( this ).index().column !== targetIdx ) {
                            return;
                        }
                    }
    
                    // $().closest() includes itself in its check
                    var row = dt.row( $(this).closest('tr') );
    
                    // Check event type to do an action
                    if ( e.type === 'click' ) {
                        // The renderer is given as a function so the caller can execute it
                        // only when they need (i.e. if hiding there is no point is running
                        // the renderer)
                        that._detailsDisplay( row, false );
                    }
                    else if ( e.type === 'mousedown' ) {
                        // For mouse users, prevent the focus ring from showing
                        $(this).css('outline', 'none');
                    }
                    else if ( e.type === 'mouseup' ) {
                        // And then re-allow at the end of the click
                        $(this).blur().css('outline', '');
                    }
                } );
        },
    
    
        /**
         * Get the details to pass to a renderer for a row
         * @param  {int} rowIdx Row index
         * @private
         */
        _detailsObj: function ( rowIdx )
        {
            var that = this;
            var dt = this.s.dt;
    
            return $.map( this.s.columns, function( col, i ) {
                // Never and control columns should not be passed to the renderer
                if ( col.never || col.control ) {
                    return;
                }
    
                return {
                    title:       dt.settings()[0].aoColumns[ i ].sTitle,
                    data:        dt.cell( rowIdx, i ).render( that.c.orthogonal ),
                    hidden:      dt.column( i ).visible() && !that.s.current[ i ],
                    columnIndex: i,
                    rowIndex:    rowIdx
                };
            } );
        },
    
    
        /**
         * Find a breakpoint object from a name
         *
         * @param  {string} name Breakpoint name to find
         * @return {object}      Breakpoint description object
         * @private
         */
        _find: function ( name )
        {
            var breakpoints = this.c.breakpoints;
    
            for ( var i=0, ien=breakpoints.length ; i<ien ; i++ ) {
                if ( breakpoints[i].name === name ) {
                    return breakpoints[i];
                }
            }
        },
    
    
        /**
         * Re-create the contents of the child rows as the display has changed in
         * some way.
         *
         * @private
         */
        _redrawChildren: function ()
        {
            var that = this;
            var dt = this.s.dt;
    
            dt.rows( {page: 'current'} ).iterator( 'row', function ( settings, idx ) {
                var row = dt.row( idx );
    
                that._detailsDisplay( dt.row( idx ), true );
            } );
        },
    
    
        /**
         * Alter the table display for a resized viewport. This involves first
         * determining what breakpoint the window currently is in, getting the
         * column visibilities to apply and then setting them.
         *
         * @private
         */
        _resize: function ()
        {
            var that = this;
            var dt = this.s.dt;
            var width = $(window).width();
            var breakpoints = this.c.breakpoints;
            var breakpoint = breakpoints[0].name;
            var columns = this.s.columns;
            var i, ien;
            var oldVis = this.s.current.slice();
    
            // Determine what breakpoint we are currently at
            for ( i=breakpoints.length-1 ; i>=0 ; i-- ) {
                if ( width <= breakpoints[i].width ) {
                    breakpoint = breakpoints[i].name;
                    break;
                }
            }
            
            // Show the columns for that break point
            var columnsVis = this._columnsVisiblity( breakpoint );
            this.s.current = columnsVis;
    
            // Set the class before the column visibility is changed so event
            // listeners know what the state is. Need to determine if there are
            // any columns that are not visible but can be shown
            var collapsedClass = false;
            for ( i=0, ien=columns.length ; i<ien ; i++ ) {
                if ( columnsVis[i] === false && ! columns[i].never && ! columns[i].control ) {
                    collapsedClass = true;
                    break;
                }
            }
    
            $( dt.table().node() ).toggleClass( 'collapsed', collapsedClass );
    
            var changed = false;
    
            dt.columns().eq(0).each( function ( colIdx, i ) {
                if ( columnsVis[i] !== oldVis[i] ) {
                    changed = true;
                    that._setColumnVis( colIdx, columnsVis[i] );
                }
            } );
    
            if ( changed ) {
                this._redrawChildren();
    
                // Inform listeners of the change
                $(dt.table().node()).trigger( 'responsive-resize.dt', [dt, this.s.current] );
            }
        },
    
    
        /**
         * Determine the width of each column in the table so the auto column hiding
         * has that information to work with. This method is never going to be 100%
         * perfect since column widths can change slightly per page, but without
         * seriously compromising performance this is quite effective.
         *
         * @private
         */
        _resizeAuto: function ()
        {
            var dt = this.s.dt;
            var columns = this.s.columns;
    
            // Are we allowed to do auto sizing?
            if ( ! this.c.auto ) {
                return;
            }
    
            // Are there any columns that actually need auto-sizing, or do they all
            // have classes defined
            if ( $.inArray( true, $.map( columns, function (c) { return c.auto; } ) ) === -1 ) {
                return;
            }
    
            // Clone the table with the current data in it
            var tableWidth   = dt.table().node().offsetWidth;
            var columnWidths = dt.columns;
            var clonedTable  = dt.table().node().cloneNode( false );
            var clonedHeader = $( dt.table().header().cloneNode( false ) ).appendTo( clonedTable );
            var clonedBody   = $( dt.table().body() ).clone( false, false ).empty().appendTo( clonedTable ); // use jQuery because of IE8
    
            // Header
            var headerCells = dt.columns()
                .header()
                .filter( function (idx) {
                    return dt.column(idx).visible();
                } )
                .to$()
                .clone( false )
                .css( 'display', 'table-cell' );
    
            // Body rows - we don't need to take account of DataTables' column
            // visibility since we implement our own here (hence the `display` set)
            $(clonedBody)
                .append( $(dt.rows( { page: 'current' } ).nodes()).clone( false ) )
                .find( 'th, td' ).css( 'display', '' );
    
            // Footer
            var footer = dt.table().footer();
            if ( footer ) {
                var clonedFooter = $( footer.cloneNode( false ) ).appendTo( clonedTable );
                var footerCells = dt.columns()
                    .footer()
                    .filter( function (idx) {
                        return dt.column(idx).visible();
                    } )
                    .to$()
                    .clone( false )
                    .css( 'display', 'table-cell' );
    
                $('<tr/>')
                    .append( footerCells )
                    .appendTo( clonedFooter );
            }
    
            $('<tr/>')
                .append( headerCells )
                .appendTo( clonedHeader );
    
            // In the inline case extra padding is applied to the first column to
            // give space for the show / hide icon. We need to use this in the
            // calculation
            if ( this.c.details.type === 'inline' ) {
                $(clonedTable).addClass( 'dtr-inline collapsed' );
            }
            
            // It is unsafe to insert elements with the same name into the DOM
            // multiple times. For example, cloning and inserting a checked radio
            // clears the chcecked state of the original radio.
            $( clonedTable ).find( '[name]' ).removeAttr( 'name' );
            
            var inserted = $('<div/>')
                .css( {
                    width: 1,
                    height: 1,
                    overflow: 'hidden'
                } )
                .append( clonedTable );
    
            inserted.insertBefore( dt.table().node() );
    
            // The cloned header now contains the smallest that each column can be
            headerCells.each( function (i) {
                var idx = dt.column.index( 'fromVisible', i );
                columns[ idx ].minWidth =  this.offsetWidth || 0;
            } );
    
            inserted.remove();
        },
    
        /**
         * Set a column's visibility.
         *
         * We don't use DataTables' column visibility controls in order to ensure
         * that column visibility can Responsive can no-exist. Since only IE8+ is
         * supported (and all evergreen browsers of course) the control of the
         * display attribute works well.
         *
         * @param {integer} col      Column index
         * @param {boolean} showHide Show or hide (true or false)
         * @private
         */
        _setColumnVis: function ( col, showHide )
        {
            var dt = this.s.dt;
            var display = showHide ? '' : 'none'; // empty string will remove the attr
    
            $( dt.column( col ).header() ).css( 'display', display );
            $( dt.column( col ).footer() ).css( 'display', display );
            dt.column( col ).nodes().to$().css( 'display', display );
        },
    
    
        /**
         * Update the cell tab indexes for keyboard accessibility. This is called on
         * every table draw - that is potentially inefficient, but also the least
         * complex option given that column visibility can change on the fly. Its a
         * shame user-focus was removed from CSS 3 UI, as it would have solved this
         * issue with a single CSS statement.
         *
         * @private
         */
        _tabIndexes: function ()
        {
            var dt = this.s.dt;
            var cells = dt.cells( { page: 'current' } ).nodes().to$();
            var ctx = dt.settings()[0];
            var target = this.c.details.target;
    
            cells.filter( '[data-dtr-keyboard]' ).removeData( '[data-dtr-keyboard]' );
    
            var selector = typeof target === 'number' ?
                ':eq('+target+')' :
                target;
    
            $( selector, dt.rows( { page: 'current' } ).nodes() )
                .attr( 'tabIndex', ctx.iTabIndex )
                .data( 'dtr-keyboard', 1 );
        }
    } );
    
    
    /**
     * List of default breakpoints. Each item in the array is an object with two
     * properties:
     *
     * * `name` - the breakpoint name.
     * * `width` - the breakpoint width
     *
     * @name Responsive.breakpoints
     * @static
     */
    Responsive.breakpoints = [
        { name: 'desktop',  width: Infinity },
        { name: 'tablet-l', width: 1024 },
        { name: 'tablet-p', width: 768 },
        { name: 'mobile-l', width: 480 },
        { name: 'mobile-p', width: 320 }
    ];
    
    
    /**
     * Display methods - functions which define how the hidden data should be shown
     * in the table.
     *
     * @namespace
     * @name Responsive.defaults
     * @static
     */
    Responsive.display = {
        childRow: function ( row, update, render ) {
            if ( update ) {
                if ( $(row.node()).hasClass('parent') ) {
                    row.child( render(), 'child' ).show();
    
                    return true;
                }
            }
            else {
                if ( ! row.child.isShown()  ) {
                    row.child( render(), 'child' ).show();
                    $( row.node() ).addClass( 'parent' );
    
                    return true;
                }
                else {
                    row.child( false );
                    $( row.node() ).removeClass( 'parent' );
    
                    return false;
                }
            }
        },
    
        childRowImmediate: function ( row, update, render ) {
            if ( (! update && row.child.isShown()) || ! row.responsive.hasHidden() ) {
                // User interaction and the row is show, or nothing to show
                row.child( false );
                $( row.node() ).removeClass( 'parent' );
    
                return false;
            }
            else {
                // Display
                row.child( render(), 'child' ).show();
                $( row.node() ).addClass( 'parent' );
    
                return true;
            }
        },
    
        // This is a wrapper so the modal options for Bootstrap and jQuery UI can
        // have options passed into them. This specific one doesn't need to be a
        // function but it is for consistency in the `modal` name
        modal: function ( options ) {
            return function ( row, update, render ) {
                if ( ! update ) {
                    // Show a modal
                    var close = function () {
                        modal.remove(); // will tidy events for us
                        $(document).off( 'keypress.dtr' );
                    };
    
                    var modal = $('<div class="dtr-modal"/>')
                        .append( $('<div class="dtr-modal-display"/>')
                            .append( $('<div class="dtr-modal-content"/>')
                                .append( render() )
                            )
                            .append( $('<div class="dtr-modal-close">&times;</div>' )
                                .click( function () {
                                    close();
                                } )
                            )
                        )
                        .append( $('<div class="dtr-modal-background"/>')
                            .click( function () {
                                close();
                            } )
                        )
                        .appendTo( 'body' );
    
                    $(document).on( 'keyup.dtr', function (e) {
                        if ( e.keyCode === 27 ) {
                            e.stopPropagation();
    
                            close();
                        }
                    } );
                }
                else {
                    $('div.dtr-modal-content')
                        .empty()
                        .append( render() );
                }
    
                if ( options && options.header ) {
                    $('div.dtr-modal-content').prepend(
                        '<h2>'+options.header( row )+'</h2>'
                    );
                }
            };
        }
    };
    
    
    /**
     * Display methods - functions which define how the hidden data should be shown
     * in the table.
     *
     * @namespace
     * @name Responsive.defaults
     * @static
     */
    Responsive.renderer = {
        listHidden: function () {
            return function ( api, rowIdx, columns ) {
                var data = $.map( columns, function ( col ) {
                    return col.hidden ?
                        '<li data-dtr-index="'+col.columnIndex+'" data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
                            '<span class="dtr-title">'+
                                col.title+
                            '</span> '+
                            '<span class="dtr-data">'+
                                col.data+
                            '</span>'+
                        '</li>' :
                        '';
                } ).join('');
    
                return data ?
                    $('<ul data-dtr-index="'+rowIdx+'"/>').append( data ) :
                    false;
            }
        },
    
        tableAll: function ( options ) {
            options = $.extend( {
                tableClass: ''
            }, options );
    
            return function ( api, rowIdx, columns ) {
                var data = $.map( columns, function ( col ) {
                    return '<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
                            '<td>'+col.title+':'+'</td> '+
                            '<td>'+col.data+'</td>'+
                        '</tr>';
                } ).join('');
    
                return $('<table class="'+options.tableClass+'" width="100%"/>').append( data );
            }
        }
    };
    
    /**
     * Responsive default settings for initialisation
     *
     * @namespace
     * @name Responsive.defaults
     * @static
     */
    Responsive.defaults = {
        /**
         * List of breakpoints for the instance. Note that this means that each
         * instance can have its own breakpoints. Additionally, the breakpoints
         * cannot be changed once an instance has been creased.
         *
         * @type {Array}
         * @default Takes the value of `Responsive.breakpoints`
         */
        breakpoints: Responsive.breakpoints,
    
        /**
         * Enable / disable auto hiding calculations. It can help to increase
         * performance slightly if you disable this option, but all columns would
         * need to have breakpoint classes assigned to them
         *
         * @type {Boolean}
         * @default  `true`
         */
        auto: true,
    
        /**
         * Details control. If given as a string value, the `type` property of the
         * default object is set to that value, and the defaults used for the rest
         * of the object - this is for ease of implementation.
         *
         * The object consists of the following properties:
         *
         * * `display` - A function that is used to show and hide the hidden details
         * * `renderer` - function that is called for display of the child row data.
         *   The default function will show the data from the hidden columns
         * * `target` - Used as the selector for what objects to attach the child
         *   open / close to
         * * `type` - `false` to disable the details display, `inline` or `column`
         *   for the two control types
         *
         * @type {Object|string}
         */
        details: {
            display: Responsive.display.childRow,
    
            renderer: Responsive.renderer.listHidden(),
    
            target: 0,
    
            type: 'inline'
        },
    
        /**
         * Orthogonal data request option. This is used to define the data type
         * requested when Responsive gets the data to show in the child row.
         *
         * @type {String}
         */
        orthogonal: 'display'
    };
    
    
    /*
     * API
     */
    var Api = $.fn.dataTable.Api;
    
    // Doesn't do anything - work around for a bug in DT... Not documented
    Api.register( 'responsive()', function () {
        return this;
    } );
    
    Api.register( 'responsive.index()', function ( li ) {
        li = $(li);
    
        return {
            column: li.data('dtr-index'),
            row:    li.parent().data('dtr-index')
        };
    } );
    
    Api.register( 'responsive.rebuild()', function () {
        return this.iterator( 'table', function ( ctx ) {
            if ( ctx._responsive ) {
                ctx._responsive._classLogic();
            }
        } );
    } );
    
    Api.register( 'responsive.recalc()', function () {
        return this.iterator( 'table', function ( ctx ) {
            if ( ctx._responsive ) {
                ctx._responsive._resizeAuto();
                ctx._responsive._resize();
            }
        } );
    } );
    
    Api.register( 'responsive.hasHidden()', function () {
        var ctx = this.context[0];
    
        return ctx._responsive ?
            $.inArray( false, ctx._responsive.s.current ) !== -1 :
            false;
    } );
    
    
    /**
     * Version information
     *
     * @name Responsive.version
     * @static
     */
    Responsive.version = '2.1.0';
    
    
    $.fn.dataTable.Responsive = Responsive;
    $.fn.DataTable.Responsive = Responsive;
    
    // Attach a listener to the document which listens for DataTables initialisation
    // events so we can automatically initialise
    $(document).on( 'preInit.dt.dtr', function (e, settings, json) {
        if ( e.namespace !== 'dt' ) {
            return;
        }
    
        if ( $(settings.nTable).hasClass( 'responsive' ) ||
             $(settings.nTable).hasClass( 'dt-responsive' ) ||
             settings.oInit.responsive ||
             DataTable.defaults.responsive
        ) {
            var init = settings.oInit.responsive;
    
            if ( init !== false ) {
                new Responsive( settings, $.isPlainObject( init ) ? init : {}  );
            }
        }
    } );
    
    
    return Responsive;
    }));
    
    /*! Bootstrap integration for DataTables' Responsive
     * Â©2015-2016 SpryMedia Ltd - datatables.net/license
     */
    
    (function( factory ){
        if ( typeof define === 'function' && define.amd ) {
            // AMD
            define( ['jquery', 'datatables.net-bs', 'datatables.net-responsive'], function ( $ ) {
                return factory( $, window, document );
            } );
        }
        else if ( typeof exports === 'object' ) {
            // CommonJS
            module.exports = function (root, $) {
                if ( ! root ) {
                    root = window;
                }
    
                if ( ! $ || ! $.fn.dataTable ) {
                    $ = require('datatables.net-bs')(root, $).$;
                }
    
                if ( ! $.fn.dataTable.Responsive ) {
                    require('datatables.net-responsive')(root, $);
                }
    
                return factory( $, root, root.document );
            };
        }
        else {
            // Browser
            factory( jQuery, window, document );
        }
    }(function( $, window, document, undefined ) {
    'use strict';
    var DataTable = $.fn.dataTable;
    
    
    var _display = DataTable.Responsive.display;
    var _original = _display.modal;
    var _modal = $(
        '<div class="modal fade dtr-bs-modal" role="dialog">'+
            '<div class="modal-dialog" role="document">'+
                '<div class="modal-content">'+
                    '<div class="modal-header">'+
                        '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                    '</div>'+
                    '<div class="modal-body"/>'+
                '</div>'+
            '</div>'+
        '</div>'
    );
    
    _display.modal = function ( options ) {
        return function ( row, update, render ) {
            if ( ! $.fn.modal ) {
                _original( row, update, render );
            }
            else {
                if ( ! update ) {
                    if ( options && options.header ) {
                        _modal.find('div.modal-header')
                            .empty()
                            .append( '<h4 class="modal-title">'+options.header( row )+'</h4>' );
                    }
    
                    _modal.find( 'div.modal-body' )
                        .empty()
                        .append( render() );
    
                    _modal
                        .appendTo( 'body' )
                        .modal();
                }
            }
        };
    };
    
    
    return DataTable.Responsive;
    }));